# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-tool-manifest-has-been-re-bound-to-a-stale-capability-attestation-after-a-hot-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-tool-manifest-has-been-re-bound-to-a-stale-capability-attestation-after-a-hot-reload.warrant.json
# Markdown SHA-256:   519450d4d114ae2f60b3f718c51253d54b61200d2fe7a61898cfcfa1c1cea79f
# Code AST SHA-256:   c6806c0c5bfee5c6f94d75d3a1b8e94c2f2eda854d77d351a25b0bac9f2eaaae
# Verified Classes:   StaleAttestationError, Manifest, Attestation, LiveProcess
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a signed manifest is paired with an attestation that does not
    describe the currently executing process image (re-binding failure)."""
    pass


@dataclass(frozen=True)
class Manifest:
    body: bytes
    declared_caps: frozenset

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


@dataclass(frozen=True)
class Attestation:
    manifest_digest: str
    image_hash: str
    sandbox_profile: str
    caps: frozenset
    issued_at: float


@dataclass(frozen=True)
class LiveProcess:
    image_hash: str
    sandbox_profile: str
    started_at: float


def authorize_call(
    manifest: Manifest,
    attestation: Attestation,
    live: LiveProcess,
    requested_cap: str,
) -> bool:
    """Gate a tool invocation on the triple binding. Fails closed."""

    # Binding 2: attestation must be about *this* manifest.
    if attestation.manifest_digest != manifest.digest:
        raise StaleAttestationError(
            f"attestation bound to manifest {attestation.manifest_digest[:12]} "
            f"but live manifest is {manifest.digest[:12]}"
        )

    # Binding 3a: attestation must describe the live image.
    if attestation.image_hash != live.image_hash:
        raise StaleAttestationError(
            f"attestation describes image {attestation.image_hash[:12]} "
            f"but live image is {live.image_hash[:12]} (hot-reload rebind missed)"
        )

    # Binding 3b: attestation must be causally later than the live process start.
    if attestation.issued_at < live.started_at:
        raise StaleAttestationError(
            f"attestation issued_at={attestation.issued_at:.0f} predates "
            f"live process started_at={live.started_at:.0f}; "
            f"attestation is stale relative to a respawned process"
        )

    # Effective capability = intersection of signed manifest and live attestation.
    effective = manifest.declared_caps & attestation.caps
    if requested_cap not in effective:
        # Not an escalation—just denied. Caller decides whether to re-attest.
        return False

    # Sandbox must be the weaker of the two profiles if they disagree.
    if attestation.sandbox_profile != live.sandbox_profile:
        raise StaleAttestationError(
            f"sandbox drift: attestation={attestation.sandbox_profile} "
            f"live={live.sandbox_profile}; effective profile is the weaker"
        )

    return True
