# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-side-effects-when-speculative-agent-branches-roll-back-after-optimistic-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-side-effects-when-speculative-agent-branches-roll-back-after-optimistic-tool-invocation.warrant.json
# Markdown SHA-256:   5e3e326df4bc945c4d37d1add0e62d32e70c55e8205cb0d104a45c676f6a4cbb
# Code AST SHA-256:   72d756891c3f34df0c672f2fee60cfec8ecbfeb318947fb5b8c680a0d62ce09a
# Verified Classes:   EffectTierViolation, OrphanedEffectError, ToolRegistry, SpeculativeBranch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EffectTierViolation(RuntimeError):
    """Raised when a speculative branch attempts a committed-only effect."""
    pass


class OrphanedEffectError(RuntimeError):
    """Raised when rollback leaves an external effect unaccounted for."""
    pass


PURE = "pure"
STAGED = "staged"
COMMITTED_ONLY = "committed_only"


class ToolRegistry:
    def __init__(self, tiers: dict[str, str]):
        self._tiers = tiers

    def tier_of(self, tool_name: str) -> str:
        if tool_name not in self._tiers:
            # Unclassified tools are treated as committed-only: fail closed.
            return COMMITTED_ONLY
        return self._tiers[tool_name]


class SpeculativeBranch:
    def __init__(self, branch_id: str, registry: ToolRegistry, committed: bool = False):
        self.branch_id = branch_id
        self.registry = registry
        self.committed = committed
        self.staged_effects: list[tuple[str, dict]] = []
        self.flushed_effects: list[tuple[str, dict]] = []

    def invoke(self, tool_name: str, args: dict, executor):
        tier = self.registry.tier_of(tool_name)
        if tier == PURE:
            return executor(tool_name, args)
        if tier == STAGED:
            self.staged_effects.append((tool_name, args))
            return {"staged": True, "branch": self.branch_id}
        if tier == COMMITTED_ONLY:
            if not self.committed:
                raise EffectTierViolation(
                    f"branch {self.branch_id} attempted committed-only tool "
                    f"{tool_name!r} before commit; rollback would orphan the effect"
                )
            result = executor(tool_name, args)
            self.flushed_effects.append((tool_name, args))
            return result
        raise EffectTierViolation(f"unknown tier {tier!r} for {tool_name!r}")

    def commit(self, executor):
        self.committed = True
        for tool_name, args in self.staged_effects:
            executor(tool_name, args)
            self.flushed_effects.append((tool_name, args))
        self.staged_effects.clear()

    def rollback(self, external_ledger: list[tuple[str, dict]]):
        # Staged effects are dropped with the branch: no external trace.
        self.staged_effects.clear()
        # Any flushed effect from an uncommitted branch is an orphan.
        for effect in self.flushed_effects:
            if effect in external_ledger:
                raise OrphanedEffectError(
                    f"branch {self.branch_id} rolled back but effect {effect!r} "
                    f"is present in the external ledger; rollback boundary crossed"
                )
        if self.flushed_effects:
            raise OrphanedEffectError(
                f"branch {self.branch_id} has flushed effects with no external "
                f"record; reconciliation cannot prove the world is clean"
            )
