# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-was-mutated-between-capability-negotiation-and-first-invocation-in-a-dynamically-loaded-agent-plugin.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-was-mutated-between-capability-negotiation-and-first-invocation-in-a-dynamically-loaded-agent-plugin.warrant.json
# Markdown SHA-256:   5fffa780e28df3cc015c273d71d2c53b6c5b50012bde8f0f11cb1af36124f271
# Code AST SHA-256:   3feb548e883e1337da518858cfe88a705fbe911f2d539d74032bad3ca7d6b7b9
# Verified Classes:   ManifestSkewError, NegotiatedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestSkewError(RuntimeError):
    """Raised when a tool manifest mutated between negotiation and invocation
    in a way that invalidates the planner's committed call plan."""


# Fields whose mutation invalidates a plan already derived from the manifest.
CONSTRAINT_FIELDS = {"pattern", "enum", "minimum", "maximum", "required", "type"}
SEMANTIC_FIELDS = {"description", "side_effects", "auth_scopes", "confirmation"}


@dataclass
class NegotiatedManifest:
    tool_id: str
    etag: str
    schema: dict[str, Any]
    snapshot_hash: str = field(init=False)

    def __post_init__(self) -> None:
        canon = json.dumps(self.schema, sort_keys=True, separators=(",", ":"))
        self.snapshot_hash = hashlib.sha256(canon.encode()).hexdigest()


def _diff_paths(a: Any, b: Any, prefix: str = "") -> list[str]:
    """Return dotted paths where two JSON structures differ."""
    out: list[str] = []
    if type(a) is not type(b):
        return [prefix or "<root>"]
    if isinstance(a, dict):
        for k in set(a) | set(b):
            p = f"{prefix}.{k}" if prefix else k
            if k not in a or k not in b:
                out.append(p)
            else:
                out.extend(_diff_paths(a[k], b[k], p))
    elif isinstance(a, list):
        if len(a) != len(b):
            out.append(prefix)
        else:
            for i, (x, y) in enumerate(zip(a, b)):
                out.extend(_diff_paths(x, y, f"{prefix}[{i}]"))
    elif a != b:
        out.append(prefix)
    return out


def _field_kind(path: str) -> str:
    leaf = path.rsplit(".", 1)[-1].split("[", 1)[0].lower()
    if leaf in CONSTRAINT_FIELDS:
        return "constraint"
    if leaf in SEMANTIC_FIELDS:
        return "semantic"
    return "other"


def verify_invocation_manifest(
    negotiated: NegotiatedManifest,
    current_schema: dict[str, Any],
    current_etag: str,
) -> None:
    """Gate an invocation against the manifest the plan was built from.

    Raises ManifestSkewError if the current registry manifest differs from the
    negotiated snapshot on any constraint or semantic field. A pure ETag bump
    with an identical body is tolerated (CDN revalidation); a body change is not.
    """
    if current_etag == negotiated.etag:
        return  # no revalidation needed

    changed = _diff_paths(negotiated.schema, current_schema)
    if not changed:
        return  # etag churn, body identical — safe to proceed

    blocking = [p for p in changed if _field_kind(p) in ("constraint", "semantic")]
    if blocking:
        raise ManifestSkewError(
            f"tool {negotiated.tool_id!r} mutated after negotiation "
            f"(etag {negotiated.etag!r} -> {current_etag!r}); "
            f"plan-invalidating fields changed: {sorted(blocking)}; "
            f"re-negotiate and re-plan before invoking"
        )
    # Non-blocking drift: log and proceed under the negotiated snapshot's
    # client-side constraints, which remain authoritative for this plan.
    return


def guarded_invoke(
    negotiated: NegotiatedManifest,
    current_schema: dict[str, Any],
    current_etag: str,
    call_args: dict[str, Any],
    invoke_fn,
):
    """Invoke a tool only after skew verification; enforce negotiated
    constraints client-side so a mutated server cannot relax them."""
    verify_invocation_manifest(negotiated, current_schema, current_etag)

    # Client-side enforcement of the negotiated constraint surface.
    params = negotiated.schema.get("parameters", {})
    for name, spec in params.items():
        if name not in call_args:
            if spec.get("required"):
                raise ManifestSkewError(
                    f"missing required arg {name!r} per negotiated manifest"
                )
            continue
        pattern = spec.get("pattern")
        if pattern is not None:
            import re
            if not re.fullmatch(pattern, str(call_args[name])):
                raise ManifestSkewError(
                    f"arg {name!r} violates negotiated pattern {pattern!r}; "
                    f"refusing call under possibly-relaxed server manifest"
                )
    return invoke_fn(call_args)
