# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-anchor-substitution-from-silently-re-rooting-a-federated-agent-mesh.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-anchor-substitution-from-silently-re-rooting-a-federated-agent-mesh.warrant.json
# Markdown SHA-256:   57b99cc3ab7bb7f04f27c9486b6af184725b632b6a7e340ffb1d286a701cba8b
# Code AST SHA-256:   8a637994f10f82ab463f0a1c62b670379416ab021c881aeb0aa928868a81b172
# Verified Classes:   TrustAnchorEpochError, AnchorSet
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class TrustAnchorEpochError(RuntimeError):
    """Raised when an attestation or reputation claim references a closed or unknown anchor epoch."""
    pass


class AnchorSet:
    def __init__(self, epoch: int, anchors: dict[str, str]):
        # anchors maps anchor_id -> key_thumbprint
        self.epoch = epoch
        self.anchors = dict(anchors)
        self.closed_epochs: set[int] = set()

    def close_epoch(self, epoch: int) -> None:
        if epoch >= self.epoch:
            raise TrustAnchorEpochError(
                f"cannot close live or future epoch {epoch}; current is {self.epoch}"
            )
        self.closed_epochs.add(epoch)

    def verify_attestation(self, attestation: dict) -> None:
        epoch = attestation["anchor_epoch"]
        anchor_id = attestation["anchor_id"]
        thumbprint = attestation["anchor_thumbprint"]

        if epoch in self.closed_epochs:
            raise TrustAnchorEpochError(
                f"attestation references closed anchor epoch {epoch}"
            )
        if epoch != self.epoch:
            raise TrustAnchorEpochError(
                f"attestation epoch {epoch} does not match live epoch {self.epoch}"
            )
        expected = self.anchors.get(anchor_id)
        if expected is None:
            raise TrustAnchorEpochError(
                f"anchor {anchor_id} not a member of epoch {epoch}"
            )
        if expected != thumbprint:
            raise TrustAnchorEpochError(
                f"anchor {anchor_id} thumbprint mismatch in epoch {epoch}"
            )

    def verify_reputation_claim(self, claim: dict, attestation: dict) -> None:
        # Provenance invariant: reputation must be signed under the same anchor epoch as the attestation.
        if claim["signer_anchor_epoch"] != attestation["anchor_epoch"]:
            raise TrustAnchorEpochError(
                "reputation claim signer epoch "
                f"{claim['signer_anchor_epoch']} differs from attestation epoch "
                f"{attestation['anchor_epoch']}"
            )
        if claim["signer_anchor_id"] != attestation["anchor_id"]:
            raise TrustAnchorEpochError(
                "reputation claim signed by anchor "
                f"{claim['signer_anchor_id']} but attestation anchored at "
                f"{attestation['anchor_id']}"
            )
        self.verify_attestation(
            {
                "anchor_epoch": claim["signer_anchor_epoch"],
                "anchor_id": claim["signer_anchor_id"],
                "anchor_thumbprint": claim["signer_anchor_thumbprint"],
            }
        )


def grant_capability(anchor_set: AnchorSet, attestation: dict, claims: list[dict]) -> bool:
    anchor_set.verify_attestation(attestation)
    for claim in claims:
        anchor_set.verify_reputation_claim(claim, attestation)
    return True
