# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-provenance-labels-decay-across-tool-output-re-entry-and-memory-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-provenance-labels-decay-across-tool-output-re-entry-and-memory-consolidation.warrant.json
# Markdown SHA-256:   65d341f51d1dafc75c21db2146a5364c3c0bd49d592235ce0231f1761c854621
# Code AST SHA-256:   4d8e6453478723b2a34b9788485412ed5e315d1d46c25b91918d4031fabca8bd
# Verified Classes:   TaintLaunderingError, Provenance, ProvenanceLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a write attempts to clear taint without an audited declassification."""
    pass


@dataclass
class Provenance:
    record_id: str
    contributors: set[str] = field(default_factory=set)  # source IDs feeding this record
    taint: bool = True  # conservative default: untrusted until proven otherwise
    origin: str = "unknown"
    declassified: bool = False


class ProvenanceLedger:
    def __init__(self) -> None:
        self._records: dict[str, Provenance] = {}
        self._source_taint: dict[str, bool] = {}

    def register_source(self, source_id: str, tainted: bool) -> None:
        self._source_taint[source_id] = tainted

    def write(
        self,
        record_id: str,
        inputs: Optional[list[str]],
        writer_origin: str,
    ) -> Provenance:
        # Invariant: taint = OR over inputs. If inputs are not enumerable,
        # the writer cannot compute the disjunction and MUST default to tainted.
        if inputs is None:
            prov = Provenance(
                record_id=record_id,
                contributors=set(),
                taint=True,
                origin=writer_origin,
            )
            self._records[record_id] = prov
            return prov

        contributors = set(inputs)
        taint = any(self._source_taint.get(src, True) for src in contributors)

        # Guardrail: a write may not clear taint relative to its inputs.
        # Caller-stamped provenance is the laundering vector; reject it.
        prior = self._records.get(record_id)
        if prior is not None and prior.taint and not taint and not prior.declassified:
            raise TaintLaunderingError(
                f"write to {record_id} would clear taint without declassification; "
                f"inputs={sorted(contributors)}"
            )

        prov = Provenance(
            record_id=record_id,
            contributors=contributors,
            taint=taint,
            origin=writer_origin,
        )
        self._records[record_id] = prov
        return prov

    def read(self, record_id: str) -> Provenance:
        prov = self._records.get(record_id)
        if prov is None:
            raise TaintLaunderingError(f"read of unknown record {record_id}")
        # Reconstruct taint from contributors, not from the stamped scalar.
        reconstructed = any(
            self._source_taint.get(src, True) for src in prov.contributors
        ) if prov.contributors else True
        if reconstructed and not prov.taint and not prov.declassified:
            raise TaintLaunderingError(
                f"record {record_id} reports clean but contributors are tainted; "
                f"label decayed across write"
            )
        return prov

    def declassify(self, record_id: str, auditor: str) -> None:
        prov = self._records[record_id]
        prov.taint = False
        prov.declassified = True
        prov.origin = f"declassified:{auditor}"


def consolidate(ledger: ProvenanceLedger, episodic_ids: list[str], summary_id: str) -> Provenance:
    # Aggregation must propagate the disjunction; dilution by volume is the failure.
    for eid in episodic_ids:
        ledger.read(eid)  # raises if any constituent is inconsistent
    return ledger.write(summary_id, inputs=episodic_ids, writer_origin="distiller")
