# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-verifiable-credential-identity-attestation-from-silently-degrading-across-agent-handoffs-when-the-witness-set-rotates-mid-ses.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-verifiable-credential-identity-attestation-from-silently-degrading-across-agent-handoffs-when-the-witness-set-rotates-mid-ses.warrant.json
# Markdown SHA-256:   62818677e805d5b41dc65f89d3f37173b21a86eec4c63522c96d6ecabfcf11cc
# Code AST SHA-256:   4a803282e4705920ba8155a0520ea63dd49f0e0da8895935f15ebd16e621cd1b
# Verified Classes:   WitnessPolicyDriftError, Countersignature, AAIFProfile
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WitnessPolicyDriftError(RuntimeError):
    """Raised when a presented attestation was collected under a witness-policy
    version that no longer matches the AAIF profile current at handoff time."""


@dataclass(frozen=True)
class Countersignature:
    witness_id: str
    profile_version: int
    sig_bytes: bytes


@dataclass(frozen=True)
class AAIFProfile:
    credential_id: str
    profile_version: int
    witness_set: frozenset
    threshold: int

    def snapshot_hash(self) -> str:
        material = f"{self.credential_id}:{self.profile_version}:" \
                   f"{','.join(sorted(self.witness_set))}:{self.threshold}"
        return hashlib.sha256(material.encode()).hexdigest()


def admit_handoff(
    presented: list,
    current_profile: AAIFProfile,
    admitted_profile_version: int,
) -> None:
    # Invariant 1: the witness policy must not have rotated since admission.
    if current_profile.profile_version != admitted_profile_version:
        raise WitnessPolicyDriftError(
            f"witness policy rotated mid-session: admitted under "
            f"profile_version={admitted_profile_version}, current="
            f"{current_profile.profile_version}; re-admission required"
        )

    # Invariant 2: every countersignature must be bound to the current version,
    # not merely produced by a currently-trusted witness.
    for cs in presented:
        if cs.profile_version != current_profile.profile_version:
            raise WitnessPolicyDriftError(
                f"countersignature from {cs.witness_id} collected under "
                f"profile_version={cs.profile_version}, expected "
                f"{current_profile.profile_version}; stale attestation"
            )
        if cs.witness_id not in current_profile.witness_set:
            raise WitnessPolicyDriftError(
                f"witness {cs.witness_id} not in current witness set"
            )

    distinct = {cs.witness_id for cs in presented}
    if len(distinct) < current_profile.threshold:
        raise WitnessPolicyDriftError(
            f"threshold not met: {len(distinct)} < {current_profile.threshold}"
        )


def handle_handoff(presented, current_profile, admitted_profile_version):
    admit_handoff(presented, current_profile, admitted_profile_version)
    return {"admitted": True, "policy_snapshot": current_profile.snapshot_hash()}
