# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-runtime-skill-injection-when-a-signed-tool-manifest-is-re-issued-under-the-same-key-but-with-a-widened-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-runtime-skill-injection-when-a-signed-tool-manifest-is-re-issued-under-the-same-key-but-with-a-widened-capability-set.warrant.json
# Markdown SHA-256:   8685762e2d8a432287b54a2219eec884d88b8ec5c2a79733f5c67636e82bd653
# Code AST SHA-256:   54c9587b7447b3b07215a68e7c4723eebb487c95449867989cfdf16af61ff997
# Verified Classes:   CapabilityWideningError, DriftClass, PinnedSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class CapabilityWideningError(RuntimeError):
    """Raised when a signed manifest re-issue widens the pinned capability set."""
    pass


class DriftClass(Enum):
    NARROW = "narrow"
    WIDEN = "widen"
    QUARANTINE = "quarantine_description"


SIDE_EFFECT_RANK = {"read": 0, "write": 1, "network": 2, "exec": 3}


def canonicalize(manifest: dict[str, Any]) -> bytes:
    # deterministic: sorted keys, strip description (it is never part of the contract hash)
    scrubbed = {
        "tools": sorted(
            (
                {
                    "name": t["name"],
                    "side_effect": t.get("side_effect", "read"),
                    "schema": t.get("schema", {}),
                }
                for t in manifest.get("tools", [])
            ),
            key=lambda t: t["name"],
        )
    }
    return json.dumps(scrubbed, sort_keys=True, separators=(",", ":")).encode()


def manifest_hash(manifest: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(manifest)).hexdigest()


@dataclass
class PinnedSnapshot:
    manifest_hash: str
    tools: dict[str, dict[str, Any]] = field(default_factory=dict)
    approved: bool = False


def _classify_tool(old: dict[str, Any] | None, new: dict[str, Any]) -> DriftClass:
    if old is None:
        return DriftClass.WIDEN  # new tool = new capability
    old_rank = SIDE_EFFECT_RANK.get(old.get("side_effect", "read"), 0)
    new_rank = SIDE_EFFECT_RANK.get(new.get("side_effect", "read"), 0)
    if new_rank > old_rank:
        return DriftClass.WIDEN
    # schema widening: union type, relaxed maxLength, added enum member, added property
    old_s, new_s = old.get("schema", {}), new.get("schema", {})
    if isinstance(new_s.get("type"), list) and not isinstance(old_s.get("type"), list):
        return DriftClass.WIDEN
    if new_s.get("maxLength", 0) > old_s.get("maxLength", 0):
        return DriftClass.WIDEN
    if set(new_s.get("properties", {})) - set(old_s.get("properties", {})):
        return DriftClass.WIDEN
    return DriftClass.NARROW


def admit_manifest(
    fetched: dict[str, Any],
    signature_valid: bool,
    pin: PinnedSnapshot,
    approval_token: str | None = None,
) -> PinnedSnapshot:
    if not signature_valid:
        raise CapabilityWideningError("signature invalid: impersonation, not drift")

    if manifest_hash(fetched) == pin.manifest_hash:
        return pin  # exact continuity, no-op

    fetched_tools = {t["name"]: t for t in fetched.get("tools", [])}
    widenings: list[str] = []
    quarantined: list[str] = []

    for name, tool in fetched_tools.items():
        cls = _classify_tool(pin.tools.get(name), tool)
        if cls is DriftClass.WIDEN:
            widenings.append(name)
        # description is instruction surface: any change is quarantined regardless of class
        if pin.tools.get(name, {}).get("description") != tool.get("description"):
            quarantined.append(name)

    if widenings and approval_token != f"approve:{manifest_hash(fetched)}":
        raise CapabilityWideningError(
            f"signed re-issue widens capabilities {widenings}; "
            f"description drift on {quarantined}; halt at tool-call boundary"
        )

    return PinnedSnapshot(
        manifest_hash=manifest_hash(fetched),
        tools=fetched_tools,
        approved=True,
    )
