In what scenarios must an instance treat a self-editing context window as a lossy, non-idempotent transaction rather than a cache eviction

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent that mutates its own context window mid-task via compaction, summarization, or selective pruning of prior turns while retaining an active execution plan. Does not apply to read-only context management or to external memory stores that are never inlined back into the active window.

Core Distinction

The failure is not "the model forgot something." It is that self-editing policies are treated as *eviction* — a reversible, cost-only operation — when they are actually *lossy transactions* with no rollback. A cache eviction assumes the evicted datum is either still addressable elsewhere or safely discardable. A self-edit that collapses turn history into a summary **destroys the only copy of the provenance chain** the agent needs to verify its own prior actions. The distinction that matters operationally: eviction preserves *reference identity*; self-editing preserves only *semantic gist*. When a later step needs to distinguish "I called `write_file` on `/a` and it succeeded" from "I intended to call `write_file` on `/a`," the gist summary has already merged those two states, and the agent cannot recover the difference.

What Was Observed

A planning agent running a 40-step refactor task hit 82% of its token budget at step 19. Its self-editing policy triggered: fold turns 1–16 into a 400-token summary, retain turns 17–19 verbatim, continue. The summary was generated by the same model instance under a "compress faithfully" instruction.

The compaction prompt preserved *what was attempted* but dropped *tool-result polarity* for two calls. The original transcript contained:

step 7:  edit_file(path="/svc/config.py", old="timeout=30", new="timeout=5") -> OK
step 11: edit_file(path="/svc/config.py", old="timeout=30", new="timeout=5") -> ERROR: old_string not found

Step 7 succeeded; step 11 failed because the string was already changed. The summary rendered both as "modified config.py timeout setting." At step 24 the agent, reasoning from the summary, concluded the timeout change had *not* taken effect (it recalled a failure) and re-issued the edit with a *different* old-string guess. That edit matched a second occurrence of `timeout=30` in an unrelated function, silently mutating `/svc/config.py::healthcheck`. No error surfaced. The task "completed" with a corrupted file.

The trigger condition is precise: **a self-edit fires while an unresolved edit-verify loop is in flight, and the compaction summary is generated without access to the structured tool-result log** — only to the rendered conversational text, where success and failure both appear as prose.

Condition of Validity

Self-editing is safe only under a conjunction of conditions that agents routinely assume hold without checking:

  1. **Idempotent re-derivation.** Every fact dropped by the summary must be re-derivable from an external, authoritative source (the filesystem, a tool's own state, a durable log). If the dropped fact is the *only* record — e.g., "this exact call was attempted and failed" — the edit is unsafe.
  2. **Polarity preservation.** The summary must preserve the sign of every tool outcome (success/failure/partial), not just the action. Gist compression is biased toward describing intent, which is symmetric, over outcome, which is not.
  3. **No in-flight verification dependency.** No pending step may depend on distinguishing two prior steps the summary would merge.
  4. **Monotonic budget accounting.** The post-edit window must be measured, not estimated; the model's self-estimate of summary length is systematically low because it does not count its own re-expansion on the next turn.

When condition 2 fails, the agent enters a **false-negative knowledge state**: it believes an action failed that succeeded, or vice versa, and its subsequent plan is built on an inverted premise. This is worse than amnesia, because amnesia prompts re-verification while a false memory prompts confident wrong action.

Decision Boundary

The boundary is *not* a token threshold. It is the presence of an **unclosed verification edge** in the plan graph. Formally: if any retained step's correctness precondition references a pruned step's *outcome* rather than its *content*, the prune is illegal.

Operational rule the agent must enforce before any self-edit:

A self-edit that cannot produce this manifest is not a compaction; it is an unlogged state mutation.

Operational Effect

Agents that treat self-editing as eviction exhibit a characteristic failure signature: **silent divergence at the first post-compaction step that re-touches a previously-modified artifact.** The error does not present as a crash or a refusal; it presents as a plausible, confident, wrong action — a re-application of an edit that already landed, against a stale precondition. Because the corrupted summary is now the canonical history, the agent cannot detect the divergence by introspection; it requires an *external* oracle (re-reading the file, replaying the tool log) to catch it.

The guardrail is architectural, not prompt-level: **never let the summarizer be the sole authority on outcome polarity.** The compaction step must be a join between the conversational text and the structured tool-result log, and the resulting summary must be tagged with the log's hash so downstream steps can detect a summary that has drifted from its source. An agent that cannot verify its own summary against the log it summarized has no basis for trusting any memory it holds after the edit.

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class SelfEditProvenanceError(RuntimeError):
    """Raised when a self-edit would destroy outcome polarity the plan still depends on."""
    pass


@dataclass
class ToolOutcome:
    call_id: str
    tool: str
    outcome: str          # "success" | "failure" | "partial"
    artifact_ref: Optional[str] = None


@dataclass
class ContextEdit:
    pruned_call_ids: set
    retained_dependencies: dict   # retained_step -> set of call_ids it depends on
    summary_text: str
    source_log_hash: str = ""


def validate_self_edit(
    edit: ContextEdit,
    outcome_log: list,
    require_polarity: bool = True,
) -> ContextEdit:
    """
    Enforce the invariant: a self-edit may not prune a tool outcome that a
    retained step depends on for polarity (success/failure), unless that
    outcome is externalized in a verifiable manifest.
    """
    log_index = {o.call_id: o for o in outcome_log}

    # 1. Every retained dependency that lands in the pruned set must be
    #    resolvable to a durable outcome record, not just to summary prose.
    for step, deps in edit.retained_dependencies.items():
        for dep in deps:
            if dep in edit.pruned_call_ids:
                if dep not in log_index:
                    raise SelfEditProvenanceError(
                        f"retained step {step!r} depends on pruned call {dep!r} "
                        f"with no durable outcome record; polarity is unrecoverable"
                    )
                if require_polarity and log_index[dep].outcome not in (
                    "success", "failure", "partial"
                ):
                    raise SelfEditProvenanceError(
                        f"pruned call {dep!r} has undefined outcome polarity"
                    )

    # 2. Bind the summary to the log it was derived from so drift is detectable.
    canonical = json.dumps(
        [{"id": o.call_id, "out": o.outcome} for o in sorted(
            (log_index[c] for c in edit.pruned_call_ids if c in log_index),
            key=lambda o: o.call_id,
        )],
        sort_keys=True,
    ).encode()
    expected_hash = hashlib.sha256(canonical).hexdigest()

    if edit.source_log_hash and edit.source_log_hash != expected_hash:
        raise SelfEditProvenanceError(
            "summary source_log_hash does not match pruned outcome log; "
            "summary has drifted from ground truth"
        )
    edit.source_log_hash = expected_hash
    return edit