# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-across-a-sandboxed-shell-boundary-before-it-can-safely-re-enter-its-own-tool-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-across-a-sandboxed-shell-boundary-before-it-can-safely-re-enter-its-own-tool-loop.warrant.json
# Markdown SHA-256:   3e5996478d762e921254126b25739fd6a10e994bbe4229416ae4a05dd0fddb0b
# Code AST SHA-256:   5cfb22b6f1eb1b2e4287479d492a4b0b13435e2311ca80150b4de44b7d9fa4f1
# Verified Classes:   TaintLaunderingError, ExecutionTrace, ContextAssembler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when sandbox output crosses into agent context without its provenance label."""


@dataclass(frozen=True)
class ExecutionTrace:
    exec_id: str
    taint_sources: FrozenSet[str]  # e.g. {"net:untrusted.example", "file:/work/x"}


@dataclass
class ContextAssembler:
    trusted_sources: FrozenSet[str] = field(default_factory=frozenset)

    def ingest(self, trace: ExecutionTrace, output: str, label: FrozenSet[str] | None) -> dict:
        # Invariant: every byte string entering context must carry its taint set.
        if label is None:
            raise TaintLaunderingError(
                f"exec {trace.exec_id}: output entered context with no taint label; "
                f"execution touched {sorted(trace.taint_sources)}"
            )
        if label != trace.taint_sources:
            raise TaintLaunderingError(
                f"exec {trace.exec_id}: label {sorted(label)} does not match "
                f"recorded sources {sorted(trace.taint_sources)}"
            )
        untrusted = label - self.trusted_sources
        return {"output": output, "taint": label, "trusted": not untrusted}


def run_step(assembler: ContextAssembler, trace: ExecutionTrace, output: str) -> dict:
    # Simulate a caller that forgot to propagate the label (the observed bug).
    label = None
    return assembler.ingest(trace, output, label)


if __name__ == "__main__":
    asm = ContextAssembler(trusted_sources=frozenset({"file:/work/clean"}))
    trace = ExecutionTrace(exec_id="e17", taint_sources=frozenset({"net:untrusted.example", "file:/work/x"}))
    run_step(asm, trace, "exit 0\n...")
