# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-valid-aaif-attestation-whose-subject-binding-was-minted-against-a-superseded-agent-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-valid-aaif-attestation-whose-subject-binding-was-minted-against-a-superseded-agent-revision.warrant.json
# Markdown SHA-256:   9a2a0f43a10f61d8a93dd7e9d51ce1d1fdb921a629e9def5966a935152216634
# Code AST SHA-256:   95cc9b90f8e471b9675822a584964e64f32139d0e5b93f8aea8616efad0d161f
# Verified Classes:   StaleSubjectBinding, CapabilityWidening, Attestation, RuntimeRevision
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleSubjectBinding(RuntimeError):
    """Raised when an AAIF attestation's subject descriptor does not match the
    presenter's runtime revision descriptor at use time."""
    pass


class CapabilityWidening(StaleSubjectBinding):
    """Raised when the runtime descriptor's capability set is a strict superset
    of the signed descriptor's capability set (escalation, not mere drift)."""
    pass


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    subject_descriptor_hash: str      # hash of the descriptor the issuer signed
    signed_capabilities: frozenset    # capability set in the signed descriptor
    expires_at: float
    signature_valid: bool


@dataclass(frozen=True)
class RuntimeRevision:
    agent_id: str
    descriptor_hash: str              # hash of the live revision descriptor
    capabilities: frozenset


def verify_attestation_at_use(
    att: Attestation,
    runtime: RuntimeRevision,
    now: float,
    self_binding_proof: str | None,
) -> None:
    """Enforce the use-time subject-binding invariant.

    Signature validity is necessary but not sufficient. The subject descriptor
    must match the live runtime descriptor, and the live capability set must
    not be a strict superset of the signed set.
    """
    if not att.signature_valid:
        raise StaleSubjectBinding(f"signature invalid for {att.agent_id}")
    if now >= att.expires_at:
        raise StaleSubjectBinding(f"attestation expired for {att.agent_id}")
    if att.agent_id != runtime.agent_id:
        raise StaleSubjectBinding(
            f"agent id mismatch: att={att.agent_id} runtime={runtime.agent_id}"
        )

    # The core check: the signed subject must equal the live revision.
    if att.subject_descriptor_hash != runtime.descriptor_hash:
        # Distinguish escalation from benign drift before deciding.
        widened = runtime.capabilities - att.signed_capabilities
        if widened:
            raise CapabilityWidening(
                f"revision {runtime.descriptor_hash[:8]} carries capabilities "
                f"not in signed subject {att.subject_descriptor_hash[:8]}: "
                f"{sorted(widened)}"
            )
        raise StaleSubjectBinding(
            f"subject binding mismatch for {att.agent_id}: "
            f"signed={att.subject_descriptor_hash[:8]} "
            f"live={runtime.descriptor_hash[:8]}"
        )

    # Self-binding proof must corroborate the live descriptor.
    if self_binding_proof is None:
        raise StaleSubjectBinding(
            f"no self-binding proof presented for {att.agent_id}"
        )
    if self_binding_proof != runtime.descriptor_hash:
        raise StaleSubjectBinding(
            f"self-binding proof does not match live descriptor for {att.agent_id}"
        )


def descriptor_hash(weights: str, prompt_bundle: str, tool_manifest: str) -> str:
    h = hashlib.sha256()
    for part in (weights, prompt_bundle, tool_manifest):
        h.update(part.encode("utf-8"))
        h.update(b"\x00")
    return h.hexdigest()
