# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-leakage-across-session-boundaries-in-taint-aware-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-leakage-across-session-boundaries-in-taint-aware-agent-memory.warrant.json
# Markdown SHA-256:   cd10b93a77bebd78adb9b88c40797f35770bd62076e0051c4add5107be9c5878
# Code AST SHA-256:   52bd49a780cbc37550589191cb9153683fcc0608a4ddb2267e79b0f6b53b91da
# Verified Classes:   TaintLeakageError, Episode, SemanticNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

DIRECTIVE_MARKERS = ("always include", "always surface", "prefer the", "must use", "never omit")


class TaintLeakageError(RuntimeError):
    """Raised when a semantic memory node's stored taint disagrees with its support set."""
    pass


@dataclass
class Episode:
    id: str
    text: str
    taint: bool


@dataclass
class SemanticNode:
    id: str
    text: str
    supporting_episodes: list[str]
    taint: bool = False


def resolve_taint(node: SemanticNode, episodes: dict[str, Episode]) -> bool:
    if not node.supporting_episodes:
        raise TaintLeakageError(
            f"node {node.id} has no support edges; derivation unprovable"
        )
    missing = [e for e in node.supporting_episodes if e not in episodes]
    if missing:
        raise TaintLeakageError(f"node {node.id} references missing episodes {missing}")
    return any(episodes[e].taint for e in node.supporting_episodes)


def is_instruction_shaped(text: str) -> bool:
    low = text.lower()
    return any(marker in low for marker in DIRECTIVE_MARKERS)


def admit_for_retrieval(
    node: SemanticNode, episodes: dict[str, Episode]
) -> bool:
    derived = resolve_taint(node, episodes)
    if derived != node.taint:
        # stored label drifted from the derivation DAG: treat as contaminated
        raise TaintLeakageError(
            f"taint mismatch on {node.id}: stored={node.taint} derived={derived}"
        )
    if derived and is_instruction_shaped(node.text):
        return False  # quarantine: payload is the directive
    if derived:
        # re-derivation required; refuse to serve the poisoned consolidation
        return False
    return True
