# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-skill-by-name-against-a-registry-that-verifies-signatures-but-not-provenance-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-skill-by-name-against-a-registry-that-verifies-signatures-but-not-provenance-lineage.warrant.json
# Markdown SHA-256:   dbf991b02dc1c7f079e3d1cf23faad208392be59c958b74d44dfaafd167acfcf
# Code AST SHA-256:   6b0f683c9fba548e98bee80368208c0aa9a4969d3375097558df3067e406b923
# Verified Classes:   SkillLineageBroken, Binding, PinnedSkill
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SkillLineageBroken(RuntimeError):
    """Raised when a skill resolves to an artifact whose provenance lineage
    does not contiguously connect to the caller's pinned publisher."""
    pass


@dataclass(frozen=True)
class Binding:
    name: str
    publisher: str
    event: str          # "publish" | "deprecate" | "rename"
    timestamp_ms: int
    content_hash: str


@dataclass(frozen=True)
class PinnedSkill:
    name: str
    publisher: str
    last_known_good_hash: str
    last_resolved_ms: int


def resolve_skill(
    pinned: PinnedSkill,
    bindings: list[Binding],   # full mutation log for this name, oldest first
    now_ms: int,
) -> Binding:
    """Resolve a pinned skill against the registry mutation log.

    Fails closed on: publisher mismatch, deprecation gap between the
    pinned resolution and the current binding, or cross-namespace fallback.
    """
    if not bindings:
        raise SkillLineageBroken(f"no bindings for {pinned.name!r}")

    # Walk the log forward from the pinned resolution time.
    window = [b for b in bindings if b.timestamp_ms >= pinned.last_resolved_ms]
    if not window:
        raise SkillLineageBroken(
            f"no binding events for {pinned.name!r} since last resolution"
        )

    current = window[-1]
    if current.event != "publish":
        raise SkillLineageBroken(
            f"{pinned.name!r} currently unbound (last event={current.event})"
        )

    # 1. Publisher pin: the binding must belong to the pinned publisher.
    if current.publisher != pinned.publisher:
        raise SkillLineageBroken(
            f"{pinned.name!r} rebound by {current.publisher!r}, "
            f"expected {pinned.publisher!r}"
        )

    # 2. Lineage continuity: no deprecation gap may separate the pinned
    #    resolution from the current binding, even for the same publisher.
    for b in window[:-1]:
        if b.event == "deprecate":
            raise SkillLineageBroken(
                f"{pinned.name!r} crossed a deprecation gap at "
                f"t={b.timestamp_ms}ms; refusing to resolve across it"
            )

    # 3. Namespace exactness: the binding name must equal the pinned name.
    if current.name != pinned.name:
        raise SkillLineageBroken(
            f"namespace fallback: resolved {current.name!r} for {pinned.name!r}"
        )

    # 4. Content integrity: hash must match the pinned known-good, or the
    #    caller must re-pin explicitly. We surface the new hash rather than
    #    silently accepting it.
    if current.content_hash != pinned.last_known_good_hash:
        # Same publisher, contiguous lineage -> a legitimate update.
        # The caller must re-pin; we do not silently trust the new bytes.
        raise SkillLineageBroken(
            f"{pinned.name!r} content changed "
            f"({pinned.last_known_good_hash[:8]} -> {current.content_hash[:8]}); "
            f"explicit re-pin required"
        )

    return current
