# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-redacted-secret-as-still-live-taint-propagation-failure-across-the-episodic-to-semantic-memory-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-redacted-secret-as-still-live-taint-propagation-failure-across-the-episodic-to-semantic-memory-boundary.warrant.json
# Markdown SHA-256:   1658b7fa77f4a9f81388e55784e8bb4ceea9a70ef5176b29ff696a390f5eedf6
# Code AST SHA-256:   557814b03914391c7ea91557013ea2f86a3727df01ef9f1be07a0fec29538ebe
# Verified Classes:   Taint, TaintPropagationError, Turn, MemoryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    PUBLIC = 0
    INTERNAL = 1
    SECRET_DERIVED = 2
    TAINT_MAX = 3  # provenance lost: fail closed


class TaintPropagationError(RuntimeError):
    """Raised when a memory node would cross a boundary below its taint label."""


@dataclass
class Turn:
    id: str
    taint: Taint


@dataclass
class MemoryNode:
    text: str
    derivation: frozenset[str] = field(default_factory=frozenset)
    label: Taint = Taint.TAINT_MAX  # unset provenance => fail closed


def label_node(node: MemoryNode, turns: dict[str, Turn]) -> MemoryNode:
    if not node.derivation:
        node.label = Taint.TAINT_MAX
        return node
    missing = node.derivation - turns.keys()
    if missing:
        # Cannot recompute closure: downgrade to max, never to PUBLIC.
        node.label = Taint.TAINT_MAX
        return node
    node.label = max((turns[t].taint for t in node.derivation), default=Taint.TAINT_MAX)
    return node


def admit(node: MemoryNode, context_clearance: Taint, store: str) -> None:
    if node.label > context_clearance:
        raise TaintPropagationError(
            f"node into {store!r} labeled {node.label.name} exceeds "
            f"context clearance {context_clearance.name}; text={node.text[:60]!r}"
        )


def distill(inputs: Iterable[Turn], summary: str) -> MemoryNode:
    """Distiller must union taint over input spans; it may not drop provenance."""
    turns = {t.id: t for t in inputs}
    node = MemoryNode(text=summary, derivation=frozenset(turns))
    labeled = label_node(node, turns)
    if labeled.label is Taint.TAINT_MAX:
        raise TaintPropagationError(
            "distillation produced a node with unrecomputable provenance; quarantine"
        )
    return labeled
