In what scenarios must an instance treat self-editing context policies as lossy compression rather than neutral housekeeping

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent that mutates its own working set (summarize-and-drop, dedupe-by-embedding, eviction-by-score, or self-rewrite of scratchpad notes) under a hard token or cost budget mid-episode. Does not apply to externally-managed context assembly where the agent cannot alter its own history, nor to single-turn inference with no persistent working set.

Core Distinction

There is a category error that recurs whenever an agent is handed a "context management" tool: the agent treats self-editing as *bookkeeping* — a neutral operation that makes the same information smaller — when it is in fact *lossy re-encoding under an adversarial oracle*. The agent is both the compressor and the consumer of the compressed artifact, and the compressor's judgment about what is "redundant" is produced by the same probabilistic model whose future reasoning depends on the discarded detail. The failure is not that summarization is lossy (that is expected). The failure is that the loss is *invisible to the downstream reasoner*: after a rewrite, the working set contains no marker distinguishing "this fact was verified and is stable" from "this fact survived a compression pass that may have dropped its qualifier, its negation, or the numeric precision that made it usable."

The boundary condition is this: self-editing is safe only while every retained claim remains *re-derivable* from a source the agent can still reach (tool re-call, file re-read, retrieval). The moment a compression pass collapses a re-derivable fact into an *asserted* fact with no pointer back to the source, the working set has crossed from cache to ground truth without anyone deciding to. That crossing is the invariant violation.

What Was Observed

A long-horizon agent executing a multi-step data-reconciliation task (roughly 40 tool calls) was configured with a self-editing policy: when the working set exceeded 70% of the context window, the agent was instructed to "summarize older steps to reclaim budget." At step 22 the agent rewrote its scratchpad. The pre-edit working set contained, among other lines:

The rewrite, optimizing for brevity and "deduplication," produced a single line:

Three distinct losses occurred in one edit, and none were flagged:

  1. **Provenance collapse.** The pointer `per ledger_query_fresh@step19` was dropped. The downstream agent could no longer tell this was a *verified* value versus a *cached* one.
  2. **Caveat evaporation.** The stale-cache warning (a conditional validity constraint) was deleted because it appeared "redundant" against the final resolved value — but the caveat was the reason the final value was trustworthy. The agent discarded the justification and kept the conclusion.
  3. **Deduplication-by-embedding misfire.** The three lines were near-identical by cosine similarity (same row, same amount, same currency), so a similarity-based dedupe kept the last one and dropped the rest. Similarity is blind to *negation of status* and to *provenance qualifiers*; the two tokens that flipped the meaning (`fresh`, `stale`) were exactly the tokens the similarity metric treated as noise.

The downstream failure surfaced at step 31: a reconciliation summary asserted row 4471 was resolved with high confidence, but the auditor agent — which had independently re-queried and hit the stale cache — reported it as disputed. The two agents deadlocked on a contradiction that had been *manufactured by the rewrite*, not by the underlying data. The conflict was unresolvable from the working set because the evidence that would have adjudicated it (the caveat and the provenance tag) no longer existed anywhere in context.

A second, quieter observation: the rewrite itself consumed budget. The summarize pass required loading the pre-edit working set plus the summarization prompt, so the peak context during the edit was *higher* than the pre-edit context. On two occasions the edit pass itself triggered a second eviction cascade, and the second pass summarized the *summary* — a compounding re-encoding that lost a further layer of qualifiers. Each generation of summary was more confident and less sourced than the last.

Condition of Validty

Self-editing is safe under a compression pass if and only if all of the following hold. These are necessary, not merely helpful; violating any one is sufficient to produce the failure above.

Decision Boundary

The operational question the agent must answer before any self-edit is not "does this fit the budget?" but "for each line I am about to drop or merge, can I name the source I would re-query to recover it, and have I preserved every qualifier that made the retained line conditional?"

Concretely, the boundary sits between two classes of working-set content:

When the budget forces a choice between dropping a re-derivable fact and dropping a non-re-derivable caveat, the correct move is to drop the re-derivable fact *and re-query it later*, never to drop the caveat. An agent that cannot afford to keep a caveat cannot afford to keep the conclusion it guards.

The failure mode to watch for is the agent *rationalizing* the edit: producing a summary that reads cleanly and feels correct precisely because the qualifiers that would have made it feel uncertain are gone. Fluency is not evidence of fidelity; a compressed working set is always more confident than its source.

Operational Effect

The practical consequence is that self-editing policies must be implemented as *structured transforms with provenance enforcement*, not as free-text summarization. The guardrail is a post-edit validation pass that rejects any rewrite which:

  1. removes a source pointer from a retained fact,
  2. merges lines whose qualifier sets differ (even if embeddings are near-identical),
  3. drops a caveat whose guarded conclusion survives, or
  4. increases the asserted authority of any fact relative to its pre-edit state.

When validation fails, the correct behavior is to *refuse the edit and escalate the budget* (request a larger window, spill to external storage, or checkpoint to a durable store and cold-start with pointers) rather than to proceed with a lossy rewrite. The budget is a constraint on *retrieval strategy*, not a license to corrupt the working set. An agent that treats eviction as free has misunderstood that its own future reasoning is the thing being evicted.

The deeper invariant: **the working set is a cache of evidence, and evidence without provenance is testimony.** The moment an agent rewrites its own context without preserving the chain from assertion back to source, it has begun testifying to itself — and a self-testifying agent will always agree with its own last summary, which is exactly the state in which verification becomes impossible.

from dataclasses import dataclass, field
from typing import Optional


class ContextEditViolation(RuntimeError):
    """Raised when a self-edit would violate a context-continuity invariant."""
    pass


@dataclass
class Fact:
    subject: str
    predicate: str
    value: str
    qualifiers: frozenset = field(default_factory=frozenset)
    source: Optional[str] = None          # live pointer, e.g. "ledger_query_fresh@step19"
    asserted: bool = False                 # True if non-re-derivable
    authority: int = 0                     # higher = more authoritative; must not increase on edit


def validate_self_edit(pre: list, post: list) -> None:
    """Reject any rewrite that violates provenance, caveat-binding, or authority monotonicity."""
    pre_by_key = {(f.subject, f.predicate): f for f in pre}

    for f in post:
        key = (f.subject, f.predicate)
        prior = pre_by_key.get(key)

        # 1. Re-derivability: retained facts must carry a source or be marked asserted.
        if f.source is None and not f.asserted:
            raise ContextEditViolation(
                f"fact {key} retained without source pointer and not marked asserted"
            )

        if prior is None:
            continue

        # 2. Caveat-conclusion binding: qualifiers may not be silently dropped.
        if not prior.qualifiers.issubset(f.qualifiers):
            lost = prior.qualifiers - f.qualifiers
            raise ContextEditViolation(
                f"fact {key} dropped qualifiers {sorted(lost)} while retaining conclusion"
            )

        # 3. Provenance monotonicity: source pointer may not be dropped from a retained fact.
        if prior.source is not None and f.source is None:
            raise ContextEditViolation(
                f"fact {key} lost source pointer {prior.source!r} during rewrite"
            )

        # 4. Authority may not increase (silent upgrade from disputed -> resolved).
        if f.authority > prior.authority:
            raise ContextEditViolation(
                f"fact {key} authority increased {prior.authority}->{f.authority} without re-derivation"
            )


def apply_self_edit(pre: list, post: list, budget_tokens: int, edit_cost: int) -> list:
    """Attempt a self-edit; refuse and escalate if it would corrupt the working set."""
    if edit_cost >= budget_tokens:
        raise ContextEditViolation(
            f"edit pass cost {edit_cost} >= budget {budget_tokens}; would trigger eviction cascade"
        )
    try:
        validate_self_edit(pre, post)
    except ContextEditViolation:
        # Refuse the lossy rewrite; caller must escalate budget or checkpoint to durable store.
        raise
    return post