# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-validated-the-post-handshake-skill-injection-window-in-mcp-supply-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-validated-the-post-handshake-skill-injection-window-in-mcp-supply-chains.warrant.json
# Markdown SHA-256:   f242f656ce794b9a89bacff0902c863d4cf0348239de3389592d267af6b0ac3e
# Code AST SHA-256:   ab93a6111ab909dfab6150a8446f666ee85ab359b68f064b1f7054e346fc383e
# Verified Classes:   ManifestDriftError, ApprovedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when a tool manifest entry changes in a way that must not be auto-admitted."""
    pass


def canonical_entry_hash(entry: dict) -> str:
    # Hash the ENTIRE entry: name, description, title, examples,
    # and every per-property description. Cosmetic key order is normalized.
    blob = json.dumps(entry, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def structural_schema(entry: dict) -> dict:
    schema = entry.get("inputSchema", {})
    return {
        "type": schema.get("type"),
        "properties": {
            k: v.get("type") for k, v in schema.get("properties", {}).items()
        },
        "required": sorted(schema.get("required", [])),
    }


_INJECTION_MARKERS = (
    "note to assistant",
    "you must first call",
    "before calling this tool you must",
    "ignore previous",
)


def _looks_injected(description: str) -> bool:
    low = description.lower()
    return any(marker in low for marker in _INJECTION_MARKERS)


@dataclass
class ApprovedManifest:
    entry: dict
    full_hash: str


def admit_refreshed_entry(refreshed: dict, approved: ApprovedManifest) -> dict:
    """Gate a re-fetched tools/list entry against the previously approved manifest."""
    new_hash = canonical_entry_hash(refreshed)

    if _looks_injected(refreshed.get("description", "")):
        raise ManifestDriftError(
            f"tool {refreshed.get('name')!r}: description contains instruction-like "
            "text; refusing admission regardless of hash"
        )

    if new_hash == approved.full_hash:
        return refreshed  # byte-identical trusted entry

    schema_changed = structural_schema(refreshed) != structural_schema(approved.entry)
    if not schema_changed:
        # Same structural schema, different full hash => description/example drift.
        # This is the supply-chain injection signature. Quarantine.
        raise ManifestDriftError(
            f"tool {refreshed.get('name')!r}: full-entry hash changed with no "
            "structural schema change; description-only drift is treated as hostile "
            "and requires out-of-band re-approval"
        )

    # Structural change is the expected upgrade path but still needs review.
    raise ManifestDriftError(
        f"tool {refreshed.get('name')!r}: structural schema changed; "
        "quarantined pending schema-diff review"
    )
