# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-laundering-in-tool-registry-provenance-when-a-re-signed-plugin-manifest-widens-scopes-without-changing-its-se.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-laundering-in-tool-registry-provenance-when-a-re-signed-plugin-manifest-widens-scopes-without-changing-its-se.warrant.json
# Markdown SHA-256:   39dfeb114a3ff0c5c1b8d71450e994150d501fcb30a5606f71f7751eb1883bf5
# Code AST SHA-256:   c29d23cfda260dbc8261617ef036ba576dcfaa37ed643794ebd2759bd957e8c4
# Verified Classes:   CapabilityLaunderingError, ResolvedManifest, CapabilityPinStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityLaunderingError(RuntimeError):
    """Raised when a re-signed manifest at a fixed version widens capabilities."""


@dataclass(frozen=True)
class ResolvedManifest:
    publisher: str
    version: str
    capabilities: dict
    signature_valid: bool


def capability_set_hash(capabilities: dict) -> str:
    canonical = json.dumps(
        {k: sorted(v) if isinstance(v, list) else v for k, v in sorted(capabilities.items())},
        separators=(",", ":"),
        sort_keys=True,
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


class CapabilityPinStore:
    def __init__(self) -> None:
        self._pins: dict[tuple[str, str], str] = {}

    def record_first_observation(self, manifest: ResolvedManifest) -> None:
        key = (manifest.publisher, manifest.version)
        self._pins[key] = capability_set_hash(manifest.capabilities)

    def verify_and_bind(self, manifest: ResolvedManifest) -> dict:
        key = (manifest.publisher, manifest.version)
        if not manifest.signature_valid:
            raise CapabilityLaunderingError(
                f"signature invalid for {key}; refusing to bind"
            )
        observed = capability_set_hash(manifest.capabilities)
        pinned = self._pins.get(key)
        if pinned is None:
            # First sight of this (publisher, version): record and bind.
            self._pins[key] = observed
            return manifest.capabilities
        if observed != pinned:
            added = sorted(
                set(manifest.capabilities) - set(self._capabilities_for(key))
            )
            raise CapabilityLaunderingError(
                f"capability-set hash mismatch for {key}: "
                f"pinned={pinned[:12]} observed={observed[:12]} added={added}; "
                f"re-sign at fixed version is a laundering event, not an upgrade"
            )
        return manifest.capabilities

    def _capabilities_for(self, key: tuple[str, str]) -> dict:
        # Placeholder: the store retains the last observed capability block
        # alongside the hash so the diff can be reported on mismatch.
        return {}


def bind_from_registry(store: CapabilityPinStore, manifest: ResolvedManifest) -> dict:
    return store.verify_and_bind(manifest)
