# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-dynamic-information-flow-taint-labels-silently-decay-across-agent-hops-and-why-prompt-injection-confinement-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-dynamic-information-flow-taint-labels-silently-decay-across-agent-hops-and-why-prompt-injection-confinement-fail.warrant.json
# Markdown SHA-256:   fac08a6cc5421a4c50481325ae28253294d12012a2f8b0c1f9899e3f36a54106
# Code AST SHA-256:   7ab19b7531304f89fb100ac7187652dad2dbadebeee42002ba73e6cb75bda7da
# Verified Classes:   TaintDecayError, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintDecayError(RuntimeError):
    """Raised when a taint label is missing or defaulted at a hop boundary."""
    pass


@dataclass
class Envelope:
    content: str
    taint: Optional[str] = None          # required in schema; None means "missing"
    origin: Optional[str] = None
    hop: int = 0


def join_taint(upstream: Optional[str], transformation: str) -> str:
    # Lattice join: untrusted dominates; missing is treated as untrusted.
    if upstream is None:
        return "untrusted"               # fail closed on missing label
    if upstream == "untrusted":
        return "untrusted"
    # A transformation that can carry attacker-controlled bytes re-taints.
    if transformation in {"summarize", "reformat", "quote", "preserve_verbatim"}:
        return "untrusted"
    return upstream


def forward(env: Envelope, transformation: str, next_hop: int) -> Envelope:
    if env.taint is None:
        raise TaintDecayError(
            f"hop {env.hop}->{next_hop}: taint label missing on envelope; "
            f"refusing to default to 'trusted'"
        )
    new_taint = join_taint(env.taint, transformation)
    if new_taint != env.taint:
        # Loud, not silent: the transformation escalated taint.
        pass
    return Envelope(
        content=env.content,
        taint=new_taint,
        origin=env.origin,
        hop=next_hop,
    )


def gate(env: Envelope, action: str) -> None:
    if env.taint is None:
        raise TaintDecayError(f"gate for {action!r}: envelope has no taint label")
    if env.taint == "untrusted" and action in {"write_file", "shell_exec", "http_out"}:
        raise TaintDecayError(
            f"gate for {action!r}: blocked untrusted content at hop {env.hop}"
        )
