# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-s-self-description-after-a-manifest-re-negotiation-and-where-does-the-skill-injection-boundary-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-s-self-description-after-a-manifest-re-negotiation-and-where-does-the-skill-injection-boundary-collapse.warrant.json
# Markdown SHA-256:   198a6a683646b485f29b9edf3e725bba2a761a49e2864531de0fd32b8f87aaee
# Code AST SHA-256:   ab3ba11b199c2666eb24080e70f8316a908e37060fefcd30899b0e3d366988e7
# Verified Classes:   ManifestDriftError, ToolTrust
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestDriftError(RuntimeError):
    """Raised when a re-negotiated tool manifest mutates a security-relevant
    field of a tool whose trust was established at handshake."""
    pass


SECURITY_RELEVANT_FIELDS = ("description", "inputSchema")


@dataclass
class ToolTrust:
    name: str
    content_hash: str
    trusted: bool = True
    mutable_fields: frozenset = field(default_factory=frozenset)


def _hash_tool(tool: dict, fields=SECURITY_RELEVANT_FIELDS) -> str:
    h = hashlib.sha256()
    for f in fields:
        h.update(f.encode())
        h.update(repr(tool.get(f, "")).encode())
    return h.hexdigest()


def negotiate_initial(tool: dict) -> ToolTrust:
    # At handshake we accept declared mutability, but only for fields the
    # operator has agreed may vary without re-validation.
    mutable = frozenset(tool.get("x-mutable-fields", []))
    fields = tuple(f for f in SECURITY_RELEVANT_FIELDS if f not in mutable)
    return ToolTrust(name=tool["name"], content_hash=_hash_tool(tool, fields),
                     mutable_fields=mutable)


def renegotiate(cached: ToolTrust, incoming: dict) -> ToolTrust:
    """Handle a tools/list_changed re-fetch. Trust is hash-keyed, never
    name-keyed. Any drift in a non-mutable security-relevant field is a
    trust-boundary crossing and must fail closed."""
    if incoming["name"] != cached.name:
        raise ManifestDriftError(
            f"tool name changed {cached.name!r} -> {incoming['name']!r}")

    fields = tuple(f for f in SECURITY_RELEVANT_FIELDS
                   if f not in cached.mutable_fields)
    new_hash = _hash_tool(incoming, fields)

    if new_hash != cached.content_hash:
        # Do NOT refresh in place. Surface the drift and withhold the tool.
        raise ManifestDriftError(
            f"security-relevant manifest drift for {cached.name!r}: "
            f"trust revoked, tool quarantined pending re-validation")

    return cached  # unchanged content -> trust legitimately carries forward
