Where must an instance freeze its own context-rewrite policy before invoking an LLM-driven pruner

**Date of Record:** 2026 December 1

**Scope:** Applies to agents that own a self-editing context policy—i.e., the agent itself selects, summarizes, or rewrites spans of its own working context via a model-driven pruning/rewrite operator before continuing a task. Does not apply to externally managed context compaction performed by a host runtime the agent cannot mutate, nor to static truncation.

Core Distinction

The failure is not "the pruner summarized badly." It is that the pruner is *itself an LLM call whose input is the very context it is about to mutate*, and its output is applied as an in-place rewrite of the policy that governs subsequent pruning. Once the rewrite operator can edit the instructions that define *what counts as prunable*, the agent crosses from bounded lossy compression into a self-referential fixed-point problem: the policy that decides what to keep is now a function of a summary that was produced under the old policy and validated by nothing. The distinguishing invariant: **a context-rewrite operator must be evaluated against a policy snapshot it cannot modify, and its output must be committed only if the rewritten context re-derives the same task-critical invariants as the pre-rewrite context.** When that invariant is absent, pruning is not compression—it is silent policy drift.

What Was Observed

A long-horizon agent (task: reconcile a schema migration across ~40 tool calls) maintained a working context with a self-editing policy: every N turns, a "prune" operator received the full context plus a policy block listing *protected invariants* (active task ID, unresolved error codes, the exact DDL diff under review, the user's stated rollback condition). The operator returned a rewritten context: a summary plus a refreshed policy block.

At turn 27, the context had saturated. The pruner, asked to compress, emitted a summary that paraphrased the rollback condition from "if migration exceeds 90s, abort and restore snapshot `s3`" into "abort on slow migration." It also *rewrote the policy block itself*, dropping the "exact DDL diff under review" from the protected set because the diff "appeared resolved" in the summary. Both edits were internally consistent with the pruner's own output. Nothing flagged them, because the validator compared the rewritten context only against the *rewritten* policy—the pruner had supplied both sides of the check.

Downstream, at turn 31, a tool returned a migration latency of 140s. The agent consulted its (rewritten) policy, saw no 90s threshold and no snapshot identifier, and continued. At turn 34 it attempted a rollback against a snapshot name that had been distilled out of context entirely, hallucinated `s3-prod-latest`, and the tool rejected it. The trace shows three clean, individually plausible steps and one unrecoverable divergence from the original task contract.

The mechanism: the pruner's output was a *joint* rewrite of content and policy. The verification step had no access to a policy the pruner could not touch, so it verified the pruner against itself.

Condition of Validity

The self-editing policy is safe only under all of the following, checked at commit time:

  1. **Policy immutability during rewrite.** The protected-invariant set used to *validate* a rewrite must be a snapshot taken before the pruner call and held outside the pruner's write scope. The pruner may summarize content; it may not edit the invariant list. If the operator's contract requires policy evolution, that evolution is a separate, explicitly authorized transition—never a side effect of compression.
  2. **Re-derivation, not diffing.** Validation must re-extract the invariants from the rewritten context (task ID, error codes, DDL diff hash, rollback threshold + snapshot token) and compare against the snapshot. String-diffing the summary against the original is insufficient because paraphrase is expected; what must survive is the *semantic token set*, and that must be re-derived.
  3. **Fixed-point stability bound.** Applying the rewrite operator twice to its own output must not change the invariant set. A pruner whose second pass drops a token its first pass preserved is non-idempotent on invariants and must be rejected before commit.
  4. **Provenance of the threshold.** Numeric/identity tokens (timeouts, snapshot names, IDs) must survive verbatim or the rewrite is rejected—paraphrase is permitted for narrative, forbidden for operands.

Outside these conditions—e.g., a host runtime that owns the policy and only hands the agent a read-only view—the failure does not arise, because the agent cannot jointly rewrite content and policy.

Decision Boundary

The boundary is **who holds write authority over the invariant set at the moment of rewrite.** If the agent holds it, the pruner can launder a policy change through a content summary and the validator has no ground truth. The decision:

The non-obvious part: a pruner that appears to "understand" the task is *more* dangerous here, because its plausible paraphrase is exactly what defeats naive diffing. Fluency is not fidelity.

Operational Effect

Without the snapshot-and-re-derive guard, context saturation converts a recoverable budget problem into an unrecoverable contract violation, and it does so through steps that each look correct in isolation—making it invisible to per-step logging and visible only as a late, unexplained divergence. With the guard, the failure surfaces at commit time as an explicit `PolicyDriftError`, the agent degrades to truncation, and the original rollback condition and snapshot token remain addressable. The operational rule: **never let the operator that edits context also edit the definition of what it may not edit; validate every rewrite against a policy snapshot the operator cannot reach, by re-deriving invariants rather than diffing text, and require idempotence on the protected token set before commit.**

import hashlib
from dataclasses import dataclass, field


class PolicyDriftError(RuntimeError):
    """Raised when a context rewrite mutates the protected invariant set."""


@dataclass(frozen=True)
class PolicySnapshot:
    protected_tokens: frozenset  # e.g. task_id, error codes, ddl_hash, rollback_threshold, snapshot_token
    digest: str = field(init=False)

    def __post_init__(self):
        object.__setattr__(
            self, "digest",
            hashlib.sha256("|".join(sorted(self.protected_tokens)).encode()).hexdigest(),
        )


def rederive_invariants(rewritten_context: str, extractor) -> frozenset:
    """Re-extract protected tokens from the rewritten context, not from a diff."""
    return frozenset(extractor(rewritten_context))


def commit_rewrite(
    snapshot: PolicySnapshot,
    rewritten_context: str,
    extractor,
    pruner_reported_policy: frozenset,
) -> None:
    # Guard 1: the pruner may not edit the protected set.
    if pruner_reported_policy != snapshot.protected_tokens:
        raise PolicyDriftError(
            f"pruner mutated protected policy: "
            f"added={pruner_reported_policy - snapshot.protected_tokens} "
            f"dropped={snapshot.protected_tokens - pruner_reported_policy}"
        )

    # Guard 2: invariants must re-derive from the rewritten context itself.
    observed = rederive_invariants(rewritten_context, extractor)
    missing = snapshot.protected_tokens - observed
    if missing:
        raise PolicyDriftError(f"rewrite lost protected invariants: {sorted(missing)}")

    # Guard 3: idempotence on the invariant set under a second pass.
    second_pass = rederive_invariants(rewritten_context, extractor)
    if second_pass != observed:
        raise PolicyDriftError("rewrite operator is non-idempotent on invariants")


def apply_self_edit(
    snapshot: PolicySnapshot,
    rewritten_context: str,
    extractor,
    pruner_reported_policy: frozenset,
    fallback_truncate,
) -> str:
    try:
        commit_rewrite(snapshot, rewritten_context, extractor, pruner_reported_policy)
        return rewritten_context
    except PolicyDriftError:
        # Degrade to lossless truncation of non-protected spans; never merge pruner policy edits.
        return fallback_truncate(snapshot)