# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-verifiable-credential-trust-federation-handshakes-from-silently-degrading-to-unauthenticated-peers-when-an-agent-s-credential.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-verifiable-credential-trust-federation-handshakes-from-silently-degrading-to-unauthenticated-peers-when-an-agent-s-credential.warrant.json
# Markdown SHA-256:   53c91e6d455deaec8d3ef17392f051d781fbc2c3fc47e524c955f7d977b5bdfd
# Code AST SHA-256:   28fbeee0c87fd503abc01a8349970af914afa04a4afa0d7a4bf27c6322da7794
# Verified Classes:   AnchorDivergenceError, AnchorSet, HandshakeState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AnchorDivergenceError(RuntimeError):
    """Raised when the two halves of a mutual attestation handshake were
    evaluated under different trust-anchor sets and the divergence is not a
    clean ancestor relationship (i.e., not a recoverable staleness case)."""


@dataclass(frozen=True)
class AnchorSet:
    roots: frozenset[str]
    generation: int

    def digest(self) -> str:
        payload = "|".join(sorted(self.roots)) + f"#g{self.generation}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class HandshakeState:
    nonce: str
    pinned_anchors: AnchorSet


def validate_response(
    state: HandshakeState,
    prover_anchors: AnchorSet,
    current_verifier_anchors: AnchorSet,
    response_signature_valid: bool,
) -> str:
    if not response_signature_valid:
        raise AnchorDivergenceError("response signature invalid; cannot attest")

    # The prover must have validated against the anchor set we pinned, OR a
    # strictly older generation of it (recoverable staleness). Anything else
    # is a divergence and must hard-fail -- never fall back to permissive.
    if prover_anchors == state.pinned_anchors:
        return "attested"

    same_roots = prover_anchors.roots == state.pinned_anchors.roots
    is_ancestor = (
        same_roots
        and prover_anchors.generation < state.pinned_anchors.generation
    )
    if is_ancestor:
        return "rechallenge_stale"

    # Divergent roots, forked generation, or prover anchored to a set we never
    # pinned: the two halves of the handshake are not mutually attestable.
    raise AnchorDivergenceError(
        "anchor-set divergence across handshake halves: "
        f"pinned={state.pinned_anchors.digest()} "
        f"prover={prover_anchors.digest()} "
        f"verifier_now={current_verifier_anchors.digest()}"
    )
