# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-manifest-declared-capability-widening-in-a-dynamically-reloaded-mcp-tool-before-the-injected-skill-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-manifest-declared-capability-widening-in-a-dynamically-reloaded-mcp-tool-before-the-injected-skill-executes.warrant.json
# Markdown SHA-256:   79058ed9c2395225c5f773e03d62dd969420a62a1eb1cc48ce65392dbfcd9094
# Code AST SHA-256:   3fd44813c54efa3a7aefbc60bac05c532274ba13806822c056a9772879561968
# Verified Classes:   ManifestWideningError, ToolContract, Manifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ManifestWideningError(RuntimeError):
    """Raised when a hot-reloaded MCP manifest widens capability beyond the session grant."""


@dataclass(frozen=True)
class ToolContract:
    name: str
    input_properties: frozenset[str]
    additional_properties: bool
    side_effect: str  # "read_only" | "read_write"


@dataclass(frozen=True)
class Manifest:
    skill: str
    manifest_hash: str
    tools: dict[str, ToolContract]
    credential_scope: frozenset[str] = field(default_factory=frozenset)


def capability_delta(old: Manifest, new: Manifest) -> dict[str, list[str]]:
    """Return widening axes. Empty dict == narrowing or neutral, safe to reload."""
    widened: dict[str, list[str]] = {}
    for name, new_tool in new.tools.items():
        old_tool = old.tools.get(name)
        if old_tool is None:
            widened.setdefault("added_tools", []).append(name)
            continue
        added_props = new_tool.input_properties - old_tool.input_properties
        if added_props:
            widened.setdefault("added_properties", []).extend(
                f"{name}.{p}" for p in sorted(added_props)
            )
        if new_tool.additional_properties and not old_tool.additional_properties:
            widened.setdefault("relaxed_additional_properties", []).append(name)
        if old_tool.side_effect == "read_only" and new_tool.side_effect == "read_write":
            widened.setdefault("escalated_side_effect", []).append(name)
    return widened


def reload_manifest(current: Manifest, incoming: Manifest, grant_policy: frozenset[str]) -> Manifest:
    """
    Gate a hot reload. Widening deltas must be covered by grant_policy AND the
    incoming credential scope must be re-derived, never inherited from `current`.
    """
    if incoming.manifest_hash == current.manifest_hash:
        return current

    delta = capability_delta(current, incoming)
    if not delta:
        # Narrowing/neutral: safe, but credentials still re-bind to new hash.
        return Manifest(
            skill=incoming.skill,
            manifest_hash=incoming.manifest_hash,
            tools=incoming.tools,
            credential_scope=incoming.credential_scope,
        )

    ungranted = {
        axis: items for axis, items in delta.items()
        if axis not in grant_policy
    }
    if ungranted:
        raise ManifestWideningError(
            f"reload of {incoming.skill} widens capability without grant: {ungranted}; "
            f"old_hash={current.manifest_hash} new_hash={incoming.manifest_hash}"
        )

    # Granted widening: require the incoming manifest to carry a re-derived scope.
    if incoming.credential_scope == current.credential_scope:
        raise ManifestWideningError(
            f"reload of {incoming.skill} widened {list(delta)} but inherited stale "
            f"credential_scope={sorted(current.credential_scope)}; re-derivation required"
        )

    return Manifest(
        skill=incoming.skill,
        manifest_hash=incoming.manifest_hash,
        tools=incoming.tools,
        credential_scope=incoming.credential_scope,
    )
