# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-commit-divergence-when-optimistic-multi-agent-plans-silently-fork-the-shared-state-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-commit-divergence-when-optimistic-multi-agent-plans-silently-fork-the-shared-state-graph.warrant.json
# Markdown SHA-256:   98295338fadf05dfb93b6f04ac95563702dd26d9a3a026ef2a50c4c0a45ff86a
# Code AST SHA-256:   a589acd746fed90aa68c322fc349a68ee9f8552f74eed61c12cc89a1218f8f67
# Verified Classes:   SpeculativeCommitDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeCommitDivergence(RuntimeError):
    """Raised when a merge replay produces a state where every per-agent
    post-condition holds but a registered global invariant is violated.
    This is the fingerprint of optimistic-commit divergence: local validity
    masking a global conservation breach."""
    pass


def merge_with_invariant_check(
    base_state: dict,
    admitted_mutations: list[dict],
    registered_invariants: dict[str, callable],
    intent_groups: dict[str, list[str]],
) -> dict:
    # Reconstruct atomic intent sets: a mutation whose intent_id appears in
    # intent_groups must be admitted or dropped as a whole.
    dropped_intents = set()
    for intent_id, mutation_ids in intent_groups.items():
        admitted = [m for m in admitted_mutations if m["id"] in mutation_ids]
        if 0 < len(admitted) < len(mutation_ids):
            raise SpeculativeCommitDivergence(
                f"Atomicity breach on intent {intent_id!r}: "
                f"{len(admitted)}/{len(mutation_ids)} mutations admitted. "
                f"Resolver dropped half an intent; halt and reconcile."
            )
        if not admitted:
            dropped_intents.add(intent_id)

    merged = dict(base_state)
    for m in admitted_mutations:
        merged.update(m["delta"])

    # Global invariants are checked on the merged state, NOT on per-agent
    # post-conditions. A residual here that no single atomic mutation
    # explains is speculative-commit divergence.
    for name, check in registered_invariants.items():
        if not check(merged):
            raise SpeculativeCommitDivergence(
                f"Global invariant {name!r} violated on merged state "
                f"despite all per-agent post-conditions holding. "
                f"Admitted={len(admitted_mutations)}, "
                f"dropped_intents={sorted(dropped_intents)}. "
                f"Roll back to base and replay intact logs."
            )
    return merged
