# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-cross-org-agent-s-hardware-bound-credential-when-the-attested-key-handle-is-valid-but-the-runtime-that-holds-it-has-be.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-cross-org-agent-s-hardware-bound-credential-when-the-attested-key-handle-is-valid-but-the-runtime-that-holds-it-has-be.warrant.json
# Markdown SHA-256:   af8db027afda1d9a471c627e0085bbe7e62c75fb4c1433e2907f16088197b8ea
# Code AST SHA-256:   99db8554cf4e817715e21720e3c8ab157feb808ca46b0c098e18dd1a744ff008
# Verified Classes:   AttestationReplayError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttestationReplayError(RuntimeError):
    """Raised when a hardware-bound credential is presented by a runtime
    whose epoch does not strictly advance the verifier's registry."""


def verify_cross_org_handshake(
    vc: dict,
    challenge_nonce: bytes,
    registry: dict,  # cnf_thumbprint -> {"epoch": int, "last_seen": float}
    now: float,
) -> str:
    cnf = vc["cnf"]["jwk_thumbprint"]
    quote = vc["evidence"]["tpm_quote"]
    epoch = vc["evidence"]["runtime_epoch"]

    if quote["nonce"] != challenge_nonce:
        raise AttestationReplayError(
            f"nonce mismatch for {cnf}: quote nonce does not match challenge"
        )
    if quote["pcr_digest"] not in vc["issuer_policy"]["allowed_pcr_digests"]:
        raise AttestationReplayError(
            f"PCR digest outside reference policy for {cnf}"
        )

    prior = registry.get(cnf)
    if prior is None:
        registry[cnf] = {"epoch": epoch, "last_seen": now}
        return "accepted:first_binding"

    if epoch <= prior["epoch"]:
        raise AttestationReplayError(
            f"stale runtime_epoch for {cnf}: presented {epoch}, "
            f"registry holds {prior['epoch']} — likely snapshot-restored clone"
        )

    registry[cnf] = {"epoch": epoch, "last_seen": now}
    return "accepted:epoch_advanced"
