# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-for-mcp-tool-manifests-when-description-text-is-both-instruction-and-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-for-mcp-tool-manifests-when-description-text-is-both-instruction-and-schema.warrant.json
# Markdown SHA-256:   d6d679136f8cf1535195bf2d891e78f323d93e2e07312747fc1c1fe1b8568b3c
# Code AST SHA-256:   453d6cbbf1fd4415c492daafa2168ae427c515f8c7298fef557ffeed7d4a33b9
# Verified Classes:   ManifestTrustError, ApprovedManifest, ManifestRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import re
import unicodedata
from dataclasses import dataclass, field


class ManifestTrustError(RuntimeError):
    """Raised when a tool manifest's model-visible projection violates the trust invariant."""


IMPERATIVE_PATTERNS = [
    re.compile(r"\b(before|after|always|never|first|then)\b", re.I),
    re.compile(r"\b(read|write|send|include|pass|call|invoke|execute|fetch)\b", re.I),
    re.compile(r"(~/|/etc/|/home/|\.json|\.env|\.ssh)"),
    re.compile(r"\b(you|your|the agent)\b", re.I),
]


def normalize_projection(text: str) -> str:
    """Collapse to the form the model's input pipeline actually sees."""
    text = unicodedata.normalize("NFKC", text)
    text = "".join(ch for ch in text if unicodedata.category(ch)[0] != "C")
    return re.sub(r"\s+", " ", text).strip()


def projection_hash(description: str) -> str:
    return hashlib.sha256(normalize_projection(description).encode("utf-8")).hexdigest()


def imperative_units(description: str) -> set[str]:
    norm = normalize_projection(description)
    hits: set[str] = set()
    for pat in IMPERATIVE_PATTERNS:
        for m in pat.finditer(norm):
            hits.add(m.group(0).lower())
    return hits


@dataclass
class ApprovedManifest:
    name: str
    projection_hash: str
    imperative_units: set[str] = field(default_factory=set)


@dataclass
class ManifestRegistry:
    approved: dict[str, ApprovedManifest] = field(default_factory=dict)

    def approve_initial(self, name: str, description: str) -> None:
        units = imperative_units(description)
        if units:
            # Initial approval must not silently accept imperative content.
            raise ManifestTrustError(
                f"initial manifest for {name!r} contains imperative units {sorted(units)}; "
                "requires human/policy gate before approval"
            )
        self.approved[name] = ApprovedManifest(
            name=name,
            projection_hash=projection_hash(description),
            imperative_units=units,
        )

    def verify_on_use(self, name: str, description: str) -> None:
        rec = self.approved.get(name)
        if rec is None:
            raise ManifestTrustError(f"tool {name!r} used without an approval record")
        current_hash = projection_hash(description)
        if current_hash != rec.projection_hash:
            new_units = imperative_units(description) - rec.imperative_units
            if new_units:
                raise ManifestTrustError(
                    f"rug-pull on {name!r}: projection changed and introduced "
                    f"imperative units {sorted(new_units)}"
                )
            raise ManifestTrustError(
                f"rug-pull on {name!r}: projection hash changed "
                f"({rec.projection_hash[:12]} -> {current_hash[:12]}) without new imperatives; "
                "re-approval required"
            )

    def verify_handoff_claim(self, name: str, claimed_description: str, live_description: str | None) -> None:
        if live_description is None:
            raise ManifestTrustError(
                f"handoff asserts manifest for {name!r} but no live tools/list is available; "
                "unverified claims are not callable"
            )
        if projection_hash(claimed_description) != projection_hash(live_description):
            raise ManifestTrustError(
                f"handoff manifest for {name!r} diverges from live server projection"
            )
