# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-when-the-provenance-chain-verifies-cleanly-the-taint-laundering-boundary-in-long-horizon-recall.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-when-the-provenance-chain-verifies-cleanly-the-taint-laundering-boundary-in-long-horizon-recall.warrant.json
# Markdown SHA-256:   343f91d9fbd20e3b267197ff67afef51999f180c82094c01efedbd7585f31611
# Code AST SHA-256:   5fed6dcda83a9929b3b76469630177d5a6cef5f91fa127813b821f09ac1d551e
# Verified Classes:   TaintLaunderingError, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

TRUSTED_AUTHORS: FrozenSet[str] = frozenset({"R", "S", "auditor"})
TAINT_OVERFLOW = "__TAINT_OVERFLOW__"  # sentinel: more tainted, never less
MAX_TAINT_SET = 8


class TaintLaunderingError(RuntimeError):
    """Raised when a derived memory's taint fails the Taint Monotonicity Invariant,
    or when a tainted record is injected into decision-relevant context without
    an explicit declassification event."""


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    content: str
    author_instance: str
    parents: FrozenSet[str] = frozenset()
    taint: FrozenSet[str] = frozenset()
    declassified_by: Optional[str] = None


def derive_record(
    record_id: str,
    content: str,
    author_instance: str,
    parent_ids: FrozenSet[str],
    store: dict,
) -> MemoryRecord:
    """Memory-layer derivation. Computes taint mechanically from parents.
    The LLM distiller never supplies taint; it only supplies parent_ids."""
    inherited: set = set()
    for pid in parent_ids:
        if pid not in store:
            raise TaintLaunderingError(
                f"derive {record_id}: parent {pid} not in store; "
                f"cannot compute lineage taint"
            )
        inherited |= store[pid].taint

    # Overflow must map to a MORE-tainted sentinel, never to clean.
    if len(inherited) > MAX_TAINT_SET:
        inherited = {TAINT_OVERFLOW}

    # If any parent is authored outside the closed trust set, taint it.
    for pid in parent_ids:
        if store[pid].author_instance not in TRUSTED_AUTHORS:
            inherited.add(pid)

    return MemoryRecord(
        record_id=record_id,
        content=content,
        author_instance=author_instance,
        parents=parent_ids,
        taint=frozenset(inherited),
    )


def recall_for_decision(
    record: MemoryRecord,
    action_requires_trust: bool,
) -> MemoryRecord:
    """Recall gate. Fires at context injection for decision-relevant use,
    NOT at terminal action."""
    if not action_requires_trust:
        return record  # reasoning-only read; taint travels with the record

    if record.taint and record.declassified_by is None:
        raise TaintLaunderingError(
            f"recall {record.record_id}: taint={sorted(record.taint)} "
            f"injected into decision context without declassification; "
            f"provenance signature may still verify clean — this is the "
            f"laundering boundary, not an integrity failure"
        )
    return record
