# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-divergent-rollback-ledger-when-speculative-branches-reconcile-against-a-shared-mutable-workspace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-divergent-rollback-ledger-when-speculative-branches-reconcile-against-a-shared-mutable-workspace.warrant.json
# Markdown SHA-256:   4b109e60beb3add1d3720c6b4ca010c4509cc8bf5123cac871ad9974d7c589ca
# Code AST SHA-256:   ae08a5053271197f6d2e35a0b8a0b2bd4a70b33909b037a6c1286ec2994587af
# Verified Classes:   RollbackOwnershipError, JournalEntry, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RollbackOwnershipError(RuntimeError):
    """Raised when a branch attempts to restore a path it no longer owns."""
    pass


@dataclass
class JournalEntry:
    path: str
    original_bytes: bytes
    fork_gen: int
    last_write_gen: int
    last_written_hash: str


@dataclass
class Branch:
    branch_id: str
    fork_gen: int
    journal: dict[str, JournalEntry] = field(default_factory=dict)


def _hash(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def guarded_rollback(branch: Branch, workspace, current_gen: int) -> list[str]:
    """
    Apply the branch's undo journal only for paths it can prove it still owns.
    workspace exposes: read(path) -> bytes, write(path, data), bump_gen() -> int
    Returns the list of paths successfully restored. Raises on ownership loss.
    """
    restored: list[str] = []
    for path, entry in branch.journal.items():
        if entry.fork_gen != branch.fork_gen:
            raise RollbackOwnershipError(
                f"{branch.branch_id}: journal entry {path} stamped fork_gen="
                f"{entry.fork_gen}, branch fork_gen={branch.fork_gen}"
            )
        if current_gen < entry.last_write_gen:
            raise RollbackOwnershipError(
                f"{branch.branch_id}: workspace gen {current_gen} precedes "
                f"branch last_write_gen {entry.last_write_gen} for {path}"
            )
        observed = workspace.read(path)
        if _hash(observed) != entry.last_written_hash:
            # Another branch has written since our last write: we lost ownership.
            raise RollbackOwnershipError(
                f"{branch.branch_id}: lost ownership of {path}; "
                f"observed hash {_hash(observed)[:12]} != "
                f"last_written_hash {entry.last_written_hash[:12]}"
            )
        workspace.write(path, entry.original_bytes)
        restored.append(path)
    if restored:
        workspace.bump_gen()
    return restored
