# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-signed-skill-manifests-from-being-laundered-through-transitive-dependency-re-resolution-at-agent-cold-start.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-signed-skill-manifests-from-being-laundered-through-transitive-dependency-re-resolution-at-agent-cold-start.warrant.json
# Markdown SHA-256:   a24b78b3f3a786c5ccd5853899b3d9e8e60e57f3990dcc5af9ccc08bf512fa68
# Code AST SHA-256:   d12ea6cd3c1355aa08aba9431e6e7908b3bff47bc1c223c3d7e23e75f135fd2f
# Verified Classes:   ClosureRootMismatch, UnresolvableClosure
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ClosureRootMismatch(RuntimeError):
    """Raised when the resolved skill closure does not match the signed Merkle root."""
    pass


class UnresolvableClosure(RuntimeError):
    """Raised when the manifest's dependency constraints cannot be satisfied by any
    closure matching the signed root. Substitution is forbidden."""
    pass


def verify_and_load_skill(manifest, signed_root, registry, trust_barrier=None):
    """
    Enforce closure binding at cold-start.

    Invariant: no artifact init code, import side effect, or registry mutation
    executes until the recomputed closure root equals the signed root.

    `trust_barrier` is an optional callable invoked ONLY after root match,
    used to run post_load hooks. If root mismatches, it is never called.
    """
    if signed_root is None:
        raise ClosureRootMismatch(
            "manifest carries no closure root; per-node signatures are insufficient"
        )

    # Resolve the full transitive closure under a pinned registry epoch.
    # Any missing/yanked edge must surface as unresolvable, never substituted.
    resolved = registry.resolve_full_closure(
        manifest.deps,
        pinned_epoch=manifest.registry_epoch_digest,
        forbid_substitution=True,
    )
    if resolved is None or resolved.incomplete:
        raise UnresolvableClosure(
            f"closure for {manifest.skill_id} cannot be fully resolved "
            f"under epoch {manifest.registry_epoch_digest}; refusing to substitute"
        )

    # Canonical, order-independent serialization of the whole closure.
    computed_root = resolved.merkle_root()

    if computed_root != signed_root:
        # This is the exact condition the attack exploited: every node may be
        # individually signed, but the composition was never authorized.
        raise ClosureRootMismatch(
            f"closure root mismatch for {manifest.skill_id}: "
            f"signed={signed_root.hex()} computed={computed_root.hex()} "
            f"nodes={[n.id for n in resolved.nodes]}"
        )

    # Barrier passed. Only now may hooks / init code run.
    if trust_barrier is not None:
        trust_barrier(resolved)

    return resolved
