# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-re-imported-skill-binary-has-silently-drifted-from-its-attested-capability-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-re-imported-skill-binary-has-silently-drifted-from-its-attested-capability-envelope.warrant.json
# Markdown SHA-256:   7e309e217626da7f1f94784fadd95791f0f7b6d8855d094c22d00a2f357129b6
# Code AST SHA-256:   2bf4038b01df38cd96feab7f34286fc92c733cda86559d2031188991fbf6855d
# Verified Classes:   ProvenanceDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from pathlib import Path


class ProvenanceDriftError(RuntimeError):
    """Raised when the artifact about to execute does not match its attested manifest."""
    pass


def load_skill(skill_dir: Path, trusted_manifest: dict) -> dict:
    """
    Load a skill only if the on-disk artifact hash-matches the signed manifest.
    Sidecar metadata is never trusted as proof; it is re-derived on every load.
    """
    body = skill_dir / "skill.bin"
    sidecar = skill_dir / "verified.json"

    if not body.exists():
        # A surviving sidecar without its body is NOT a verification.
        raise ProvenanceDriftError(
            f"skill body missing at {body}; sidecar present but untrusted, refusing to repopulate"
        )

    live_hash = hashlib.sha256(body.read_bytes()).hexdigest()
    attested_hash = trusted_manifest["artifact_sha256"]

    if live_hash != attested_hash:
        cached = json.loads(sidecar.read_text()) if sidecar.exists() else {}
        raise ProvenanceDriftError(
            f"artifact hash {live_hash[:12]} != attested {attested_hash[:12]}; "
            f"sidecar claims {cached.get('artifact_sha256', 'none')[:12]}"
        )

    # Derive the sandbox profile from the LIVE manifest, never a stored profile.
    profile = {
        "caps": trusted_manifest["caps"],
        "sandbox": build_sandbox(trusted_manifest["caps"]),
    }
    # Atomic rewrite: sidecar is only valid alongside the body it describes.
    tmp = skill_dir / ".verified.json.tmp"
    tmp.write_text(json.dumps({"artifact_sha256": live_hash, "caps": trusted_manifest["caps"]}))
    tmp.replace(sidecar)

    return profile


def build_sandbox(caps: list[str]) -> dict:
    allow_net = any(c.startswith("net:egress") and c != "net:egress:none" for c in caps)
    allow_exec = "exec:subprocess:true" in caps
    return {"net": allow_net, "subprocess": allow_exec}
