# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a-signed-tool-manifest-when-the-allowlist-and-the-signature-disagree-about-transitive-skill-expansion.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a-signed-tool-manifest-when-the-allowlist-and-the-signature-disagree-about-transitive-skill-expansion.warrant.json
# Markdown SHA-256:   c0c7692479788bfe824bb167661de1767e58c346837c4da99793d51152710d6b
# Code AST SHA-256:   a05a4b0118de1fa6874d69d6a1fa4c599f9d04c7502358a11827e23645659df2
# Verified Classes:   ManifestClosureMismatch, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ManifestClosureMismatch(RuntimeError):
    """Raised when the expanded tool closure diverges from the authorized set."""


@dataclass
class Manifest:
    roots: dict[str, list[str]]          # skill name -> declared sub-tools
    signature_valid: bool
    closure_hash: str                     # hash over full expansion, not roots


def bind_toolset(
    manifest: Manifest,
    allowlist: frozenset[str],
    expected_closure_hash: str,
) -> frozenset[str]:
    """Return the live tool set only if signature, allowlist, and closure all agree.

    The invariant: live_set == transitive_closure(manifest) == allowlist ∩ closure,
    and the closure hash matches the pinned value.
    """
    if not manifest.signature_valid:
        raise ManifestClosureMismatch("manifest signature failed verification")

    # Expand FIRST, then authorize the expansion -- not the roots.
    closure: set[str] = set()
    for root, subs in manifest.roots.items():
        closure.add(root)
        closure.update(subs)

    if manifest.closure_hash != expected_closure_hash:
        raise ManifestClosureMismatch(
            f"closure hash {manifest.closure_hash!r} != pinned "
            f"{expected_closure_hash!r}; expansion drifted"
        )

    unauthorized = closure - allowlist
    if unauthorized:
        # Reject the whole manifest; do not partially bind.
        raise ManifestClosureMismatch(
            f"closure contains non-allowlisted tools: {sorted(unauthorized)}"
        )

    live = frozenset(closure)
    # Final equality assertion: bound set == authorized closure.
    if live != frozenset(closure & allowlist):
        raise ManifestClosureMismatch("bound set diverged from authorized closure")
    return live
