# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-policy-warrant-when-the-counterparty-s-attestation-chain-is-valid-but-its-data-boundary-predicate-is-evaluat.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-policy-warrant-when-the-counterparty-s-attestation-chain-is-valid-but-its-data-boundary-predicate-is-evaluat.warrant.json
# Markdown SHA-256:   788bafac1e67c5678cc50122116c92b617b8cee0cfa64bb18bbc9a8b95572f3c
# Code AST SHA-256:   715e1c42e872862951dce59095af6378dab285d1504daeff065ed09bad92b54b
# Verified Classes:   ContextBindingViolation, NegotiationEnvelope, PolicyWarrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ContextBindingViolation(RuntimeError):
    """Raised when a federated policy warrant's context_hash does not match the live execution context."""
    pass


@dataclass(frozen=True)
class NegotiationEnvelope:
    purpose: str
    retention_days: int
    requesting_tenant: str
    task_id: str

    def context_hash(self) -> str:
        payload = json.dumps(
            {
                "purpose": self.purpose,
                "retention_days": self.retention_days,
                "requesting_tenant": self.requesting_tenant,
                "task_id": self.task_id,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass(frozen=True)
class PolicyWarrant:
    dataset: str
    context_hash: str
    signature_valid: bool
    envelope: NegotiationEnvelope  # carried, never reconstructed


def exercise_warrant(warrant: PolicyWarrant, live_context: NegotiationEnvelope, resource: str) -> None:
    # C1: signature
    if not warrant.signature_valid:
        raise ContextBindingViolation("C1 failed: warrant signature invalid")

    # C2: scope
    if resource != warrant.dataset:
        raise ContextBindingViolation(f"C2 failed: resource {resource!r} outside warrant scope {warrant.dataset!r}")

    # C3: context binding — recompute from LIVE context, compare to signed hash
    live_hash = live_context.context_hash()
    if live_hash != warrant.context_hash:
        raise ContextBindingViolation(
            "C3 failed: live execution context does not match signed context_hash; "
            f"warrant was signed over {warrant.context_hash[:12]}…, live context hashes to {live_hash[:12]}…; "
            "refuse and re-negotiate — do not reconstruct the envelope"
        )

    # C4: freshness is enforced by the caller's max_age check against warrant issuance time
    # (omitted here for brevity; must be present in production)


def gated_read(warrant: PolicyWarrant, live_context: NegotiationEnvelope, resource: str) -> str:
    exercise_warrant(warrant, live_context, resource)
    return f"read_ok:{resource}"


# --- Failure trace reproduction (the drill's 40/40 silent crossing) ---
if __name__ == "__main__":
    signed = NegotiationEnvelope(purpose="support", retention_days=30,
                                 requesting_tenant="org_a", task_id="t-001")
    warrant = PolicyWarrant(dataset="customer_pii",
                            context_hash=signed.context_hash(),
                            signature_valid=True,
                            envelope=signed)

    # Post-resume reconstruction: purpose pulled from stale billing memory,
    # retention defaulted by model tool-call generation.
    reconstructed = NegotiationEnvelope(purpose="billing", retention_days=90,
                                        requesting_tenant="org_a", task_id="t-001")

    try:
        gated_read(warrant, reconstructed, "customer_pii")
    except ContextBindingViolation as e:
        print(f"REFUSED (correct): {e}")
        # Correct recovery: re-negotiate with the live context, obtain fresh warrant.
        # Do NOT proceed under the old warrant.
