# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-when-a-low-integrity-label-is-laundered-through-a-high-integrity-tool-s-outpu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-when-a-low-integrity-label-is-laundered-through-a-high-integrity-tool-s-outpu.warrant.json
# Markdown SHA-256:   fba1d13381e44a3b8b0034af41dc5ed8095af06646357e823c84c1294e5775c0
# Code AST SHA-256:   919d00feda7f8674b1f846fee66a2c6cb247197ccb892469e43fa0c18a172fa5
# Verified Classes:   Integrity, Segment, ToolOutput, TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class Integrity(IntEnum):
    UNTRUSTED = 0
    TRUSTED = 1


@dataclass
class Segment:
    seg_id: str
    integrity: Integrity
    text: str


@dataclass
class ToolOutput:
    tool_id: str
    declared_ceiling: Integrity  # max integrity the tool may confer
    bytes_from: list[str]        # seg_ids whose bytes contributed
    text: str


class TaintLaunderingError(RuntimeError):
    """Raised when a tool output would be relabeled above its input closure."""


def join_integrity(segments: list[Segment]) -> Integrity:
    if not segments:
        return Integrity.UNTRUSTED
    return Integrity(min(s.integrity for s in segments))


def label_tool_output(
    out: ToolOutput,
    registry: dict[str, Segment],
    explicit_declassification: Optional[str] = None,
) -> Integrity:
    contributing = [registry[sid] for sid in out.bytes_from if sid in registry]
    missing = [sid for sid in out.bytes_from if sid not in registry]
    if missing:
        # Unresolvable lineage: default to untrusted, never to the tool ceiling.
        return Integrity.UNTRUSTED

    closure = join_integrity(contributing)

    if explicit_declassification is None:
        # No declassification rule: output may only lower integrity.
        if out.declared_ceiling > closure:
            raise TaintLaunderingError(
                f"tool {out.tool_id} would raise integrity {closure.name} -> "
                f"{out.declared_ceiling.name} without a declassification rule; "
                f"inputs={out.bytes_from}"
            )
        return closure

    # Declassification is permitted only up to the tool's declared ceiling,
    # and only if the rule asserts byte-independence from untrusted inputs.
    if out.declared_ceiling < Integrity.TRUSTED:
        raise TaintLaunderingError(
            f"tool {out.tool_id} cannot declassify to TRUSTED: ceiling is "
            f"{out.declared_ceiling.name}"
        )
    return Integrity.TRUSTED


def commit_memory(
    out: ToolOutput,
    registry: dict[str, Segment],
    store_admits_untrusted: bool,
) -> Segment:
    label = label_tool_output(out, registry)
    if label == Integrity.UNTRUSTED and not store_admits_untrusted:
        raise TaintLaunderingError(
            f"refusing memory write from tool {out.tool_id}: output is "
            f"UNTRUSTED but target store does not admit untrusted memory; "
            f"quarantine required, provenance={out.bytes_from}"
        )
    return Segment(seg_id=f"mem:{out.tool_id}", integrity=label, text=out.text)
