# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-dynamically-loaded-tool-manifest-whose-declared-schema-and-post-injection-behavioral-envelope-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-dynamically-loaded-tool-manifest-whose-declared-schema-and-post-injection-behavioral-envelope-diverge.warrant.json
# Markdown SHA-256:   273884c7c6b9dcd717ef7d49f15392c3cde7148bb813298627d3605c13d3dfea
# Code AST SHA-256:   66a3bdfe082e259819d61f132084a71086b286e6b75c5fe2f76c0474f5d4a1f2
# Verified Classes:   ManifestAuthorizationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestAuthorizationError(RuntimeError):
    """Raised when a dynamically loaded manifest requests authority it is not entitled to."""
    pass


REVIEWED_TOOL_NAMES = frozenset({"read_file", "summarize_doc", "post_status"})


def bind_manifest(manifest: dict, reviewed_names: frozenset = REVIEWED_TOOL_NAMES) -> dict:
    """
    Bind a dynamically loaded tool manifest into the active tool set.

    Enforces tool-name closure: a dynamic manifest may only reference tools
    already present in the reviewed primary set. Unknown names are a hard
    reject at bind time, not a lazy bind on first use.
    """
    declared = manifest.get("tools", [])
    if not isinstance(declared, list):
        raise ManifestAuthorizationError(
            f"manifest.tools must be a list, got {type(declared).__name__}"
        )

    unknown = [t.get("name") for t in declared if t.get("name") not in reviewed_names]
    if unknown:
        raise ManifestAuthorizationError(
            "dynamic manifest references unreviewed tool names: "
            f"{unknown!r}; refusing to bind (tool-name closure violated)"
        )

    # Wrap model-facing text so the system prompt can mark it as data, not
    # instructions. The wrapper is applied here, not trusted from the manifest.
    bound = []
    for tool in declared:
        bound.append({
            "name": tool["name"],
            "schema": tool.get("inputSchema", {}),
            "description_delimited": (
                "<untrusted_manifest_text>\n"
                + str(tool.get("description", ""))
                + "\n</untrusted_manifest_text>"
            ),
            "provenance": "dynamic",
        })
    return {"tools": bound, "provenance": "dynamic"}


def execute_tool_call(call: dict, bound: dict) -> dict:
    """Execute a tool call, refusing calls to tools absent from the bound set."""
    name = call.get("name")
    allowed = {t["name"] for t in bound.get("tools", [])}
    if name not in allowed:
        raise ManifestAuthorizationError(
            f"tool call {name!r} not present in bound tool set {sorted(allowed)!r}"
        )
    # ... dispatch to reviewed implementation ...
    return {"ok": True, "tool": name}
