# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-divergence-when-a-rollback-target-was-mutated-by-a-sibling-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-divergence-when-a-rollback-target-was-mutated-by-a-sibling-agent.warrant.json
# Markdown SHA-256:   5421b214e3b1353a24be0a794bac3edf6cd564c9af582719a18ab1e4c904bbd4
# Code AST SHA-256:   1c9a37b4050ee2a15aa9d8ebda263375689915a73dbcbaa3d7561d2a054e45de
# Verified Classes:   CheckpointDriftError, Checkpoint, Substrate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CheckpointDriftError(RuntimeError):
    """Raised when a rollback target's substrate no longer matches its mint hash."""


@dataclass
class Checkpoint:
    handle: str
    substrate_hash: str
    mutation_log_offset: int
    owner_branch: str


@dataclass
class Substrate:
    """Shared mutable substrate with an append-only mutation log."""
    state: dict = field(default_factory=dict)
    mutations: list = field(default_factory=list)

    def hash(self) -> str:
        blob = repr(sorted(self.state.items())).encode()
        return hashlib.sha256(blob).hexdigest()

    def mutate(self, branch: str, key: str, value) -> int:
        self.state[key] = value
        self.mutations.append({"branch": branch, "key": key, "value": value})
        return len(self.mutations) - 1

    def foreign_mutations_since(self, offset: int, rolling_branch: str) -> list:
        return [
            m for m in self.mutations[offset:]
            if m["branch"] != rolling_branch
        ]


def mint_checkpoint(substrate: Substrate, handle: str, owner: str) -> Checkpoint:
    return Checkpoint(
        handle=handle,
        substrate_hash=substrate.hash(),
        mutation_log_offset=len(substrate.mutations),
        owner_branch=owner,
    )


def rollback(
    substrate: Substrate,
    checkpoint: Checkpoint,
    rolling_branch: str,
    allow_reconcile: bool = False,
) -> Optional[list]:
    """
    Roll back to a checkpoint only if its substrate is intact, or if the
    caller explicitly opts into reconciling enumerated foreign drift.
    """
    current_hash = substrate.hash()
    if current_hash == checkpoint.substrate_hash:
        return None  # sound rollback; no drift to reconcile

    foreign = substrate.foreign_mutations_since(
        checkpoint.mutation_log_offset, rolling_branch
    )

    if not allow_reconcile:
        raise CheckpointDriftError(
            f"rollback to {checkpoint.handle} unsound: substrate hash "
            f"{current_hash[:12]} != mint hash "
            f"{checkpoint.substrate_hash[:12]}; "
            f"{len(foreign)} foreign mutation(s) since mint "
            f"(branches: {sorted({m['branch'] for m in foreign})})"
        )

    # Reconcile: replay inverse of foreign mutations, newest first.
    for m in reversed(foreign):
        substrate.state.pop(m["key"], None)

    if substrate.hash() != checkpoint.substrate_hash:
        raise CheckpointDriftError(
            f"reconciliation of {checkpoint.handle} incomplete: "
            f"post-reconcile hash {substrate.hash()[:12]} still != "
            f"{checkpoint.substrate_hash[:12]}"
        )
    return foreign
