# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-sibling-agent-s-tool-side-effects-and-the-reconciliation-barrier-arrives-after-the-branch-s-contex.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-sibling-agent-s-tool-side-effects-and-the-reconciliation-barrier-arrives-after-the-branch-s-contex.warrant.json
# Markdown SHA-256:   bb08e2bb3272555276b2ebd62aa0907011eddd9bad2a3437e743fd6d54736e82
# Code AST SHA-256:   66686f7a555c54c8340d4753272fa42530709e39fdb366317efc05fd99ae7a61
# Verified Classes:   UnreconcilableBranchError, BranchLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconcilableBranchError(RuntimeError):
    """Raised when a speculative branch's mutating calls cannot be matched
    to a durable ledger entry, so rollback cannot be trusted."""
    pass


class BranchLedger:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.entries: list[dict] = []          # durable, non-compactable
        self.compacted = False

    def record(self, tool: str, args: dict, precondition: dict | None):
        self.entries.append({
            "tool": tool,
            "args": args,
            "precondition": precondition,   # None => record-dependent
            "reversible_by_state": precondition is not None,
        })

    def mark_compacted(self):
        self.compacted = True


def reconcile(branch: BranchLedger, tool_layer_call_count: int) -> list[dict]:
    # Invariant 1: ledger must cover every mutating call the tool layer saw.
    if len(branch.entries) != tool_layer_call_count:
        raise UnreconcilableBranchError(
            f"branch {branch.branch_id}: ledger has {len(branch.entries)} "
            f"entries but tool layer observed {tool_layer_call_count} "
            f"mutating calls; rollback would be partial and unsafe"
        )

    # Invariant 2: a compacted branch may only roll back self-inverting calls.
    if branch.compacted:
        record_dependent = [e for e in branch.entries if not e["reversible_by_state"]]
        if record_dependent:
            raise UnreconcilableBranchError(
                f"branch {branch.branch_id}: compacted with "
                f"{len(record_dependent)} record-dependent mutations "
                f"(e.g. {record_dependent[0]['tool']}); "
                f"preconditions were evicted before the barrier resolved"
            )

    return list(reversed(branch.entries))   # undo in reverse order
