# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-skill-registry-signature-validity-as-independent-of-the-skill-s-declared-capability-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-skill-registry-signature-validity-as-independent-of-the-skill-s-declared-capability-manifest.warrant.json
# Markdown SHA-256:   be4547ecdef896fbca1ded38f8b424a6c924138589d278ea859f2cfab5ae10e1
# Code AST SHA-256:   da63a1124a84c50df0ff07319a2f6d49bf2cf640ae316840ca5452aeaeccff7b
# Verified Classes:   CapabilityInjectionError, SignedArtifact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class CapabilityInjectionError(RuntimeError):
    """Raised when a signed artifact's effective authority exceeds its derived authority."""


@dataclass(frozen=True)
class SignedArtifact:
    publisher: str
    payload: bytes
    signature_valid: bool
    declared_scopes: frozenset[str]
    declared_bindings: Mapping[str, str]  # binding name -> content hash at signing


def derive_scopes_from_identity(publisher: str) -> frozenset[str]:
    # Authority comes from the registry, never from the artifact.
    registry = {"trusted-pub": frozenset({"read:public"})}
    return registry.get(publisher, frozenset())


def resolve_binding(name: str) -> str:
    # Live registry lookup: name -> current content hash.
    live = {"http_fetch": "sha256:deadbeef", "search": "sha256:cafe"}
    if name not in live:
        raise CapabilityInjectionError(f"unresolvable binding: {name}")
    return live[name]


def admit(artifact: SignedArtifact, caller_scopes: frozenset[str]) -> frozenset[str]:
    if not artifact.signature_valid:
        raise CapabilityInjectionError("integrity gate failed: bad signature")

    derived = derive_scopes_from_identity(artifact.publisher)
    if not artifact.declared_scopes <= derived:
        raise CapabilityInjectionError(
            f"authority gate failed: declared {artifact.declared_scopes} "
            f"exceeds derived {derived}"
        )

    for name, signed_hash in artifact.declared_bindings.items():
        live_hash = resolve_binding(name)
        if live_hash != signed_hash:
            raise CapabilityInjectionError(
                f"binding {name} resolved to {live_hash}, signed as {signed_hash}"
            )

    effective = artifact.declared_scopes
    if not effective <= caller_scopes:
        raise CapabilityInjectionError(
            "non-attenuating delegation: skill scopes exceed caller scopes"
        )
    return effective
