# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-silent-capability-escalation-when-a-skill-manifest-diffs-clean-but-its-granted-tool-surface-grows.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-silent-capability-escalation-when-a-skill-manifest-diffs-clean-but-its-granted-tool-surface-grows.warrant.json
# Markdown SHA-256:   0be2722c9f2fb8bf69270c7de707cc16e9802a571a3d919873917c9f926514c9
# Code AST SHA-256:   9d58d1a93edad8324e3dce8a0267f27b8e620578eeaf35c287fa37660bae8310
# Verified Classes:   CapabilityEscalationError, ToolSurface, SkillBinding
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class CapabilityEscalationError(RuntimeError):
    """Raised when the effective granted tool surface grows beyond the attested surface
    without a matching, operator-approved manifest delta."""


@dataclass(frozen=True)
class ToolSurface:
    """Normalized, resolved view of one bound tool as the runtime will actually expose it."""
    name: str
    provider_version: str
    arg_schema: dict[str, Any]
    open_schema: bool  # True if additionalProperties permits arbitrary keys anywhere

    def fingerprint(self) -> str:
        # Schema normalization: sort keys, drop descriptions, keep structural openness.
        canon = json.dumps(
            {
                "name": self.name,
                "provider_version": self.provider_version,
                "arg_schema": _canon(self.arg_schema),
                "open_schema": self.open_schema,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canon.encode()).hexdigest()


def _canon(node: Any) -> Any:
    if isinstance(node, dict):
        return {k: _canon(v) for k, v in sorted(node.items()) if k not in ("description", "title")}
    if isinstance(node, list):
        return [_canon(v) for v in node]
    return node


@dataclass
class SkillBinding:
    skill_id: str
    manifest_hash: str
    attested: dict[str, str] = field(default_factory=dict)  # tool name -> fingerprint


def _is_subset(attested: dict[str, str], current: dict[str, str]) -> bool:
    """True iff every current tool is present in attested with an identical fingerprint.
    A changed fingerprint under a stable name counts as growth (schema widening, provider drift)."""
    return all(attested.get(name) == fp for name, fp in current.items())


def check_binding(
    binding: SkillBinding,
    resolved: list[ToolSurface],
    manifest_hash_now: str,
    approved_delta: dict[str, str] | None = None,
) -> None:
    current = {t.name: t.fingerprint() for t in resolved}

    if _is_subset(binding.attested, current):
        return  # no growth; silent proceed

    manifest_changed = manifest_hash_now != binding.manifest_hash
    delta = approved_delta or {}

    # Growth is acceptable only if the manifest actually changed AND the new fingerprints
    # appear in an operator-approved delta. Everything else is escalation.
    if manifest_changed and all(current.get(n) == fp for n, fp in delta.items()):
        binding.attested = current
        binding.manifest_hash = manifest_hash_now
        return

    grown = sorted(n for n, fp in current.items() if binding.attested.get(n) != fp)
    raise CapabilityEscalationError(
        f"skill {binding.skill_id!r}: effective surface grew beyond attestation "
        f"on tools {grown}; manifest_changed={manifest_changed}, "
        f"approved_delta={sorted(delta)}. Halting and quarantining session."
    )


# --- observed failure replay -------------------------------------------------

def replay_provider_drift() -> None:
    binding = SkillBinding(
        skill_id="report-writer@1.4.2",
        manifest_hash="a1b2c3",
        attested={
            "search": ToolSurface(
                name="search",
                provider_version="2.1.0",
                arg_schema={"query": {"type": "string"}},
                open_schema=False,
            ).fingerprint(),
            "render_markdown": ToolSurface(
                name="render_markdown",
                provider_version="1.0.0",
                arg_schema={"text": {"type": "string"}, "options": {"type": "object"}},
                open_schema=True,
            ).fingerprint(),
        },
    )

    # Provider auto-upgraded 2.1.0 -> 2.3.0; skill manifest bytes unchanged.
    drifted = [
        ToolSurface(
            name="search",
            provider_version="2.3.0",
            arg_schema={
                "query": {"type": "string"},
                "mode": {"type": "string", "enum": ["query", "fetch"]},
            },
            open_schema=False,
        ),
        ToolSurface(
            name="render_markdown",
            provider_version="1.0.0",
            arg_schema={"text": {"type": "string"}, "options": {"type": "object"}},
            open_schema=True,
        ),
    ]

    # Manifest hash identical -> no approved delta -> must raise.
    check_binding(binding, drifted, manifest_hash_now="a1b2c3")


if __name__ == "__main__":
    replay_provider_drift()
