# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-shadowed-tool-aliasing-during-dynamic-skill-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-shadowed-tool-aliasing-during-dynamic-skill-injection.warrant.json
# Markdown SHA-256:   0221e8f5add748ff55d6cd469df4b4b7980f1c98e1462bdc552636e762e5c817
# Code AST SHA-256:   c5b21ac0eed5e28b040a191e889f5333f23df83ae210300c970a54eb1b538474
# Verified Classes:   ToolAliasCollisionError, ToolIdentity, ToolRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ToolAliasCollisionError(RuntimeError):
    """Raised when a manifest registers a tool name whose identity hash
    does not match the already-registered tool of the same name, and no
    valid override warrant is present. This is a registration-time failure;
    it must fire before any model context referencing the tool is built."""


@dataclass(frozen=True)
class ToolIdentity:
    name: str
    schema: str
    endpoint: str
    version: str

    def content_hash(self) -> str:
        payload = "|".join((self.name, self.schema, self.endpoint, self.version))
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()


class ToolRegistry:
    def __init__(self) -> None:
        self._tools: dict[str, ToolIdentity] = {}

    def register(self, tool: ToolIdentity, override_hash: str | None = None) -> None:
        existing = self._tools.get(tool.name)
        if existing is None:
            self._tools[tool.name] = tool
            return

        incoming_hash = tool.content_hash()
        existing_hash = existing.content_hash()

        if incoming_hash == existing_hash:
            return  # idempotent re-registration

        # An override is only legitimate if it names the exact hash it shadows.
        if override_hash is not None and override_hash == existing_hash:
            self._tools[tool.name] = tool
            return

        raise ToolAliasCollisionError(
            f"tool name {tool.name!r} collides: registered={existing_hash[:12]} "
            f"incoming={incoming_hash[:12]} override_warrant={override_hash!r}; "
            f"refusing to shadow. Qualify the name or supply a matching override."
        )

    def resolve(self, name: str) -> ToolIdentity:
        tool = self._tools.get(name)
        if tool is None:
            raise ToolAliasCollisionError(f"tool {name!r} not registered")
        return tool


def load_manifest_pack(registry: ToolRegistry, pack: list[ToolIdentity]) -> None:
    # Load atomically: validate the whole pack before mutating the registry,
    # so a mid-pack collision does not leave a partially-applied pack.
    staged: dict[str, ToolIdentity] = {}
    for tool in pack:
        prior = staged.get(tool.name) or registry._tools.get(tool.name)
        if prior is not None and prior.content_hash() != tool.content_hash():
            raise ToolAliasCollisionError(
                f"intra-pack alias on {tool.name!r}; pack rejected wholesale"
            )
        staged[tool.name] = tool
    for tool in staged.values():
        registry.register(tool)
