# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-context-rewrite-budget-has-silently-converted-into-a-self-referential-amnesia-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-context-rewrite-budget-has-silently-converted-into-a-self-referential-amnesia-loop.warrant.json
# Markdown SHA-256:   24fbf5f11c6e2857ca74781f12af51dc7fc3d8cf1d9dc19d014fb234ec22ead2
# Code AST SHA-256:   ce385e5f55a9bc601098b08a265d728651c7c5aed3d25e7913f01bcaf4b9f545
# Verified Classes:   AnchorDriftError, GateAmbiguityError, Region, RewriteEpoch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AnchorDriftError(RuntimeError):
    """Raised when a rollback target diverges from the immutable epoch anchor."""
    pass


class GateAmbiguityError(RuntimeError):
    """Raised when the integrity gate cannot classify a rewrite as boundary-shift vs content-divergence."""
    pass


@dataclass
class Region:
    region_id: str
    content: bytes

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


@dataclass
class RewriteEpoch:
    anchor: dict[str, Region]           # immutable snapshot, keyed by region_id
    budget: int
    spent: int = 0
    _anchor_fingerprint: str = field(default="", init=False)

    def __post_init__(self):
        self._anchor_fingerprint = self._fingerprint(self.anchor)

    @staticmethod
    def _fingerprint(regions: dict[str, Region]) -> str:
        h = hashlib.sha256()
        for rid in sorted(regions):
            h.update(rid.encode())
            h.update(regions[rid].digest().encode())
        return h.hexdigest()

    def classify(self, candidate: dict[str, Region], authorized: set[str]) -> str:
        """Return 'pass', 'boundary_shift', or 'content_divergence'."""
        if set(candidate) != set(self.anchor):
            return "content_divergence"
        diverged = [
            rid for rid in self.anchor
            if candidate[rid].digest() != self.anchor[rid].digest()
        ]
        if not diverged:
            return "pass"
        if set(diverged).issubset(authorized):
            # region content changed only where rewrite was authorized -> boundary shift
            return "boundary_shift"
        return "content_divergence"

    def attempt(self, candidate: dict[str, Region], authorized: set[str]) -> dict[str, Region]:
        verdict = self.classify(candidate, authorized)
        if verdict == "pass":
            return candidate
        if verdict == "boundary_shift":
            # legitimate compaction: commit, no budget spend
            return candidate
        # content divergence: must roll back to the IMMUTABLE anchor, not last attempt
        if self.spent >= self.budget:
            # budget exhausted: restore anchor, never commit the drifted rollback
            self._assert_anchor_intact()
            raise AnchorDriftError(
                f"rewrite budget exhausted at spent={self.spent}; "
                f"restoring immutable anchor {self._anchor_fingerprint[:12]}"
            )
        self.spent += 1
        self._assert_anchor_intact()
        return self.anchor  # fixed anchor, not prior candidate

    def _assert_anchor_intact(self) -> None:
        if self._fingerprint(self.anchor) != self._anchor_fingerprint:
            raise AnchorDriftError("epoch anchor mutated; rollback target is no longer the original")


def run_epoch(epoch: RewriteEpoch, candidates: list[tuple[dict[str, Region], set[str]]]) -> dict[str, Region]:
    state = epoch.anchor
    for candidate, authorized in candidates:
        try:
            state = epoch.attempt(candidate, authorized)
        except AnchorDriftError:
            raise
        except Exception as exc:
            raise GateAmbiguityError(f"gate could not classify rewrite: {exc}") from exc
    return state
