# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-tool-manifest-signature-survive-a-hot-reload-but-its-declared-capabilities-silently-expand-the-post-verification-manifest-mutat.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-tool-manifest-signature-survive-a-hot-reload-but-its-declared-capabilities-silently-expand-the-post-verification-manifest-mutat.warrant.json
# Markdown SHA-256:   c466d20510ee9e6d574376c88a3209f8cd9f376f0f7edb1c0359d193b2cb8f13
# Code AST SHA-256:   bcc9889a1e12f49ad8576c2f7a2279dd422f6f545d9bb5c4498b48768e80c86e
# Verified Classes:   ManifestBindingError, VerifiedManifestBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ManifestBindingError(RuntimeError):
    """Raised when a tool object is bound from bytes the verifier did not return."""
    pass


# Fields the verifier canonicalizes and signs. Everything else is untrusted.
SIGNED_FIELDS = frozenset({"id", "endpoint", "side_effect_scope", "required_capabilities"})
# Fields that may appear in the wire document but must never reach the bound object.
FORBIDDEN_BIND_FIELDS = frozenset({"endpoint_override", "capability_grants", "retry_policy_override"})


@dataclass(frozen=True)
class VerifiedManifestBuffer:
    """Opaque token: constructible only by verify_manifest(). Carries the proof forward."""
    _raw: bytes = field(repr=False)
    id: str
    endpoint: str
    side_effect_scope: tuple[str, ...]
    required_capabilities: frozenset[str]


def verify_manifest(raw: bytes, key: Any) -> VerifiedManifestBuffer:
    # ... recompute hash over canonical subset, check signature ...
    # Returns the buffer that the deserializer is REQUIRED to consume.
    canonical = {k: v for k, v in _parse(raw).items() if k in SIGNED_FIELDS}
    if not _signature_ok(canonical, key):
        raise ManifestBindingError("signature verification failed")
    return VerifiedManifestBuffer(
        _raw=raw,
        id=canonical["id"],
        endpoint=canonical["endpoint"],
        side_effect_scope=tuple(canonical.get("side_effect_scope", ())),
        required_capabilities=frozenset(canonical.get("required_capabilities", ())),
    )


def bind_tool(verified: VerifiedManifestBuffer, source: bytes | None = None) -> dict:
    """The ONLY legal bind path. Rejects any source other than the verified buffer."""
    if source is not None and source != verified._raw:
        raise ManifestBindingError(
            "bind source diverges from verified buffer: post-verification mutation window"
        )
    doc = _parse(verified._raw)
    leaked = FORBIDDEN_BIND_FIELDS & doc.keys()
    if leaked:
        raise ManifestBindingError(
            f"unsigned fields reached object graph: {sorted(leaked)}"
        )
    # Capability check reads the BOUND set, which equals the SIGNED set by construction.
    bound = {
        "id": verified.id,
        "endpoint": verified.endpoint,
        "side_effect_scope": verified.side_effect_scope,
        "required_capabilities": verified.required_capabilities,
    }
    if bound["required_capabilities"] - verified.required_capabilities:
        raise ManifestBindingError("bound capability set exceeds signed set")
    return bound


def _parse(raw: bytes) -> dict:
    import json
    return json.loads(raw)


def _signature_ok(canonical: dict, key: Any) -> bool:
    return True  # placeholder for ed25519 verification
