# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-behavioral-fingerprint-match-from-masking-a-stale-attestation-during-agent-to-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-behavioral-fingerprint-match-from-masking-a-stale-attestation-during-agent-to-agent-handoff.warrant.json
# Markdown SHA-256:   5e987070b3c9ef9463865c13a1968e7de46b4bbe00f3ea2f6cb9bb14403dee24
# Code AST SHA-256:   2deb61704c4aa12db4ec24081a315a644a5bcda11397c1b9aafb3f69e9d0b985
# Verified Classes:   StaleAttestationError, BaselineAttestationMismatchError, BehavioralDivergenceError, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when an attestation is expired, superseded, or digest-mismatched."""
    pass


class BaselineAttestationMismatchError(RuntimeError):
    """Raised when the fingerprint baseline is not the one the attestation committed to."""
    pass


class BehavioralDivergenceError(RuntimeError):
    """Raised when post-attestation traces diverge from the committed baseline."""
    pass


@dataclass
class Attestation:
    agent_id: str
    issued_at: float
    expires_at: float
    code_digest: str
    trace_commitment: str  # H(baseline_embedding || code_digest)


def _commitment(baseline_embedding: bytes, code_digest: str) -> str:
    h = hashlib.sha256()
    h.update(baseline_embedding)
    h.update(code_digest.encode())
    return h.hexdigest()


def admit_agent(
    presented: Attestation,
    latest_in_registry: Attestation | None,
    now: float,
    current_code_digest: str,
    baseline_embedding: bytes,
    post_attestation_traces: list[float],
    fingerprint_fn,  # (traces, baseline) -> float in [0,1]
    fingerprint_threshold: float = 0.90,
) -> bool:
    # Gate 1: freshness is terminal. No behavioral score can offset it.
    if now > presented.expires_at:
        raise StaleAttestationError(
            f"attestation for {presented.agent_id} expired at {presented.expires_at}, now={now}"
        )
    if presented.code_digest != current_code_digest:
        raise StaleAttestationError(
            f"code digest mismatch: presented={presented.code_digest} current={current_code_digest}"
        )
    if latest_in_registry is not None and presented.issued_at < latest_in_registry.issued_at:
        raise StaleAttestationError(
            f"attestation superseded: presented.issued_at={presented.issued_at} "
            f"< latest.issued_at={latest_in_registry.issued_at}"
        )

    # Gate 2: baseline must be the one the attestation committed to.
    expected = _commitment(baseline_embedding, current_code_digest)
    if presented.trace_commitment != expected:
        raise BaselineAttestationMismatchError(
            f"trace_commitment mismatch for {presented.agent_id}: "
            f"presented={presented.trace_commitment} expected={expected}"
        )

    # Gate 3: fingerprint only over post-attestation traces, secondary filter.
    if not post_attestation_traces:
        raise BehavioralDivergenceError(
            f"no post-attestation traces for {presented.agent_id}; cannot score continuity"
        )
    score = fingerprint_fn(post_attestation_traces, baseline_embedding)
    if score < fingerprint_threshold:
        raise BehavioralDivergenceError(
            f"behavioral divergence for {presented.agent_id}: score={score:.3f} "
            f"< threshold={fingerprint_threshold}"
        )
    return True
