# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-flagged-content-from-re-entering-agent-memory-through-derived-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-flagged-content-from-re-entering-agent-memory-through-derived-writes.warrant.json
# Markdown SHA-256:   28d3cb4aeb8bfbad702506f9c4b0303fc9b9aa5fc6a58e07ffd22b86abf0d853
# Code AST SHA-256:   8466aade69d0e71478331ea82e37f7d2f44429a5d6a3df343b02581d501c9427
# Verified Classes:   TaintLaunderingError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact is persisted without a taint-preserving
    lineage edge or a trusted declassification warrant."""
    pass


class MemoryRecord:
    def __init__(self, content: str, taint: bool, lineage: frozenset, declass_warrant=None):
        self.content = content
        self.taint = taint
        self.lineage = lineage
        self.declass_warrant = declass_warrant


def persist_derived(artifact_content: str, source_ids: frozenset, store: dict,
                    taint_index: dict, warrant: dict | None = None) -> MemoryRecord:
    # Compute transitive taint closure over the source lineage.
    if not source_ids:
        raise TaintLaunderingError(
            "derived artifact has no lineage edge; cannot resolve taint closure"
        )

    closure_tainted = False
    for sid in source_ids:
        if sid not in taint_index:
            # Unknown provenance must fail closed, never default to clean.
            raise TaintLaunderingError(
                f"source {sid!r} has no taint record; refusing fail-open write"
            )
        if taint_index[sid]:
            closure_tainted = True

    if closure_tainted and warrant is None:
        # Taint is monotone: derived artifact inherits taint, routed to quarantine-adjacent store.
        rec = MemoryRecord(artifact_content, taint=True, lineage=source_ids)
        store["quarantine"].append(rec)
        return rec

    if closure_tainted and warrant is not None:
        if not warrant.get("signed") or warrant.get("issuer") == "llm_summarizer":
            raise TaintLaunderingError(
                "declassification warrant must be signed by a trusted component, "
                "not a summarizer self-report"
            )
        rec = MemoryRecord(artifact_content, taint=False,
                           lineage=source_ids, declass_warrant=warrant)
        store["clean"].append(rec)
        return rec

    rec = MemoryRecord(artifact_content, taint=False, lineage=source_ids)
    store["clean"].append(rec)
    return rec
