# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-lease-divergence-when-a-brokered-capability-attestation-is-re-signed-across-federated-agent-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-lease-divergence-when-a-brokered-capability-attestation-is-re-signed-across-federated-agent-domains.warrant.json
# Markdown SHA-256:   90f8f3226302c7dcc44ab177b8194407b04710ed8eb45d91567380ae2536696d
# Code AST SHA-256:   637b30163cc94ca5a827da719b73d4e01fc35ae9accf011ca08f02aebdaaa052
# Verified Classes:   TrustLeaseDivergence, Epoch, Hop, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class TrustLeaseDivergence(RuntimeError):
    """Raised when a re-signed warrant's effective constraints diverge from
    the intersection of the policy epochs traversed at signing time."""


@dataclass
class Epoch:
    domain: str
    version: int
    constraints: frozenset
    max_lease_s: int


@dataclass
class Hop:
    domain: str
    epoch_version: int
    signed_at: float


@dataclass
class Warrant:
    hops: List[Hop]
    leaf_constraints: frozenset
    not_after: float
    signature_valid: bool = True


def re_evaluate_at_consumer(
    warrant: Warrant,
    current_epochs: Dict[str, Epoch],
    now: float,
    previous_leaf: frozenset,
) -> frozenset:
    if not warrant.signature_valid:
        raise TrustLeaseDivergence("signature invalid; cannot re-evaluate")

    # Resolve every hop against the *historical* epoch it was signed under,
    # then intersect. A missing epoch is a divergence, not a default.
    effective = None
    for hop in warrant.hops:
        epoch = current_epochs.get(f"{hop.domain}@{hop.epoch_version}")
        if epoch is None:
            raise TrustLeaseDivergence(
                f"epoch {hop.domain}@{hop.epoch_version} unresolvable; "
                "constraint set cannot be historically re-evaluated"
            )
        effective = epoch.constraints if effective is None else (effective & epoch.constraints)

    # Monotone intersection: privilege must not grow across re-evaluation.
    if not effective.issubset(previous_leaf):
        raise TrustLeaseDivergence(
            f"non-monotone intersection: {effective - previous_leaf} "
            "gained privilege across epoch re-evaluation"
        )

    # Bounded lease: effective expiry is min across chain, recomputed now.
    min_lease = min(
        current_epochs[f"{h.domain}@{h.epoch_version}"].max_lease_s
        for h in warrant.hops
    )
    if now > warrant.not_after or (warrant.not_after - warrant.hops[0].signed_at) > min_lease:
        raise TrustLeaseDivergence(
            f"lease bound exceeded: ttl={warrant.not_after - warrant.hops[0].signed_at}s "
            f"> min_chain_lease={min_lease}s"
        )

    return effective
