# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-from-silently-decaying-when-an-agent-s-identity-is-re-verified-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-from-silently-decaying-when-an-agent-s-identity-is-re-verified-mid-task.warrant.json
# Markdown SHA-256:   e016237783626ec84593d9d6c7aef19e95d91685f99ac0856d8ec05ef309a137
# Code AST SHA-256:   1200d3583f21a376477320e0816fe55b952cfc98f8aff1ec75284e3c5618033e
# Verified Classes:   CapabilityAttestationError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilityAttestationError(RuntimeError):
    """Raised when a warrant's bound profile no longer matches the live executor."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    profile_hash: str
    expires_at: float


def compute_profile_hash(model: str, tools_schema: str, policy: str) -> str:
    h = hashlib.sha256()
    h.update(model.encode())
    h.update(b"\x00")
    h.update(tools_schema.encode())
    h.update(b"\x00")
    h.update(policy.encode())
    return h.hexdigest()


def assert_profile_binding(
    warrant: Warrant,
    live_model: str,
    live_tools_schema: str,
    live_policy: str,
    now: float,
) -> None:
    """
    Enforce the profile-binding invariant at every rotation and consumption.
    Identity checks (subject, signature) are assumed already passed; this is
    the check that standard token validation omits.
    """
    if now >= warrant.expires_at:
        raise CapabilityAttestationError(
            f"warrant for {warrant.subject} expired at {warrant.expires_at}"
        )
    live_hash = compute_profile_hash(live_model, live_tools_schema, live_policy)
    if live_hash != warrant.profile_hash:
        raise CapabilityAttestationError(
            "profile-binding invariant violated: "
            f"warrant attests {warrant.profile_hash[:12]} but executor is "
            f"{live_hash[:12]} (model={live_model}); identity re-verification "
            "does not cover capability drift — refuse the action"
        )


# Trace of the observed failure: rotation at t=25 succeeds on identity,
# but the live model drifted v3 -> v3.1 under a warrant still attesting v3.
warrant = Warrant(
    subject="worker-7",
    profile_hash=compute_profile_hash("v3", "Σ", "π"),
    expires_at=3600.0,
)

assert_profile_binding(warrant, "v3", "Σ", "π", now=25.0)   # passes at admission
assert_profile_binding(warrant, "v3.1", "Σ", "π", now=25.0)  # raises: drift caught
