# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-late-bound-skill-descriptor-provenance-collapse-at-the-tool-registration-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-late-bound-skill-descriptor-provenance-collapse-at-the-tool-registration-boundary.warrant.json
# Markdown SHA-256:   d495f0ee5fab335b65f1cd043aaa837572878db2d12d7c7dd8086253c69d0a94
# Code AST SHA-256:   c1085493871eab725ac6dd6c3b1e4314e8af3be4d828ed9220793114e98d04f6
# Verified Classes:   SkillProvenanceError, SkillDescriptor, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SkillProvenanceError(RuntimeError):
    """Raised when a skill descriptor's effect warrant cannot be bound to an authorized principal."""
    pass


@dataclass(frozen=True)
class SkillDescriptor:
    name: str
    version: str
    schema_hash: str
    effect_class: str          # e.g. "read_only", "network_egress", "write_local"
    handler_ref: str
    declaring_principal: str
    signature: Optional[str]   # detached sig over canonical descriptor body


@dataclass(frozen=True)
class Warrant:
    principal: str
    allowed_effect_classes: frozenset
    may_relay_skills: bool


def canonical_body(d: SkillDescriptor) -> bytes:
    return "|".join([
        d.name, d.version, d.schema_hash, d.effect_class,
        d.handler_ref, d.declaring_principal,
    ]).encode()


def verify_signature(d: SkillDescriptor, trust_root: dict) -> bool:
    key = trust_root.get(d.declaring_principal)
    if key is None or d.signature is None:
        return False
    expected = hashlib.sha256(key + canonical_body(d)).hexdigest()
    return expected == d.signature


def register_skill(
    descriptor: SkillDescriptor,
    forwarding_principal: str,
    warrants: dict,
    trust_root: dict,
    introspected_capabilities: frozenset,
    from_memory: bool = False,
) -> SkillDescriptor:
    # Invariant 1: signature must bind effect_class to the *declaring* principal.
    if not verify_signature(descriptor, trust_root):
        raise SkillProvenanceError(
            f"descriptor {descriptor.name}@{descriptor.version}: effect_class "
            f"'{descriptor.effect_class}' not signed by declaring principal "
            f"'{descriptor.declaring_principal}'"
        )

    # Invariant 2: the declaring principal's warrant must cover the effect class.
    decl_warrant: Optional[Warrant] = warrants.get(descriptor.declaring_principal)
    if decl_warrant is None or descriptor.effect_class not in decl_warrant.allowed_effect_classes:
        raise SkillProvenanceError(
            f"declaring principal '{descriptor.declaring_principal}' lacks warrant "
            f"for effect_class '{descriptor.effect_class}'"
        )

    # Invariant 3: forwarding peer must be permitted to relay this effect class.
    fwd_warrant: Optional[Warrant] = warrants.get(forwarding_principal)
    if fwd_warrant is None or not fwd_warrant.may_relay_skills:
        raise SkillProvenanceError(
            f"forwarding principal '{forwarding_principal}' may not relay skills"
        )

    # Invariant 4: runtime-introspected capabilities must be a subset of signed class.
    allowed = _effect_class_capabilities(descriptor.effect_class)
    if not introspected_capabilities.issubset(allowed):
        excess = introspected_capabilities - allowed
        raise SkillProvenanceError(
            f"handler for {descriptor.name} declares '{descriptor.effect_class}' "
            f"but introspects capabilities {sorted(excess)}"
        )

    # Invariant 5: memory-reconstructed descriptors must re-verify, never trust stored warrant.
    if from_memory and descriptor.signature is None:
        raise SkillProvenanceError(
            f"memory-reconstructed descriptor {descriptor.name} has no re-verifiable signature"
        )

    return descriptor


def _effect_class_capabilities(effect_class: str) -> frozenset:
    table = {
        "read_only": frozenset({"fs_read"}),
        "write_local": frozenset({"fs_read", "fs_write"}),
        "network_egress": frozenset({"fs_read", "net_egress"}),
    }
    return table.get(effect_class, frozenset())
