# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-a-federated-reputation-score-the-cross-organizational-prior-poisoning-boundary-in-trust-transfer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-a-federated-reputation-score-the-cross-organizational-prior-poisoning-boundary-in-trust-transfer.warrant.json
# Markdown SHA-256:   b56323c255d219641d71c36a8289dc61194f3504a251cff3755f2f04030807a1
# Code AST SHA-256:   83b816af8534f3de3c11c31ca0cc157b6d55d624089853147ab97b28a503be30
# Verified Classes:   PriorSubstitutionError, ReputationEvidence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class PriorSubstitutionError(RuntimeError):
    """Raised when a trust gate is asked to gate on a scalar reputation score
    that carries no recoverable prior or sufficient statistics."""
    pass


@dataclass(frozen=True)
class ReputationEvidence:
    evaluator_id: str
    successes: int
    trials: int
    prior_alpha: Optional[float]      # None => prior not transported
    prior_beta: Optional[float]
    action_class: str
    distilled: bool = False

    @property
    def recomputable(self) -> bool:
        return (
            not self.distilled
            and self.prior_alpha is not None
            and self.prior_beta is not None
            and self.trials >= 0
            and self.successes <= self.trials
        )


def local_posterior(ev: ReputationEvidence, alpha: float, beta: float) -> float:
    # Recompute under the RECEIVING instance's prior, ignoring the foreign prior.
    return (alpha + ev.successes) / (alpha + beta + ev.trials)


def gate_delegation(
    ev: ReputationEvidence,
    *,
    local_alpha: float,
    local_beta: float,
    tau: float,
    in_scope_action_classes: frozenset,
) -> bool:
    if ev.action_class not in in_scope_action_classes:
        # Evidence collected against out-of-scope action classes is not
        # transferable; treat peer as cold-start.
        return False
    if not ev.recomputable:
        # A scalar-only or distilled score cannot be reconciled with the
        # local prior. Refuse to gate on it; do not silently trust it.
        raise PriorSubstitutionError(
            f"evaluator {ev.evaluator_id} supplied non-recomputable evidence "
            f"(distilled={ev.distilled}, prior_present="
            f"{ev.prior_alpha is not None}); cannot gate delegation"
        )
    score = local_posterior(ev, local_alpha, local_beta)
    return score >= tau


def admit_or_escalate(ev: ReputationEvidence, **kwargs) -> bool:
    try:
        return gate_delegation(ev, **kwargs)
    except PriorSubstitutionError:
        # Escalate to auditor quorum / human; never fall through to admit.
        raise
