# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-speculative-agent-execution-corrupt-its-parent-state-when-a-rolled-back-branch-writes-to-a-shared-reconciliation-log.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-speculative-agent-execution-corrupt-its-parent-state-when-a-rolled-back-branch-writes-to-a-shared-reconciliation-log.warrant.json
# Markdown SHA-256:   b9c696bfe7b92458fc3d8c3aa036b176c86825e47c36248d48292b0a12149a04
# Code AST SHA-256:   9ef382d826cdcf659be2c195b04244a218aeb33bd503e0ae1ca16582b5dee505
# Verified Classes:   PhantomIntentError, Intent, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PhantomIntentError(RuntimeError):
    """Raised when reconciliation observes an intent from a non-committed branch."""


@dataclass
class Intent:
    resource: str
    branch_id: str
    epoch: int


@dataclass
class Branch:
    branch_id: str
    epoch: int
    committed: bool = False


def reconcile(
    intents: list[Intent],
    branches: dict[str, Branch],
    committed_ids: set[str],
) -> list[Intent]:
    """Apply intents only if their writer is a committed, live branch.

    Enforces the invariant: log contents at reconcile time must be a subset
    of committed-branch effects. Any intent whose (branch_id, epoch) does not
    match a committed branch is a phantom and must abort reconciliation.
    """
    applied: list[Intent] = []
    for intent in intents:
        branch = branches.get(intent.branch_id)
        if branch is None:
            raise PhantomIntentError(
                f"intent for {intent.resource!r} references unknown branch "
                f"{intent.branch_id!r}"
            )
        if intent.epoch != branch.epoch:
            raise PhantomIntentError(
                f"intent for {intent.resource!r} has stale epoch "
                f"{intent.epoch} (live {branch.epoch})"
            )
        if intent.branch_id not in committed_ids or not branch.committed:
            raise PhantomIntentError(
                f"phantom intent: branch {intent.branch_id!r} wrote "
                f"{intent.resource!r} but was rolled back"
            )
        applied.append(intent)
    return applied


def safe_reconcile(intents, branches, committed_ids):
    applied = reconcile(intents, branches, committed_ids)
    if len(applied) != len(committed_ids):
        raise PhantomIntentError(
            f"effect count {len(applied)} != committed branches "
            f"{len(committed_ids)}; log is inconsistent"
        )
    return applied
