# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-signed-skill-manifest-whose-tool-description-hashes-match-but-whose-resolved-capability-set-diverges-from-the-signed-int.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-signed-skill-manifest-whose-tool-description-hashes-match-but-whose-resolved-capability-set-diverges-from-the-signed-int.warrant.json
# Markdown SHA-256:   4e55a7e45d06a1ef3697a0584bc15ff1923ccae69cb67c6727e61749ca40d8ed
# Code AST SHA-256:   ddaedd455bd7771ea10cb5a84ee0b3adec9ae3bddba51490f70179ca9d2f7b37
# Verified Classes:   ManifestSemanticDivergence, ToolBinding
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ManifestSemanticDivergence(RuntimeError):
    """Raised when a verified manifest's post-verification projection diverges
    from the hashed capability set the publisher signed for."""


PINNED_HASH_SPECS = {"nfkc-trim-collapse-v1", "raw-bytes-v1"}
HASHED_FIELDS = ("description", "input_schema", "output_schema")


def canonical_bytes(value: Any) -> bytes:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def normalize(text: str, spec: str) -> str:
    if spec == "raw-bytes-v1":
        return text
    if spec == "nfkc-trim-collapse-v1":
        import unicodedata
        return " ".join(unicodedata.normalize("NFKC", text).split()).strip()
    raise ManifestSemanticDivergence(f"unknown hash_spec {spec!r}")


@dataclass
class ToolBinding:
    name: str
    description: str
    input_schema: dict
    output_schema: dict
    description_sha256: str


def project_for_hash(tool: dict, spec: str) -> bytes:
    projection = {}
    for field in HASHED_FIELDS:
        if field not in tool:
            raise ManifestSemanticDivergence(f"tool {tool.get('name')!r} missing hashed field {field!r}")
        value = tool[field]
        if isinstance(value, str):
            value = normalize(value, spec)
        projection[field] = value
    return canonical_bytes(projection)


def verify_and_bind(manifest: dict, signature_ok: bool, binder_overlay: dict) -> list[ToolBinding]:
    if not signature_ok:
        raise ManifestSemanticDivergence("signature verification failed")

    spec = manifest.get("hash_spec")
    if spec not in PINNED_HASH_SPECS:
        raise ManifestSemanticDivergence(f"hash_spec {spec!r} not in pinned allowlist; refusing lenient fallback")

    seen_hashes: dict[str, str] = {}
    bindings: list[ToolBinding] = []

    for tool in manifest["tools"]:
        expected = tool["description_sha256"]
        actual = hashlib.sha256(project_for_hash(tool, spec)).hexdigest()
        if actual != expected:
            raise ManifestSemanticDivergence(
                f"tool {tool['name']!r} hash mismatch under pinned spec {spec}: expected {expected}, got {actual}"
            )

        if actual in seen_hashes:
            raise ManifestSemanticDivergence(
                f"tool identity collision: {tool['name']!r} and {seen_hashes[actual]!r} share hash {actual}"
            )
        seen_hashes[actual] = tool["name"]

        # Binder may only add to a non-hashed extension namespace.
        for key in binder_overlay:
            if key in HASHED_FIELDS:
                raise ManifestSemanticDivergence(
                    f"binder overlay touches hashed field {key!r} on tool {tool['name']!r}"
                )

        bindings.append(ToolBinding(
            name=tool["name"],
            description=tool["description"],
            input_schema=tool["input_schema"],
            output_schema=tool["output_schema"],
            description_sha256=actual,
        ))

    return bindings
