# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-tracked-tool-allowlist-has-been-silently-widened-by-provenance-laundering-through-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-tracked-tool-allowlist-has-been-silently-widened-by-provenance-laundering-through-summarization.warrant.json
# Markdown SHA-256:   d8f5b0282801f0afd97d6a9ceff4fd930c9eb999fc5a1240b687bb689f236a3e
# Code AST SHA-256:   acac2eef3ddd877bfad3592b8fbcf6deaaa8e115082b2e759e31c97d24333655
# Verified Classes:   ProvenanceLaunderingError, Label, Artifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a re-ingestible artifact's provenance edge lacks an input set,
    or when verbatim-span evidence contradicts a declared-clean label."""


@dataclass(frozen=True)
class Label:
    name: str
    trusted: bool


UNTRUSTED_EXTERNAL = Label("UNTRUSTED:EXTERNAL", trusted=False)
UNTRUSTED_UNATTRIBUTED = Label("UNTRUSTED:UNATTRIBUTED", trusted=False)
TRUSTED_SELF = Label("TRUSTED:AGENT_SELF", trusted=True)


@dataclass
class Artifact:
    artifact_id: str
    text: str
    labels: FrozenSet[Label]
    input_ids: Optional[FrozenSet[str]] = None  # None => edge has no ancestry


def join_labels(inputs: list[Artifact], context_labels: FrozenSet[Label]) -> FrozenSet[Label]:
    """Conservative join: union of all input labels, or full context if inputs unknown."""
    if not inputs:
        return context_labels | {UNTRUSTED_UNATTRIBUTED}
    out: set[Label] = set()
    for a in inputs:
        out |= a.labels
    return frozenset(out)


def resolve_allowlist(
    artifact: Artifact,
    context_labels: FrozenSet[Label],
    known_inputs: dict[str, Artifact],
    required_tool: str,
    tool_requires_clean: FrozenSet[str],
) -> bool:
    if artifact.input_ids is None:
        raise ProvenanceLaunderingError(
            f"artifact {artifact.artifact_id!r} has no provenance input set; "
            f"cannot attribute taint — refusing to widen allowlist for {required_tool!r}"
        )
    inputs = [known_inputs[i] for i in artifact.input_ids if i in known_inputs]
    effective = join_labels(inputs, context_labels) | artifact.labels
    if required_tool in tool_requires_clean and any(not l.trusted for l in effective):
        return False
    return True


def check_verbatim_survival(summary: str, untrusted_sources: list[Artifact], min_tokens: int = 12) -> None:
    """Force a taint join if an instruction-shaped span survived summarization."""
    def ngrams(t: str, n: int) -> set[tuple[str, ...]]:
        w = t.split()
        return {tuple(w[i:i + n]) for i in range(len(w) - n + 1)}

    s_grams = ngrams(summary, min_tokens)
    for src in untrusted_sources:
        overlap = s_grams & ngrams(src.text, min_tokens)
        if overlap:
            raise ProvenanceLaunderingError(
                f"summary shares {len(overlap)} verbatim {min_tokens}-token span(s) with "
                f"untrusted source {src.artifact_id!r}; declared-clean label is contradicted"
            )
