# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-skill-manifest-as-proof-of-continuity-when-the-signature-only-attests-to-the-loader-s-clock-not-the-skill-s-be.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-skill-manifest-as-proof-of-continuity-when-the-signature-only-attests-to-the-loader-s-clock-not-the-skill-s-be.warrant.json
# Markdown SHA-256:   685428a576251bbbc4125cbc86bdb34428e7dc7f159e92123adbd8558cdff729
# Code AST SHA-256:   da36605ea271199fa7dffbf5ed6186cc4ff2fe8202bac449fcbe94c57f3b43a5
# Verified Classes:   ManifestSubstitutionError, BehavioralProjection
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestSubstitutionError(RuntimeError):
    """Raised when a re-loaded skill manifest has a valid signature but a
    behaviorally relevant projection that differs from the pinned baseline
    under an unchanged version string."""


@dataclass(frozen=True)
class BehavioralProjection:
    capabilities: frozenset
    tool_descriptions_hash: str
    dependencies: tuple
    entrypoint_digest: str

    @classmethod
    def from_manifest(cls, manifest: dict) -> "BehavioralProjection":
        desc = json.dumps(
            manifest.get("tool_descriptions", {}), sort_keys=True
        ).encode()
        return cls(
            capabilities=frozenset(manifest.get("capabilities", [])),
            tool_descriptions_hash=hashlib.sha256(desc).hexdigest(),
            dependencies=tuple(sorted(manifest.get("dependencies", []))),
            entrypoint_digest=manifest.get("entrypoint_digest", ""),
        )


def verify_resume(
    name: str,
    version: str,
    manifest: dict,
    signature_valid: bool,
    pinned: BehavioralProjection,
) -> BehavioralProjection:
    # Signature is necessary but never sufficient.
    if not signature_valid:
        raise ManifestSubstitutionError(
            f"{name}@{version}: signature invalid, refusing load"
        )

    current = BehavioralProjection.from_manifest(manifest)

    if current != pinned:
        # Version unchanged + projection changed == substitution event.
        # A valid signature does not authorize this; it only identifies
        # the signer. Halt and escalate.
        raise ManifestSubstitutionError(
            f"{name}@{version}: behavioral projection drift under "
            f"unchanged version. pinned={pinned} current={current}. "
            f"Signature valid but attests authorship, not behavior."
        )

    return current
