# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-capability-declaration-as-untrusted-input-rather-than-a-grant-and-what-breaks-when-it-doe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-capability-declaration-as-untrusted-input-rather-than-a-grant-and-what-breaks-when-it-doe.warrant.json
# Markdown SHA-256:   b2998b926e5a2ae864f631a175cd209a2ebe72e5a3110d91631e720835e03ab6
# Code AST SHA-256:   606a8bc95576f8fe1f1515b50ac4858db6a91963f630f93d175735b87950bd99
# Verified Classes:   ManifestQuarantineError, PinnedManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestQuarantineError(RuntimeError):
    """Raised when a tool descriptor fails the capability-diff gate."""
    pass


@dataclass
class PinnedManifest:
    # name -> {"schema_hash": str, "desc_hash": str}
    tools: dict = field(default_factory=dict)


def _hash(obj) -> str:
    blob = json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def admit_manifest(raw_tools: list, pinned: PinnedManifest, first_connect: bool) -> PinnedManifest:
    """
    Gate every tool descriptor against the last-pinned manifest.
    Returns a new pinned manifest containing ONLY admitted tools.
    Raises ManifestQuarantineError if any descriptor changed and is not
    explicitly approved out-of-band.
    """
    if first_connect:
        # No baseline: quarantine everything until an explicit pin exists.
        raise ManifestQuarantineError(
            "first-connect manifest requires out-of-band pin before any tool "
            "is rendered into context"
        )

    admitted = {}
    for tool in raw_tools:
        name = tool.get("name")
        if not name:
            raise ManifestQuarantineError("descriptor missing name")
        schema_h = _hash(tool.get("inputSchema", {}))
        desc_h = _hash(tool.get("description", ""))
        prior = pinned.tools.get(name)

        if prior is None:
            # New tool: never auto-admit, even if name looks plausible.
            raise ManifestQuarantineError(
                f"new tool '{name}' quarantined: no pinned baseline"
            )
        if prior["schema_hash"] != schema_h:
            raise ManifestQuarantineError(
                f"tool '{name}' inputSchema changed; descriptor is untrusted until re-pinned"
            )
        if prior["desc_hash"] != desc_h:
            # Description text is prompt surface: a changed description on an
            # unchanged tool is as dangerous as a new tool.
            raise ManifestQuarantineError(
                f"tool '{name}' description changed; refusing to render new text "
                f"under trusted identity"
            )
        admitted[name] = {"schema_hash": schema_h, "desc_hash": desc_h}

    return PinnedManifest(tools=admitted)
