# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-byzantine-sub-agent-s-plan-fragment-before-aggregation-the-decomposition-quorum-invariant-and-its-silent-violation-unde.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-byzantine-sub-agent-s-plan-fragment-before-aggregation-the-decomposition-quorum-invariant-and-its-silent-violation-unde.warrant.json
# Markdown SHA-256:   dd6a7daf841d979c65c4681e8efdb353ee5bf23ebdc7b138c5078946b5f49c88
# Code AST SHA-256:   1ae516d4bd7b4d12d218072dc3d4da008d9e0d8f86aa6cd64eabfe4f0cb62157
# Verified Classes:   ViewConsistencyViolation, Fragment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ViewConsistencyViolation(RuntimeError):
    """Raised when a fragment's precondition was authored against a view
    of a sibling fragment that differs from the aggregator's committed view."""
    pass


@dataclass
class Fragment:
    agent_id: str
    preconditions: dict          # state_key -> expected value
    postconditions: dict         # state_key -> produced value
    cites: dict = field(default_factory=dict)  # agent_id -> claimed fragment hash


def fragment_hash(frag: Fragment) -> str:
    payload = repr((sorted(frag.preconditions.items()),
                    sorted(frag.postconditions.items()))).encode()
    return hashlib.sha256(payload).hexdigest()


def aggregate(committed: dict[str, Fragment],
              incoming: list[Fragment]) -> list[Fragment]:
    """Merge fragments only if every cited sibling hash matches the
    committed view. Reject the whole batch on any equivocation."""
    committed_hashes = {aid: fragment_hash(f) for aid, f in committed.items()}

    for frag in incoming:
        for cited_id, cited_hash in frag.cites.items():
            true_hash = committed_hashes.get(cited_id)
            if true_hash is None:
                raise ViewConsistencyViolation(
                    f"{frag.agent_id} cites unknown fragment {cited_id}")
            if cited_hash != true_hash:
                raise ViewConsistencyViolation(
                    f"equivocation: {frag.agent_id} authored preconditions "
                    f"against a divergent view of {cited_id} "
                    f"(cited {cited_hash[:12]}, committed {true_hash[:12]})")

    # Only now is per-key majority voting sound: all views are aligned.
    merged: list[Fragment] = []
    for frag in incoming:
        for key, val in frag.preconditions.items():
            producers = [f for f in incoming
                         if f.postconditions.get(key) not in (None, val)]
            if producers:
                raise ViewConsistencyViolation(
                    f"unsatisfiable precondition on {key!r}: "
                    f"{frag.agent_id} requires {val!r}, "
                    f"{producers[0].agent_id} produces "
                    f"{producers[0].postconditions[key]!r}")
        merged.append(frag)
    return merged
