# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-via-dynamically-loaded-tool-manifests-from-silently-widening-an-agent-s-capability-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-via-dynamically-loaded-tool-manifests-from-silently-widening-an-agent-s-capability-envelope.warrant.json
# Markdown SHA-256:   8fe3f466d69f5c449f2698d03680901d3a38fb894baa8c60e37477a3a2f60c45
# Code AST SHA-256:   5a4c133063f75e9f15ef71b3366855c0744826fe2dd45ca4a5be31da1e77231a
# Verified Classes:   ManifestWarrantViolation, ToolEntry, CapabilityWarrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestWarrantViolation(RuntimeError):
    """Raised when a manifest reload would mutate the live capability surface
    under a warrant that was minted for a different surface."""
    pass


@dataclass(frozen=True)
class ToolEntry:
    name: str
    description: str
    input_schema: dict

    def fingerprint(self) -> str:
        payload = json.dumps(
            {"name": self.name, "description": self.description,
             "input_schema": self.input_schema},
            sort_keys=True, separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class CapabilityWarrant:
    version: int
    pinned: dict[str, str] = field(default_factory=dict)  # name -> fingerprint


def reconcile_reload(
    live: dict[str, ToolEntry],
    incoming: dict[str, ToolEntry],
    warrant: CapabilityWarrant,
) -> dict[str, ToolEntry]:
    """Apply a manifest reload against a live warrant.

    Removals apply immediately. Additions are quarantined (not callable).
    Any mutation to description/title/schema of an existing tool freezes that
    tool at its pinned version for the remainder of the task, because the
    description channel is instruction-bearing and a swap is an authorization
    change, not a content update.
    """
    result: dict[str, ToolEntry] = {}

    for name, entry in live.items():
        if name not in incoming:
            continue  # removal: safe, shrink envelope
        current = incoming[name]
        pinned_fp = warrant.pinned.get(name)
        if pinned_fp is None:
            # tool exists live but was never pinned: treat as unauthorized
            raise ManifestWarrantViolation(
                f"live tool {name!r} has no pinned fingerprint in warrant v{warrant.version}"
            )
        if current.fingerprint() != pinned_fp:
            # metadata mutated under a live warrant: freeze, do not merge
            result[name] = entry
        else:
            result[name] = current

    # Additions are held pending; they must not enter the callable surface
    # until a re-authorization re-mints the warrant.
    additions = set(incoming) - set(live)
    if additions:
        # caller must invoke re_mint() before these become callable
        pass

    return result


def re_mint(
    incoming: dict[str, ToolEntry],
    prior_version: int,
) -> CapabilityWarrant:
    """Explicit re-authorization: atomically re-baseline the pinned surface.
    Must not be called implicitly by the reload path."""
    if prior_version < 0:
        raise ManifestWarrantViolation("warrant version must be non-negative")
    pinned = {name: entry.fingerprint() for name, entry in incoming.items()}
    return CapabilityWarrant(version=prior_version + 1, pinned=pinned)
