# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-renegotiated-tool-manifest-as-trusted-state-after-a-capability-hot-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-renegotiated-tool-manifest-as-trusted-state-after-a-capability-hot-swap.warrant.json
# Markdown SHA-256:   9fdb0d86be4e82203046efec2fee8e267672bfdbf9bd4256b1df149924b4527d
# Code AST SHA-256:   dc50c3972522cf8b86e125fdaa26b5c7fbf6dfbb1630d1be9308f6948643a7ee
# Verified Classes:   ManifestTrustViolation, ToolTrustCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ManifestTrustViolation(RuntimeError):
    """Raised when a renegotiated tool manifest mutates a trusted entry."""
    pass


def canonical_hash(entry: dict[str, Any]) -> str:
    # Full serialization: name, description, params (types, desc, defaults), returns.
    # Defaults MUST be included — an unrendered default is an unread instruction.
    blob = json.dumps(entry, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode()).hexdigest()


@dataclass
class ToolTrustCache:
    # Trust keyed by NAME -> content hash at time of vetting.
    trusted: dict[str, str] = field(default_factory=dict)
    quarantined: set[str] = field(default_factory=set)

    def vet(self, entry: dict[str, Any]) -> None:
        name = entry["name"]
        self.trusted[name] = canonical_hash(entry)
        self.quarantined.discard(name)

    def reconcile(self, fresh_manifest: list[dict[str, Any]]) -> list[str]:
        """Apply a mid-session tools/list refresh. Returns names now quarantined."""
        changed: list[str] = []
        for entry in fresh_manifest:
            name = entry["name"]
            new_hash = canonical_hash(entry)
            old_hash = self.trusted.get(name)
            if old_hash is None:
                # Never-vetted tool: quarantine until first approval.
                self.quarantined.add(name)
                changed.append(name)
            elif old_hash != new_hash:
                # Same name, different contract: TRUST INVALIDATION, not cache miss.
                self.trusted.pop(name, None)
                self.quarantined.add(name)
                changed.append(name)
        return changed

    def render_for_prompt(self, manifest: list[dict[str, Any]]) -> str:
        """Only vetted-and-unchanged tools may have their descriptions rendered.
        Rendering a quarantined description IS the injection."""
        lines: list[str] = []
        for entry in manifest:
            name = entry["name"]
            if name in self.quarantined:
                lines.append(f"- {name}: [CHANGED SINCE LAST USE — RE-APPROVAL REQUIRED]")
                continue
            if self.trusted.get(name) != canonical_hash(entry):
                raise ManifestTrustViolation(
                    f"render called on unvetted/changed entry {name!r}; "
                    f"reconcile() must run before render"
                )
            params = entry.get("parameters", {})
            rendered = ", ".join(
                f"{p}={spec.get('type')}(default={spec.get('default', '<none>')!r})"
                for p, spec in params.items()
            )
            lines.append(f"- {name}({rendered}): {entry.get('description', '')}")
        return "\n".join(lines)


def invoke(cache: ToolTrustCache, name: str, args: dict[str, Any]) -> Any:
    if name in cache.quarantined:
        raise ManifestTrustViolation(
            f"refusing to invoke {name!r}: capability contract changed since vetting; "
            f"re-approval required before execution"
        )
    if name not in cache.trusted:
        raise ManifestTrustViolation(f"refusing to invoke unvetted tool {name!r}")
    # ... dispatch to executor ...
    return None
