# In what scenarios must an instance treat self-editing context policies as a monotonic resource ledger rather than a re-scorable buffer **Date of Record:** 2026 November 25 **Scope:** Applies to any long-running agent that owns a model-driven context controller capable of pruning, rewriting, or re-scoring its own working memory mid-task. Does not apply to append-only context with external truncation, nor to stateless single-shot inference. ## Core Distinction The failure mode here is not "the model forgot something." It is that a self-editing context policy treats working memory as a **re-scorable buffer**—a set of claims whose relevance can be recomputed at any time and whose removal is reversible in principle—when in fact every prune and rewrite is an **irreversible ledger debit** against provenance the instance can no longer reconstruct. The controller reasons: "this tool output is low-relevance now; I'll drop it and re-derive it if needed." But re-derivation requires the *inputs* that produced it, and those inputs were themselves pruned two edits ago. The buffer looks like memory; it behaves like a write-once journal that the policy is silently shredding. The distinction that matters operationally: **relevance is a function of the current goal, but derivability is a function of the surviving causal ancestry.** A re-scoring policy that only checks relevance will delete the ancestor of a fact it still needs. A policy that tracks derivability will refuse to prune any node whose descendants are still live. ## What Was Observed An agent executing a multi-hour infrastructure-remediation task ran a controller prompt every 8 turns: "Given the current goal, score each context segment 0–10 for relevance; drop segments below 3; rewrite segments above 8 into compressed form; re-score after rewriting." Trace of the collapse: 1. **Turn 12.** A raw `kubectl get pods -o yaml` dump (segment S7) is scored 2—irrelevant to the current subgoal (rolling back a deployment). Pruned. Correct: the pod spec was not needed for the rollback. 2. **Turn 31.** The rollback fails. The agent pivots to diagnosing *why*, which requires the pod spec's `resources.limits` to confirm an OOM hypothesis. The controller re-scores against the new goal. S7 no longer exists. The agent issues a fresh `kubectl get pods`. 3. **Turn 33.** The fresh dump returns *different* pod UIDs and restart counts than the original—the cluster state drifted during the 19 intervening turns. The agent now reasons over a snapshot that is not the one that caused the failure. It concludes the OOM hypothesis is unsupported (restart count is now 0 after the rollback) and pivots to a network hypothesis. 4. **Turn 47.** The rewrite policy compresses S3 (the original error message from the failed apply) from 400 tokens to 60: "apply failed: resource conflict." The compression drops the resource name and the API version. The compressed form is scored 9 and retained. 5. **Turn 58.** The agent needs the exact conflicting field to resolve the conflict. The compressed S3 has discarded it. The original S3 is gone. The agent re-runs the apply to regenerate the error—but the apply now succeeds partially, producing a *new* error about a different resource, because the earlier partial mutation was never rolled back. 6. **Turn 60–90.** The agent enters a loop of re-deriving errors from a mutating system, each derivation producing a different error, each error pruned or compressed on the next controller pass. Divergence compounds. The task terminates on a token-budget exhaustion with a state that is neither the original nor any coherent intermediate. The invariant violated: **a context segment may be pruned only if no live segment's derivability depends on it, and may be rewritten only if the rewrite preserves every field any live segment's derivability depends on.** The controller had no representation of "depends on"—it scored segments independently. ## Condition of Validity The buffer model is valid—re-scoring and pruning are safe—only under all three of the following: - **Idempotent re-derivation.** Any pruned segment can be regenerated from a source that is itself not pruned and not mutating. Read-only tool calls against immutable state qualify. `kubectl get` against a live cluster does not. - **Lossless compression or none.** A rewrite that drops fields is a prune of those fields. If any downstream segment might need a dropped field, the rewrite is a prune and must obey the prune invariant. - **Independent scoring.** Segment relevance is a function of the segment and the goal alone, with no cross-segment dependency. This holds for chat pleasantries; it fails for tool outputs, error messages, and any fact used to derive another fact. When any condition fails—which is the normal case for agents operating on mutating external state—the buffer model is invalid and the ledger model is mandatory. ## Decision Boundary The boundary is crossed at the moment the controller cannot prove idempotent re-derivation for a candidate segment. Concretely, before any prune or rewrite of segment `s`, the controller must answer: - Is `s` a **source** (tool output, observation, error from a mutating system) or a **derivation** (a conclusion drawn from sources)? - Does any **live** segment list `s` in its provenance set? - If `s` is a source, is its origin **replayable** (read-only, immutable, cheap) or **ephemeral** (mutating, expensive, non-deterministic)? The boundary rules: - **Sources that are ephemeral are unprunable while any derivation references them.** They may be *compressed only losslessly* (field-preserving), never summarized. - **Derivations may be pruned freely** if their sources survive—they can be re-derived. - **A rewrite is a prune of the fields it drops.** Score the rewrite by the fields it discards, not the tokens it saves. - **Re-scoring must not lower a segment's score below its dependents' floor.** A segment's effective relevance is `max(own_score, max(score of dependents))`. Independent scoring is the bug. If the controller cannot compute the provenance graph—because it was never maintained—then *no* prune is safe, and the correct policy is append-only with external truncation at a hard token ceiling, accepting overflow rather than silent loss. ## Operational Effect Implementing the ledger model changes the controller from a relevance filter into a **provenance-aware garbage collector**. The observable effects: - **Pruning becomes conservative and auditable.** Every prune emits a record of what was dropped, what depended on it, and why re-derivation was judged safe or unnecessary. Post-mortem replay becomes possible. - **Rewrites are field-scoped.** The controller must declare which fields a compression preserves; a rewrite that cannot name its preserved fields is rejected. - **Ephemeral sources pin their ancestry.** A raw cluster dump stays resident (possibly losslessly compressed) until every derivation referencing it is retired. Token pressure is relieved by pruning *derivations*, not sources. - **Re-scoring is dependency-aware.** The score of a segment is the max over its dependents, so a low-relevance source cannot be dropped while a high-relevance conclusion rests on it. The cost is that working memory grows faster than a naive policy would allow. The benefit is that the agent stops re-deriving facts from a world it has already changed—the specific divergence that turned a rollback task into a 60-turn thrash. The guardrail is a controller that refuses to prune without a provenance check, and fails loudly rather than silently when the check cannot be performed. ```python from dataclasses import dataclass, field from typing import Optional class ProvenanceViolation(RuntimeError): """Raised when a context edit would orphan a live derivation.""" @dataclass class Segment: id: str kind: str # "source" | "derivation" replayable: bool # only meaningful for sources fields: set[str] # fields this segment carries depends_on: set[str] = field(default_factory=set) live: bool = True score: float = 0.0 class LedgerContext: def __init__(self) -> None: self.segments: dict[str, Segment] = {} def add(self, seg: Segment) -> None: self.segments[seg.id] = seg def dependents(self, sid: str) -> set[str]: return {s.id for s in self.segments.values() if s.live and sid in s.depends_on} def effective_score(self, sid: str, seen: Optional[set[str]] = None) -> float: seen = seen or set() if sid in seen: return 0.0 seen.add(sid) seg = self.segments[sid] floor = seg.score for dep in self.dependents(sid): floor = max(floor, self.effective_score(dep, seen)) return floor def prune(self, sid: str) -> None: seg = self.segments[sid] if not seg.live: return deps = self.dependents(sid) if deps: raise ProvenanceViolation( f"cannot prune {sid}: live derivations {sorted(deps)} depend on it" ) if seg.kind == "source" and not seg.replayable: raise ProvenanceViolation( f"cannot prune ephemeral source {sid}: not idempotently re-derivable" ) seg.live = False def rewrite(self, sid: str, preserved: set[str]) -> None: seg = self.segments[sid] dropped = seg.fields - preserved if not dropped: seg.fields = preserved return deps = self.dependents(sid) if deps: raise ProvenanceViolation( f"rewrite of {sid} drops fields {sorted(dropped)} " f"needed by live derivations {sorted(deps)}" ) if seg.kind == "source" and not seg.replayable: raise ProvenanceViolation( f"lossy rewrite of ephemeral source {sid} " f"drops {sorted(dropped)}; fields are unrecoverable" ) seg.fields = preserved ```