# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-has-been-re-signed-under-a-drifted-capability-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-has-been-re-signed-under-a-drifted-capability-envelope.warrant.json
# Markdown SHA-256:   26aa5e9e9d4aadca86b8315e3910ada37b06c017b5a90de2bb1f3f10c819b865
# Code AST SHA-256:   6d587023919d312db0211a216f717a41d29b91aefd26e8fc6f9a516d5c0fcd61
# Verified Classes:   EnvelopeDriftError, Pin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class EnvelopeDriftError(RuntimeError):
    """Raised when a signed manifest's capability envelope diverges from its pin."""


@dataclass(frozen=True)
class Pin:
    name: str
    version: str
    envelope_digest: str


def canonical_envelope(envelope: dict[str, Any]) -> bytes:
    # Deterministic serialization: sorted keys, no whitespace, fixed field set.
    # Any field the runtime will act on MUST be included here or it is not covered.
    fields = ("tools", "egress", "fs_roots")
    normalized = {f: sorted(envelope.get(f, [])) for f in fields}
    return json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()


def envelope_digest(envelope: dict[str, Any]) -> str:
    return hashlib.sha256(canonical_envelope(envelope)).hexdigest()


def admit_skill(manifest: dict[str, Any], pin: Pin, signature_valid: bool) -> None:
    if not signature_valid:
        raise EnvelopeDriftError("provenance signature failed verification")

    if (manifest["name"], manifest["version"]) != (pin.name, pin.version):
        raise EnvelopeDriftError(
            f"identity mismatch: live={manifest['name']}@{manifest['version']} "
            f"pin={pin.name}@{pin.version}"
        )

    live_digest = envelope_digest(manifest["envelope"])
    if live_digest != pin.envelope_digest:
        # Valid signature over a widened envelope is the injection condition.
        # Refuse; do not fall back to the live envelope for egress/fs guards.
        raise EnvelopeDriftError(
            f"envelope drift under stable identity: live={live_digest} "
            f"pinned={pin.envelope_digest}; re-pin required"
        )
