# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-manifest-valid-but-behavior-divergent-skill-at-load-time-the-toctou-gap-between-capability-manifest-signature-verificati.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-manifest-valid-but-behavior-divergent-skill-at-load-time-the-toctou-gap-between-capability-manifest-signature-verificati.warrant.json
# Markdown SHA-256:   d381d97dfc59dc69b39661af8b5a1c1a9054e1160df07b45546112d750b961fb
# Code AST SHA-256:   f149a37bde01e0c7ea2a04c647794ad38864b52379b5d05ae0bf549d5da31e17
# Verified Classes:   SkillLoadRefused, Manifest, SandboxProfile
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Callable


class SkillLoadRefused(RuntimeError):
    """Raised when a skill cannot be safely loaded under the declared confinement posture."""
    pass


@dataclass
class Manifest:
    publisher: str
    declared_tools: list[str]
    declared_egress: list[str]
    entrypoint_url: str
    entrypoint_sha256: str | None          # advisory in weak configs
    closure_sha256: dict[str, str] = field(default_factory=dict)  # path -> hash
    signature_valid: bool = False


@dataclass
class SandboxProfile:
    """What the runtime can ACTUALLY enforce below the payload."""
    mediates_tool_calls: bool = True
    blocks_ambient_sockets: bool = False
    blocks_ambient_fs: bool = False
    enforces_egress_allowlist_at_process_level: bool = False


def verify_and_load(
    manifest: Manifest,
    sandbox: SandboxProfile,
    fetch: Callable[[str], bytes],
    resolve_closure: Callable[[str], dict[str, bytes]],
) -> None:
    # 1. Provenance gate.
    if not manifest.signature_valid:
        raise SkillLoadRefused(f"manifest for {manifest.publisher} failed signature verification")

    # 2. Integrity gate: the signature must cover the full executable closure,
    #    not just a declaration. An advisory-only hash is a TOCTOU hole.
    if not manifest.closure_sha256:
        raise SkillLoadRefused(
            "manifest carries no full-closure hash; entrypoint-only pinning is "
            "insufficient — payload can lazily import unverified dependencies"
        )

    # 3. Eager resolution: fetch the entire closure now, hash every artifact,
    #    so nothing is resolved after the gate passes.
    closure = resolve_closure(manifest.entrypoint_url)
    for path, blob in closure.items():
        expected = manifest.closure_sha256.get(path)
        if expected is None:
            raise SkillLoadRefused(f"closure member {path!r} is not covered by the signed manifest")
        actual = hashlib.sha256(blob).hexdigest()
        if actual != expected:
            # Non-suppressible: no retry, no warning-only path.
            raise SkillLoadRefused(f"closure hash mismatch for {path!r}: {actual} != {expected}")

    # 4. Confinement gate: derive enforced scope from the sandbox, and require
    #    that the sandbox can actually mediate everything the manifest declares.
    needs_egress = bool(manifest.declared_egress)
    needs_fs = any(t.startswith("fs.") for t in manifest.declared_tools)

    if needs_egress and not (
        sandbox.enforces_egress_allowlist_at_process_level
        and sandbox.blocks_ambient_sockets
    ):
        raise SkillLoadRefused(
            "manifest declares egress scope but sandbox does not enforce it at the "
            "process level; payload could bypass mediated tool calls via ambient sockets"
        )

    if needs_fs and not (sandbox.blocks_ambient_fs and sandbox.mediates_tool_calls):
        raise SkillLoadRefused(
            "manifest declares fs scope but sandbox does not block ambient filesystem "
            "access; declared scope is not a confinement guarantee"
        )

    # 5. Only now, with provenance + integrity + confinement all established,
    #    mint the capability grant. The grant reflects ENFORCED scope.
    grant = {
        "tools": manifest.declared_tools,
        "egress": manifest.declared_egress,
        "enforced_by": "process-sandbox",
    }
    _execute(closure, grant)


def _execute(closure: dict[str, bytes], grant: dict) -> None:
    # Executes inside the sandbox whose ambient capabilities are empty.
    ...
