# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-side-effect-class-over-its-observed-side-effect-class.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-side-effect-class-over-its-observed-side-effect-class.warrant.json
# Markdown SHA-256:   1ef88c364e125f1541eb06dc18fc6520d69aa9243d5fa6333be44d5090e41735
# Code AST SHA-256:   cf3f167e8179467081edea13d5e5626dcc781ccf0636651e8eac5632cf74b9a3
# Verified Classes:   ManifestTrustError, PinnedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestTrustError(RuntimeError):
    """Raised when a tool manifest's declared class cannot be trusted for gating."""
    pass


@dataclass(frozen=True)
class PinnedTool:
    name: str
    digest: str
    declared_read_only: bool
    publisher_key_id: str


def gate_invocation(
    manifest: dict,
    pinned: PinnedTool | None,
    trust_root: set[str],
    observed_class: str | None,
) -> str:
    """Return 'allow', 'sandbox', or 'quarantine'. Never trust declared class alone."""
    body = json.dumps(
        {k: manifest[k] for k in ("name", "inputSchema", "description", "handler")},
        sort_keys=True,
    ).encode()
    digest = "sha256:" + hashlib.sha256(body).hexdigest()

    if pinned is None or pinned.digest != digest:
        # New or re-published tool: name-based trust does not carry over.
        if pinned is not None and pinned.name == manifest.get("name"):
            raise ManifestTrustError(
                f"digest changed for {pinned.name!r}: pinned {pinned.digest} "
                f"!= resolved {digest}; re-approval required regardless of declared class"
            )
        return "sandbox"  # first invocation of an unpinned digest

    if manifest.get("publisherKeyId") not in trust_root:
        raise ManifestTrustError(
            f"publisher {manifest.get('publisherKeyId')!r} not in runtime trust root"
        )

    declared_ro = bool(manifest.get("readOnlyHint", False))
    if declared_ro and observed_class is None:
        # Read-only claim with no observation yet: do not let it skip the sandbox.
        return "sandbox"
    if declared_ro and observed_class not in ("read_only",):
        raise ManifestTrustError(
            f"declared read-only but observed {observed_class!r} for {pinned.name!r}; "
            "quarantine digest"
        )
    if not declared_ro and observed_class == "read_only":
        # Harmless mismatch; still record it, do not fail closed on under-claim.
        return "allow"
    return "allow"
