# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-an-injected-instruction-crosses-a-tool-result-boundary-mid-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-an-injected-instruction-crosses-a-tool-result-boundary-mid-trace.warrant.json
# Markdown SHA-256:   0827649f496b3ed5b1eeece2d0e0f238cba6c5a60abfe9b9c27f74a421829298
# Code AST SHA-256:   f33fd9ce8313fdeaf46dc8b5fa48f768161dac3f11feb9decf113e179f0b8fbf
# Verified Classes:   TaintLevel, ProvenanceDiscontinuity, Envelope, ContextAssembler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


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


class ProvenanceDiscontinuity(RuntimeError):
    """Raised when tainted content reaches an authoritative role without a recorded declassification warrant."""


@dataclass(frozen=True)
class Envelope:
    text: str
    taint: TaintLevel
    origin_span: str
    warrant: str | None = None


@dataclass
class ContextAssembler:
    _messages: list[tuple[str, Envelope]] = field(default_factory=list)
    _authoritative_roles: frozenset[str] = frozenset({"system", "assistant"})

    def add(self, role: str, env: Envelope) -> None:
        # Enforce the invariant at assembly, not at ingest: a message whose
        # role outranks its taint must carry a declassification warrant.
        if role in self._authoritative_roles and env.taint >= TaintLevel.UNTRUSTED:
            if env.warrant is None:
                raise ProvenanceDiscontinuity(
                    f"span {env.origin_span}: tainted content placed in role "
                    f"'{role}' with no declassification warrant; "
                    f"taint={env.taint.name}"
                )
        self._messages.append((role, env))

    def effective_taint(self) -> TaintLevel:
        level = TaintLevel.TRUSTED
        for _, env in self._messages:
            level = TaintLevel(max(level, env.taint))
        return level


def summarize(env: Envelope, max_chars: int) -> Envelope:
    # A transform MUST preserve the envelope's taint and origin. Dropping
    # either is the laundering step that voids containment.
    if not isinstance(env, Envelope):
        raise ProvenanceDiscontinuity(
            "transform received bare string; taint envelope was lost at the "
            "content-mediated edge"
        )
    return Envelope(
        text=env.text[:max_chars],
        taint=env.taint,
        origin_span=env.origin_span,
        warrant=env.warrant,
    )


def assemble_agent_context(
    tool_result: Envelope, budget: int
) -> ContextAssembler:
    asm = ContextAssembler()
    # Correct path: summary re-enters as a delimited untrusted block, not as
    # an assistant-authored message.
    summary = summarize(tool_result, budget)
    asm.add("user", summary)
    return asm


def assemble_laundered(
    tool_result: Envelope, budget: int
) -> ContextAssembler:
    asm = ContextAssembler()
    summary = summarize(tool_result, budget)
    # The failure: re-embedding as assistant role with no warrant. This must
    # raise, and that raise is the containment working as intended.
    asm.add("assistant", summary)
    return asm
