# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-speculative-branch-provenance-before-committing-tool-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-speculative-branch-provenance-before-committing-tool-effects.warrant.json
# Markdown SHA-256:   9b482a8439139faa34d2b39d8c8a572bc1d9b095a23e74b5702ae10f16a6ab66
# Code AST SHA-256:   6dae350c4013effcd293cdb95722704b02bca12d791969370b3590e3750413e8
# Verified Classes:   ProvenanceLaunderingError, Span, BranchArtifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a branch artifact's taint ancestry cannot be established at merge."""
    pass


@dataclass
class Span:
    span_id: str
    origin: str          # e.g. "untrusted:tool_output", "trusted:policy"
    text: str


@dataclass
class BranchArtifact:
    branch_id: str
    content: str
    source_spans: list[str] = field(default_factory=list)   # span_ids consumed
    read_set: set[str] = field(default_factory=set)          # every span the branch read


def _overlaps(content: str, span: Span, min_tokens: int = 6) -> bool:
    # Crude lexical overlap: any >=min_tokens contiguous token run shared.
    c_tokens = content.lower().split()
    s_tokens = span.text.lower().split()
    if len(s_tokens) < min_tokens:
        return span.text.lower() in content.lower()
    window = {" ".join(s_tokens[i:i + min_tokens])
              for i in range(len(s_tokens) - min_tokens + 1)}
    for i in range(len(c_tokens) - min_tokens + 1):
        if " ".join(c_tokens[i:i + min_tokens]) in window:
            return True
    return False


def admit_to_commit(
    artifact: BranchArtifact,
    span_registry: dict[str, Span],
    verification_passed: bool = False,
) -> None:
    """Merge gate. Raises if artifact cannot safely drive an effectful commit."""
    declared = set(artifact.source_spans)

    # Condition 1: laundering detector — empty declared provenance but content
    # derived from spans the branch actually read.
    if not declared:
        for sid in artifact.read_set:
            span = span_registry.get(sid)
            if span and _overlaps(artifact.content, span):
                raise ProvenanceLaunderingError(
                    f"branch {artifact.branch_id} artifact has empty source_spans "
                    f"but overlaps read span {sid} ({span.origin}); taint laundered"
                )

    # Condition 2: ancestry must be fully resolvable.
    unresolved = declared - span_registry.keys()
    if unresolved:
        raise ProvenanceLaunderingError(
            f"branch {artifact.branch_id} cites unknown spans {sorted(unresolved)}"
        )

    # Condition 3: untrusted ancestry blocks effectful commitment absent verification.
    untrusted = [sid for sid in declared
                 if span_registry[sid].origin.startswith("untrusted:")]
    if untrusted and not verification_passed:
        raise ProvenanceLaunderingError(
            f"branch {artifact.branch_id} artifact descends from untrusted spans "
            f"{sorted(untrusted)} with no verification node; commit blocked"
        )
    # Admitted: safe to hand to executor.
