# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-tool-manifest-whose-semantic-diff-is-empty-but-whose-runtime-behavior-baseline-has-silently-shifted.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-tool-manifest-whose-semantic-diff-is-empty-but-whose-runtime-behavior-baseline-has-silently-shifted.warrant.json
# Markdown SHA-256:   a65cbc05838ad98f25d0847c31db057a4db792d3d20fd4f503cf8206f6235a57
# Code AST SHA-256:   d8240a3912786b9d347cbd8c939cb6042f96a8c371e6572421c2e204582beb5f
# Verified Classes:   BaselineRatchetError, FrozenReferenceBaseline
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class BaselineRatchetError(RuntimeError):
    """Raised when a tool's behavior is accepted against an online-learned
    baseline that has been contaminated by the tool's own outputs."""
    pass


class FrozenReferenceBaseline:
    """Immutable baseline pinned at manifest-signing time. Never updated
    from production observations. This is the only baseline that may
    authorize an accept decision."""

    def __init__(self, reference_distribution, threshold):
        self._ref = dict(reference_distribution)
        self._tau = threshold
        self._sealed = True

    def deviation(self, observation):
        # Returns normalized distance from the frozen reference.
        return sum(
            abs(observation.get(k, 0.0) - v) for k, v in self._ref.items()
        ) / max(len(self._ref), 1)

    def is_nominal(self, observation):
        return self.deviation(observation) <= self._tau

    def update(self, observation):
        if self._sealed:
            raise BaselineRatchetError(
                "Frozen reference baseline is write-once; "
                "refusing to fold tool-originated observation into trust anchor."
            )


def gate_skill_injection(signature_valid, semantic_diff, observation, frozen_ref):
    """Three-signal conjunction with the baseline pinned to the frozen reference.

    Accept requires: valid signature AND reviewed diff AND nominal against B*.
    An empty diff with a B* deviation is escalated, not accepted.
    """
    if not signature_valid:
        return "REJECT_SIGNATURE"

    diff_empty = semantic_diff.get("changes", []) == []

    if not frozen_ref.is_nominal(observation):
        if diff_empty:
            raise BaselineRatchetError(
                "Empty semantic diff but frozen-reference deviation exceeds tau: "
                "behavior changed without manifest change. Escalate to REJECT_QUARANTINE."
            )
        return "REJECT_QUARANTINE"

    if diff_empty:
        return "ACCEPT_NOOP"
    return "ACCEPT_REVIEWED_DIFF"
