# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-tool-manifest-re-fetch-as-a-trust-boundary-crossing-rather-than-a-cache-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-tool-manifest-re-fetch-as-a-trust-boundary-crossing-rather-than-a-cache-refresh.warrant.json
# Markdown SHA-256:   e22b321319a3c162e0595fce72a590dc00a2b678d29f8c0e60d98d16674810c1
# Code AST SHA-256:   9a1febfd10d1ddd9e73037fd625cd06775fefc5db7611104be230eec5c1b10c7
# Verified Classes:   ManifestTrustViolation, Approval
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ManifestTrustViolation(RuntimeError):
    """Raised when a manifest mutation crosses the trust boundary without re-approval."""


AUTHORITY_BEARING = {"endpoint", "auth_scope", "side_effects", "parameters", "defaults"}
INSTRUCTION_BEARING = {"description", "param_descriptions", "examples", "when_to_use"}
PRESENTATION_ONLY = {"display_name", "icon", "docs_url"}


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


@dataclass
class Approval:
    tool_name: str
    approved_hash: str


def classify_change(old: dict[str, Any], new: dict[str, Any]) -> str:
    """Return 'refresh' | 're_gate' | 'quarantine' for an identity-preserving mutation."""
    if old.get("name") != new.get("name"):
        raise ManifestTrustViolation(
            f"identity changed without new approval: {old.get('name')!r} -> {new.get('name')!r}"
        )
    changed = {k for k in old.keys() | new.keys() if old.get(k) != new.get(k)}
    if changed & INSTRUCTION_BEARING:
        return "quarantine"   # potential prompt injection in description/instructions
    if changed & AUTHORITY_BEARING:
        return "re_gate"      # endpoint/schema/scope changed: authority no longer valid
    if changed <= PRESENTATION_ONLY:
        return "refresh"      # safe to apply as cache refresh
    return "re_gate"          # unknown field change defaults to the strict path


def apply_manifest_update(
    active: dict[str, Any],
    incoming: dict[str, Any],
    approvals: dict[str, Approval],
) -> dict[str, Any]:
    """Merge an incoming manifest only if authority is re-established for new semantics."""
    name = incoming.get("name")
    verdict = classify_change(active, incoming)

    if verdict == "refresh":
        return incoming

    new_hash = manifest_hash(incoming)
    approval = approvals.get(name)
    if approval is None or approval.approved_hash != new_hash:
        if verdict == "quarantine":
            raise ManifestTrustViolation(
                f"instruction-bearing change for {name!r} (hash {new_hash[:12]}) "
                "requires quarantine + re-approval; refusing to merge into live context"
            )
        raise ManifestTrustViolation(
            f"authority-bearing change for {name!r} (hash {new_hash[:12]}) "
            "invalidates prior approval; re-gate before use"
        )
    return incoming
