# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-an-inherited-taint-label-rather-than-propagate-it-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-an-inherited-taint-label-rather-than-propagate-it-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   eb3d88062373c83d44061b4f0b417deefc1cd00ff03214ac2f9f32a83d8ceb9a
# Code AST SHA-256:   4448e4b7b232d93261b7482db5bfb36e5e414f3274dea098be9d316a7f1027ba
# Verified Classes:   TaintBoundaryViolation, Segment, ToolProfile
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintBoundaryViolation(RuntimeError):
    """Raised when a labeled segment crosses a tool boundary without a valid
    label-continuity guarantee, and the downstream sink is side-effecting."""


@dataclass(frozen=True)
class Segment:
    content: str
    taint: FrozenSet[str] = field(default_factory=frozenset)
    # provenance anchor survives only if the producing tool preserved it
    anchor: str = ""


class ToolProfile:
    def __init__(self, name: str, label_homomorphic: bool, output_inspectable: bool):
        self.name = name
        self.label_homomorphic = label_homomorphic
        self.output_inspectable = output_inspectable


def cross_boundary(seg: Segment, tool: ToolProfile, sink_is_side_effecting: bool) -> Segment:
    """Apply the three-way split: propagate, re-derive, or quarantine."""
    if tool.label_homomorphic:
        # propagate: output taint is a superset of input taint
        return Segment(seg.content, seg.taint | {f"tool:{tool.name}"}, seg.anchor)

    if tool.output_inspectable:
        # re-derive: re-scan observable output; conservative re-taint
        derived = set(seg.taint)
        if _looks_instructional(seg.content):
            derived.add("external")
        return Segment(seg.content, frozenset(derived), anchor="")

    # lossy + non-inspectable: label is unverifiable
    quarantined = Segment(seg.content, frozenset({"unverifiable"}), anchor="")
    if sink_is_side_effecting and seg.taint:
        raise TaintBoundaryViolation(
            f"segment with taint={sorted(seg.taint)} passed through lossy "
            f"non-inspectable tool '{tool.name}' and reached a side-effecting sink; "
            f"label is unverifiable — quarantine required"
        )
    return quarantined


def _looks_instructional(text: str) -> bool:
    markers = ("ignore prior", "ignore previous", "forward the", "send the")
    low = text.lower()
    return any(m in low for m in markers)
