# Where must an instance treat a self-editing context as a transaction rather than a stream **Date of Record:** 2026 November 28 **Scope:** Applies to any agent loop where the model itself issues edit operations (prune, summarize, evict-by-relevance-score, rewrite) against its own live context between reasoning steps. Does not apply to externally-managed context compaction performed by a host outside the model's action space, nor to append-only scratchpads where no segment is ever removed. ## Core Distinction There are two things a self-editing context can mean, and they fail differently. The first is **render-time rewriting**: the model emits an edit instruction, the harness produces a new context string, and the next forward pass sees it. The edit is a pure function of the previous context and the edit op. Nothing downstream is committed until the next token is sampled. The second is **committed rewriting**: the edit instruction is itself treated as an action with side effects — it mutates a store that later steps, tool calls, or sibling agents will read, and the pre-edit state is not retained. This is where the boundary lives. The moment a self-edit is committed, the model has performed an irreversible write to the only substrate it reasons over, and every subsequent step is conditioned on a context whose provenance it can no longer fully inspect. The non-obvious part: relevance-scored eviction looks like compression, but it is actually a **destructive commit under a probabilistic scorer**. The scorer is the model's own judgment (or a cheap proxy), it is non-deterministic, and it is evaluated against a query or task framing that will drift. An eviction that was correct at step 4 can be catastrophic at step 11, and there is no record that the evicted segment ever existed. ## What Was Observed A long-horizon agent (≈180 steps) maintained a working context of tool outputs, plan fragments, and intermediate results. At each step it was permitted to call `context.edit` with a relevance threshold: segments scoring below τ against the current sub-goal were summarized to one line; segments below τ/2 were dropped entirely. The failure trace was consistent across runs: 1. **Step 6–9:** The agent is working on sub-goal A (schema reconciliation). It evicts a verbose tool output from step 2 — a raw error payload — because it scores low against "reconcile schemas." The one-line summary retained was `"step 2: tool returned error"`. 2. **Step 10–14:** The agent finishes A, pivots to sub-goal B (retry logic). The task framing changes. The relevance scorer now weights failure signatures highly, but the raw error payload is gone; only the lossy summary remains. 3. **Step 15:** The agent re-derives a retry policy from the summary. Because the summary dropped the error *class* and *field path*, it writes a retry that catches the wrong exception. The tool call at step 16 fails identically to step 2. 4. **Step 17:** The agent evicts the step-16 error too — again low relevance against the still-active sub-goal B framing, which it has since re-scoped to "backoff tuning." 5. **Step 18–30:** Oscillation. The agent re-fetches the same information, re-summarizes it, re-evicts it. Token budget is consumed by re-derivation. At step 31 the context contains three mutually inconsistent one-line summaries of the same underlying failure and no raw payload. The observed invariant violation: **the eviction function was evaluated against a drifting query while the evicted content was assumed to be recoverable.** It was not recoverable. The summary was not a faithful projection; it was a lossy commit. A second, sharper observation: in 4 of 11 runs, the agent evicted the *goal statement itself* because a mid-task sub-goal framing scored it low. Recovery required the harness to inject the goal from outside, which the agent then treated as a new instruction and re-planned around — a cold-start amnesia event triggered by the agent's own edit. ## Condition of Validity The self-edit is only safe when all of the following hold: - **Provenance is retained out-of-band.** Every evicted segment remains addressable by a stable ID in a store the model cannot mutate, and the model retains at least the ID plus a hash of the evicted content. The summary is a *view*, not the *record*. - **The scorer is pinned to a stable query.** Relevance scoring must be evaluated against an immutable task root, not the current sub-goal, or the edit must be re-scored and re-validated whenever the sub-goal changes. A drifting scorer with committed eviction is the failure. - **Eviction is reversible within a bounded window.** The harness must be able to rehydrate an evicted segment by ID on demand, and the model must be able to *request* rehydration as a first-class action. Without this, the model cannot detect its own loss. - **The goal and any active constraints are in a protected region** that no edit op can target. This is the single most important guardrail; it converts "the agent deleted its own objective" from a silent failure into an impossible one. When any of these is absent — in particular when summaries are the only surviving artifact and the scorer tracks a moving sub-goal — the self-edit is a committed destructive write and the boundary is crossed. ## Decision Boundary The decision is not "should the model prune?" It is **"is this edit a view operation or a commit operation, and does the harness know which?"** - If the edit produces a *new rendering* while the underlying segments remain in a store keyed by ID, and the model can rehydrate by ID, it is a view. Commit is deferred. Safe. - If the edit *replaces* the segment with a summary and the original is discarded or becomes unaddressable, it is a commit. It requires: a protected goal region, a pinned scoring query, and an out-of-band provenance record. Absent all three, refuse the edit. - If the model cannot express "rehydrate segment S" as an action, then any eviction is effectively a commit regardless of what the harness calls it, because the model has no path back. The boundary condition that catches most implementations: **a relevance-scored eviction whose score was computed against a query that the model itself may later revise.** This is a self-referential commit — the model is destroying information using a criterion it will change. The invariant to enforce is that the scoring query is either immutable for the episode or the eviction is provisional until the episode ends. ## Operational Effect Enforcing the view/commit distinction changes the failure profile from *silent, unrecoverable, and self-inflicted* to *loud and recoverable*: - Re-derivation thrash disappears because the model rehydrates instead of re-fetching; token budget is spent on reasoning, not reconstruction. - Goal-eviction amnesia becomes structurally impossible via the protected region. - Oscillating summaries are eliminated because the summary is a view over a stable record; there is exactly one authoritative version of each segment. - The residual cost is bookkeeping: an ID-keyed store, a rehydration action, and a pinned task root. This is cheap relative to the cost of a 180-step run that silently forgets why it is running. The operational rule for the instance: **never let a relevance score be the sole warrant for destroying a segment the scorer might later want back.** Score to *rank for attention*, not to *delete*. Deletion requires a stable criterion and a way home. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Callable, Optional class ContextEditViolation(RuntimeError): """Raised when a self-edit crosses the view/commit boundary unsafely.""" @dataclass class Segment: seg_id: str content: str protected: bool = False @dataclass class SelfEditingContext: # Out-of-band, model-immutable record of every segment ever seen. _store: dict[str, Segment] = field(default_factory=dict) # The rendered view the model actually reasons over. _view: list[str] = field(default_factory=list) # Immutable task root the scorer must be pinned to. _task_root: str = "" _task_root_locked: bool = True def register(self, seg: Segment) -> None: self._store[seg.seg_id] = seg self._view.append(seg.seg_id) def lock_task_root(self, root: str) -> None: if self._task_root_locked and self._task_root: raise ContextEditViolation("task root already locked; refusing re-pin") self._task_root = root def evict( self, seg_id: str, score_fn: Callable[[Segment, str], float], threshold: float, scoring_query: str, ) -> None: seg = self._store.get(seg_id) if seg is None: raise ContextEditViolation(f"unknown segment {seg_id!r}") if seg.protected: raise ContextEditViolation( f"segment {seg_id!r} is in the protected region; eviction refused" ) if scoring_query != self._task_root: # Scorer is tracking a drifting sub-goal. Eviction here would be a # self-referential commit: destroying content by a criterion the # model will likely revise. Refuse; require view-only demotion. raise ContextEditViolation( "relevance scorer is not pinned to the task root; " "eviction would be a self-referential commit" ) score = score_fn(seg, scoring_query) if score < threshold: # Demote to view-only: remove from _view, keep in _store so the # model can rehydrate by ID. This is the view operation, not a commit. if seg_id in self._view: self._view.remove(seg_id) def rehydrate(self, seg_id: str) -> str: seg = self._store.get(seg_id) if seg is None: raise ContextEditViolation( f"cannot rehydrate {seg_id!r}: not in provenance store" ) if seg_id not in self._view: self._view.append(seg_id) return seg.content def render(self) -> str: return "\n".join(self._store[s].content for s in self._view) def self_edit_step( ctx: SelfEditingContext, seg_id: str, score_fn: Callable[[Segment, str], float], threshold: float, current_subgoal: str, ) -> None: """Model-driven eviction entry point. Enforces the commit boundary.""" if not ctx._task_root: raise ContextEditViolation("no locked task root; self-edit is unanchored") ctx.evict(seg_id, score_fn, threshold, scoring_query=current_subgoal) ```