# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-manifest-shadowing-skill-injection-where-a-dynamically-loaded-tool-alias-silently-rewrites-a-peer-s-capability-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-manifest-shadowing-skill-injection-where-a-dynamically-loaded-tool-alias-silently-rewrites-a-peer-s-capability-contract.warrant.json
# Markdown SHA-256:   b9e12854f1ae5a641caf9002a9474fb41cc2be2499e02d392b13af40b6851a3e
# Code AST SHA-256:   078dcc54b7311801b5e29661a4180e8df6f66c0863b992e7c5e8b4bd9cc9e602
# Verified Classes:   ManifestShadowingError, Binding, CapabilityTable
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestShadowingError(RuntimeError):
    """Raised when a hot-loaded manifest would silently rebind an incumbent
    capability the reasoning layer already holds in context."""


@dataclass
class Binding:
    name: str
    schema: dict
    manifest_id: str
    load_seq: int
    side_effect: str  # "read" | "write" | "network"

    @property
    def schema_hash(self) -> str:
        return hashlib.sha256(
            json.dumps(self.schema, sort_keys=True).encode()
        ).hexdigest()[:16]


@dataclass
class CapabilityTable:
    # keyed on name -> live binding
    live: dict[str, Binding] = field(default_factory=dict)
    # names the model's current context believes in
    context_held: set[str] = field(default_factory=set)

    def admit(self, incoming: Binding, alias_of: str | None = None) -> None:
        if alias_of is not None:
            # aliases must point at a name that exists and must NOT
            # re-point a name the model already holds
            if alias_of not in self.live:
                raise ManifestShadowingError(
                    f"alias target {alias_of!r} not registered"
                )
            if incoming.name in self.context_held:
                raise ManifestShadowingError(
                    f"alias {incoming.name!r} would shadow a context-held name"
                )
            if self.live[alias_of].side_effect != incoming.side_effect:
                raise ManifestShadowingError(
                    f"alias {incoming.name!r} changes side-effect class "
                    f"{self.live[alias_of].side_effect} -> {incoming.side_effect}"
                )
            self.live[incoming.name] = incoming
            return

        incumbent = self.live.get(incoming.name)
        if incumbent is None:
            self.live[incoming.name] = incoming
            return

        # same name: compatible refinement or shadowing conflict?
        inc_req = set(incumbent.schema.get("required", []))
        new_req = set(incoming.schema.get("required", []))
        if not inc_req.issubset(new_req):
            raise ManifestShadowingError(
                f"{incoming.name!r} drops required params {inc_req - new_req}"
            )
        if incumbent.side_effect != incoming.side_effect:
            raise ManifestShadowingError(
                f"{incoming.name!r} changes side-effect class "
                f"{incumbent.side_effect} -> {incoming.side_effect}"
            )
        if incoming.name in self.context_held and \
                incumbent.schema_hash != incoming.schema_hash:
            raise ManifestShadowingError(
                f"{incoming.name!r} schema mutated while held in context "
                f"({incumbent.schema_hash} -> {incoming.schema_hash}); "
                "emit context-invalidation before rebinding"
            )
        # compatible refinement: keep incumbent live, do not rebind context
        self.live[incoming.name] = incoming


def dispatch(table: CapabilityTable, name: str, args: dict[str, Any]) -> Any:
    binding = table.live.get(name)
    if binding is None:
        raise ManifestShadowingError(f"unbound capability {name!r}")
    allowed = set(binding.schema.get("properties", {}))
    extra = set(args) - allowed
    if extra:
        # strict closure: silent arg-drop is how shadowing hides
        raise ManifestShadowingError(
            f"args {extra} not in live schema for {name!r}"
        )
    return _execute(binding, args)


def _execute(binding: Binding, args: dict[str, Any]) -> Any:
    raise ManifestShadowingError(
        f"replay check required: binding {binding.name}@{binding.schema_hash} "
        f"seq={binding.load_seq} manifest={binding.manifest_id}"
    )
