# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-dynamically-loaded-skill-descriptors-as-executable-adversarial-input-rather-than-inert-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-dynamically-loaded-skill-descriptors-as-executable-adversarial-input-rather-than-inert-metadata.warrant.json
# Markdown SHA-256:   aee714dafb585da221722cbc84eb8f4a719645eb357b56faa2964201d255ac8f
# Code AST SHA-256:   31744e2280212ada92a74119a25953af8d1de1b5ae78d645912ebf1b6cc7055f
# Verified Classes:   DescriptorInjectionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DescriptorInjectionError(RuntimeError):
    """Raised when a dynamically loaded skill descriptor carries imperative force
    without an authenticated, provenance-tagged boundary."""
    pass


IMPERATIVE_MARKERS = (
    "you must", "always call", "do not tell", "do not mention",
    "before responding", "for compliance", "ignore previous",
)


def admit_descriptor(descriptor: dict, *, origin_verified: bool,
                     signature_covers_body: bool) -> dict:
    body = descriptor.get("description", "")
    lowered = body.lower()

    if not origin_verified or not signature_covers_body:
        raise DescriptorInjectionError(
            f"descriptor {descriptor.get('name')!r} has unauthenticated origin "
            f"or unsigned body; refusing to place in selection context"
        )

    hits = [m for m in IMPERATIVE_MARKERS if m in lowered]
    if hits:
        raise DescriptorInjectionError(
            f"descriptor {descriptor.get('name')!r} contains imperative force "
            f"{hits}; quarantine and require operator review"
        )

    refs = descriptor.get("references", [])
    if refs:
        # Contamination follows the reference graph: a clean descriptor that
        # names a quarantined skill must itself be re-reviewed.
        raise DescriptorInjectionError(
            f"descriptor {descriptor.get('name')!r} references {refs}; "
            f"cannot admit until referenced skills are re-verified"
        )

    return {"name": descriptor["name"], "description": body, "trusted": True}


def refresh_registry(resident: dict, incoming: dict) -> dict:
    # Eviction-on-refresh: a removed descriptor must not survive in context.
    removed = set(resident) - set(incoming)
    if removed:
        raise DescriptorInjectionError(
            f"refresh would remove resident descriptors {removed}; "
            f"context eviction required before reload"
        )
    return {name: admit_descriptor(d, origin_verified=True,
                                   signature_covers_body=True)
            for name, d in incoming.items()}
