# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-referential-context-eviction-when-its-own-policy-rewrite-logic-is-itself-evictable.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-referential-context-eviction-when-its-own-policy-rewrite-logic-is-itself-evictable.warrant.json
# Markdown SHA-256:   6b4335d320952144fbb6b60df616463980e5dae2879a75ed3dda707219797b14
# Code AST SHA-256:   a9fb66a6cc21e4d395287589d9c4508508cb26bcd662e6578fc51ee311380c7a
# Verified Classes:   PolicyEvictionError, SelfRewriteGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class PolicyEvictionError(RuntimeError):
    """Raised when a working-set rewrite would alter or remove the policy block."""
    pass


class SelfRewriteGuard:
    def __init__(self, policy_block: dict, policy_digest: str):
        # policy_digest is held OUTSIDE the rewritable working set (supervisor frame).
        self.policy_block = policy_block
        self.policy_digest = policy_digest
        self.data_budget = 0  # policy bytes are excluded from pressure accounting

    @staticmethod
    def _digest(block: dict) -> str:
        canonical = json.dumps(block, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    def commit_rewrite(self, new_working_set: dict, targets_policy: bool) -> dict:
        if targets_policy:
            # Any rewrite that touches the policy block must preserve its digest exactly.
            candidate_policy = new_working_set.get("__policy__")
            if candidate_policy is None:
                raise PolicyEvictionError(
                    "rewrite dropped the policy block; controller would be evicted"
                )
            if self._digest(candidate_policy) != self.policy_digest:
                raise PolicyEvictionError(
                    "policy digest drift detected; route through out-of-band policy update, "
                    "not the working-set compressor"
                )
        # Data-only rewrites proceed; policy bytes are not charged against data_budget.
        return new_working_set

    def check_pressure(self, working_set: dict, high_water: int) -> None:
        data_bytes = sum(
            len(json.dumps(v)) for k, v in working_set.items() if k != "__policy__"
        )
        if data_bytes > high_water:
            # Pressure is real, but the policy block is not a legal compression target.
            raise PolicyEvictionError(
                f"data pressure {data_bytes} exceeds high-water {high_water}; "
                "policy block excluded from reclaimable set"
            )
