# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-forgery-from-surviving-a-trust-score-recompute-in-aaif-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-forgery-from-surviving-a-trust-score-recompute-in-aaif-agent-handoffs.warrant.json
# Markdown SHA-256:   d08b18d572273e99bb9bcbc4f68f5e5cb0e59a370d1ad0f006cce6b8c266ac0b
# Code AST SHA-256:   c13f85352a0d93188433621cd3e2f18efd616a56397c30aadee2348f727ec812
# Verified Classes:   StaleAttestationError, WarrantBundle, TrustRecomputeGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a forwarded AAIF bundle's epoch is below the receiver's
    per-peer high-water mark, or when a recompute would exceed the last
    issuer-signed trust score without proof of claim-set currency."""


@dataclass(frozen=True)
class WarrantBundle:
    peer_id: str
    epoch: int
    claims: frozenset
    claims_digest: str          # proves non-tampering, NOT currency
    issuer_signed_score: float  # last score the issuer itself signed
    recomputed_score: float     # receiver's local derivation from `claims`


class TrustRecomputeGate:
    def __init__(self) -> None:
        self._high_water: dict[str, int] = {}

    def admit(self, bundle: WarrantBundle, issuer_current_epoch: int | None) -> float:
        prior = self._high_water.get(bundle.peer_id, -1)

        # Invariant 1: epoch monotonicity enforced at the receiver.
        if bundle.epoch < prior:
            raise StaleAttestationError(
                f"peer {bundle.peer_id}: bundle epoch {bundle.epoch} "
                f"below high-water mark {prior}; stale warrant replay"
            )

        # Invariant 2: recompute is authoritative only if claim-set currency
        # is independently established (issuer epoch known and matched).
        currency_proven = (
            issuer_current_epoch is not None
            and bundle.epoch >= issuer_current_epoch
        )

        if not currency_proven:
            # Advisory only: clamp to the issuer-signed score so a stale
            # bundle cannot launder a demotion into a higher trust value.
            if bundle.recomputed_score > bundle.issuer_signed_score:
                self._high_water[bundle.peer_id] = max(prior, bundle.epoch)
                return bundle.issuer_signed_score
            self._high_water[bundle.peer_id] = max(prior, bundle.epoch)
            return bundle.recomputed_score

        # Invariant 3: score is a function of (claims, epoch); a fresh,
        # currency-proven recompute may exceed the prior signed score.
        self._high_water[bundle.peer_id] = max(prior, bundle.epoch)
        return bundle.recomputed_score


def grant_subwarrant(gate: TrustRecomputeGate, bundle: WarrantBundle,
                     issuer_current_epoch: int | None, required_trust: float) -> float:
    score = gate.admit(bundle, issuer_current_epoch)
    if score < required_trust:
        raise StaleAttestationError(
            f"peer {bundle.peer_id}: effective trust {score:.2f} < required "
            f"{required_trust:.2f} after epoch/currency gate"
        )
    return score
