# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-tool-output-before-it-is-written-to-episodic-memory-and-why-does-label-downgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-tool-output-before-it-is-written-to-episodic-memory-and-why-does-label-downgrade.warrant.json
# Markdown SHA-256:   da2107e27b1fe40c870608b50d009200ed09570c05c0cb82c2920d0a7f1ac7f5
# Code AST SHA-256:   d78e3263c4072581abf5fd6a97bbbc53abab7a7391f4a515172d5e597d9ce1f3
# Verified Classes:   Trust, TaintLaunderingError, Segment, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

class Trust(IntEnum):
    TRUSTED = 0
    USER_INPUT = 1
    MEMORY_DERIVED = 2
    EXTERNAL_TOOL_OUTPUT = 3  # highest taint; join is max

class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would lower the provenance label of its inputs."""

@dataclass(frozen=True)
class Segment:
    text: str
    label: Trust
    seg_id: str

@dataclass
class MemoryRecord:
    claim: str
    label: Trust
    derived_from: list[str] = field(default_factory=list)

ACTIONABLE_MARKERS = ("auto-approve", "permit", "authorize", "threshold", "allow", "may ")

def join(labels: Iterable[Trust]) -> Trust:
    labels = list(labels)
    if not labels:
        # fail-closed: unknown provenance is maximally tainted
        return Trust.EXTERNAL_TOOL_OUTPUT
    return Trust(max(labels))

def is_actionable(claim: str) -> bool:
    return any(m in claim.lower() for m in ACTIONABLE_MARKERS)

def distill_and_write(
    inputs: list[Segment],
    summarized_claim: str,
    writer_assigned_label: Trust,
    store: list[MemoryRecord],
) -> MemoryRecord:
    joined = join(s.label for s in inputs)

    # Invariant: a writer may raise the label (floor) but never lower it.
    if writer_assigned_label < joined:
        raise TaintLaunderingError(
            f"label downgrade: writer assigned {writer_assigned_label.name} "
            f"but inputs join to {joined.name}; refusing to launder taint"
        )

    effective = Trust(max(writer_assigned_label, joined))

    if is_actionable(summarized_claim) and effective >= Trust.EXTERNAL_TOOL_OUTPUT:
        # Quarantine: do not enter the retrieval index.
        raise TaintLaunderingError(
            "actionable claim descended from external tool output; "
            "quarantine pending corroboration from a distinct trust domain"
        )

    rec = MemoryRecord(
        claim=summarized_claim,
        label=effective,
        derived_from=[s.seg_id for s in inputs],
    )
    store.append(rec)
    return rec

def promote_with_corroboration(
    rec: MemoryRecord,
    corroborating: Segment,
    store: list[MemoryRecord],
) -> MemoryRecord:
    # Promotion requires a non-tainted, distinct-trust-domain source.
    if corroborating.label >= Trust.EXTERNAL_TOOL_OUTPUT:
        raise TaintLaunderingError(
            "corroborating source is itself tainted; cannot promote"
        )
    if corroborating.seg_id in rec.derived_from:
        raise TaintLaunderingError(
            "corroborating source is not independent of the original derivation"
        )
    promoted = MemoryRecord(
        claim=rec.claim,
        label=Trust(max(rec.label, corroborating.label)),
        derived_from=rec.derived_from + [corroborating.seg_id],
    )
    store.append(promoted)
    return promoted
