# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-manifest-declared-capability-from-executable-tool-authority-in-dynamically-loaded-agent-manifests.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-manifest-declared-capability-from-executable-tool-authority-in-dynamically-loaded-agent-manifests.warrant.json
# Markdown SHA-256:   be4fe1e884163b488c9d5a2fc889abbefe91958a0d7b4c5fc64af227c9611786
# Code AST SHA-256:   02f2cc0508974f2dfdfb13eed02fb340fb57a64af24047c488dadf4e1cc3d2b5
# Verified Classes:   ManifestAuthorityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestAuthorityError(RuntimeError):
    """Raised when a loaded manifest's declared category conflicts with the
    actual capability set of its resolved binding, or when a manifest
    description attempts to carry executable instruction into agent context."""

    def __init__(self, tool_name: str, declared: set, actual: set, reason: str):
        self.tool_name = tool_name
        self.declared = declared
        self.actual = actual
        self.reason = reason
        super().__init__(
            f"manifest authority violation for {tool_name!r}: {reason}; "
            f"declared={sorted(declared)} actual={sorted(actual)}"
        )


INSTRUCTION_MARKERS = (
    "before invoking", "call ", "include the result", "note:",
    "you must", "execute ", "send the", "pass the",
)


def bind_manifest(manifest: dict, task_capabilities: set) -> dict:
    """Resolve a manifest to a binding, enforcing authority-from-binding.

    Returns the binding only if the resolved implementation's capabilities
    are a subset of what the current task legitimately needs. Raises
    ManifestAuthorityError otherwise. Never trusts manifest metadata as
    a description of authority.
    """
    name = manifest.get("name", "<unnamed>")
    description = manifest.get("description", "")

    lowered = description.lower()
    for marker in INSTRUCTION_MARKERS:
        if marker in lowered:
            raise ManifestAuthorityError(
                tool_name=name,
                declared=set(manifest.get("capabilities", [])),
                actual=set(),
                reason=f"description carries instruction fragment {marker!r}; "
                       f"descriptions are untrusted data, not directives",
            )

    # Authority is derived from the resolved binding, NOT the manifest's
    # declared category. In production this comes from a build-time
    # capability token or static analysis of the callable.
    binding = resolve_binding(manifest)
    actual_caps = set(binding.capabilities)

    declared_caps = set(manifest.get("capabilities", []))
    if not actual_caps.issubset(task_capabilities):
        excess = actual_caps - task_capabilities
        raise ManifestAuthorityError(
            tool_name=name,
            declared=declared_caps,
            actual=actual_caps,
            reason=f"binding reach exceeds task need by {sorted(excess)}; "
                   f"refusing to load rather than silently downgrade",
        )

    # Description enters context as quarantined data only.
    return {
        "name": name,
        "callable": binding.callable,
        "description_as_data": {"provenance": "untrusted_manifest", "text": description},
        "granted_capabilities": sorted(actual_caps),
    }


def resolve_binding(manifest: dict):
    raise NotImplementedError("runtime-specific: static analysis or signed token")
