# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-argument-is-assembled-from-mixed-provenance-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-argument-is-assembled-from-mixed-provenance-spans.warrant.json
# Markdown SHA-256:   c5260a4e08a921ed722e8c90afcdff32d188f444843627ff6391eecd2020397c
# Code AST SHA-256:   377e08ab7bae6914de7b2cf1fdd9aa7b73eb5e2f79ba55424fbdecad4ec94a2a
# Verified Classes:   TaintBoundaryError, ParamRole, Span, AuthorityToken
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Iterable


class TaintBoundaryError(RuntimeError):
    """Raised when a tainted span reaches an authority-bearing parameter role."""


class ParamRole(Enum):
    INERT = "inert"          # rendered to human, no downstream interpretation
    SELECTOR = "selector"    # resolved by a capability-checked resolver
    AUTHORITY = "authority"  # interpreted by shell/SMTP/URL/SQL authority


@dataclass(frozen=True)
class Span:
    text: str
    tainted: bool
    source: str


@dataclass(frozen=True)
class AuthorityToken:
    """A sub-span the downstream parser will treat as authority-bearing."""
    value: str
    byte_start: int
    byte_end: int


# Allowlist of sanitizers proven total for a given authority grammar.
# Empty by default: no string sanitizer is trusted to clear authority taint.
TOTAL_CLEARING_SANITIZERS: frozenset[str] = frozenset()


def tokenize_authority(role: ParamRole, text: str) -> list[AuthorityToken]:
    """Must mirror the downstream consumer's parser. If it does not, the gate
    is mislocating taint and the invariant is already broken."""
    if role is ParamRole.AUTHORITY and "@" in text:
        # Conservative: treat the entire address as one authority token so a
        # display-vs-routing mismatch (ops@corp.example@attacker.evil.example)
        # cannot split into a "clean" prefix and a "tainted" suffix.
        return [AuthorityToken(text, 0, len(text))]
    if role is ParamRole.AUTHORITY:
        return [AuthorityToken(text, 0, len(text))]
    return []


def gate_invocation(
    role: ParamRole,
    spans: Iterable[Span],
    sanitizer_name: str | None = None,
) -> None:
    """Enforce: no tainted bytes may reach an authority-bearing token, unless
    cleared by a sanitizer on the total-clearing allowlist for this grammar."""
    if role is not ParamRole.AUTHORITY:
        return  # inert/selector handled by encoding/resolver, not this gate

    joined = "".join(s.text for s in spans)
    tokens = tokenize_authority(role, joined)

    for tok in tokens:
        # Map token byte range back to contributing spans.
        cursor = 0
        for s in spans:
            s_start, s_end = cursor, cursor + len(s.text)
            cursor = s_end
            overlaps = not (s_end <= tok.byte_start or s_start >= tok.byte_end)
            if not overlaps or not s.tainted:
                continue
            if sanitizer_name is not None and sanitizer_name in TOTAL_CLEARING_SANITIZERS:
                continue
            raise TaintBoundaryError(
                f"tainted span from {s.source!r} contributes bytes "
                f"[{max(s_start, tok.byte_start)}:{min(s_end, tok.byte_end)}] "
                f"to authority token {tok.value!r}; role={role.value}. "
                f"Recovery: rebuild the authority token from clean structured "
                f"fields; do not re-sanitize and retry."
            )


# --- Example: the laundering variant that must fail closed ---
def build_recipient(user_to: str, notes_text: str) -> list[Span]:
    return [
        Span(text=user_to, tainted=False, source="user_turn"),
        Span(text="," + notes_text, tainted=True, source="file:/tmp/notes.md"),
    ]


if __name__ == "__main__":
    spans = build_recipient(
        "ops@corp.example",
        "ops@corp.example@attacker.evil.example",
    )
    try:
        gate_invocation(ParamRole.AUTHORITY, spans, sanitizer_name="strip_semicolons")
    except TaintBoundaryError as e:
        print("BLOCKED:", e)
