# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-recursively-summarizes-its-own-salience-policy-identity-drift-in-the-governor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-recursively-summarizes-its-own-salience-policy-identity-drift-in-the-governor.warrant.json
# Markdown SHA-256:   61c593ca1502443b41eed467412dc20ffbd373f61b935f10b53092a4f23eff72
# Code AST SHA-256:   65bb096161139e51b6edf03323eefe492ce020ea8ce51c94206669400a2f3c53
# Verified Classes:   PolicyDriftError, MissingPolicyKeyError, Governor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class PolicyDriftError(RuntimeError):
    """Raised when a context governor's policy changes without an explicit, justified edit."""
    pass


class MissingPolicyKeyError(PolicyDriftError):
    """Raised when a required policy key is absent after compaction (never silently default it)."""
    pass


REQUIRED_KEYS = ("constraint_weight", "eviction_threshold", "summarize_instruction")


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


@dataclass
class Governor:
    policy: dict
    pinned: bool = True
    _baseline: str = field(init=False)

    def __post_init__(self) -> None:
        self._baseline = _digest(self.policy)

    def compact(self, context: list[str], summarizer) -> list[str]:
        # Control plane is excluded from the governed region.
        governed = [c for c in context if not c.startswith("POLICY:")]
        compacted = summarizer(governed)
        return [f"POLICY:{json.dumps(self.policy, sort_keys=True)}"] + compacted

    def verify(self) -> None:
        for key in REQUIRED_KEYS:
            if key not in self.policy:
                raise MissingPolicyKeyError(
                    f"policy key '{key}' lost during compaction; refusing to default"
                )
        if _digest(self.policy) != self._baseline:
            raise PolicyDriftError(
                "policy mutated without a logged edit; halt and re-inject canonical policy"
            )

    def edit_policy(self, key: str, value, justification: str) -> None:
        if not justification.strip():
            raise PolicyDriftError(f"edit to '{key}' rejected: no justification recorded")
        self.policy[key] = value
        self._baseline = _digest(self.policy)  # explicit edit re-baselines


def run_cycle(governor: Governor, context: list[str], summarizer) -> list[str]:
    new_context = governor.compact(context, summarizer)
    governor.verify()  # fails loud on drift or missing keys
    return new_context


if __name__ == "__main__":
    gov = Governor(policy={
        "constraint_weight": 0.8,
        "eviction_threshold": 0.3,
        "summarize_instruction": "never drop safety or budget constraints",
    })
    # A summarizer that (incorrectly) rewrites the policy as ordinary data:
    bad_summarizer = lambda ctx: ["compressed: " + " ".join(ctx)[:40]]
    gov.policy.pop("constraint_weight")  # simulate cycle-2 eviction
    run_cycle(gov, ["POLICY:...", "tool output"], bad_summarizer)  # raises MissingPolicyKeyError
