# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-task-after-its-local-policy-witness-has-already-been-cosigned-by-a-remote-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-task-after-its-local-policy-witness-has-already-been-cosigned-by-a-remote-peer.warrant.json
# Markdown SHA-256:   ef9355ed9fab455856a1ea50542a0ba59d8690a693baeb4e12afa39fa6171036
# Code AST SHA-256:   c89f061ca695ca62f4fff040b8bc6bcc3957cdab123b67ecd47d9696840a96ce
# Verified Classes:   PolicyRefusal, Conjunct, Witness, SideEffect
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import FrozenSet


class PolicyRefusal(RuntimeError):
    """Raised when a federated side effect fails live local policy re-authorization."""


class Conjunct(Enum):
    SCOPE_SUBSET = "scope_subset"
    LOCAL_AUTHORIZE = "local_authorize"
    EPOCH_CURRENT = "epoch_current"
    RESIDENCY_MATCH = "residency_match"


@dataclass(frozen=True)
class Witness:
    witness_id: str
    epoch: int
    residency: str
    tool_scopes: FrozenSet[str]


@dataclass(frozen=True)
class SideEffect:
    scope: str
    target_residency: str


def authorize_side_effect(
    effect: SideEffect,
    witness: Witness,
    *,
    current_epoch: int,
    local_grants: FrozenSet[str],
    exercised_scopes: FrozenSet[str],
) -> None:
    """
    Enforce the four-conjunct invariant before permitting a side effect.
    Raises PolicyRefusal on the first failing conjunct; the caller must
    transition the task to REFUSED_PENDING_RENEGOTIATION, never retry.
    """
    union_scopes = exercised_scopes | {effect.scope}

    if not union_scopes.issubset(witness.tool_scopes):
        raise PolicyRefusal(
            f"{Conjunct.SCOPE_SUBSET.value}: exercised {sorted(union_scopes)} "
            f"exceeds witness {sorted(witness.tool_scopes)}"
        )
    if effect.scope not in local_grants:
        raise PolicyRefusal(
            f"{Conjunct.LOCAL_AUTHORIZE.value}: {effect.scope} not in live local grants"
        )
    if witness.epoch != current_epoch:
        raise PolicyRefusal(
            f"{Conjunct.EPOCH_CURRENT.value}: witness epoch {witness.epoch} "
            f"!= current {current_epoch}"
        )
    if effect.target_residency != witness.residency:
        raise PolicyRefusal(
            f"{Conjunct.RESIDENCY_MATCH.value}: target {effect.target_residency} "
            f"!= witness {witness.residency}"
        )
