# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-taint-a-value-that-survives-a-summary-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-taint-a-value-that-survives-a-summary-boundary.warrant.json
# Markdown SHA-256:   b3c990ca511b01e2f04a98d1a9010f08a39acfe95f44a1b60edf606c6961837e
# Code AST SHA-256:   e12d2be10b842d47f0539bb7e3978ca0d6271490d5ffa7cdb64403b18ece3d2c
# Verified Classes:   TaintContinuityError, Span, SummarySentence, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Iterable, Mapping


class TaintContinuityError(RuntimeError):
    """Raised when a compression boundary would lose or falsify taint provenance."""


@dataclass(frozen=True)
class Span:
    chunk_id: str
    labels: FrozenSet[str]  # e.g. frozenset({"untrusted:web:evil.example"})


@dataclass(frozen=True)
class SummarySentence:
    text: str
    contributing_spans: FrozenSet[str]  # chunk_ids cited by the summarizer


@dataclass
class MemoryRecord:
    summary: str
    taint_labels: FrozenSet[str]
    requires_human_review: bool = False


UNKNOWN = frozenset({"untrusted:unknown"})
ACTIONABLE_MARKERS = ("instruct", "initiate", "call", "transfer", "before responding")


def write_summary(
    sentences: Iterable[SummarySentence],
    span_index: Mapping[str, Span],
    schema_supports_label_sets: bool = True,
) -> MemoryRecord:
    if not schema_supports_label_sets:
        # Boolean-only schema cannot represent span-level taint; refuse rather than guess.
        raise TaintContinuityError(
            "memory schema does not support taint label sets; "
            "boolean taint would force an unsound default"
        )

    labels: set[str] = set()
    actionable = False
    text_parts: list[str] = []

    for sent in sentences:
        text_parts.append(sent.text)
        if not sent.contributing_spans:
            # Summarizer failed to attribute this sentence; conservative default.
            labels |= UNKNOWN
            continue
        for cid in sent.contributing_spans:
            span = span_index.get(cid)
            if span is None:
                raise TaintContinuityError(
                    f"summary cites unknown chunk_id={cid!r}; provenance broken"
                )
            labels |= span.labels
        lowered = sent.text.lower()
        if any(marker in lowered for marker in ACTIONABLE_MARKERS):
            actionable = True

    if actionable and any(lbl.startswith("untrusted:") for lbl in labels):
        # Paraphrased instruction from untrusted provenance: escalate.
        return MemoryRecord(
            summary=" ".join(text_parts),
            taint_labels=frozenset(labels),
            requires_human_review=True,
        )

    return MemoryRecord(
        summary=" ".join(text_parts),
        taint_labels=frozenset(labels),
    )


def gate_tool_call(
    tool_name: str,
    arg_taint: FrozenSet[str],
    justification_taint: FrozenSet[str],
) -> None:
    if any(lbl.startswith("untrusted:") for lbl in justification_taint):
        raise TaintContinuityError(
            f"tool call {tool_name!r} justified by tainted memory "
            f"{sorted(justification_taint)}; arguments clean but reason is not"
        )
