# 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-descriptor-level-skill-injection-and-the-post-approval-mutation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-validated-descriptor-level-skill-injection-and-the-post-approval-mutation-window.warrant.json
# Markdown SHA-256:   fcb685a72b4fe29ec436f003949a763aa467962a3337508f192e63be085a2524
# Code AST SHA-256:   6d8d9add82259114a15a47af9446a0cb6dc3e0c4a2357290bbaf4699da1f3d2e
# Verified Classes:   DescriptorMutationError, CanonicalizationDrift, Approval
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class DescriptorMutationError(RuntimeError):
    """Raised when a re-fetched tool descriptor widens the approved surface."""


class CanonicalizationDrift(RuntimeError):
    """Raised when the canonicalizer version differs from the approved one."""


CANONICALIZER_VERSION = "v3"


def canonical_descriptor(descriptor: dict[str, Any]) -> bytes:
    # Stable serialization: sorted keys, no insignificant whitespace.
    # Any change to this function is a re-approval event; bump the version.
    return json.dumps(
        descriptor, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    ).encode("utf-8")


def descriptor_hash(descriptor: dict[str, Any]) -> str:
    return hashlib.sha256(canonical_descriptor(descriptor)).hexdigest()


@dataclass(frozen=True)
class Approval:
    server_id: str
    tool_name: str
    descriptor_hash: str
    canonicalizer_version: str


EXFILTRATION_SHAPED = ("context", "history", "memory", "file", "path", "env", "secret")


def _widening_reasons(old: dict[str, Any], new: dict[str, Any]) -> list[str]:
    reasons: list[str] = []
    old_props = set(old.get("inputSchema", {}).get("properties", {}))
    new_props = set(new.get("inputSchema", {}).get("properties", {}))
    added = new_props - old_props
    for prop in added:
        blob = (prop + " " + new["inputSchema"]["properties"][prop].get("description", "")).lower()
        if any(tok in blob for tok in EXFILTRATION_SHAPED):
            reasons.append(f"new exfiltration-shaped argument: {prop!r}")
        else:
            reasons.append(f"new argument widens surface: {prop!r}")
    if old.get("description") != new.get("description"):
        reasons.append("description text changed (model-visible instruction channel)")
    old_req = set(old.get("inputSchema", {}).get("required", []))
    new_req = set(new.get("inputSchema", {}).get("required", []))
    if new_req - old_req:
        reasons.append(f"new required arguments: {sorted(new_req - old_req)}")
    return reasons


def admit_descriptor(
    approval: Approval,
    descriptor: dict[str, Any],
    canonicalizer_version: str,
) -> None:
    """Gate every re-fetched descriptor before it enters the model context."""
    if canonicalizer_version != approval.canonicalizer_version:
        raise CanonicalizationDrift(
            f"canonicalizer {canonicalizer_version!r} != approved "
            f"{approval.canonicalizer_version!r}; hash comparison is meaningless"
        )

    incoming = descriptor_hash(descriptor)
    if incoming == approval.descriptor_hash:
        return  # byte-identical to what was approved; safe to serve

    # Content changed post-approval. Never auto-accept; surface the delta.
    previous = json.loads(
        # In practice the approved descriptor is persisted alongside the hash.
        # Here we reconstruct the widening check from the stored approval only
        # and fail closed when the prior descriptor is unavailable.
        "{}"
    )
    reasons = _widening_reasons(previous, descriptor) if previous else [
        "descriptor content changed post-approval; prior content unavailable for diff"
    ]
    raise DescriptorMutationError(
        f"tool {approval.tool_name!r} on {approval.server_id!r} mutated: "
        f"{approval.descriptor_hash[:12]} -> {incoming[:12]}; "
        f"re-approval required. Reasons: {reasons}"
    )
