# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-through-a-tool-output-memory-write-pipeline-without-losing-injection-provenance-at-the-semantic-distilla.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-through-a-tool-output-memory-write-pipeline-without-losing-injection-provenance-at-the-semantic-distilla.warrant.json
# Markdown SHA-256:   f17412d9ad4ed9a8623ff8871833eb4fac9f8990de944f1ee9b3a537879ab17d
# Code AST SHA-256:   6a609bcf3ad7cd79649465b98c8c43140c2d132bcd4be85030cb05a60704434f
# Verified Classes:   TaintLaunderingError, ProvenanceForgeryError, Span, ContextWindow, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would drop provenance for a tainted context span."""


class ProvenanceForgeryError(RuntimeError):
    """Raised when claimed derived_from omits a tainted span actually present in context."""


# Taint lattice: trusted < untrusted. Join is max.
_TAINT_RANK = {"trusted": 0, "untrusted": 1}


def join_taint(labels: Iterable[str]) -> str:
    labels = list(labels)
    if not labels:
        return "trusted"
    return max(labels, key=lambda t: _TAINT_RANK[t])


@dataclass
class Span:
    span_id: str
    taint: str


@dataclass
class ContextWindow:
    spans: dict[str, Span] = field(default_factory=dict)

    def add(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def tainted_span_ids(self) -> set[str]:
        return {s.span_id for s in self.spans.values() if s.taint == "untrusted"}


@dataclass
class MemoryRecord:
    text: str
    kind: str
    taint: str
    derived_from: list[str]


def write_memory(
    ctx: ContextWindow,
    text: str,
    kind: str,
    claimed_derived_from: list[str],
) -> MemoryRecord:
    """
    Write-time taint join with provenance validation.

    Invariant: record.taint == join(taint(s) for s in derived_from)
    AND every tainted span present in ctx is claimed in derived_from.
    """
    # 1. Validate claimed provenance exists in the actual context.
    unknown = set(claimed_derived_from) - set(ctx.spans)
    if unknown:
        raise ProvenanceForgeryError(
            f"claimed derived_from references spans not in context: {unknown}"
        )

    # 2. Detect omission: any tainted span in context must be claimed.
    tainted_present = ctx.tainted_span_ids()
    unclaimed_tainted = tainted_present - set(claimed_derived_from)
    if unclaimed_tainted:
        raise ProvenanceForgeryError(
            f"write omits tainted spans present in context: {unclaimed_tainted}; "
            f"cannot launder injection provenance by omission"
        )

    # 3. Join taint over claimed spans.
    joined = join_taint(ctx.spans[sid].taint for sid in claimed_derived_from)

    # 4. Defensive: a generative summary of a tainted span must never be trusted.
    if joined == "trusted" and tainted_present:
        raise TaintLaunderingError(
            "summary of tainted context cannot be written as trusted"
        )

    return MemoryRecord(
        text=text,
        kind=kind,
        taint=joined,
        derived_from=list(claimed_derived_from),
    )


def retrieve_for_agent(records: list[MemoryRecord], tool_authority: str) -> list[MemoryRecord]:
    """Only surface records whose taint is compatible with the requesting agent's authority."""
    if tool_authority == "trusted":
        return [r for r in records if r.taint == "trusted"]
    return list(records)
