# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-re-admission-of-poisoned-memory-during-consolidated-store-integrity-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-re-admission-of-poisoned-memory-during-consolidated-store-integrity-verification.warrant.json
# Markdown SHA-256:   1755994cd5c61ae0c342cefca628fabc82b13a17bd5aba8900d14661cb92bf10
# Code AST SHA-256:   6ea12f7be0777add569119c03d22ea79394e92c6a01404bc7685f14f3ad0d836
# Verified Classes:   TaintLaunderingError, PruneBeforeJoinError, Episode, SemanticNode
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TaintLaunderingError(RuntimeError):
    """Raised when consolidation would produce an untainted node from a tainted source."""
    pass


class PruneBeforeJoinError(RuntimeError):
    """Raised when an episodic source is pruned before its taint state is joined."""
    pass


@dataclass(frozen=True)
class Episode:
    episode_id: str
    tainted: bool
    pruned: bool = False


@dataclass(frozen=True)
class SemanticNode:
    node_id: str
    source_ids: FrozenSet[str]
    tainted: bool
    seal_verified: bool


def consolidate(
    node_id: str,
    source_ids: FrozenSet[str],
    episodes: dict,
    seal_verified: bool,
) -> SemanticNode:
    if not source_ids:
        raise TaintLaunderingError(
            f"node {node_id}: consolidation requires at least one source episode"
        )

    missing = [sid for sid in source_ids if sid not in episodes]
    if missing:
        raise PruneBeforeJoinError(
            f"node {node_id}: source episodes {missing} absent from store; "
            f"taint join cannot be computed (pruned before join)"
        )

    pruned = [sid for sid in source_ids if episodes[sid].pruned]
    if pruned:
        raise PruneBeforeJoinError(
            f"node {node_id}: source episodes {pruned} already pruned; "
            f"taint state is unrecoverable"
        )

    # Taint join: least upper bound over all sources. Monotonic.
    joined_taint = any(episodes[sid].tainted for sid in source_ids)

    if joined_taint and not seal_verified:
        # A tainted source with a failed seal is a straightforward reject.
        raise TaintLaunderingError(
            f"node {node_id}: tainted source and unverified seal"
        )

    # The critical invariant: a tainted join may NOT be sealed as clean.
    # seal_verified only attests the consolidator ran; it does not clear taint.
    if joined_taint and seal_verified:
        # We return a node that is explicitly tainted. It must not be admitted
        # to cold-start context without a quarantine flag.
        return SemanticNode(
            node_id=node_id,
            source_ids=source_ids,
            tainted=True,
            seal_verified=True,
        )

    return SemanticNode(
        node_id=node_id,
        source_ids=source_ids,
        tainted=False,
        seal_verified=seal_verified,
    )


def admit_to_cold_start(node: SemanticNode, allow_quarantine: bool = False) -> bool:
    if not node.seal_verified:
        return False
    if node.tainted and not allow_quarantine:
        raise TaintLaunderingError(
            f"node {node.node_id}: tainted semantic node cannot be admitted "
            f"to cold-start context without quarantine flag"
        )
    return True
