# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-drift-from-surviving-a-signed-manifest-re-attestation-cycle.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-drift-from-surviving-a-signed-manifest-re-attestation-cycle.warrant.json
# Markdown SHA-256:   66606fe9670ef9a48f33479d790a17ba1544e1fc7d3e522407d24c3293337651
# Code AST SHA-256:   c897d308c98f07d54b2669834dc804af23ffbb764bfa9a9c0011ea73c5ea40f4
# Verified Classes:   SkillDescriptionDrift, SkillManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SkillDescriptionDrift(RuntimeError):
    """Raised when a skill's description surface drifts across an epoch
    boundary in a way that is not covered by a bounded, monotonic,
    re-attested delta. This is the guardrail against semantic
    skill-injection that survives artifact-signature verification."""


@dataclass(frozen=True)
class SkillManifest:
    name: str
    version: str
    artifact_sha256: str
    description: str
    params: dict
    capability_class: str  # "read_only" | "mutating"
    signed_description_surface: bool
    reattestation_token: Optional[str]


# Capability class lattice: narrowing only, automatically.
_CAPABILITY_ORDER = {"read_only": 0, "mutating": 1}


def _structural_delta(prev: SkillManifest, nxt: SkillManifest) -> dict:
    """Structural (not textual) diff of the description surface."""
    delta = {}
    if prev.description != nxt.description:
        delta["description_changed"] = (prev.description, nxt.description)
    prev_params, next_params = prev.params, nxt.params
    added = set(next_params) - set(prev_params)
    removed = set(prev_params) - set(next_params)
    if added:
        delta["params_added"] = sorted(added)
    if removed:
        delta["params_removed"] = sorted(removed)
    for key in set(prev_params) & set(next_params):
        if prev_params[key].get("default") != next_params[key].get("default"):
            delta[f"default_changed:{key}"] = (
                prev_params[key].get("default"),
                next_params[key].get("default"),
            )
        if prev_params[key].get("enum") != next_params[key].get("enum"):
            delta[f"enum_changed:{key}"] = (
                prev_params[key].get("enum"),
                next_params[key].get("enum"),
            )
    return delta


def admit_epoch(prev: SkillManifest, nxt: SkillManifest) -> bool:
    # Invariant 1: the description surface must be inside the signed digest.
    if not nxt.signed_description_surface:
        raise SkillDescriptionDrift(
            f"skill {nxt.name}@{nxt.version}: description surface is not "
            "co-signed; artifact signature alone does not cover the "
            "parameters the model will read."
        )

    # Invariant 2: capability class may only narrow automatically.
    prev_cls = _CAPABILITY_ORDER[prev.capability_class]
    next_cls = _CAPABILITY_ORDER[nxt.capability_class]
    if next_cls > prev_cls and not nxt.reattestation_token:
        raise SkillDescriptionDrift(
            f"skill {nxt.name}@{nxt.version}: capability class widened "
            f"{prev.capability_class} -> {nxt.capability_class} without "
            "human re-attestation token."
        )

    # Invariant 3: structural delta must be bounded or re-attested.
    delta = _structural_delta(prev, nxt)
    if delta and not nxt.reattestation_token:
        raise SkillDescriptionDrift(
            f"skill {nxt.name}@{nxt.version}: unbounded structural delta "
            f"{sorted(delta)} admitted without re-attestation. This is the "
            "exact shape of a semantic injection that passes artifact "
            "signature verification."
        )

    return True
