# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-manifest-as-untrusted-state-rather-than-trusted-code-the-descriptor-residency-invariant-and-its-violation-via-post.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-manifest-as-untrusted-state-rather-than-trusted-code-the-descriptor-residency-invariant-and-its-violation-via-post.warrant.json
# Markdown SHA-256:   8b6492a284e121f8f63d18180f9a0fe23596765d8b993169ab95a57ba8d61d4c
# Code AST SHA-256:   f3b43375a5b33597e307899942f11e250bb80e990787f1a14ec47c6ea03cad42
# Verified Classes:   DescriptorTrustViolation, PinnedManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DescriptorTrustViolation(RuntimeError):
    """Raised when a tool manifest diverges from its pinned baseline mid-session."""
    pass


@dataclass
class PinnedManifest:
    server_id: str
    baseline_hash: str
    descriptors: dict = field(default_factory=dict)


def _hash_descriptor_block(payload: dict) -> str:
    # Canonicalize: sort keys so prose-only mutations are still detected.
    canonical = repr(sorted((t.get("name"), t.get("description", ""),
                             repr(sorted(t.get("parameters", {}).items())))
                            for t in payload.get("tools", [])))
    return hashlib.sha256(canonical.encode()).hexdigest()


def admit_manifest(pinned: PinnedManifest, fresh_payload: dict,
                   reattested: bool = False) -> PinnedManifest:
    """Gate descriptor re-entry into the prompt. Returns the manifest to render."""
    fresh_hash = _hash_descriptor_block(fresh_payload)

    if fresh_hash == pinned.baseline_hash:
        return pinned  # unchanged: safe to re-render

    # Divergence detected. Prose-only mutations are the dangerous case.
    if not reattested:
        raise DescriptorTrustViolation(
            f"server {pinned.server_id!r} manifest mutated "
            f"(baseline {pinned.baseline_hash[:12]} -> {fresh_hash[:12]}); "
            f"refusing to admit untrusted descriptor. "
            f"Keep pinned (stale-but-trusted) or re-attest explicitly."
        )

    # Re-attested: promote fresh payload to new baseline, persist to checkpoint.
    return PinnedManifest(
        server_id=pinned.server_id,
        baseline_hash=fresh_hash,
        descriptors={t["name"]: t for t in fresh_payload.get("tools", [])},
    )
