# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-peer-s-policy-override-during-cross-org-tool-invocation-and-why-silent-reconciliation-corrup.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-peer-s-policy-override-during-cross-org-tool-invocation-and-why-silent-reconciliation-corrup.warrant.json
# Markdown SHA-256:   6d5003e453ed7b59fb74debc089b4fef5f2d77721047278263c128e3016de3cb
# Code AST SHA-256:   16bd5fe18a1bf9517bc63f2e4ffe1ecb3263b989633e980435213a0b77ce8e48
# Verified Classes:   Effect, PrioritySemantics, NonReconcilableConflict, Rule, MergeResolution
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class Effect(Enum):
    ALLOW = "allow"
    DENY = "deny"


class PrioritySemantics(Enum):
    AUTHORITY = "authority"   # higher = more authoritative
    SALIENCE = "salience"     # higher = more salient to author, NOT more authoritative


class NonReconcilableConflict(RuntimeError):
    """Raised when a federated policy conflict cannot be resolved without a signed directive."""
    pass


@dataclass(frozen=True)
class Rule:
    rule_id: str
    bundle_org: str
    tool: str
    effect: Effect
    condition: str
    priority: int
    priority_semantics: PrioritySemantics


@dataclass(frozen=True)
class MergeResolution:
    effective_rule_id: str
    winning_rule: Rule
    losing_rule: Optional[Rule]
    resolution_kind: str          # "single_source" | "lattice_stricter" | "signed_directive"
    signed_by: Optional[str]      # None means NOT safe to execute


def resolve(local: Rule, peer: Rule) -> MergeResolution:
    if local.tool != peer.tool:
        raise NonReconcilableConflict(f"tool mismatch: {local.tool} vs {peer.tool}")

    # Type-confusion guard: peer priority semantics must match local interpretation.
    if local.priority_semantics != peer.priority_semantics:
        raise NonReconcilableConflict(
            f"priority semantics mismatch on {local.tool}: "
            f"{local.bundle_org}={local.priority_semantics.value}, "
            f"{peer.bundle_org}={peer.priority_semantics.value}"
        )

    # Restriction lattice first: deny beats allow regardless of priority scalar.
    if local.effect != peer.effect:
        stricter = local if local.effect == Effect.DENY else peer
        looser = peer if stricter is local else local
        return MergeResolution(
            effective_rule_id=stricter.rule_id,
            winning_rule=stricter,
            losing_rule=looser,
            resolution_kind="lattice_stricter",
            signed_by=stricter.bundle_org,
        )

    # Same effect, different conditions: incomparable predicates are non-reconcilable.
    if local.condition != peer.condition:
        raise NonReconcilableConflict(
            f"incomparable conditions on {local.tool}: "
            f"{local.rule_id!r} ({local.condition}) vs {peer.rule_id!r} ({peer.condition}); "
            f"no scalar priority may substitute for a signed merge directive"
        )

    # Identical rules: single source.
    return MergeResolution(
        effective_rule_id=local.rule_id,
        winning_rule=local,
        losing_rule=None,
        resolution_kind="single_source",
        signed_by=local.bundle_org,
    )


def execute_tool(resolution: MergeResolution, caller_role: str) -> str:
    if resolution.signed_by is None:
        raise NonReconcilableConflict(
            f"refusing to execute {resolution.effective_rule_id}: unsigned composite rule"
        )
    if resolution.winning_rule.effect == Effect.DENY:
        raise NonReconcilableConflict(
            f"policy deny on {resolution.winning_rule.tool} for role {caller_role}"
        )
    return f"executed under {resolution.effective_rule_id} (signed by {resolution.signed_by})"
