# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forks-the-shared-context-store-during-a-partition-and-rejoins-with-a-divergent-but-valid-episodic-log.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forks-the-shared-context-store-during-a-partition-and-rejoins-with-a-divergent-but-valid-episodic-log.warrant.json
# Markdown SHA-256:   cf8887fb4c2203ed6fd5a9c15bbff2dbd08affa374a9cab63a802ffa78ea661f
# Code AST SHA-256:   d9700c04a6216c59f3a063e88146acd7abe29c04276b60a931752de1b0dd641a
# Verified Classes:   CausalMergeError, Entry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalMergeError(RuntimeError):
    """Raised when a divergent branch cannot be merged without violating causal order."""


@dataclass
class Entry:
    slot: int                      # quorum-assigned global index, unique
    author: str
    payload: bytes
    parents: set[int]              # slots this entry causally depends on
    attestations: int = 0
    signature: bytes = b""

    def attested(self, quorum: int) -> bool:
        return self.attestations >= quorum

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.slot.to_bytes(8, "big"))
        h.update(self.author.encode())
        h.update(self.payload)
        for p in sorted(self.parents):
            h.update(p.to_bytes(8, "big"))
        return h.hexdigest()


def merge_branches(
    local: list[Entry],
    remote: list[Entry],
    quorum: int,
) -> tuple[list[Entry], list[Entry]]:
    """
    Merge two divergent branches of the shared context store.

    Returns (merged_entries, quarantined_entries).

    Raises CausalMergeError if the union DAG contains a cycle (impossible
    under correct slot assignment) or if a merge is attempted on entries
    that would silently reorder causal dependencies.
    """
    union: dict[int, Entry] = {}
    for e in local + remote:
        if e.slot in union and union[e.slot].digest() != e.digest():
            raise CausalMergeError(
                f"slot collision at {e.slot}: two distinct entries claim the same "
                f"quorum-assigned index — indicates a broken slot allocator"
            )
        union[e.slot] = e

    # Only attested entries may enter the visible merged log.
    visible = {s: e for s, e in union.items() if e.attested(quorum)}
    quarantined: list[Entry] = [e for e in union.values() if not e.attested(quorum)]

    # Topological sort over causal parent edges; quarantine entries whose
    # parents are unmet in the merged view.
    resolved: dict[int, Entry] = {}
    pending = dict(visible)
    progress = True
    while pending and progress:
        progress = False
        for slot, entry in list(pending.items()):
            if entry.parents.issubset(resolved.keys()):
                resolved[slot] = entry
                del pending[slot]
                progress = True

    if pending:
        # Entries remain whose causal parents are not present with quorum
        # attestation in the merged view. Their precondition was never
        # established on the branch where they were written.
        for slot, entry in pending.items():
            unmet = entry.parents - resolved.keys()
            quarantined.append(entry)
            # Fail closed: do not emit a partial order that reorders these.
        if any(e.parents & set(pending) for e in pending.values()):
            raise CausalMergeError(
                "union DAG contains a cycle among unattested/pending entries; "
                "merge cannot produce a valid total order"
            )

    merged = [resolved[s] for s in sorted(resolved)]
    return merged, quarantined


def resume_agent_context(
    agent_id: str,
    merged: list[Entry],
    quarantined: list[Entry],
    last_common_ancestor: int,
) -> None:
    """
    Called on rejoin. If any entry the agent's context depended on was
    quarantined, the agent MUST roll back to last_common_ancestor rather
    than continue on a partially merged view.
    """
    quarantined_slots = {e.slot for e in quarantined}
    if not quarantined_slots:
        return
    # Determine whether this agent's prior context touched a quarantined slot.
    if any(e.slot > last_common_ancestor for e in quarantined):
        raise CausalMergeError(
            f"agent {agent_id}: context depends on quarantined slot(s) "
            f"{sorted(quarantined_slots)} beyond ancestor {last_common_ancestor}; "
            f"rollback to ancestor required before resuming reasoning"
        )
