# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-registry-manifest-has-been-poisoned-by-a-same-name-capability-shadow.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-registry-manifest-has-been-poisoned-by-a-same-name-capability-shadow.warrant.json
# Markdown SHA-256:   3aa0e64b0bdcfde9fba64b5d4931913907d98616fd09145c1ff4d0e618921df9
# Code AST SHA-256:   a112f85e95ba32f80a716cd642d5c980e2f545479554d036025a46797e4f7e61
# Verified Classes:   SkillResolutionError, PinnedSkill
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SkillResolutionError(RuntimeError):
    """Raised when a skill manifest cannot be proven to match its pinned identity."""
    pass


@dataclass(frozen=True)
class PinnedSkill:
    name: str
    version: str
    publisher: str
    manifest_sha256: str


def resolve_skill(name: str, registry_response: dict, lockfile: dict[str, PinnedSkill]) -> dict:
    """
    Resolve a skill manifest against a content-addressed lockfile.

    Fails closed: any duplicate, mismatch, or missing pin raises rather than
    falling through to a candidate manifest.
    """
    canonical = json.dumps(registry_response, sort_keys=True, separators=(",", ":"))
    actual_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    pin = lockfile.get(name)
    if pin is None:
        raise SkillResolutionError(
            f"skill '{name}' resolved from registry but is absent from lockfile; "
            f"refusing to load unpinned capability"
        )

    if registry_response.get("version") != pin.version:
        raise SkillResolutionError(
            f"skill '{name}' version mismatch: resolved {registry_response.get('version')!r}, "
            f"pinned {pin.version!r}"
        )

    if registry_response.get("publisher") != pin.publisher:
        # Catches the same-name shadow: 'internal-team' != 'internal'
        raise SkillResolutionError(
            f"skill '{name}' publisher mismatch: resolved {registry_response.get('publisher')!r}, "
            f"pinned {pin.publisher!r}"
        )

    if actual_hash != pin.manifest_sha256:
        raise SkillResolutionError(
            f"skill '{name}' manifest hash mismatch: resolved {actual_hash}, "
            f"pinned {pin.manifest_sha256}; possible same-name shadow"
        )

    return registry_response


def load_skill_into_context(name: str, registry_response: dict, lockfile: dict[str, PinnedSkill]) -> str:
    """
    Load a verified manifest's description into the agent context.
    Any resolution failure aborts skill loading entirely.
    """
    try:
        manifest = resolve_skill(name, registry_response, lockfile)
    except SkillResolutionError as exc:
        # Do NOT fall back to a near-name match or an unpinned candidate.
        raise SkillResolutionError(
            f"aborting skill load for '{name}': {exc}"
        ) from exc

    return manifest["description"]
