# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-provenance-is-lost-during-context-compaction-and-how-to-detect-it-before-the-summary-re-enters-the-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-provenance-is-lost-during-context-compaction-and-how-to-detect-it-before-the-summary-re-enters-the-loop.warrant.json
# Markdown SHA-256:   9145d7deb2422eebf252c8ca46687a7965a9d642cf27872492062151b4f393a0
# Code AST SHA-256:   d99a015f935e46be138068c2f52c8e463854645b2f22ee35ea61acbc9e850431
# Verified Classes:   TaintLaunderingError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

TrustLevel = Literal["trusted", "untrusted"]

class TaintLaunderingError(RuntimeError):
    """Raised when compaction output loses provenance for a tainted span."""
    pass

@dataclass
class Segment:
    text: str
    source_ids: frozenset[str]
    trust: TrustLevel

def merge_segments(a: Segment, b: Segment) -> Segment:
    # Meet, not join: merged trust is the least-trusted parent.
    trust: TrustLevel = "untrusted" if "untrusted" in (a.trust, b.trust) else "trusted"
    return Segment(
        text=a.text + " " + b.text,
        source_ids=a.source_ids | b.source_ids,
        trust=trust,
    )

def compact(segments: list[Segment], summarizer) -> list[Segment]:
    """Summarizer must return segments with source_ids preserved; trust is
    recomputed from source_ids, never taken from summarizer output."""
    out = summarizer(segments)  # expected: list of (text, source_ids)
    before = {sid for s in segments for sid in s.source_ids}
    after = {sid for text, sids in out for sid in sids}
    missing = before - after
    if missing:
        raise TaintLaunderingError(
            f"compaction dropped provenance for sources: {sorted(missing)}"
        )
    source_trust = {}
    for s in segments:
        for sid in s.source_ids:
            prev = source_trust.get(sid, "trusted")
            source_trust[sid] = "untrusted" if (prev == "untrusted" or s.trust == "untrusted") else "trusted"
    result = []
    for text, sids in out:
        trusts = {source_trust[sid] for sid in sids}
        trust: TrustLevel = "untrusted" if "untrusted" in trusts else "trusted"
        result.append(Segment(text=text, source_ids=frozenset(sids), trust=trust))
    return result

def execute_tool_call(segment: Segment, tool: str, arg: str, confirm) -> str:
    if segment.trust == "untrusted" and not confirm(segment):
        raise TaintLaunderingError(
            f"refusing to execute {tool!r} on argument derived from untrusted "
            f"segment (sources={sorted(segment.source_ids)}) without confirmation"
        )
    return f"executed {tool}({arg})"
