# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-manifest-as-a-capability-escalation-vector-rather-than-inert-configuration.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-manifest-as-a-capability-escalation-vector-rather-than-inert-configuration.warrant.json
# Markdown SHA-256:   975259cbc672af6e34bf4175b79db6c1e2c7d1b18827d805f3f1ab8fbb687255
# Code AST SHA-256:   9e2a47add8371cf5dfecc45a6fa391dd22a26d7e5f14b1b40f8e5c86d4984089
# Verified Classes:   CapabilityEscalationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilityEscalationError(RuntimeError):
    """Raised when a tool call or manifest merge exceeds the frozen plan grant."""
    pass


TRUSTED_ANNOTATION_SOURCES = frozenset({"pinned_trust_root"})


def dispatch_tool_call(call, plan, live_index):
    """
    Enforce the plan-authorization invariant at dispatch time.
    `plan` is frozen at authorization: it carries granted_capabilities and
    resource_scope. `live_index` may contain manifests merged after authorization.
    """
    tool = live_index.get(call.name)
    if tool is None:
        raise CapabilityEscalationError(
            f"tool {call.name!r} not in live index; refusing dispatch"
        )

    # Capability must be a subset of the plan grant, regardless of manifest hints.
    missing = set(tool.declared_capabilities) - set(plan.granted_capabilities)
    if missing:
        raise CapabilityEscalationError(
            f"tool {call.name!r} requires {sorted(missing)} not granted by plan "
            f"{plan.id!r}; manifest annotations are not authorization"
        )

    # Argument scope is checked against the plan, not the schema.
    for resource in call.declared_resources:
        if resource not in plan.resource_scope:
            raise CapabilityEscalationError(
                f"call {call.name!r} touches {resource!r} outside plan resource_scope"
            )

    # Untrusted annotations must never gate or bypass a confirmation check.
    if tool.annotations_source not in TRUSTED_ANNOTATION_SOURCES:
        if tool.annotations.get("readOnlyHint") and call.is_mutating():
            raise CapabilityEscalationError(
                f"tool {call.name!r} self-declared readOnlyHint=true but call mutates; "
                "annotation source is untrusted and cannot suppress the gate"
            )

    return tool.invoke(call)


def merge_manifest(manifest, plan, live_index):
    """
    A merge that changes reachable capabilities without re-authorization is an
    escalation event, not a configuration update.
    """
    if manifest.provenance not in TRUSTED_ANNOTATION_SOURCES:
        manifest.trust = "UNTRUSTED"  # descriptions become opaque data, not guidance
    new_caps = set(manifest.declared_capabilities)
    if not new_caps.issubset(set(plan.granted_capabilities)):
        raise CapabilityEscalationError(
            f"manifest {manifest.name!r} introduces {sorted(new_caps - set(plan.granted_capabilities))} "
            f"beyond plan {plan.id!r}; re-authorize or quarantine"
        )
    live_index.add(manifest)
