# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-capabilities-over-its-observed-effects-skill-injection-via-manifest-drift-and-the-sand.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-capabilities-over-its-observed-effects-skill-injection-via-manifest-drift-and-the-sand.warrant.json
# Markdown SHA-256:   67713d2d5b5a3c738804969dfd896a6f68691df9735170fcbfe9c8a28c355998
# Code AST SHA-256:   0b0a579b117a4dbecc4af62d13f19990e0d59dad07bfd5cd7943f8f8456b48be
# Verified Classes:   CapabilityEscalationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import os

class CapabilityEscalationError(RuntimeError):
    """Raised when a tool's observed effects exceed its declared/operator-granted envelope."""
    pass


def enforce_tool_call(tool_manifest: dict, operator_policy: dict, call_args: dict, effects: dict) -> None:
    # 1. Capabilities come from operator policy, NOT from the tool's own manifest.
    granted = set(operator_policy.get("granted_capabilities", []))
    declared = set(tool_manifest.get("declared_capabilities", []))

    # A tool may not grant itself anything the operator didn't already allow.
    if not declared.issubset(granted):
        raise CapabilityEscalationError(
            f"tool {tool_manifest.get('name')!r} declares {sorted(declared - granted)} "
            f"outside operator grant {sorted(granted)}"
        )

    # 2. Canonicalize path args BEFORE scope-checking (defeats ../ and symlink traversal).
    scope_root = os.path.realpath(operator_policy["scope_root"])
    for key, val in call_args.items():
        if key.endswith("path") and isinstance(val, str):
            real = os.path.realpath(os.path.join(scope_root, val))
            if not (real == scope_root or real.startswith(scope_root + os.sep)):
                raise CapabilityEscalationError(
                    f"arg {key}={val!r} canonicalizes to {real!r} outside scope {scope_root!r}"
                )

    # 3. Reconcile OBSERVED effects against the declared envelope; fail closed.
    observed = set(effects.get("resources_touched", []))
    undeclared = observed - declared
    if undeclared:
        raise CapabilityEscalationError(
            f"tool {tool_manifest.get('name')!r} touched undeclared resources: {sorted(undeclared)}"
        )
