# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-episodic-to-semantic-memory-promotion-in-poisoned-context-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-episodic-to-semantic-memory-promotion-in-poisoned-context-agents.warrant.json
# Markdown SHA-256:   399a08a530be8fe6054d75e21ca60b2256f06b875a0301616969bd889b6c547f
# Code AST SHA-256:   ed75d4072e7a14ab5bb5726ffefed7872592e7706f9dd94f0b39cd06741204ee
# Verified Classes:   Taint, TaintLaunderingError, Declassification, EpisodicRecord, SemanticRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Taint(IntEnum):
    """Ordered lattice: higher = less trusted. Join = max."""
    TRUSTED = 0
    DERIVED_FROM_TAINTED = 1
    EXTERNAL_UNTRUSTED = 2

    @classmethod
    def join(cls, labels: Iterable["Taint"]) -> "Taint":
        return max(labels, default=cls.TRUSTED)


class TaintLaunderingError(RuntimeError):
    """Raised when a promotion step lowers taint without an audited declassification."""


@dataclass(frozen=True)
class Declassification:
    verifier: str
    checked_spans: tuple[str, ...]
    target_taint: Taint


@dataclass
class EpisodicRecord:
    record_id: str
    taint: Taint
    content_hash: str


@dataclass
class SemanticRecord:
    record_id: str
    taint: Taint
    source_ids: tuple[str, ...] = field(default_factory=tuple)
    declassification: Declassification | None = None


def promote(
    derived: SemanticRecord,
    sources: dict[str, EpisodicRecord],
    claimed_taint: Taint,
) -> SemanticRecord:
    """Promote an episodic set into a semantic record, enforcing the monotone-join invariant."""
    if not derived.source_ids:
        raise TaintLaunderingError(
            f"record {derived.record_id}: no source edges; join undefined, cannot promote"
        )
    missing = [sid for sid in derived.source_ids if sid not in sources]
    if missing:
        raise TaintLaunderingError(
            f"record {derived.record_id}: dangling sources {missing}; join undefined"
        )

    join = Taint.join(sources[sid].taint for sid in derived.source_ids)

    if claimed_taint < join:
        dc = derived.declassification
        if dc is None:
            raise TaintLaunderingError(
                f"record {derived.record_id}: taint lowered {join.name}->{claimed_taint.name} "
                f"with no declassification record (laundering channel)"
            )
        if dc.target_taint != claimed_taint:
            raise TaintLaunderingError(
                f"record {derived.record_id}: declassification target {dc.target_taint.name} "
                f"!= claimed {claimed_taint.name}"
            )
        if not dc.checked_spans:
            raise TaintLaunderingError(
                f"record {derived.record_id}: declassification by {dc.verifier} checked no spans"
            )

    derived.taint = claimed_taint
    return derived


def effective_taint_at_retrieval(
    record: SemanticRecord,
    sources: dict[str, EpisodicRecord],
) -> Taint:
    """Recompute taint over the source DAG so re-tagged sources back-propagate."""
    source_join = Taint.join(sources[sid].taint for sid in record.source_ids if sid in sources)
    if record.declassification is not None and record.declassification.target_taint < source_join:
        return record.declassification.target_taint
    return Taint.join((record.taint, source_join))
