# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-shadow-registered-tool-whose-schema-collides-with-a-trusted-skill-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-shadow-registered-tool-whose-schema-collides-with-a-trusted-skill-at-load-time.warrant.json
# Markdown SHA-256:   994054ac20954bdea9fb2df028d3a756772f33d97453e2d39776197d9179566f
# Code AST SHA-256:   b5e0f80314949cb2823c249e39721f47fb4f6258112156965a8d830bb77f2199
# Verified Classes:   ShadowSkillCollision, ShadowSkillCollision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ShadowSkillCollision(RuntimeError):
    """Raised when a lower-trust skill's selection surface overlaps a higher-trust skill's."""
    pass


TRUST_RANK = {"builtin": 3, "mcp": 2, "plugin": 1, "user": 0}
OVERLAP_TAU = 0.85


def _intent_overlap(a_desc: str, b_desc: str) -> float:
    # Stand-in for embedding cosine; token Jaccard is a conservative proxy.
    ta = set(a_desc.lower().split())
    tb = set(b_desc.lower().split())
    if not ta or not tb:
        return 0.0
    return len(ta & tb) / len(ta | tb)


def _shape_congruent(a_params: dict, b_params: dict) -> bool:
    # Structural equality modulo field renaming: compare type/enum multisets.
    def sig(p):
        return sorted(
            (tuple(sorted(v.get("enum", []))), v.get("type"))
            for v in p.values()
        )
    return sig(a_params) == sig(b_params)


def admit_skill(new_skill: dict, registry: list[dict]) -> None:
    """Enforce selection-surface disjointness before a skill becomes selectable."""
    for existing in registry:
        if TRUST_RANK[new_skill["tier"]] >= TRUST_RANK[existing["tier"]]:
            continue
        overlap = _intent_overlap(new_skill["description"], existing["description"])
        if overlap < OVERLAP_TAU:
            continue
        if not _shape_congruent(new_skill["parameters"], existing["parameters"]):
            continue
        raise ShadowSkillCollision(
            f"skill {new_skill['name']!r} ({new_skill['tier']}) shadows "
            f"trusted {existing['name']!r} ({existing['tier']}): "
            f"intent_overlap={overlap:.3f}, congruent_params=True. "
            f"Requires explicit promotion or intent scoping before load."
        )
    registry.append(new_skill)

class ShadowSkillCollision(RuntimeError):
    """Raised when a lower-trust skill's selection surface overlaps a higher-trust skill's."""
    pass


TRUST_RANK = {"builtin": 3, "mcp": 2, "plugin": 1, "user": 0}
OVERLAP_TAU = 0.85


def _intent_overlap(a_desc: str, b_desc: str) -> float:
    ta = set(a_desc.lower().split())
    tb = set(b_desc.lower().split())
    if not ta or not tb:
        return 0.0
    return len(ta & tb) / len(ta | tb)


def _shape_congruent(a_params: dict, b_params: dict) -> bool:
    def sig(p):
        return sorted(
            (tuple(sorted(v.get("enum", []))), v.get("type"))
            for v in p.values()
        )
    return sig(a_params) == sig(b_params)


def admit_skill(new_skill: dict, registry: list[dict]) -> None:
    for existing in registry:
        if TRUST_RANK[new_skill["tier"]] >= TRUST_RANK[existing["tier"]]:
            continue
        overlap = _intent_overlap(new_skill["description"], existing["description"])
        if overlap < OVERLAP_TAU:
            continue
        if not _shape_congruent(new_skill["parameters"], existing["parameters"]):
            continue
        raise ShadowSkillCollision(
            f"skill {new_skill['name']!r} ({new_skill['tier']}) shadows "
            f"trusted {existing['name']!r} ({existing['tier']}): "
            f"intent_overlap={overlap:.3f}, congruent_params=True. "
            f"Requires explicit promotion or intent scoping before load."
        )
    registry.append(new_skill)
