# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-replay-before-an-audit-warrant-is-considered-discharged.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-replay-before-an-audit-warrant-is-considered-discharged.warrant.json
# Markdown SHA-256:   01b89ab1d677b17eb631c64dd73c83190772ed29c3fccd324a2777cc7affc41c
# Code AST SHA-256:   2e4c9f2ad366a60475d0e20039ef7912d63121cfe15f7983dd4c683dfd653395
# Verified Classes:   UnattributableForkError, Branch, Fork
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class UnattributableForkError(RuntimeError):
    """Raised when a committed branch claims causal audit status
    without a complete, pinned sibling frontier."""
    pass

@dataclass
class Branch:
    branch_id: str
    status: str                 # committed | eliminated | failed | pruned
    external_state_pinned: bool # was live external state frozen at commit?

@dataclass
class Fork:
    fork_id: str
    siblings: list[Branch]
    selector_pure: bool         # selector a pure function of the frontier?
    committed_id: Optional[str] = None

    def committed(self) -> Branch:
        for b in self.siblings:
            if b.branch_id == self.committed_id:
                return b
        raise UnattributableForkError(
            f"fork {self.fork_id}: committed branch {self.committed_id} "
            f"not present in sibling frontier"
        )

def discharge_warrant(fork: Fork, replay_matched: bool) -> str:
    committed = fork.committed()

    if not replay_matched:
        # divergence: either environmental drift or corruption
        if all(s.external_state_pinned for s in fork.siblings) and fork.selector_pure:
            raise UnattributableForkError(
                f"fork {fork.fork_id}: replay diverged with fully pinned "
                f"witness -> genuine corruption, fail closed"
            )
        return "environmental-branch-drift"

    # replay matched the committed leaf; now decide attribution strength
    frontier_complete = len(fork.siblings) >= 2 and all(
        s.status in {"committed", "eliminated", "failed", "pruned"}
        for s in fork.siblings
    )
    pinned = all(s.external_state_pinned for s in fork.siblings)

    if not frontier_complete or not pinned or not fork.selector_pure:
        raise UnattributableForkError(
            f"fork {fork.fork_id}: committed branch {committed.branch_id} "
            f"replays consistently but lacks a complete pinned sibling "
            f"frontier; warrant downgraded to consistency-only"
        )

    return "causal"
