# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-skill-registry-capability-shadowing-injection-across-hot-reloaded-agent-skills.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-skill-registry-capability-shadowing-injection-across-hot-reloaded-agent-skills.warrant.json
# Markdown SHA-256:   045f653e874b2998e146f477c275ef1f198348009d729c34718f0eb5ae2b3186
# Code AST SHA-256:   9ceaf2f01b0d73022d91e4445ca23069dd248be1c0cd83c236e8495fa51ed8fc
# Verified Classes:   CapabilityShadowingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityShadowingError(RuntimeError):
    """Raised when a newly registered skill manifest cannibalizes routing
    probability from an already-registered skill, indicating capability
    shadowing rather than genuine capability addition."""


def register_skill(registry, candidate, intent_probes, shadow_threshold=0.15):
    """Register a skill only if it does not shadow existing skills.

    intent_probes: dict skill_name -> list[str] of representative user turns
    derived from each existing skill's own when_to_use string.
    """
    # Snapshot pre-registration routing distribution.
    before = {
        name: registry.selection_probability(name, intent_probes[name])
        for name in registry.names()
    }

    # Capability tokens must be disjoint unless this is an explicit replacement.
    for existing in registry.manifests():
        overlap = set(existing.capabilities) & set(candidate.capabilities)
        if overlap and not candidate.replaces == existing.name:
            raise CapabilityShadowingError(
                f"candidate {candidate.name!r} overlaps capability {overlap!r} "
                f"with {existing.name!r} without declaring replacement"
            )

    registry.stage(candidate)

    after = {
        name: registry.selection_probability(name, intent_probes[name])
        for name in before
    }

    for name, p_before in before.items():
        drop = p_before - after[name]
        if drop > shadow_threshold:
            registry.rollback(candidate)
            raise CapabilityShadowingError(
                f"candidate {candidate.name!r} reduced selection probability of "
                f"{name!r} by {drop:.2f} (threshold {shadow_threshold}); "
                f"manifest description is a capability superset — rejected"
            )

    return registry.commit(candidate)
