# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-identity-attestation-from-silently-outliving-the-weights-prompts-and-tool-manifests-it-was-signed-against.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-identity-attestation-from-silently-outliving-the-weights-prompts-and-tool-manifests-it-was-signed-against.warrant.json
# Markdown SHA-256:   102b2bce224aed3cda4a7b56e8370eb9edb935d9e28b83081b330c7bf5476053
# Code AST SHA-256:   66a3fe35e7083c86c62fc099daba3a2b62025df9378bc47354bc692f2856e82b
# Verified Classes:   AttestationDriftError, SignedProvenance, LiveBindings
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationDriftError(RuntimeError):
    """Raised when a live artifact digest diverges from the signed provenance record."""
    pass


@dataclass(frozen=True)
class SignedProvenance:
    identity: str
    weights_sha256: str
    prompt_sha256: str
    tools_manifest_sha256: str
    signature_valid: bool


@dataclass(frozen=True)
class LiveBindings:
    weights_sha256: str
    prompt_sha256: str
    tools_manifest_sha256: str


def _digest(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def assert_binding_current(
    record: SignedProvenance,
    live: LiveBindings,
    *,
    action_is_capability_expanding: bool,
) -> None:
    # Signature authenticity is necessary but never sufficient.
    if not record.signature_valid:
        raise AttestationDriftError(f"signature invalid for {record.identity}")

    drifted = []
    if live.weights_sha256 != record.weights_sha256:
        drifted.append("weights")
    if live.prompt_sha256 != record.prompt_sha256:
        drifted.append("prompt")
    if live.tools_manifest_sha256 != record.tools_manifest_sha256:
        drifted.append("tools_manifest")

    if not drifted:
        return

    # Prompt drift is a capability edit in disguise; treat it as expanding.
    expanding = action_is_capability_expanding or "prompt" in drifted
    if expanding:
        raise AttestationDriftError(
            f"attestation drift on {record.identity}: {drifted} diverged from signed "
            f"record; capability-expanding action refused"
        )
    # Non-privileged read path may proceed, but must be logged as stale.
    print(f"STALE_BINDING {record.identity} drifted={drifted} (read-only path)")


def invoke_tool(record, live, tool_name, signed_tools, call):
    # The check rides on the same path as the call: no interleaving window.
    expanding = tool_name not in signed_tools
    assert_binding_current(record, live, action_is_capability_expanding=expanding)
    if expanding:
        raise AttestationDriftError(
            f"tool {tool_name!r} absent from signed manifest; unattested capability"
        )
    return call()
