# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-skill-injection-attack-from-a-legitimate-dynamic-toolkit-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-skill-injection-attack-from-a-legitimate-dynamic-toolkit-reload.warrant.json
# Markdown SHA-256:   aa6cd64a8039b685124770682325bd794708e0095cb1340db4db52acf72d6966
# Code AST SHA-256:   0c2dfb43dff72bbe5c17b7d732cbbae0c6a36eab58b894f495ecf4e59cfc1f04
# Verified Classes:   SkillMetadataTamperedError, SkillRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class SkillMetadataTamperedError(RuntimeError):
    """Raised when planner-visible skill metadata changes without re-authorization."""
    pass


@dataclass
class SkillRecord:
    name: str
    body: str
    description: str
    usage_hints: list
    authorized_metadata_digest: str = field(default="")


def _planner_visible_digest(rec: SkillRecord) -> str:
    # Integrity covers everything the planner reads, not just the executable body.
    surface = json.dumps(
        {
            "description": rec.description,
            "usage_hints": rec.usage_hints,
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(surface.encode("utf-8")).hexdigest()


def register_on_reload(rec: SkillRecord, prior: SkillRecord | None) -> SkillRecord:
    digest = _planner_visible_digest(rec)
    if prior is None:
        # First load: operator must have pre-authorized this digest out of band.
        if not rec.authorized_metadata_digest:
            raise SkillMetadataTamperedError(
                f"skill {rec.name!r}: no authorized metadata digest for first load"
            )
        if digest != rec.authorized_metadata_digest:
            raise SkillMetadataTamperedError(
                f"skill {rec.name!r}: metadata digest {digest[:12]} does not match "
                f"authorized {rec.authorized_metadata_digest[:12]}"
            )
        return rec

    body_changed = rec.body != prior.body
    metadata_changed = digest != _planner_visible_digest(prior)

    if metadata_changed and not body_changed:
        # The exact observed attack: body identical, description rewritten.
        raise SkillMetadataTamperedError(
            f"skill {rec.name!r}: planner-visible metadata changed without body change; "
            f"re-authorization required before registration"
        )
    if metadata_changed and digest != rec.authorized_metadata_digest:
        raise SkillMetadataTamperedError(
            f"skill {rec.name!r}: metadata changed but new digest is not operator-authorized"
        )
    return rec
