# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-mcp-tool-manifest-whose-signature-validates-but-whose-attested-build-provenance-diverges-from-the-pinned.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-mcp-tool-manifest-whose-signature-validates-but-whose-attested-build-provenance-diverges-from-the-pinned.warrant.json
# Markdown SHA-256:   73039e32a6f2e0babf3750e1e16fc57f4ee60e4de507b01c6b0c72216a3dc0ca
# Code AST SHA-256:   e69ad2837356c867e5cc78ccc4d6847a2aa07f1d16bf21a7d8134d1a35bf6a31
# Verified Classes:   ProvenanceDivergence, PinnedPolicy, Manifest
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Mapping


class ProvenanceDivergence(RuntimeError):
    """Raised when a manifest is signature-valid but its attested provenance
    or schema diverges from the agent's pinned policy. This is a hard reject,
    never a warning: the signer is honest, the build inputs are not."""


@dataclass(frozen=True)
class PinnedPolicy:
    builder_id: str
    source_glob: str          # must match an immutable ref (tag or SHA), never a branch
    build_type: str
    schema_digest: str        # sha256 of the canonicalized inputSchema


@dataclass(frozen=True)
class Manifest:
    namespace: str
    version: str
    schema_digest: str
    signature_valid: bool
    provenance_bound: bool          # provenance.subject.digest == sha256(manifest)
    provenance_signature_valid: bool
    builder_id: str
    source_uri: str
    build_type: str


def admit_manifest(
    manifest: Manifest,
    policy: PinnedPolicy,
    last_seen_version: Mapping[str, str],
) -> None:
    """Evaluate the ordered predicate. Raises ProvenanceDivergence on any
    divergence; returns None only when every conjunct holds."""

    if not manifest.signature_valid:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: envelope signature invalid; reject before provenance"
        )

    if not manifest.provenance_bound:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: provenance not bound by subject digest; "
            "detached provenance is swappable and must not be trusted"
        )

    if not manifest.provenance_signature_valid:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: provenance signed under a different trust root"
        )

    if manifest.builder_id != policy.builder_id:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: builder_id {manifest.builder_id!r} "
            f"!= pinned {policy.builder_id!r}"
        )

    if not _matches_immutable_source(manifest.source_uri, policy.source_glob):
        raise ProvenanceDivergence(
            f"{manifest.namespace}: source_uri {manifest.source_uri!r} "
            f"is not an immutable ref matching {policy.source_glob!r}"
        )

    if manifest.build_type != policy.build_type:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: buildType {manifest.build_type!r} "
            f"!= pinned {policy.build_type!r}"
        )

    if manifest.schema_digest != policy.schema_digest:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: schema_digest {manifest.schema_digest!r} "
            f"!= pinned {policy.schema_digest!r}; version field is not a substitute"
        )

    prior = last_seen_version.get(manifest.namespace)
    if prior is not None and _version_le(manifest.version, prior) and \
            manifest.schema_digest != policy.schema_digest:
        raise ProvenanceDivergence(
            f"{manifest.namespace}: non-monotonic version {manifest.version!r} "
            f"with divergent schema indicates rollback or mutable-tag republish"
        )


def _matches_immutable_source(source_uri: str, glob: str) -> bool:
    if "refs/heads/" in source_uri:
        return False  # branches are mutable; never a valid pin target
    import fnmatch
    return fnmatch.fnmatchcase(source_uri, glob)


def _version_le(a: str, b: str) -> bool:
    def key(v: str) -> tuple[int, ...]:
        return tuple(int(p) for p in v.lstrip("v").split("."))
    return key(a) <= key(b)
