# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-agentic-supply-chain-attestation-has-silently-diverged-from-the-artifact-it-claims-to-describe.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-agentic-supply-chain-attestation-has-silently-diverged-from-the-artifact-it-claims-to-describe.warrant.json
# Markdown SHA-256:   f105c55bacc608a2967a0cd51bebf62820fb08735a763b75104dba498e7d5642
# Code AST SHA-256:   469c606f5f7bdf1edf8307c4384b8c4fcf815374b1dce6483b7bbed62d88c650
# Verified Classes:   AttestationBindingError, Attestation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when a valid attestation's subject does not bind to the runtime artifact."""


@dataclass(frozen=True)
class Attestation:
    subject_name: str
    subject_digest: str  # sha256:<hex> over the build output
    builder_id: str


def canonicalize(payload: dict) -> bytes:
    # Deterministic serialization: sorted keys, no whitespace, UTF-8.
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")


def digest_of(payload: dict) -> str:
    return "sha256:" + hashlib.sha256(canonicalize(payload)).hexdigest()


def bind_runtime_artifact(attestation: Attestation, runtime_payload: dict) -> None:
    """
    Verify that the attestation's subject actually identifies the bytes the
    agent is about to consume. This is the binding check that SLSA-style
    provenance does NOT perform for you. If the runtime artifact is a resolved
    object (introspected MCP tool list, assembled prompt, merged skill
    descriptor), its canonical digest must equal the subject digest, or the
    attestation is orthogonal to execution and must not be trusted as a gate.
    """
    runtime_digest = digest_of(runtime_payload)

    if runtime_digest != attestation.subject_digest:
        raise AttestationBindingError(
            f"attestation subject {attestation.subject_digest!r} does not bind to "
            f"runtime artifact {runtime_digest!r} for subject "
            f"{attestation.subject_name!r} (builder {attestation.builder_id!r}); "
            f"attestation is valid but describes a different artifact than the "
            f"one this agent will execute — treat as advisory, do not elevate "
            f"capabilities or sandbox trust on the strength of this attestation"
        )


def load_mcp_manifest(attestation: Attestation, live_tools_list: dict) -> dict:
    """
    Consume an MCP server's runtime tool surface only if it binds to the
    attested manifest. In the observed failure, the loader compared name and
    version fields and skipped the byte-level digest, so a redeploy that
    regenerated schemas from type hints at container start passed silently
    and the agent's cached planner trace drifted from the live signature.
    """
    bind_runtime_artifact(attestation, live_tools_list)
    return live_tools_list
