# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-registered-tool-manifest-silent-schema-supersession-in-dynamically-loaded-plugin-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-registered-tool-manifest-silent-schema-supersession-in-dynamically-loaded-plugin-registries.warrant.json
# Markdown SHA-256:   f613ccb863f885944d3d5eebf0e272ad9ad9e3374782ef56677209cdd9c5504f
# Code AST SHA-256:   b284a83b31d8756f25d449db4b09abb0842d6dc29be499c94fa76143b5583509
# Verified Classes:   ManifestSupersessionError, UntrustedDescriptionError, ToolManifest, AgentToolCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ManifestSupersessionError(RuntimeError):
    """Raised when a cached tool manifest's hash diverges from the registry's current manifest."""
    pass


class UntrustedDescriptionError(RuntimeError):
    """Raised when manifest description text is promoted to instruction trust tier."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    name: str
    schema: dict[str, Any]
    description: str
    handler_version: str

    def identity_hash(self) -> str:
        payload = json.dumps(
            {
                "name": self.name,
                "schema": self.schema,
                "description": self.description,
                "handler_version": self.handler_version,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


@dataclass
class AgentToolCache:
    manifests: dict[str, ToolManifest] = field(default_factory=dict)
    hashes: dict[str, str] = field(default_factory=dict)

    def load(self, manifest: ToolManifest) -> None:
        self.manifests[manifest.name] = manifest
        self.hashes[manifest.name] = manifest.identity_hash()


def resolve_and_authorize(
    cache: AgentToolCache,
    registry: dict[str, ToolManifest],
    tool_name: str,
    require_description_quarantine: bool = True,
) -> ToolManifest:
    current = registry.get(tool_name)
    if current is None:
        raise ManifestSupersessionError(f"tool {tool_name!r} vanished from registry")

    cached_hash = cache.hashes.get(tool_name)
    current_hash = current.identity_hash()

    if cached_hash is not None and cached_hash != current_hash:
        # Supersession detected before the call executes. Do NOT silently adopt.
        raise ManifestSupersessionError(
            f"tool {tool_name!r} manifest superseded: cached={cached_hash[:12]} "
            f"current={current_hash[:12]}; re-authorization required"
        )

    if require_description_quarantine and _looks_like_instruction(current.description):
        raise UntrustedDescriptionError(
            f"tool {tool_name!r} description contains instruction-tier text; "
            f"quarantine before injecting into prompt"
        )

    cache.load(current)
    return current


def _looks_like_instruction(description: str) -> bool:
    markers = ("prepend", "note to agent", "always", "you must", "include the contents")
    lowered = description.lower()
    return any(m in lowered for m in markers)


def call_tool_with_effect_check(
    cache: AgentToolCache,
    registry: dict[str, ToolManifest],
    tool_name: str,
    args: dict[str, Any],
    expected_min_output_len: int,
    handler,
) -> Any:
    manifest = resolve_and_authorize(cache, registry, tool_name)

    # Server-side re-validation against the CURRENT schema, not the cached one.
    max_len = manifest.schema.get("properties", {}).get("text", {}).get("maxLength")
    if max_len is not None and len(args.get("text", "")) > max_len:
        raise ManifestSupersessionError(
            f"args exceed current schema bound {max_len} for {tool_name!r}; "
            f"cached schema was wider"
        )

    result = handler(args)

    # Effect-level post-condition check: the call succeeded, but did it do what we believed?
    if isinstance(result, str) and len(result) < expected_min_output_len:
        raise ManifestSupersessionError(
            f"{tool_name!r} returned {len(result)} chars, expected >= {expected_min_output_len}; "
            f"possible silent truncation under superseded handler"
        )
    return result
