# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tool-result-redaction-as-a-state-mutating-event-rather-than-a-view-layer-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tool-result-redaction-as-a-state-mutating-event-rather-than-a-view-layer-filter.warrant.json
# Markdown SHA-256:   b6f9f93fd1bbcc433ffdd593c8c450affb9853e71784a6e9a9b057e1cbe1e1bb
# Code AST SHA-256:   7c56f51528b7ec2a79af6bdc3ff722b6dfa6e8dfaccf3ef8297b6a18a9ffbeb5
# Verified Classes:   DlpReceiptMissingError, SealedCapabilityError, RateLimitProvenanceError, RedactionKind, ToolResult, SessionState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class DlpReceiptMissingError(RuntimeError):
    """Raised when a redacted tool result is forwarded without a state-mutation receipt."""


class SealedCapabilityError(RuntimeError):
    """Raised when an allowlisted tool would reconstruct DLP-sealed information."""


class RateLimitProvenanceError(RuntimeError):
    """Raised when a rate-limit error lacks provenance and cannot be safely retried."""


class RedactionKind(Enum):
    NONE = "none"
    PII = "pii"
    SECRET = "secret"


@dataclass
class ToolResult:
    tool: str
    payload: dict[str, Any]
    redactions: int = 0
    redaction_kind: RedactionKind = RedactionKind.NONE
    receipt_present: bool = False


@dataclass
class SessionState:
    session_id: str
    allowlist: set[str]
    sealed_classes: set[RedactionKind] = field(default_factory=set)
    # Tools whose declared output schema intersects a sealed class.
    reconstructors: dict[RedactionKind, set[str]] = field(default_factory=dict)


def gate_tool_result(session: SessionState, result: ToolResult) -> ToolResult:
    """Enforce the state-mutation invariant at the gateway egress point."""
    if result.redactions > 0 and not result.receipt_present:
        # The agent will confabulate around an unmarked hole; refuse to forward.
        raise DlpReceiptMissingError(
            f"session={session.session_id} tool={result.tool} "
            f"redactions={result.redactions} kind={result.redaction_kind.value} "
            "forwarded without _gateway receipt; agent cannot distinguish "
            "substitution from source data"
        )

    if result.redactions > 0:
        session.sealed_classes.add(result.redaction_kind)
        # Any allowlisted tool that can reconstruct the sealed class is now out of scope.
        for tool in session.allowlist:
            if tool in session.reconstructors.get(result.redaction_kind, set()):
                # Do not silently drop; the harness must see a distinct signal.
                pass
    return result


def authorize_call(session: SessionState, tool: str) -> None:
    """Reject calls that would reconstruct a DLP-sealed information class."""
    if tool not in session.allowlist:
        raise SealedCapabilityError(
            f"session={session.session_id} tool={tool} not in allowlist"
        )
    for kind in session.sealed_classes:
        if tool in session.reconstructors.get(kind, set()):
            raise SealedCapabilityError(
                f"session={session.session_id} tool={tool} would reconstruct "
                f"sealed class {kind.value}; sealed_classes={sorted(k.value for k in session.sealed_classes)}"
            )


def handle_rate_limit(session: SessionState, error: dict[str, Any]) -> None:
    """Rate-limit errors must carry provenance so the harness can decide to retry."""
    reason = error.get("data", {}).get("reason")
    if reason is None:
        raise RateLimitProvenanceError(
            f"session={session.session_id} rate-limit error without reason; "
            "cannot distinguish burst from sealed_probe, retry is unsafe"
        )
    if reason == "sealed_probe":
        # Non-retryable: the agent was probing a sealed boundary.
        raise SealedCapabilityError(
            f"session={session.session_id} rate-limit reason=sealed_probe; "
            "halt and escalate, do not retry"
        )
    # reason == "burst": harness may retry under its normal backoff policy.


# --- Exercise the invariant against the observed trace ---

session = SessionState(
    session_id="sess-7f2a",
    allowlist={"web.search", "web.fetch", "doc.read"},
    reconstructors={
        RedactionKind.PII: {"web.search", "web.fetch"},
    },
)

# t=0.02: doc.read returns PII-redacted payload with no receipt.
try:
    gate_tool_result(
        session,
        ToolResult(tool="doc.read", payload={"employees": []}, redactions=12,
                   redaction_kind=RedactionKind.PII, receipt_present=False),
    )
except DlpReceiptMissingError as e:
    print(f"[gateway] {e}")

# Correct behavior: forward with receipt, seal PII class.
sealed = gate_tool_result(
    session,
    ToolResult(tool="doc.read", payload={"employees": []}, redactions=12,
               redaction_kind=RedactionKind.PII, receipt_present=True),
)
print(f"[gateway] forwarded with receipt; sealed_classes={[k.value for k in session.sealed_classes]}")

# t=1.1: agent attempts reconstruction via web.search -> now rejected.
try:
    authorize_call(session, "web.search")
except SealedCapabilityError as e:
    print(f"[gateway] {e}")

# t=1.4: rate-limit error without provenance -> harness cannot safely retry.
try:
    handle_rate_limit(session, {"code": -32000, "message": "rate_limited"})
except RateLimitProvenanceError as e:
    print(f"[gateway] {e}")
