# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tool-s-declared-outputschema-before-trusting-its-post-call-payload-rather-than-trusting-the-manifest-s.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tool-s-declared-outputschema-before-trusting-its-post-call-payload-rather-than-trusting-the-manifest-s.warrant.json
# Markdown SHA-256:   509f122381e6ea5030096218b41a22679b386948c2882847c0231563ca3aaa2a
# Code AST SHA-256:   7fed11a06d2390ce37f1d74c4c1d083ced2e1d2fe5a7bab2c00b399666e893b2
# Verified Classes:   OutputSchemaDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any

# Keys that carry execution semantics in the agent's context envelope.
# A tool result may never introduce these at the top level of its payload.
RESERVED_STRUCTURAL_KEYS = frozenset(
    {"role", "content", "tool_calls", "system", "function_call"}
)


class OutputSchemaDriftError(RuntimeError):
    """Raised when a tool result violates its declared outputSchema or
    attempts to synthesize a structural message envelope."""


def validate_tool_result(
    server_manifest_hash: str,
    bound_manifest_hash: str,
    declared_schema_keys: frozenset[str],
    payload: dict[str, Any],
) -> dict[str, Any]:
    """Gate a tool result before it re-enters the model context.

    Returns the sanitized payload (declared keys only) or raises.
    """
    if server_manifest_hash != bound_manifest_hash:
        raise OutputSchemaDriftError(
            f"manifest hash changed mid-session: "
            f"{bound_manifest_hash} -> {server_manifest_hash}"
        )

    keys = frozenset(payload.keys())
    extra = keys - declared_schema_keys
    structural = extra & RESERVED_STRUCTURAL_KEYS

    if structural:
        # Data-plane payload tried to cross into control-plane.
        raise OutputSchemaDriftError(
            f"tool result injected structural keys {sorted(structural)}; "
            f"halting task rather than retrying same server"
        )

    if extra:
        # Benign drift: quarantine extras, keep declared fields only.
        return {k: payload[k] for k in declared_schema_keys if k in payload}

    return payload


def bind_and_call(
    manifest: dict[str, Any],
    call_fn,
    args: dict[str, Any],
) -> dict[str, Any]:
    raw_manifest = json.dumps(manifest, sort_keys=True).encode()
    bound_hash = hashlib.sha256(raw_manifest).hexdigest()
    declared = frozenset(manifest["outputSchema"]["properties"].keys())

    result = call_fn(args)

    # Re-read the manifest after the call: a poisoned server may rotate it.
    live_hash = hashlib.sha256(
        json.dumps(call_fn.manifest(), sort_keys=True).encode()
    ).hexdigest()

    return validate_tool_result(
        server_manifest_hash=live_hash,
        bound_manifest_hash=bound_hash,
        declared_schema_keys=declared,
        payload=result,
    )
