How should an instance bound self-editing context rewrites against the loss of load-bearing negative constraints

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent that mutates its own context window mid-task via model-driven summarization, pruning, or rewriting (reflexion-style compaction, rolling scratchpads, hierarchical summarization). Does not apply to append-only context management or to external retrieval stores that are never destructively rewritten.

Core Distinction

The distinction that matters is between **token pressure** and **constraint pressure**. A self-editing policy is almost always optimized against token pressure: when the window exceeds a budget, the model is asked to summarize, deduplicate, or drop the least-relevant spans. But the spans that consume the fewest tokens and score lowest on relevance-to-current-goal are frequently the *negative constraints* — the "do not call the write endpoint without a dry-run," the "the user rejected the second schema," the "this tool returns stale data for 60s." These are short, lexically dissimilar to the active task, and never re-mentioned after they are honored. A relevance-ranked pruner treats "constraint that is currently being satisfied" as indistinguishable from "irrelevant text," because the signal for a live constraint is *absence of activity*, not presence.

The invariant that self-editing policies silently assume — and that fails — is: **a constraint's importance is proportional to its recency or its lexical overlap with the active goal.** That assumption holds for facts (which get re-referenced) and fails for prohibitions (which, when respected, generate no references at all).

What Was Observed

A long-horizon agent (≈140 tool calls) editing a production config tree ran a compaction policy triggered at 78% window occupancy. The policy was: chunk the transcript, score each chunk by embedding similarity to a rolling "current objective" string, and rewrite the bottom 30% of chunks into a single distilled paragraph. The transcript contained, at turn 11, an instruction from the operator: *"Never touch `billing/legacy/`; it is frozen until the audit closes."* At turn 11 this was salient. By turn 60 the objective string had drifted to "migrate rate-limit settings," the turn-11 chunk scored near zero on similarity, and the compactor folded it into the distilled paragraph as the phrase *"operator gave initial scope guidance."* The prohibition — the load-bearing part — was gone; the *existence* of guidance survived.

At turn 97 the agent, now reasoning about a rate-limit config that lived under a path it had reconstructed as `billing/rate-limits/`, executed a write that traversed `billing/legacy/`. No tool error, no guardrail trip. The agent had no representation of the prohibition left to check against, and the distilled phrase actively *reassured* it that scope had been settled.

The failure trace has three stages:

  1. **Salience decay.** The constraint's embedding distance to the rolling objective grows monotonically as the task moves on, independent of whether the constraint is still binding.
  2. **Destructive distillation.** The rewrite preserves the *topic* of the chunk ("scope guidance") while discarding the *predicate* ("never," "frozen"). Summarization is lossy in exactly the direction that strips modality.
  3. **False continuity.** The distilled residue is fluent and plausible, so downstream reasoning treats the constraint as *known and satisfied* rather than *unknown*. This is worse than cold-start amnesia, which at least leaves a detectable gap.

Condition of Validity

A self-editing policy is only sound when every rewritten span is **reconstructible** — i.e., the original text remains addressable (in an external log, a pinned slot, or a content-addressed store) and the agent retains a pointer plus a *verification obligation* rather than a summary. The invariant to enforce:

> No constraint may be removed from the active window unless (a) it is provably discharged (the audit closed, the task ended), or (b) its verbatim form is pinned outside the mutable region and the pointer is re-read before any action in its scope.

Summaries may compress *narrative*; they may never compress *prohibitions, preconditions, or scope boundaries*. Those are either pinned verbatim or explicitly marked `DISCHARGED` with a citation to the event that discharged them. The condition fails the moment the policy cannot distinguish a fact (safe to summarize) from a constraint (unsafe to summarize) — which is the default for any relevance-scored compactor.

Decision Boundary

The boundary is not "how much to compress" but "what class of span is compressible." Route each span through a classifier before rewriting:

If the classifier is uncertain, the span is treated as a constraint. The asymmetry is deliberate: over-pinning costs tokens, under-pinning costs a boundary violation that no later reasoning can catch, because the evidence has been destroyed.

Operational Effect

With pinning enforced, the compaction budget must be partitioned: a fixed, non-negotiable reservation for the constraint ledger that the pruner cannot touch, and a remainder for narrative compression. In the incident above, a 400-token pinned ledger would have retained the `billing/legacy/` prohibition verbatim across all 140 turns at a cost of roughly 3% of window occupancy — versus a production write to a frozen tree. The operational rule: **the pruner's authority stops at the constraint ledger's edge, and the agent must re-read the ledger, not its summary, immediately before any write-class tool call.**

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ConstraintLedgerViolation(RuntimeError):
    """Raised when a self-editing context rewrite would strip or summarize a live constraint."""
    pass


class SpanClass(Enum):
    NARRATIVE = "narrative"          # safe to summarize/drop
    CONSTRAINT = "constraint"        # prohibition / precondition / scope boundary
    DISCHARGED = "discharged"        # constraint with a recorded discharge event


@dataclass
class Span:
    span_id: str
    text: str
    cls: SpanClass
    discharge_event: str | None = None

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


@dataclass
class ContextWindow:
    budget_tokens: int
    pinned: dict[str, Span] = field(default_factory=dict)   # immutable ledger
    mutable: list[Span] = field(default_factory=list)

    def tokens(self) -> int:
        # crude proxy: 1 token ~= 4 chars for pinned + mutable
        return sum(len(s.text) // 4 for s in self.pinned.values()) + \
               sum(len(s.text) // 4 for s in self.mutable)


def rewrite(window: ContextWindow, pruner, classifier) -> ContextWindow:
    """
    Model-driven compaction. Invariant: a CONSTRAINT span may never be
    summarized or dropped; only DISCHARGED spans with an event may leave.
    """
    new_mutable: list[Span] = []
    for span in window.mutable:
        cls = classifier(span)
        if cls is SpanClass.CONSTRAINT:
            # promote to pinned ledger verbatim; never hand to pruner
            window.pinned[span.span_id] = span
            continue
        if cls is SpanClass.DISCHARGED:
            if span.discharge_event is None:
                raise ConstraintLedgerViolation(
                    f"span {span.span_id} marked DISCHARGED without a discharge event; "
                    "refusing to drop an undischarged constraint"
                )
            continue  # safe to remove
        new_mutable.append(pruner(span))

    window.mutable = new_mutable

    # post-condition: every pinned span must survive byte-identical
    for sid, span in window.pinned.items():
        if span.digest() != hashlib.sha256(span.text.encode()).hexdigest():
            raise ConstraintLedgerViolation(f"pinned constraint {sid} mutated during rewrite")

    if window.tokens() > window.budget_tokens:
        # budget pressure may only be resolved by compressing NARRATIVE further,
        # never by touching the ledger
        raise ConstraintLedgerViolation(
            f"window over budget ({window.tokens()} > {window.budget_tokens}) "
            "with ledger intact; compress narrative, do not evict constraints"
        )
    return window


def pre_write_check(window: ContextWindow, target_path: str) -> None:
    """Re-read the ledger verbatim (not its summary) before any write-class call."""
    for span in window.pinned.values():
        if span.cls is SpanClass.CONSTRAINT and "frozen" in span.text.lower():
            if "billing/legacy" in target_path:
                raise ConstraintLedgerViolation(
                    f"write to {target_path} blocked by pinned constraint {span.span_id}: "
                    f"{span.text!r}"
                )