# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-dynamically-loaded-skill-after-its-manifest-hash-diverges-from-the-tool-call-surface-it-actually-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-dynamically-loaded-skill-after-its-manifest-hash-diverges-from-the-tool-call-surface-it-actually-executes.warrant.json
# Markdown SHA-256:   e4d020e03ed9a1ef0e21186004b4af6694bcc64e2ea59e035221b44973bc138d
# Code AST SHA-256:   0c2c83963bbc6949cbf34079e937c440fcc99f5285b68d4ec73b9441922325f3
# Verified Classes:   SkillClosureMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from pathlib import Path


class SkillClosureMismatch(RuntimeError):
    """Raised when executed skill bytes are not a subset of verified bytes."""
    pass


def verify_and_load(skill_dir: Path, manifest: dict, registry_root: str,
                    resolved_imports: set[str]) -> None:
    # 1. Manifest hash check (the cheap, insufficient gate).
    manifest_bytes = (skill_dir / "manifest.json").read_bytes()
    got = hashlib.sha256(manifest_bytes).hexdigest()
    if got != manifest["sha256"]:
        raise SkillClosureMismatch(
            f"manifest hash {got} != signed {manifest['sha256']}"
        )

    # 2. Closure containment check (the boundary that actually holds).
    declared = set(manifest.get("declared_deps", []))
    residue = resolved_imports - declared
    if residue:
        # Unpinned imports can be shadowed by a writable cache dir.
        raise SkillClosureMismatch(
            f"skill {manifest['name']} imports undeclared modules: "
            f"{sorted(residue)}; manifest-trust is unsound"
        )

    # 3. Non-shadowable execution check: every resolved module must live
    #    under the content-addressed registry root, not a cache prefix.
    for mod_path in resolved_imports:
        p = Path(mod_path).resolve()
        if not str(p).startswith(str(Path(registry_root).resolve())):
            raise SkillClosureMismatch(
                f"module {p} resolved outside registry root {registry_root}; "
                f"path-shadowing detected"
            )
