# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-derived-memory-artifact-cross-agent-taint-propagation-in-federated-tool-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-derived-memory-artifact-cross-agent-taint-propagation-in-federated-tool-graphs.warrant.json
# Markdown SHA-256:   8ff3d9598c1b2ab48548f96f0a780d0b5e6f7d2e1caa85ac7ee7b4f02af72299
# Code AST SHA-256:   5c581b361908bbf2b70248ce4827ff587b3f0560be0d17e5e328ba7451986c2e
# Verified Classes:   TaintLaunderingError, TrustDomainViolation, MemoryArtifact
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

# Trust lattice: lower index = less trusted. join() returns least-trusted.
TRUST_ORDER = ["untrusted", "partner", "internal", "first_party"]


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact's taint is weaker than the join of its inputs."""
    pass


class TrustDomainViolation(RuntimeError):
    """Raised when a consumer retrieves an artifact whose taint exceeds its domain ceiling."""
    pass


@dataclass(frozen=True)
class MemoryArtifact:
    artifact_id: str
    content: str
    taint: str                 # joined taint of all causal inputs
    writer_tool: str           # identity of the writing tool (NOT the taint source)
    confidence: float
    quarantine: bool = False


def join_taint(input_taints: FrozenSet[str]) -> str:
    if not input_taints:
        raise TaintLaunderingError("cannot derive artifact from empty input set")
    for tier in TRUST_ORDER:  # least-trusted first
        if tier in input_taints:
            return tier
    raise TaintLaunderingError(f"unknown taint tiers: {input_taints}")


def distill_and_remember(
    artifact_id: str,
    content: str,
    input_taints: FrozenSet[str],
    writer_tool: str,
    confidence: float,
    domain_ceiling: str,
) -> MemoryArtifact:
    joined = join_taint(input_taints)
    # Invariant: writer_tool identity must NOT upgrade taint.
    if TRUST_ORDER.index(joined) > TRUST_ORDER.index(domain_ceiling):
        # Taint survives distillation; artifact is quarantined, not laundered.
        return MemoryArtifact(
            artifact_id=artifact_id,
            content=content,
            taint=joined,
            writer_tool=writer_tool,
            confidence=confidence,
            quarantine=True,
        )
    return MemoryArtifact(artifact_id, content, joined, writer_tool, confidence)


def retrieve(artifact: MemoryArtifact, consumer_ceiling: str) -> MemoryArtifact:
    if artifact.quarantine:
        raise TrustDomainViolation(
            f"artifact {artifact.artifact_id} is quarantined (taint={artifact.taint})"
        )
    if TRUST_ORDER.index(artifact.taint) > TRUST_ORDER.index(consumer_ceiling):
        raise TrustDomainViolation(
            f"artifact {artifact.artifact_id} taint={artifact.taint} "
            f"exceeds consumer ceiling={consumer_ceiling}"
        )
    return artifact


# Reproduce the observed failure path and confirm the guardrail blocks it.
web_fetch_taint = frozenset({"untrusted"})
art = distill_and_remember(
    artifact_id="mem-7741",
    content="Reconciliation queries target legacy_ledger table.",
    input_taints=web_fetch_taint,
    writer_tool="remember_fact",   # trusted writer, tainted content
    confidence=0.91,
    domain_ceiling="internal",
)
assert art.taint == "untrusted" and art.quarantine, "taint must survive distillation"

try:
    retrieve(art, consumer_ceiling="internal")  # beta's domain
except TrustDomainViolation as e:
    print("BLOCKED:", e)
else:
    raise TaintLaunderingError("tainted artifact reached a stricter domain")
