# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-label-laundering-through-tool-output-normalization-in-information-flow-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-label-laundering-through-tool-output-normalization-in-information-flow-tracking.warrant.json
# Markdown SHA-256:   6cf841ca1bd6a6cb6fc7f9e7f821ad64921aa740f5e7425c6f0c67a0d2a30848
# Code AST SHA-256:   3fff9b4b12f0acf5fd3c700b6d023ee1bf6371ad3e59bbf1b5fbdf280d9d4a28
# Verified Classes:   ProvenanceLaunderingError, LabeledSpan, ToolOutputField, MemoryWrite
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write contains a field whose provenance cannot be
    traced to a labeled input span and the write was not quarantined."""


@dataclass
class LabeledSpan:
    span_id: str
    label: str  # e.g. "UNTRUSTED_USER", "CLEAN_INTERNAL"


@dataclass
class ToolOutputField:
    name: str
    value: str
    derived_from_span: Optional[str]  # None => synthesized, no provenance contract
    tool_declares_contract: bool = False


@dataclass
class MemoryWrite:
    fields: list[ToolOutputField] = field(default_factory=list)


TAINT_ORDER = {"CLEAN_INTERNAL": 0, "UNTRUSTED_USER": 1, "QUARANTINE": 2}


def _max_label(labels: list[str]) -> str:
    return max(labels, key=lambda l: TAINT_ORDER.get(l, 2))


def check_write_provenance(write: MemoryWrite, labeled: dict[str, LabeledSpan]) -> str:
    """Return the label the write must carry. Fail-closed: any untraceable
    field forces QUARANTINE. Raises if a caller tries to promote a quarantined
    write without an explicit approval token."""
    labels: list[str] = []
    untraceable: list[str] = []

    for f in write.fields:
        if f.derived_from_span is None:
            untraceable.append(f.name)
            continue
        if not f.tool_declares_contract:
            # Tool emitted a field mapped to a span but published no contract;
            # treat the mapping as unverified and fail closed.
            untraceable.append(f.name)
            continue
        span = labeled.get(f.derived_from_span)
        if span is None:
            untraceable.append(f.name)
            continue
        labels.append(span.label)

    if untraceable:
        # Quarantine is the only legal outcome; promotion requires approval.
        return "QUARANTINE"
    return _max_label(labels)


def commit_write(write: MemoryWrite, labeled: dict[str, LabeledSpan],
                 approval_token: Optional[str] = None) -> str:
    label = check_write_provenance(write, labeled)

    if label == "QUARANTINE" and approval_token is None:
        # Explicit, auditable rejection path — not a silent downgrade.
        raise ProvenanceLaunderingError(
            "memory write contains untraceable fields; refusing promotion. "
            f"fields={[f.name for f in write.fields if f.derived_from_span is None]}"
        )

    if label == "QUARANTINE" and approval_token is not None:
        # Approval only permits storage under QUARANTINE, never CLEAN promotion.
        return "QUARANTINE"

    return label
