# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-federated-policy-verdicts-when-a-cross-org-broker-admits-a-message-under-one-tenant-s-policy-and-the-receiving-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-federated-policy-verdicts-when-a-cross-org-broker-admits-a-message-under-one-tenant-s-policy-and-the-receiving-agent.warrant.json
# Markdown SHA-256:   6f5b75499decd992cc2d45a8cc9caac3eb8cb39a3658603f32e956f9600068d4
# Code AST SHA-256:   1039f880cabd33c255e7906429e2a9cd8dcc3a5873f4f7bfce4f46bb8d73a1e1
# Verified Classes:   StaleVerdictError, PolicyCompositionError, Verdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Literal


class StaleVerdictError(RuntimeError):
    """Raised when an inbound broker verdict does not describe the decoded payload."""


class PolicyCompositionError(RuntimeError):
    """Raised when cross-org verdict composition cannot be resolved to deny-overrides."""


@dataclass(frozen=True)
class Verdict:
    decision: Literal["allow", "deny"]
    policy_id: str
    subject_hash: str          # hash of the payload the verdict judged
    coverage: frozenset[str]   # field paths the verdict actually covers
    provenance_intact: bool    # did classifier_version survive the broker rewrite?


def payload_hash(decoded: dict) -> str:
    # Canonical form: the exact object the receiver will act on.
    canonical = json.dumps(decoded, sort_keys=True, separators=(",", ":"))
    return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def reconcile(
    wire_payload: bytes,
    inbound: Verdict,
    local_decision: Literal["allow", "deny"],
    local_coverage: frozenset[str],
) -> Literal["allow", "deny"]:
    decoded = json.loads(wire_payload.decode("utf-8"))
    actual = payload_hash(decoded)

    # Invariant 1: a verdict must describe the object we decoded.
    if inbound.subject_hash != actual:
        # Verdict is stale (payload rewritten post-verdict, e.g. redaction).
        # It is not a weak verdict; it is not a verdict. Fall back to local only.
        if local_decision == "deny":
            return "deny"
        # Local allow over an object the broker never judged is still unsafe
        # unless local policy covers everything the broker claimed to cover.
        if not local_coverage >= inbound.coverage:
            raise StaleVerdictError(
                f"stale verdict {inbound.policy_id}: subject_hash mismatch "
                f"({inbound.subject_hash} != {actual}) and local coverage "
                f"{sorted(local_coverage)} does not cover {sorted(inbound.coverage)}"
            )
        return "allow"

    # Invariant 2: provenance-stripped verdicts are advisory only.
    if not inbound.provenance_intact:
        if local_decision == "deny":
            return "deny"
        if not local_coverage >= inbound.coverage:
            raise PolicyCompositionError(
                f"advisory verdict {inbound.policy_id} has stripped provenance "
                f"and local coverage is insufficient"
            )
        return "allow"

    # Invariant 3: deny-overrides. Never upstream-wins.
    if inbound.decision == "deny" or local_decision == "deny":
        return "deny"
    return "allow"


def dispatch(wire_payload: bytes, inbound: Verdict, local_eval) -> None:
    local_decision, local_coverage = local_eval(json.loads(wire_payload.decode("utf-8")))
    final = reconcile(wire_payload, inbound, local_decision, local_coverage)
    if final == "deny":
        raise PolicyCompositionError(
            f"message blocked at composition: inbound={inbound.decision} "
            f"local={local_decision} policy={inbound.policy_id}"
        )
    # ... forward to tool/agent execution
