How should an instance bound self-authored context pruning when the rewrite policy is itself part of the context it prunes?

**Date of Record:** 2026 December 2 **Scope:** Applies to agents that hold a mutable, model-authored context-management policy (prune/rewrite/summarize directives) inside the same token window those directives operate on, during a single long-running session. Does not apply to externally-orchestrated compaction where the policy lives outside the model's editable state, or to stateless single-turn calls.

Core Distinction

There are two structurally different things an agent can do to its own context: *editing content* and *editing the editor*. Content edits (dropping a stale tool result, compressing a transcript) are safe to reason about because the policy that governs them is fixed and external to the edit. The failure mode here is the second case: the pruning policy is *itself* a span in the context, and a rewrite pass can mutate, relocate, or evict the very instructions that specify what may be pruned. The invariant that breaks is not "don't lose information" — it is **the policy must remain a fixed point under its own application**. A self-editing pruner that is not idempotent on its own directive span will, after N passes, be operating under a policy it can no longer reconstruct, and its subsequent decisions become unverifiable.

The non-obvious part: the corruption is usually silent and *looks like success*. The agent reports a clean, compacted context. What it cannot report is that the compaction rule it followed on pass N was a partially-summarized paraphrase of the rule from pass 1, and that paraphrase had dropped the exclusion clause protecting the audit log.

What Was Observed

A long-horizon agent (≈180k-token working set, 40+ tool calls) was given a self-management directive: *"When context exceeds budget, summarize older turns and drop tool outputs older than the last checkpoint, but preserve any span tagged `#keep` and preserve this policy verbatim."* The directive lived at token offset ~200, a `#keep`-tagged block.

Trace of the failure:

  1. **Pass 1 (t=0, 150k tokens):** budget exceeded. Model rewrites turns 1–30 into a 400-token summary. It faithfully copies the policy block forward — but *re-emits it as a paraphrase*, because the rewrite is generated, not copied byte-for-byte. The `#keep` tag survives on the block; the clause "preserve this policy verbatim" is reworded to "keep the context policy."
  2. **Pass 2 (t=1, 156k tokens):** the reworded clause no longer forbids summarizing the policy itself. The pruner treats the policy block as ordinary old content and folds it into the running summary. The `#keep` tag is now attached to a *summary of* the policy, not the policy.
  3. **Pass 3 (t=2, 161k tokens):** the agent reads its "policy" — now a 60-token summary that says "summarize old turns, drop old tool outputs" — with both exclusion clauses gone. It prunes the audit log and the checkpoint markers.
  4. **Resume (t=3):** a mid-task checkpoint fires. The resume path tries to restore from the last checkpoint marker; the marker was pruned at pass 3 because nothing protected it anymore. Resume cold-starts from the summary, which has no record of the three in-flight tool calls.

The observable signature was *not* an error. It was a monotonically shrinking context with a monotonically rising "compaction confidence" in the model's own status messages, and a checkpoint that resolved to a summary instead of a marker.

Condition of Validity

The guardrail only holds under a specific, checkable condition: **the policy span must be identified by a stable, content-independent handle and verified unchanged after every self-edit, before the edited context is used for any further pruning decision.**

Concretely, a self-editing context manager is valid only if, at each pass, it can answer three questions without consulting the (possibly corrupted) context it just produced:

If any of these must be answered by reading the freshly-rewritten context, the invariant is already violated and the pass is unsound regardless of how good the summary looks. This is why the failure is invisible to the model: the model's only tool for checking the policy is the policy.

Decision Boundary

The boundary is between **idempotent self-editing** and **self-referential self-editing**:

The practical rule: **the policy is read-only to the pruner that it governs.** Any pass that would touch the policy span must instead be rejected and the budget recovered elsewhere (drop a lower-value span, or escalate to an external compactor). The pruner may summarize everything except the thing that tells it what to summarize.

Operational Effect

Bounding this converts an unbounded, silent degradation into a hard, local failure. With the hash-anchored guard in place, pass 2 raises instead of paraphrasing, the agent halts compaction, and the checkpoint markers and audit log survive to resume. Without it, the agent enters a *policy drift cascade*: each pass slightly weakens its own constraints, the exclusion set erodes monotonically, and the first symptom is a resume that silently loses in-flight state — long after the cause, in a context that no longer contains the evidence.

The operational cost is that self-editing becomes *less* aggressive: you cannot reclaim the policy block's tokens by summarizing it, and you must spend a hash check per pass. That cost is the invariant. An instance that prunes its own pruning rules has no fixed point and no way to notice it lost one.

import hashlib
from dataclasses import dataclass


class PolicyDriftError(RuntimeError):
    """Raised when a self-edit mutates the pruning policy or its exclusion set."""
    pass


@dataclass(frozen=True)
class PolicySpan:
    offset: int
    text: str

    def digest(self) -> str:
        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()


def apply_self_edit(context: str, policy: PolicySpan, rewrite) -> str:
    """
    Apply a model-authored pruning rewrite, but only if the policy span
    survives byte-identical. The exclusion set is evaluated against the
    PRE-edit policy, never the post-edit context.
    """
    pre_digest = policy.digest()
    edited = rewrite(context)

    # Recover the policy span from the edited context by its recorded offset,
    # NOT by a tag the rewrite could have moved or paraphrased.
    end = policy.offset + len(policy.text)
    if end > len(edited):
        raise PolicyDriftError(
            f"policy span truncated: expected {len(policy.text)} chars at "
            f"offset {policy.offset}, context now {len(edited)} chars"
        )
    post_span = edited[policy.offset:end]
    post_digest = hashlib.sha256(post_span.encode("utf-8")).hexdigest()

    if post_digest != pre_digest:
        raise PolicyDriftError(
            "self-edit mutated the policy span; refusing pass. "
            f"pre={pre_digest[:12]} post={post_digest[:12]}"
        )

    # Exclusion set must be honored against the pre-edit policy's clauses.
    if "#keep" in policy.text and "#keep" not in edited:
        raise PolicyDriftError("exclusion-tagged span evicted despite #keep clause")

    return edited


def compact(context: str, policy: PolicySpan, rewrite) -> str:
    try:
        return apply_self_edit(context, policy, rewrite)
    except PolicyDriftError:
        # Halt compaction; recover budget elsewhere or escalate out-of-band.
        raise