# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-windows-from-silently-deleting-the-premises-of-an-in-flight-reasoning-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-windows-from-silently-deleting-the-premises-of-an-in-flight-reasoning-chain.warrant.json
# Markdown SHA-256:   bf710b16a662ac7c1ff4b43886dc32a3bc5af23e4d8918227dba93b83ab773d7
# Code AST SHA-256:   1bec7e8143da847ceaf9289fcc9c284f97a516d726babcb5f918ed2adff3a353
# Verified Classes:   PremiseDeletionError, CommitmentGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class PremiseDeletionError(RuntimeError):
    """Raised when a context rewrite would orphan or drift a live handle."""
    pass


@dataclass
class CommitmentGraph:
    # handle -> canonical binding string, maintained OUTSIDE the mutable context
    bindings: dict[str, str] = field(default_factory=dict)
    live: set[str] = field(default_factory=set)

    def commit(self, handle: str, binding: str) -> None:
        self.bindings[handle] = binding
        self.live.add(handle)

    def retire(self, handle: str) -> None:
        self.live.discard(handle)


def reference_closure_gate(
    candidate_context: str,
    graph: CommitmentGraph,
    resolve: Callable[[str, str], str | None],
) -> None:
    """
    resolve(handle, context) -> the binding the agent would dereference from
    `context`, or None if the handle is unresolvable. Must be the SAME resolver
    the downstream reasoning step uses; a different resolver voids the gate.
    """
    unresolved: list[str] = []
    drifted: list[str] = []

    for handle in graph.live:
        expected = graph.bindings[handle]
        actual = resolve(handle, candidate_context)
        if actual is None:
            unresolved.append(handle)
        elif actual.strip() != expected.strip():
            drifted.append(handle)

    if unresolved or drifted:
        raise PremiseDeletionError(
            f"rewrite inadmissible: unresolved={unresolved} drifted={drifted}; "
            f"occupancy pressure does not override reference closure"
        )


def rewrite_context(
    context: str,
    graph: CommitmentGraph,
    rewriter: Callable[[str], str],
    resolve: Callable[[str, str], str | None],
    occupancy: float,
    threshold: float = 0.70,
) -> str:
    if occupancy < threshold:
        return context  # no pressure, no rewrite, no risk

    candidate = rewriter(context)

    # Gate BEFORE commit: reject if any live handle fails closure.
    reference_closure_gate(candidate, graph, resolve)

    # Post-commit audit is redundant here because the gate is the same resolver,
    # but it is retained for the case where the rewriter mutates the graph.
    reference_closure_gate(candidate, graph, resolve)
    return candidate
