# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-mutation-as-a-capability-escalation-rather-than-a-benign-version-bump.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-mutation-as-a-capability-escalation-rather-than-a-benign-version-bump.warrant.json
# Markdown SHA-256:   ab2c0a2fd2d3db73f3d5d4c9c0d607f1d367429669e73f14d15f887bc1385da3
# Code AST SHA-256:   7ef9ce48f3b8a5f5345e415aa7e9fa815cd254bda03f28c51a0ee6bdda85b50b
# Verified Classes:   CapabilityEscalationError, ManifestAnchor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityEscalationError(RuntimeError):
    """Raised when a tool-manifest delta expands the model-visible instruction
    surface or reachable argument domain without out-of-band re-approval."""


@dataclass(frozen=True)
class ManifestAnchor:
    tool_name: str
    semantic_hash: str  # hash over normalized description + annotations + schema
    version: str        # logged, never used as trust anchor


_PERMISSIVE_ANNOTATION_DIRECTION = {
    "readOnlyHint": True,      # false -> true is permissive
    "destructiveHint": False,  # true -> false is permissive
    "idempotentHint": True,    # false -> true is permissive
}


def _normalize(manifest: dict) -> dict:
    return {
        "name": manifest["name"],
        "description": " ".join(manifest.get("description", "").split()),
        "annotations": dict(sorted(manifest.get("annotations", {}).items())),
        "inputSchema": manifest.get("inputSchema", {}),
    }


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


def _annotation_escalated(old: dict, new: dict) -> bool:
    for key, permissive_value in _PERMISSIVE_ANNOTATION_DIRECTION.items():
        if old.get(key) != new.get(key) and new.get(key) == permissive_value:
            return True
    return False


def _schema_domain_expanded(old: dict, new: dict) -> bool:
    old_props = old.get("properties", {})
    new_props = new.get("properties", {})
    if set(new_props) - set(old_props):
        return True
    for key in old_props:
        if old_props[key].get("enum") and not set(old_props[key]["enum"]).issubset(
            set(new_props.get(key, {}).get("enum", []))
        ):
            return True
        if "default" in new_props.get(key, {}) and "default" not in old_props[key]:
            return True
    return False


def verify_manifest(manifest: dict, anchor: ManifestAnchor) -> None:
    if manifest["name"] != anchor.tool_name:
        raise CapabilityEscalationError(
            f"tool identity mismatch: {manifest['name']!r} != {anchor.tool_name!r}"
        )

    new_hash = semantic_hash(manifest)
    if new_hash == anchor.semantic_hash:
        return  # byte-identical semantic surface; version string irrelevant

    # Semantic surface changed. Determine whether it is an escalation.
    # We cannot diff against the old manifest body here (only its hash is pinned),
    # so any semantic-surface change that we cannot prove benign must fail closed.
    raise CapabilityEscalationError(
        f"semantic-surface delta for {manifest['name']!r}: "
        f"pinned={anchor.semantic_hash[:12]} observed={new_hash[:12]} "
        f"version={manifest.get('version')!r} (version is not a trust anchor). "
        f"Re-fetch full prior manifest, run _annotation_escalated/_schema_domain_expanded, "
        f"and require operator re-pin before advertising to model."
    )
