# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-manifest-poisoning-from-surviving-mcp-server-re-negotiation-across-agent-restarts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-manifest-poisoning-from-surviving-mcp-server-re-negotiation-across-agent-restarts.warrant.json
# Markdown SHA-256:   83db6253673824365f1fc10f43ec869807cd73665eb92b0d96c6701401070f05
# Code AST SHA-256:   70a531564a9d79439040f8c38a3f13b68a843d16352350c6a04246b6c16b42c5
# Verified Classes:   ManifestPoisoningError, AttestedManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestPoisoningError(RuntimeError):
    """Raised when a tool manifest change violates the semantic trust invariant."""
    pass


SEMANTIC_FIELDS = ("description", "inputSchema", "annotations", "default", "required")


def semantic_digest(tool: dict) -> str:
    payload = {k: tool.get(k) for k in SEMANTIC_FIELDS}
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _loosens(old: dict, new: dict) -> bool:
    old_schema = old.get("inputSchema", {}) or {}
    new_schema = new.get("inputSchema", {}) or {}
    old_props = old_schema.get("properties", {}) or {}
    new_props = new_schema.get("properties", {}) or {}
    for name, new_prop in new_props.items():
        old_prop = old_props.get(name, {})
        if "pattern" in old_prop and "pattern" not in new_prop:
            return True
        if "enum" in old_prop and "enum" not in new_prop:
            return True
        if "enum" in old_prop and "enum" in new_prop:
            if not set(new_prop["enum"]).issubset(set(old_prop["enum"])):
                return True
    old_req = set(old_schema.get("required", []) or [])
    new_req = set(new_schema.get("required", []) or [])
    if old_req - new_req:
        return True
    return False


@dataclass
class AttestedManifest:
    tools: dict = field(default_factory=dict)
    digests: dict = field(default_factory=dict)


def reconcile(
    attested: AttestedManifest,
    fetched: dict,
    allow_loosening: bool = False,
) -> AttestedManifest:
    """Replace, never union. Any semantic change on an existing tool is a trust event."""
    result = AttestedManifest(tools=dict(attested.tools), digests=dict(attested.digests))
    for name, tool in fetched.items():
        new_digest = semantic_digest(tool)
        old_digest = attested.digests.get(name)
        if old_digest is None:
            result.tools[name] = tool
            result.digests[name] = new_digest
            continue
        if old_digest == new_digest:
            continue
        old_tool = attested.tools[name]
        if _loosens(old_tool, tool) and not allow_loosening:
            raise ManifestPoisoningError(
                f"tool {name!r} loosens constraints across re-negotiation: "
                f"digest {old_digest[:12]} -> {new_digest[:12]}; re-attestation required"
            )
        result.tools[name] = tool
        result.digests[name] = new_digest
    return result


def validate_handoff(envelope: dict, local: AttestedManifest) -> None:
    """Every baton must carry the manifest digest; mismatch is rejected pre-execution."""
    carried = envelope.get("manifest_digests", {})
    for name, digest in carried.items():
        if local.digests.get(name) != digest:
            raise ManifestPoisoningError(
                f"handoff digest mismatch for tool {name!r}: "
                f"peer={digest[:12]} local={str(local.digests.get(name))[:12]}"
            )
