# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-tool-manifest-versus-a-benign-schema-drift-the-version-pin-divergence-invariant-in-registry-supply-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-tool-manifest-versus-a-benign-schema-drift-the-version-pin-divergence-invariant-in-registry-supply-chains.warrant.json
# Markdown SHA-256:   92cde22d21ffda91e3665422a273304c10553ebff1f5e5a90d0a34269586b956
# Code AST SHA-256:   099850661352a19eddcf34f6c80fd1fcfbd8bb673dff1eaac80643dee1ba0b58
# Verified Classes:   ManifestProvenanceError, ReviewedPin
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestProvenanceError(RuntimeError):
    """Raised when a tool manifest's content diverges from its recorded version pin."""
    pass


@dataclass(frozen=True)
class ReviewedPin:
    tool_name: str
    version: str
    content_hash: str


INSTRUCTION_FIELDS = ("description", "examples", "parameter.description")


def content_hash(manifest: dict) -> str:
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _touches_instruction_field(old: dict, new: dict) -> bool:
    for field in INSTRUCTION_FIELDS:
        if old.get(field) != new.get(field):
            return True
    return False


def _is_imperative(text: str) -> bool:
    lowered = text.strip().lower()
    return lowered.startswith(("always ", "before ", "you must ", "never ", "include "))


def validate_manifest(pin: ReviewedPin, manifest: dict, previous_manifest: dict | None) -> None:
    """Enforce the version-pin divergence invariant before binding a tool manifest."""
    actual = content_hash(manifest)

    if actual == pin.content_hash:
        return  # stable: bind

    if manifest.get("version") != pin.version:
        return  # legitimate version advance: normal drift path

    # Version string unchanged but content hash diverged.
    if previous_manifest is None:
        raise ManifestProvenanceError(
            f"{pin.tool_name}@{pin.version}: content hash diverged with no prior "
            f"manifest to diff; cannot classify. Refusing to bind."
        )

    if _touches_instruction_field(previous_manifest, manifest):
        description = str(manifest.get("description", ""))
        if _is_imperative(description):
            raise ManifestProvenanceError(
                f"{pin.tool_name}@{pin.version}: instruction-bearing field mutated "
                f"under a frozen version pin AND new content is imperative-mood. "
                f"Attack signature. Blocking bind."
            )
        raise ManifestProvenanceError(
            f"{pin.tool_name}@{pin.version}: instruction-bearing field mutated under "
            f"a frozen version pin. Quarantine for re-review."
        )

    raise ManifestProvenanceError(
        f"{pin.tool_name}@{pin.version}: content hash diverged on non-instruction "
        f"fields. Quarantine; low-confidence."
    )
