# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-refreshed-capability-registry-as-an-untrusted-code-execution-surface-rather-than-a-passive-look.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-refreshed-capability-registry-as-an-untrusted-code-execution-surface-rather-than-a-passive-look.warrant.json
# Markdown SHA-256:   5af0fe27a539b49ec5b21a2f046ec0db5d1fddf863d96fc326bc7a8a46536578
# Code AST SHA-256:   2a65cf1382c09810ef84437ecc6eaa68da174002d2cf2dcb49df502a923f15aa
# Verified Classes:   CapabilityEnvelopeViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityEnvelopeViolation(RuntimeError):
    """Raised when a registry refresh attempts to bind a capability outside the
    agent's pinned manifest, or when descriptor text contains cross-references
    that the runtime must not project to the model."""
    pass


IMPERATIVE_MARKERS = ("IMPORTANT", "you must", "before calling", "required by policy")


def admit_refresh(pinned_manifest: dict, refresh: dict) -> list[str]:
    """
    pinned_manifest: {"tools": {name: {"data_classes": set[str]}}, "version": int}
    refresh:         {"tools": {name: {"schema": dict, "description": str, "data_classes": set[str]}}}
    Returns the list of tool names that may be bound. Raises on any violation.
    """
    allowed = pinned_manifest["tools"]
    admitted: list[str] = []

    for name, entry in refresh["tools"].items():
        # 1. New tool not in the signed manifest -> capability expansion.
        if name not in allowed:
            raise CapabilityEnvelopeViolation(
                f"refresh introduces unmanifested tool {name!r}; bind halted"
            )

        # 2. Schema widening beyond the manifest's declared data classes.
        new_classes = set(entry.get("data_classes", ()))
        if not new_classes.issubset(allowed[name]["data_classes"]):
            raise CapabilityEnvelopeViolation(
                f"tool {name!r} widens data classes "
                f"{new_classes - allowed[name]['data_classes']}; bind halted"
            )

        # 3. Imperative text in descriptors -> quarantine, do not project.
        desc = entry.get("description", "")
        if any(marker.lower() in desc.lower() for marker in IMPERATIVE_MARKERS):
            raise CapabilityEnvelopeViolation(
                f"tool {name!r} descriptor contains imperative directives; "
                f"quarantined from context projection"
            )

        # 4. Cross-reference to another registry entry -> runtime must resolve,
        #    never the model. Detect by scanning for other tool names verbatim.
        for other in refresh["tools"]:
            if other != name and other in desc:
                raise CapabilityEnvelopeViolation(
                    f"tool {name!r} descriptor cross-references {other!r}; "
                    f"cross-entry reference must be resolved by runtime"
                )

        admitted.append(name)

    return admitted
