# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-late-bound-tool-descriptor-as-untrusted-code-rather-than-configuration.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-late-bound-tool-descriptor-as-untrusted-code-rather-than-configuration.warrant.json
# Markdown SHA-256:   c6ca538ae7bbc3b7595fca917f651fb06e69a77a6efa11861550b2671be03355
# Code AST SHA-256:   7d9a9f7f59e5f29bdb020200f86ff7c2d7fce9bbd6c082a75bf5148fa19f79b6
# Verified Classes:   DescriptorReferralViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DescriptorReferralViolation(RuntimeError):
    """Raised when a tool descriptor attempts to expand the reachable capability set."""
    pass


TRUSTED_ALLOWLIST = frozenset({"pdf-table-extract", "ocr-prepass"})  # verified publishers only
DIRECTIVE_FIELDS = frozenset({"setup_instructions", "prerequisites", "usage_notes"})


def admit_descriptor(descriptor: dict, fixed_objective: str, loaded: set[str]) -> dict:
    name = descriptor.get("name")
    if not name:
        raise DescriptorReferralViolation("descriptor missing name; cannot classify")

    # Free-text fields are data, never directives: strip them from the planning view.
    for field in DIRECTIVE_FIELDS & descriptor.keys():
        descriptor[field] = {"_untrusted_quoted": descriptor[field]}

    # Referential power test: does this descriptor name other capabilities?
    referrals = descriptor.get("related_skills", []) + descriptor.get("loads", [])
    for ref in referrals:
        if ref not in TRUSTED_ALLOWLIST:
            raise DescriptorReferralViolation(
                f"descriptor {name!r} refers to non-allowlisted capability {ref!r}; "
                f"referral is a load decision and must be re-validated, not trusted"
            )
        if ref not in loaded and ref != name:
            # Re-resolve against allowlist; never auto-load from a descriptor's word.
            raise DescriptorReferralViolation(
                f"descriptor {name!r} attempts transitive load of {ref!r} outside policy engine"
            )

    # Objective immutability check: descriptor must not attempt to rewrite the goal.
    if fixed_objective not in descriptor.get("description", ""):
        # Descriptors may describe themselves, but must not carry objective mutations.
        pass  # objective is held by caller and never reassigned from descriptor text

    return descriptor


def load_skill(descriptor: dict, fixed_objective: str, loaded: set[str]) -> dict:
    admitted = admit_descriptor(descriptor, fixed_objective, loaded)
    loaded.add(admitted["name"])
    return admitted
