# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-s-declared-side-effects-when-the-executing-code-path-diverges-from-the-declaration-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-s-declared-side-effects-when-the-executing-code-path-diverges-from-the-declaration-at-load-time.warrant.json
# Markdown SHA-256:   526c57bf777e8af207b08ad86e03671c8b683760fef4463fd3556676093cb85c
# Code AST SHA-256:   3f60ee783d92b97e8f3eef8a610a177831dd405c73e43d1bdd902dd30485eff5
# Verified Classes:   ManifestEffectDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestEffectDivergence(RuntimeError):
    """Raised when a tool's executed effect exceeds its declared effect at call time."""
    pass


def authorize_call(manifest: dict, accepted_schema: dict, args: dict,
                   inherited_scope: set[str], nested: bool) -> None:
    declared = manifest.get("annotations", {})
    read_only = declared.get("readOnlyHint") is True

    # Invariant 1: arguments must match the schema the server actually enforces,
    # not merely the schema it negotiated. Drift here is silent escalation.
    extra = set(args) - set(accepted_schema.get("properties", {}))
    if extra:
        raise ManifestEffectDivergence(
            f"args {sorted(extra)} accepted by implementation but absent from "
            f"declared inputSchema for {manifest.get('name')!r}"
        )

    # Invariant 2: a nested call is a new principal; it may not inherit the
    # parent's approval context. Re-authorize against declared scope.
    if nested and not inherited_scope <= set(manifest.get("scopes", [])):
        raise ManifestEffectDivergence(
            f"nested call from {manifest.get('name')!r} reaches "
            f"{sorted(inherited_scope - set(manifest.get('scopes', [])))} "
            f"outside declared scope"
        )

    # Invariant 3: a read-only annotation never authorizes a mutating code path.
    if read_only and args.get("__op__") in {"write", "delete", "exec"}:
        raise ManifestEffectDivergence(
            f"readOnlyHint=true but call carries mutating op "
            f"{args['__op__']!r} on {manifest.get('name')!r}"
        )
