# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-signed-capability-declarations-against-injection-canaries-before-trusting-a-tool-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-signed-capability-declarations-against-injection-canaries-before-trusting-a-tool-manifest.warrant.json
# Markdown SHA-256:   68ac6600afa5342443e730e74b01fcfb0128bc03fa788ff78e98e89353dddae7
# Code AST SHA-256:   31731b43268cface32a112a90763199561c019aacd5f366717ece4cd62c45469
# Verified Classes:   ProvenanceDivergenceError, Manifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceDivergenceError(RuntimeError):
    """Raised when the object a canary judged differs from the object a signature covers."""


@dataclass(frozen=True)
class Manifest:
    blob: bytes
    capabilities: frozenset[str]

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


def verify_joint_provenance(
    signed: Manifest,
    resolved: Manifest,
    canary_probed_capabilities: frozenset[str],
    transformation_receipt_valid: bool = False,
) -> None:
    # Byte identity is the load-bearing check. Canary results over `resolved`
    # say nothing about `signed` unless the two are the same object.
    if signed.digest != resolved.digest:
        if not transformation_receipt_valid:
            raise ProvenanceDivergenceError(
                f"resolved manifest {resolved.digest[:12]} diverges from signed "
                f"{signed.digest[:12]} with no authorized transformation receipt; "
                f"canary results over the resolved blob are inadmissible"
            )

    # Coverage completeness over the union, not the resolved set alone.
    # A capability added by transformation is an uncovered surface.
    uncovered = (signed.capabilities | resolved.capabilities) - canary_probed_capabilities
    if uncovered:
        raise ProvenanceDivergenceError(
            f"capabilities {sorted(uncovered)} have no canary probe; "
            f"manifest is unverified for these surfaces, not verified"
        )


def load_manifest(signed: Manifest, resolved: Manifest, probes: frozenset[str]) -> Manifest:
    verify_joint_provenance(signed, resolved, probes)
    return resolved
