# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-dynamic-information-flow-label-before-persisting-tool-output-to-episodic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-dynamic-information-flow-label-before-persisting-tool-output-to-episodic-memory.warrant.json
# Markdown SHA-256:   a0c86ee8d12f9b8ea71e8756755f5674e66a88e54d9a492387fc9cfb2a94300e
# Code AST SHA-256:   7b1181cbd29f4ea9c5a64fee8635a97bba76a04d3d425dc58f776541df433cd2
# Verified Classes:   TaintLaunderingError, Label
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a persistence sink receives a value whose provenance
    cannot be reconstructed by the runtime and no fail-closed label applies."""


@dataclass(frozen=True)
class Label:
    level: str  # "first_party" | "external:untrusted"
    sources: tuple = field(default_factory=tuple)

    def join(self, other: "Label") -> "Label":
        # Least upper bound: untrusted dominates; union sources.
        lvl = "external:untrusted" if "untrusted" in (self.level, other.level) else "first_party"
        return Label(lvl, tuple(sorted(set(self.sources) | set(other.sources))))


TOP = Label("external:untrusted", ("<unlabeled>",))


def resolve_write_label(
    payload: str,
    referenced_ids: list[str],
    label_store: dict[str, Label],
    first_party_spans: list[str],
) -> Label:
    """Compute the label the runtime will persist with a memory write.

    Rules, in order:
      1. If the payload references labeled objects, join their labels.
      2. If the payload is byte-identical to a first-party span, it is clean.
      3. Otherwise the provenance is model-authored and non-reconstructable:
         fail closed to TOP unless the caller explicitly overrides.
    """
    joined: Optional[Label] = None
    for rid in referenced_ids:
        if rid not in label_store:
            # A reference to an object the runtime never labeled is itself
            # a laundering signal: the model invented a provenance handle.
            raise TaintLaunderingError(
                f"write references unlabeled object id={rid!r}; "
                "runtime cannot reconstruct provenance"
            )
        joined = label_store[rid] if joined is None else joined.join(label_store[rid])

    if joined is not None:
        return joined

    if any(payload == span for span in first_party_spans):
        return Label("first_party", ("user_msg",))

    # Model-authored free text with no reconstructable provenance.
    # Do NOT return an empty/clean label here; that is the laundering bug.
    return TOP


def persist_memory_write(
    key: str,
    payload: str,
    referenced_ids: list[str],
    label_store: dict[str, Label],
    first_party_spans: list[str],
    allow_quarantine: bool = True,
) -> Label:
    label = resolve_write_label(payload, referenced_ids, label_store, first_party_spans)
    if label.level == "external:untrusted":
        if not allow_quarantine:
            raise TaintLaunderingError(
                f"refusing to persist {key!r} as authoritative: "
                f"provenance unresolved, effective label={label.level} "
                f"sources={label.sources}"
            )
        # Persist, but as non-authoritative: retrievable, never satisfies
        # an authority check without re-derivation.
        label_store[f"mem:{key}"] = label
        return label
    label_store[f"mem:{key}"] = label
    return label
