# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-speculative-sub-agent-fan-out-before-merge-reconciliation-and-how-do-you-bound-the-divergence-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-speculative-sub-agent-fan-out-before-merge-reconciliation-and-how-do-you-bound-the-divergence-window.warrant.json
# Markdown SHA-256:   f2482c2ab62e97c7aa5cd97dba8909947cce9e4f49ef3d16cc38da069f957299
# Code AST SHA-256:   371e80e5cd8437d029b3b853ae970897f0d7e553dc0445eba829d89bdc00b273
# Verified Classes:   SpeculativeMergeDivergence, SubPlan, DraftPlan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class SpeculativeMergeDivergence(RuntimeError):
    """Raised when a speculative fan-out cannot be soundly reconciled."""


@dataclass(frozen=True)
class SubPlan:
    agent_index: int
    step_ids: frozenset
    targets: frozenset          # resolved referents, e.g. {"users", "users_archive"}
    ambiguity_witness: tuple    # non-empty => sub-agent resolved an underdetermined referent
    status: str


@dataclass(frozen=True)
class DraftPlan:
    step_graph_order: tuple
    referent_closure: frozenset  # all referents the draft could denote
    ambiguity_set: frozenset     # referents the draft leaves underdetermined


def reconcile(draft: DraftPlan, subplans: Iterable[SubPlan]) -> tuple:
    subplans = list(subplans)
    if len(subplans) < 2:
        # Single sub-agent: no merge, no divergence possible.
        return tuple(subplans[0].step_ids) if subplans else ()

    # Guard 1: witness obligation. Absence of a witness is not evidence of
    # absence of ambiguity when the draft's ambiguity set is non-empty.
    for sp in subplans:
        if sp.status != "ok":
            raise SpeculativeMergeDivergence(
                f"sub-agent {sp.agent_index} not ok: {sp.status}"
            )
        if sp.ambiguity_witness:
            raise SpeculativeMergeDivergence(
                f"sub-agent {sp.agent_index} resolved underdetermined referent: "
                f"{sp.ambiguity_witness}"
            )
        if draft.ambiguity_set and not sp.ambiguity_witness:
            # Witness was not enforced; we cannot prove soundness.
            raise SpeculativeMergeDivergence(
                f"draft ambiguity set {sorted(draft.ambiguity_set)} non-empty but "
                f"sub-agent {sp.agent_index} emitted no witness; fan-out unsound"
            )

    # Guard 2: target-set intersection under the draft's referent closure.
    seen: dict = {}
    for sp in subplans:
        for t in sp.targets & draft.referent_closure:
            if t in seen and seen[t] != sp.agent_index:
                raise SpeculativeMergeDivergence(
                    f"referent {t!r} resolved by both agent {seen[t]} and "
                    f"agent {sp.agent_index}; merge order would be metadata-derived"
                )
            seen[t] = sp.agent_index

    # Guard 3: order must derive from the draft's step graph, not agent_index.
    all_steps = set()
    for sp in subplans:
        all_steps |= set(sp.step_ids)
    missing = all_steps - set(draft.step_graph_order)
    if missing:
        raise SpeculativeMergeDivergence(
            f"sub-plans emitted steps {sorted(missing)} not in draft step graph; "
            f"merge order is not a function of draft semantics"
        )
    return tuple(s for s in draft.step_graph_order if s in all_steps)
