# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-signed-agent-manifest-because-capability-attestation-freshness-diverges-from-warrant-validity-at-th.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-signed-agent-manifest-because-capability-attestation-freshness-diverges-from-warrant-validity-at-th.warrant.json
# Markdown SHA-256:   4570d4504792a2242a6ebbf7ad9eafab5f89bc55cca1504d80501b1085ce815f
# Code AST SHA-256:   30fa58852fd3fcb2380414dd0888093e0f82d70b32dedb6550c4cda4f8cd89ba
# Verified Classes:   TrustBoundaryError, AttestationWarrantMismatch, WarrantOutlivesAttestation, UnboundReAttestation, TrustClockSkew, Attestation, Warrant, ReceiverPolicy
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from datetime import datetime, timedelta


class TrustBoundaryError(RuntimeError):
    """Base class for cross-org manifest admission failures."""


class AttestationWarrantMismatch(TrustBoundaryError):
    """Warrant does not cryptographically bind the presented attestation."""


class WarrantOutlivesAttestation(TrustBoundaryError):
    """Warrant lifetime exceeds the receiver's attestation freshness window."""


class UnboundReAttestation(TrustBoundaryError):
    """Peer rotated attestation mid-task without a re-issued warrant."""


class TrustClockSkew(TrustBoundaryError):
    """Timestamps diverge beyond tolerance; freshness is unverifiable."""


@dataclass(frozen=True)
class Attestation:
    version: str
    sandbox_profile: str
    model: str
    timestamp: datetime
    signature_valid: bool

    def digest(self) -> str:
        body = f"{self.version}|{self.sandbox_profile}|{self.model}|{self.timestamp.isoformat()}"
        return hashlib.sha256(body.encode()).hexdigest()


@dataclass(frozen=True)
class Warrant:
    version: str
    scopes: tuple
    issued_at: datetime
    expires_at: datetime
    binds_attestation_hash: str
    signature_valid: bool


@dataclass(frozen=True)
class ReceiverPolicy:
    max_attestation_age: timedelta
    clock_skew_tolerance: timedelta


def admit_peer(
    attestation: Attestation,
    warrant: Warrant,
    policy: ReceiverPolicy,
    now: datetime,
    admitted_attestation_hash: str | None = None,
) -> str:
    """Return the admitted attestation hash, or raise TrustBoundaryError.

    admitted_attestation_hash is the hash bound at initial handshake; if
    provided, this call is a mid-task re-verification.
    """
    if not attestation.signature_valid or not warrant.signature_valid:
        raise TrustBoundaryError("signature verification failed")

    # Condition 3: the warrant must commit to this exact attestation.
    if warrant.binds_attestation_hash != attestation.digest():
        raise AttestationWarrantMismatch(
            f"warrant {warrant.version} binds {warrant.binds_attestation_hash[:12]}, "
            f"peer presented {attestation.digest()[:12]}"
        )

    # Condition 4: mid-task rotation must carry a re-issued warrant.
    if admitted_attestation_hash is not None and attestation.digest() != admitted_attestation_hash:
        raise UnboundReAttestation(
            f"attestation rotated from {admitted_attestation_hash[:12]} to "
            f"{attestation.digest()[:12]} without re-handshake"
        )

    # Condition 1: attestation must not predate the warrant.
    if attestation.timestamp < warrant.issued_at:
        raise AttestationWarrantMismatch("attestation predates warrant issue")

    # Clock skew guard on both artifacts.
    for label, ts in (("attestation", attestation.timestamp), ("warrant", warrant.issued_at)):
        if abs((now - ts).total_seconds()) > policy.clock_skew_tolerance.total_seconds():
            raise TrustClockSkew(f"{label} timestamp diverges from receiver clock")

    # Condition 2: attestation within freshness window.
    if now - attestation.timestamp > policy.max_attestation_age:
        raise TrustBoundaryError("attestation stale beyond freshness window")

    # Structural guard: warrant must not outlive the freshness window
    # unless it forces periodic re-attestation (encoded as scope).
    if (warrant.expires_at - now) > policy.max_attestation_age and "re_attest_required" not in warrant.scopes:
        raise WarrantOutlivesAttestation(
            f"warrant valid {(warrant.expires_at - now)} but attestation "
            f"freshness is only {policy.max_attestation_age}"
        )

    return attestation.digest()
