# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-semantic-conflict-when-merging-peer-agent-plans-whose-tool-call-graphs-are-individually-valid-but-jointly-non-commutativ.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-semantic-conflict-when-merging-peer-agent-plans-whose-tool-call-graphs-are-individually-valid-but-jointly-non-commutativ.warrant.json
# Markdown SHA-256:   cbdcc82efd11653505d20bd8ba258df30f4e7e94415c8316cab703248d3333c8
# Code AST SHA-256:   6ae36f7439d9111d322f2578119229238f50d8624bbd893421fc00e183ca1db9
# Verified Classes:   NonCommutativeMergeError, Operation, Plan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class NonCommutativeMergeError(RuntimeError):
    """Raised when two locally-valid plans conflict on a shared resource
    in a way that makes the merged outcome order-dependent and unverified."""


@dataclass(frozen=True)
class Operation:
    name: str
    reads: FrozenSet[str]
    writes: FrozenSet[str]
    guards: FrozenSet[str]  # resource keys referenced in guard predicates
    irreversible: bool = False


@dataclass
class Plan:
    agent_id: str
    ops: list[Operation] = field(default_factory=list)


def detect_merge_conflict(p1: Plan, p2: Plan) -> list[str]:
    """Return conflict descriptions; empty list means merge is safe to order."""
    conflicts = []
    for op1 in p1.ops:
        for op2 in p2.ops:
            shared_write = (op1.writes & op2.writes) | (op1.writes & op2.reads) | (op2.writes & op1.reads)
            if not shared_write:
                continue
            # A guard on either side reads a key the other side writes -> guard instability.
            guard_instability = (op1.guards & op2.writes) | (op2.guards & op1.writes)
            if guard_instability:
                conflicts.append(
                    f"{p1.agent_id}:{op1.name} <-> {p2.agent_id}:{op2.name} "
                    f"guard-unstable on {sorted(guard_instability)}"
                )
            elif shared_write and (op1.irreversible or op2.irreversible):
                conflicts.append(
                    f"{p1.agent_id}:{op1.name} <-> {p2.agent_id}:{op2.name} "
                    f"irreversible write overlap on {sorted(shared_write)}"
                )
    return conflicts


def merge_plans(p1: Plan, p2: Plan, allow_serialize: bool = False) -> list[Operation]:
    conflicts = detect_merge_conflict(p1, p2)
    if not conflicts:
        return p1.ops + p2.ops
    if not allow_serialize:
        raise NonCommutativeMergeError(
            "Refusing to merge plans with order-dependent effects: " + "; ".join(conflicts)
        )
    # Serialization path requires post-order guard re-validation, which is
    # only sound for reversible writes; any irreversible conflict aborts.
    for c in conflicts:
        if "irreversible" in c:
            raise NonCommutativeMergeError(
                "Cannot serialize merge with irreversible write conflict: " + c
            )
    raise NonCommutativeMergeError(
        "Serialized merge requires external guard re-validation not performed here: "
        + "; ".join(conflicts)
    )
