# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-its-identity-attestation-to-the-exact-model-weights-toolchain-and-runtime-it-is-executing-and-what-breaks-when-it-binds-to.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-its-identity-attestation-to-the-exact-model-weights-toolchain-and-runtime-it-is-executing-and-what-breaks-when-it-binds-to.warrant.json
# Markdown SHA-256:   dae690ebecef8086687963d307bc102693277fb04a5ed571fa46283d5c47a692
# Code AST SHA-256:   134904a66b46b9091c1aafe474f426b38c48f8743ec4655197722c625cfef356
# Verified Classes:   AttestationBindingError, Substrate, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class AttestationBindingError(RuntimeError):
    """Raised when an attestation does not bind to the currently executing substrate."""
    pass


@dataclass
class Substrate:
    weight_digest: str          # sha256 of weight tensor content
    manifest_digest: str        # sha256 of canonicalized, post-resolution tool manifest
    runtime_image_digest: str   # sha256 of runtime container image
    epoch: int                  # bumped on any mutation


@dataclass
class Attestation:
    claim_weight_digest: str
    claim_manifest_digest: str
    claim_runtime_image_digest: str
    claim_epoch: int
    binding: str = "content"    # "content" or "reference"
    signature_valid: bool = True


def canonical_manifest_digest(manifest: dict) -> str:
    blob = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def verify_attestation(att: Attestation, live: Substrate,
                       last_observed_mutation_epoch: int) -> None:
    if not att.signature_valid:
        raise AttestationBindingError("signature invalid; cannot trust claim")

    if att.binding != "content":
        # Reference-bound attestations cannot be checked against substrate.
        # Fail closed here unless the caller has explicitly opted into reference trust.
        raise AttestationBindingError(
            f"attestation binding={att.binding!r}; reference-bound claims are not "
            "substrate-verifiable and must not authorize irreversible actions"
        )

    if att.claim_epoch < last_observed_mutation_epoch:
        raise AttestationBindingError(
            f"stale attestation: claim epoch {att.claim_epoch} < observed mutation "
            f"epoch {last_observed_mutation_epoch}; substrate mutated without re-signing"
        )

    mismatches = []
    if att.claim_weight_digest != live.weight_digest:
        mismatches.append("weights")
    if att.claim_manifest_digest != live.manifest_digest:
        mismatches.append("tool_manifest")
    if att.claim_runtime_image_digest != live.runtime_image_digest:
        mismatches.append("runtime_image")

    if mismatches:
        raise AttestationBindingError(
            "attestation-to-substrate binding drift on: " + ", ".join(mismatches)
        )


def authorize_tool_call(att: Attestation, live: Substrate,
                        last_observed_mutation_epoch: int,
                        irreversible: bool) -> None:
    # Content binding is mandatory for irreversible actions; enforce before any dispatch.
    if irreversible and att.binding != "content":
        raise AttestationBindingError(
            "irreversible tool call requires content-bound attestation"
        )
    verify_attestation(att, live, last_observed_mutation_epoch)
