# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-freeze-its-self-rewritten-system-prompt-to-prevent-policy-oscillation-lockup.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-freeze-its-self-rewritten-system-prompt-to-prevent-policy-oscillation-lockup.warrant.json
# Markdown SHA-256:   8430ab306670524e7ff94d20b72d6460a43d4e19c83159ba9cb7b34387afef6f
# Code AST SHA-256:   6a6e2900f1ce935205e2cc2ab666858bba63f70d278a7282f49e16d353f90e84
# Verified Classes:   PolicyOscillationError, SelfEditingPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PolicyOscillationError(RuntimeError):
    """Raised when a self-rewritten policy fails the freeze invariant."""
    pass


@dataclass
class SelfEditingPolicy:
    current: str
    history: list = field(default_factory=list)          # committed policy hashes
    non_dominance_streak: int = 0
    max_prompt_tokens: int = 8192
    context_window: int = 32768
    saturation_frac: float = 0.35
    max_streak: int = 3

    def _hash(self, text: str) -> str:
        return hashlib.sha256(text.encode()).hexdigest()[:16]

    def propose(self, candidate: str, probe_score: float, incumbent_score: float,
                self_score: float, incumbent_self_score: float,
                candidate_tokens: int) -> str:
        # Guard 1: period-2 oscillation (candidate matches policy from two rewrites ago)
        if len(self.history) >= 2 and self._hash(candidate) == self.history[-2]:
            raise PolicyOscillationError(
                f"period-2 oscillation: candidate {self._hash(candidate)} "
                f"repeats history[-2]; freezing at incumbent"
            )

        # Guard 2: evaluator divergence (self-score up, probe-score down)
        probe_delta = probe_score - incumbent_score
        self_delta = self_score - incumbent_self_score
        if probe_delta < 0 and self_delta > 0:
            raise PolicyOscillationError(
                "evaluator divergence: self-assessment rose while exogenous "
                "probe fell; rewrite is circularly graded"
            )

        # Guard 3: budget saturation
        if candidate_tokens > self.context_window * self.saturation_frac:
            raise PolicyOscillationError(
                f"prompt saturation: {candidate_tokens} tokens exceeds "
                f"{self.saturation_frac:.0%} of context window"
            )

        # Guard 4: non-dominance streak
        if probe_delta <= 0:
            self.non_dominance_streak += 1
            if self.non_dominance_streak >= self.max_streak:
                raise PolicyOscillationError(
                    f"non-dominance streak={self.non_dominance_streak}; "
                    "rewrite search has stalled, freeze policy"
                )
            return self.current  # reject, keep incumbent

        # Commit: strict domination on exogenous probe
        self.non_dominance_streak = 0
        self.history.append(self._hash(self.current))
        self.current = candidate
        return self.current
