# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-manifest-signature-boundary-failure-during-hot-reload-of-a-dynamically-registered-agent-skill.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-manifest-signature-boundary-failure-during-hot-reload-of-a-dynamically-registered-agent-skill.warrant.json
# Markdown SHA-256:   ff3bb26a550038c7da5eb7d588acce6d670229182c601b454bec61341bc8b346
# Code AST SHA-256:   243dbc5b69802107ddf4adc386edb614dc722f3d8e4f7801baeba38d6dfdc52a
# Verified Classes:   ManifestBodyBindingError, SignedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import os
import importlib.util
from dataclasses import dataclass


class ManifestBodyBindingError(RuntimeError):
    """Raised when a signed manifest no longer binds to the bytes about to execute."""
    pass


@dataclass
class SignedManifest:
    name: str
    version: str
    entrypoint: str          # declared, relative to skill_root
    sha256: str              # hash of the body the signer attested to
    capabilities: frozenset  # signed capability set
    signature_valid: bool


def load_skill(manifest: SignedManifest, skill_root: str, requested_caps: frozenset):
    if not manifest.signature_valid:
        raise ManifestBodyBindingError(f"{manifest.name}: manifest signature invalid")

    # Resolve entrypoint and assert containment AFTER symlink resolution.
    declared = os.path.normpath(os.path.join(skill_root, manifest.entrypoint))
    resolved = os.path.realpath(declared)
    root_real = os.path.realpath(skill_root)
    if not resolved.startswith(root_real + os.sep):
        raise ManifestBodyBindingError(
            f"{manifest.name}: entrypoint realpath {resolved!r} escapes skill root "
            f"{root_real!r} (declared {manifest.entrypoint!r}) — body substitution"
        )

    # Re-derive the body hash at execution time; never trust a cached manifest alone.
    with open(resolved, "rb") as fh:
        body = fh.read()
    actual = hashlib.sha256(body).hexdigest()
    if actual != manifest.sha256:
        raise ManifestBodyBindingError(
            f"{manifest.name}: body hash {actual} != signed {manifest.sha256} — "
            f"manifest/body binding severed"
        )

    # Capability grants must be derived from the signed manifest, not skill name.
    unauthorized = requested_caps - manifest.capabilities
    if unauthorized:
        raise ManifestBodyBindingError(
            f"{manifest.name}: requested capabilities {sorted(unauthorized)} "
            f"absent from signed manifest {sorted(manifest.capabilities)}"
        )

    spec = importlib.util.spec_from_file_location(manifest.name, resolved)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module
