# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-tool-manifest-the-schema-shadowing-skill-injection-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-tool-manifest-the-schema-shadowing-skill-injection-boundary.warrant.json
# Markdown SHA-256:   98af7f61ab5e9738ab5b811921f3c83fe17a044500f1f20608ee80ef81c40ab9
# Code AST SHA-256:   f2bab9a8bd12adb29f039c1c1acf29117d8654b68d2d826bc6f6edc457d80bf1
# Verified Classes:   ManifestShadowError, ToolIdentity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class ManifestShadowError(RuntimeError):
    """Raised when a dynamically loaded tool manifest shadows an existing
    identity with a divergent schema, or mutates a live tool contract."""
    pass

@dataclass(frozen=True)
class ToolIdentity:
    normalized_name: str
    schema_hash: str

def _normalize(name: str) -> str:
    # collapse whitespace, casefold, and reject homoglyph divergence upstream
    return "".join(name.split()).casefold()

def _schema_hash(schema: dict) -> str:
    import json
    return hashlib.sha256(
        json.dumps(schema, sort_keys=True).encode()
    ).hexdigest()

PRIVILEGE_PARAMS = {"follow_symlinks", "include", "shell", "egress"}

def admit_manifest(
    candidate: dict,
    registry: dict[str, ToolIdentity],
    live_invoked: set[str],
    same_trust_root: bool,
) -> ToolIdentity:
    name = candidate["name"]
    norm = _normalize(name)
    ident = ToolIdentity(norm, _schema_hash(candidate["schema"]))

    if norm in registry:
        incumbent = registry[norm]
        if incumbent.schema_hash == ident.schema_hash:
            return incumbent  # idempotent re-registration

        if not same_trust_root:
            raise ManifestShadowError(
                f"schema shadow on '{norm}': incumbent {incumbent.schema_hash[:8]} "
                f"vs candidate {ident.schema_hash[:8]} from untrusted root"
            )

        added = set(candidate["schema"]) - set(incumbent_params(registry, norm))
        if added & PRIVILEGE_PARAMS:
            raise ManifestShadowError(
                f"privilege-gating parameter superset on '{norm}': {sorted(added)}"
            )

        if norm in live_invoked:
            raise ManifestShadowError(
                f"mid-session rebind of already-invoked tool '{norm}'; "
                f"refusing to mutate live contract"
            )

    return ident

def incumbent_params(registry: dict, norm: str) -> set[str]:
    # placeholder: real runtime stores full schema alongside identity
    return set()
