# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-tracking-fidelity-at-the-label-join-boundary-when-a-tool-output-is-re-ingested-through-memory-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-tracking-fidelity-at-the-label-join-boundary-when-a-tool-output-is-re-ingested-through-memory-compaction.warrant.json
# Markdown SHA-256:   063e027dbe66aeb1d77fc078fba77a939fc9f2a1fb45e800e37ef0a7d5bd82b9
# Code AST SHA-256:   db7fd4246c4d4b14e02ca9e29b6c73d31ee73c23dec0149fa99f9d8261abe33d
# Verified Classes:   TaintJoinViolation, Segment
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

# Taint lattice: UNTRUSTED > TRUSTED. join = max.
TRUSTED = 0
UNTRUSTED = 1


class TaintJoinViolation(RuntimeError):
    """Raised when a compaction summary's label does not dominate the join of its inputs."""
    pass


@dataclass
class Segment:
    text: str
    label: int


def join_labels(labels: Iterable[int]) -> int:
    labels = list(labels)
    if not labels:
        raise TaintJoinViolation("cannot join an empty label set; fail closed")
    return max(labels)


def compact(segments: list[Segment], summarizer) -> Segment:
    """Compact N labeled segments into one summary segment.

    The summarizer is treated as an untrusted label-transformer: its output
    text is accepted, but its label is overridden by the join of input labels.
    """
    if not segments:
        raise TaintJoinViolation("compaction called with no segments")

    expected = join_labels(s.label for s in segments)
    summary_text = summarizer([s.text for s in segments])

    # Reconstruct label from the INPUT multiset, never from summarizer output.
    summary = Segment(text=summary_text, label=expected)

    # Invariant: summary label must dominate the join of all inputs.
    if summary.label < expected:
        raise TaintJoinViolation(
            f"summary label {summary.label} does not dominate input join {expected}"
        )
    return summary


def prune(segments: list[Segment], keep_idx: int) -> Segment:
    """Prune all but one segment; fold pruned labels into the survivor."""
    survivor = segments[keep_idx]
    folded = join_labels(s.label for s in segments)
    if folded > survivor.label:
        # Survivor must absorb the taint of everything it replaced.
        return Segment(text=survivor.text, label=folded)
    return survivor


def policy_permits(segment: Segment, action: str) -> bool:
    if action == "transfer_funds" and segment.label == UNTRUSTED:
        return False
    return True


def run_agent_action(summary: Segment, action: str) -> None:
    if not policy_permits(summary, action):
        raise TaintJoinViolation(
            f"blocked action {action!r}: summary carries UNTRUSTED taint"
        )
    # ... execute action ...
