# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-agent-card-whose-capability-fingerprint-is-reproducible-but-whose-manifest-attestation-chain-diverges-at-a-tran.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-agent-card-whose-capability-fingerprint-is-reproducible-but-whose-manifest-attestation-chain-diverges-at-a-tran.warrant.json
# Markdown SHA-256:   cfcca0d7dd7e1a37748ea9d44dae63e0057d2ae942a2b49e9556555f9ef65327
# Code AST SHA-256:   21018c967fa4dab5d78413ac6ac4224b47be0b30f0ecd99aa0295dacd6caa59e
# Verified Classes:   AttestationChainDivergence, Hop, AgentCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AttestationChainDivergence(RuntimeError):
    """Raised when a signed agent-card's attestation chain is not byte-continuous
    or its origin signer cannot be verified against the pinned origin set."""
    pass


@dataclass
class Hop:
    signer: str
    signed_bytes: bytes          # the exact bytes this hop's signature covers
    signature_valid: bool        # result of verifying sig over signed_bytes


@dataclass
class AgentCard:
    manifest: bytes
    claimed_fingerprint: str     # fp as carried inside the ORIGIN signed payload
    envelope: list[Hop]          # ordered origin -> ... -> terminal


def fingerprint(manifest: bytes) -> str:
    return hashlib.sha256(manifest).hexdigest()


def admit_card(card: AgentCard, pinned_origins: set[str]) -> None:
    if not card.envelope:
        raise AttestationChainDivergence("empty attestation envelope")

    origin = card.envelope[0]

    # 1. Origin signer must be pinned and its signature valid.
    if origin.signer not in pinned_origins:
        raise AttestationChainDivergence(
            f"origin signer {origin.signer!r} not in pinned origin set"
        )
    if not origin.signature_valid:
        raise AttestationChainDivergence("origin signature invalid")

    # 2. Byte-continuity across every adjacent hop.
    for inner, outer in zip(card.envelope, card.envelope[1:]):
        if inner.signed_bytes != outer.signed_bytes:
            raise AttestationChainDivergence(
                f"byte divergence between {inner.signer!r} and {outer.signer!r}: "
                "manifest was transformed mid-chain"
            )
        if not outer.signature_valid:
            raise AttestationChainDivergence(
                f"signature invalid at hop {outer.signer!r}"
            )

    # 3. Fingerprint must match the ORIGIN-claimed value, not a recomputed one.
    recomputed = fingerprint(card.manifest)
    if recomputed != card.claimed_fingerprint:
        raise AttestationChainDivergence(
            f"fingerprint mismatch: recomputed {recomputed} != "
            f"origin-claimed {card.claimed_fingerprint}"
        )

    # 4. Terminal hop must cover the same bytes the origin signed.
    if card.envelope[-1].signed_bytes != card.manifest:
        raise AttestationChainDivergence(
            "terminal signature does not cover the received manifest bytes"
        )
