# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-bounded-context-rewrite-budget-has-silently-inverted-into-a-monotonic-drift-ratchet.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-bounded-context-rewrite-budget-has-silently-inverted-into-a-monotonic-drift-ratchet.warrant.json
# Markdown SHA-256:   51d1beddb9b362e8a4e010060e93e31e86be3577f403cba959c4c67a81deccca
# Code AST SHA-256:   728056c24193995a3d699e8d4a2dc9ebfcfad2efff62658c9e0ccc5284b9a08f
# Verified Classes:   DriftRatchetError, ContextPolicy, BoundedRewriter
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field


class DriftRatchetError(RuntimeError):
    """Raised when a rewrite would silently advance the drift baseline."""


@dataclass
class ContextPolicy:
    vec: tuple[float, ...]
    edits_remaining: int
    frozen: bool = False


def _cosine_distance(a: tuple[float, ...], b: tuple[float, ...]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    if na == 0 or nb == 0:
        return 1.0
    return 1.0 - dot / (na * nb)


@dataclass
class BoundedRewriter:
    baseline: tuple[float, ...]          # immutable for the episode
    policy: ContextPolicy
    d_max: float = 0.5                   # cumulative ceiling
    eps_step: float = 0.1                # per-edit velocity bound
    _baseline_locked: bool = field(default=True)

    def _current_drift(self, candidate: tuple[float, ...]) -> float:
        return _cosine_distance(candidate, self.baseline)

    def rewrite(self, candidate: tuple[float, ...]) -> None:
        if self.policy.frozen:
            raise DriftRatchetError("policy frozen; reset required out-of-band")
        if self.policy.edits_remaining <= 0:
            raise DriftRatchetError("rewrite budget exhausted")

        cum = self._current_drift(candidate)
        step = cum - self._current_drift(self.policy.vec)

        # Structural guard: baseline must be the immutable P_0.
        if not self._baseline_locked:
            raise DriftRatchetError(
                "baseline is mutable inside write path: drift ratchet active"
            )

        if cum >= self.d_max:
            self.policy.frozen = True
            raise DriftRatchetError(
                f"cumulative drift {cum:.3f} >= D_max {self.d_max}; freezing"
            )
        if step >= self.eps_step:
            raise DriftRatchetError(
                f"per-edit step {step:.3f} >= eps_step {self.eps_step}"
            )

        # Commit only after all checks pass. Baseline is NOT touched.
        self.policy.vec = candidate
        self.policy.edits_remaining -= 1

    def monitor_flatness(self, samples: list[float], rewrites: int) -> None:
        """Alarm on flat drift under active rewriting: ratchet fingerprint."""
        if rewrites > 0 and samples and max(samples) - min(samples) < 1e-6:
            raise DriftRatchetError(
                "drift score flat under active rewrites; reference frame inverted"
            )
