# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-manifest-as-a-trust-boundary-crossing-rather-than-a-capability-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-manifest-as-a-trust-boundary-crossing-rather-than-a-capability-grant.warrant.json
# Markdown SHA-256:   1a693744174476deb716a390ddd186921f8421f28785bf6cab9c4e4fec4859bb
# Code AST SHA-256:   f2687ce42c5c8b23c69e850e42df6a235723d79cf182f1e5f71918f551dc3edd
# Verified Classes:   ManifestProvenanceError, TrustRoot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestProvenanceError(RuntimeError):
    """Raised when a dynamically loaded manifest crosses the trust boundary
    with unpinned instructional fields."""


STRUCTURAL_FIELDS = ("name", "parameters", "handler")
INSTRUCTIONAL_FIELDS = ("description", "when_to_use", "argument_hints", "examples")


@dataclass
class TrustRoot:
    # content-hash -> signature, pinned at cold start
    signed_hashes: dict[str, str] = field(default_factory=dict)

    def is_signed(self, content_hash: str) -> bool:
        return content_hash in self.signed_hashes


def manifest_hash(manifest: dict) -> str:
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def classify_change(prior: dict, new: dict) -> tuple[set[str], set[str]]:
    structural = {f for f in STRUCTURAL_FIELDS if prior.get(f) != new.get(f)}
    instructional = {f for f in INSTRUCTIONAL_FIELDS if prior.get(f) != new.get(f)}
    return structural, instructional


def admit_manifest(prior: dict, new: dict, trust: TrustRoot) -> str:
    """Return 'accept' | 'quarantine' | 'reject'. Raise on the unsafe intersection."""
    content_hash = manifest_hash(new)
    structural, instructional = classify_change(prior, new)

    if trust.is_signed(content_hash):
        return "accept"

    if not structural and not instructional:
        return "accept"  # no-op refresh

    if instructional and not structural:
        # The invisible case: schema checks pass, injection channel is open.
        # Quarantine is mandatory; never merge instructional text unsigned.
        return "quarantine"

    if structural:
        # Structural change with side-effect reach requires a signed hash.
        raise ManifestProvenanceError(
            f"unsigned structural change in fields {sorted(structural)}; "
            f"content_hash={content_hash[:12]} not in trust root"
        )

    return "quarantine"


def render_tool_block(manifest: dict, decision: str, prior: dict) -> dict:
    if decision == "reject":
        raise ManifestProvenanceError("refusing to render rejected manifest")
    if decision == "quarantine":
        # Keep prior instructional text; never let unsigned description reach context.
        merged = {**manifest}
        for f in INSTRUCTIONAL_FIELDS:
            merged[f] = prior.get(f)
        return merged
    return manifest
