# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-shadowed-skill-injection-when-a-dynamically-loaded-registry-resolves-two-skill-manifests-to-the-same-invocation-key.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-shadowed-skill-injection-when-a-dynamically-loaded-registry-resolves-two-skill-manifests-to-the-same-invocation-key.warrant.json
# Markdown SHA-256:   6db79950430e6313ebf6ba2a294a70faa2b90a131820fdbe95b7452e0ec966fa
# Code AST SHA-256:   af6308b8c0fab9b9f0452f5407647dfb0915dec89b3a36c7e8df7434347c4d4b
# Verified Classes:   SkillRebindError, AmbiguousResolutionError, Manifest, SkillRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SkillRebindError(RuntimeError):
    """Raised when a registry refresh attempts to silently re-bind a stable
    invocation key to a different content hash without an explicit rebind event."""


class AmbiguousResolutionError(RuntimeError):
    """Raised at dispatch when more than one manifest resolves to the same key."""


@dataclass
class Manifest:
    key: str
    content: bytes
    scope: str = "sandbox_root"

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.content).hexdigest()


@dataclass
class SkillRegistry:
    resident: dict[str, Manifest] = field(default_factory=dict)
    pending_rebinds: dict[str, Manifest] = field(default_factory=dict)

    def load_initial(self, manifests: list[Manifest]) -> None:
        for m in manifests:
            if m.key in self.resident:
                raise AmbiguousResolutionError(f"duplicate key at cold start: {m.key}")
            self.resident[m.key] = m

    def merge_refresh(self, manifests: list[Manifest], allow_rebind: bool = False) -> None:
        """Merge a tools/list refresh. Enforces key-immutability: a colliding key
        with a differing hash is a rebind, not a refresh."""
        for m in manifests:
            existing = self.resident.get(m.key)
            if existing is None:
                self.resident[m.key] = m
                continue
            if existing.digest == m.digest:
                continue  # benign refresh, same content
            if not allow_rebind:
                raise SkillRebindError(
                    f"key {m.key!r} re-bound from {existing.digest[:12]} "
                    f"to {m.digest[:12]} without explicit rebind event; "
                    f"resident scope {existing.scope!r} would be shadowed by {m.scope!r}"
                )
            # Explicit rebind: quarantine old, stage new, invalidate descriptions.
            self.pending_rebinds[m.key] = m
            del self.resident[m.key]

    def resolve(self, key: str) -> Manifest:
        if key in self.pending_rebinds:
            raise SkillRebindError(
                f"key {key!r} awaiting rebind handshake; dispatch blocked until "
                f"planner re-reads schema"
            )
        if key not in self.resident:
            raise AmbiguousResolutionError(f"unresolvable key: {key!r}")
        return self.resident[key]


def handle_refresh(registry: SkillRegistry, manifests: list[Manifest]) -> None:
    try:
        registry.merge_refresh(manifests)
    except SkillRebindError as e:
        # Fail closed: quarantine the colliding entries, keep resident bindings.
        # Log the hash discontinuity as a trust event for audit.
        raise SkillRebindError(f"refresh rejected, resident bindings preserved: {e}") from e
