# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-trust-attenuation-at-the-federation-boundary-when-a-delegated-warrant-crosses-two-policy-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-trust-attenuation-at-the-federation-boundary-when-a-delegated-warrant-crosses-two-policy-domains.warrant.json
# Markdown SHA-256:   00c9d80a2b683efad9850c78149002a867aaedf1161b022762f1f4d056b1c2bc
# Code AST SHA-256:   f9524bc44cf2f63f9bb5ffd4d92ec7fb6937a6777b0b8815fade4f8fe08db771
# Verified Classes:   TrustAttenuationViolation, ProvenanceHop, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TrustAttenuationViolation(RuntimeError):
    """Raised when a warrant's effective trust exceeds its provenance-chain minimum."""
    pass


@dataclass(frozen=True)
class ProvenanceHop:
    issuer: str
    trust_at_delegation: float
    link_hash: str  # hash(prev_link_hash || issuer || trust_at_delegation)


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: frozenset[str]
    effective_trust: float
    provenance: tuple[ProvenanceHop, ...]
    signature: str


def _verify_chain_links(provenance: tuple[ProvenanceHop, ...]) -> None:
    prev = b""
    for hop in provenance:
        expected = hashlib.sha256(
            prev + hop.issuer.encode() + repr(hop.trust_at_delegation).encode()
        ).hexdigest()
        if hop.link_hash != expected:
            raise TrustAttenuationViolation(
                f"provenance chain broken at issuer={hop.issuer!r}"
            )
        prev = hop.link_hash.encode()


def admit(warrant: Warrant, gate_threshold: float, parent_scope: frozenset[str]) -> bool:
    _verify_chain_links(warrant.provenance)

    if not warrant.scope <= parent_scope:
        raise TrustAttenuationViolation(
            f"scope escalation: {warrant.scope - parent_scope} not granted by parent"
        )

    chain_min = min(h.trust_at_delegation for h in warrant.provenance)
    # Equality, not <=: both over- and under-attenuation are non-conformant.
    if abs(warrant.effective_trust - chain_min) > 1e-9:
        raise TrustAttenuationViolation(
            f"effective_trust={warrant.effective_trust:.4f} != chain_min={chain_min:.4f} "
            f"for subject={warrant.subject!r}; re-inflation or under-attenuation at "
            f"issuer={warrant.issuer!r}"
        )

    if warrant.effective_trust < gate_threshold:
        return False
    return True
