# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-cross-org-speculative-divergence-before-commit-quorum-in-federated-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-cross-org-speculative-divergence-before-commit-quorum-in-federated-agent-execution.warrant.json
# Markdown SHA-256:   4862fc7f4ea5103925bec75c7cc5b9009c78862d03c7f2376d76e547bdf699ad
# Code AST SHA-256:   911153b83be5417c5fa500155aa20d72cc14a6f1d8f9cec687ac0a08446575eb
# Verified Classes:   SpeculativeEpochDivergence
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeEpochDivergence(RuntimeError):
    """Raised when a participant's write-set was sealed against a namespace
    epoch that no longer matches the commit quorum's epoch, and the write-set
    is non-commutative — making output-based quorum certification unsound."""
    pass


COMMUTATIVE_OPS = frozenset({"add_member", "increment_counter", "set_flag"})


def verify_participant_seal(participant: dict, commit_epoch: int) -> None:
    """
    participant: {
        "org": str,
        "base_epoch": int,      # epoch the plan envelope told the agent to assume
        "seal_epoch": int,      # epoch of local mirror when write-set was frozen
        "write_ops": list[str], # operation kinds in the write-set
        "predicted_output": any
    }
    """
    gap = participant["seal_epoch"] - participant["base_epoch"]
    non_commutative = any(
        op not in COMMUTATIVE_OPS for op in participant["write_ops"]
    )

    if participant["seal_epoch"] != commit_epoch and non_commutative:
        raise SpeculativeEpochDivergence(
            f"org={participant['org']} sealed write-set at epoch "
            f"{participant['seal_epoch']} but commit epoch is {commit_epoch} "
            f"(base_epoch={participant['base_epoch']}, gap={gap}); "
            f"write-set contains non-commutative ops {participant['write_ops']}; "
            f"predicted_output={participant['predicted_output']!r} is not "
            f"sufficient evidence of consistency — abort and re-speculate."
        )

    # Commutative write-sets may proceed even across an epoch gap, but the
    # gap must still be recorded for audit.
    if gap != 0:
        participant["audit_note"] = (
            f"seal_epoch gap {gap} tolerated: write-set is commutative"
        )


def certify_quorum(participants: list[dict], commit_epoch: int) -> bool:
    for p in participants:
        verify_participant_seal(p, commit_epoch)
    return True
