# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-taint-labeled-envelope-as-non-authoritative-when-a-downstream-agent-re-signs-its-own-observations.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-taint-labeled-envelope-as-non-authoritative-when-a-downstream-agent-re-signs-its-own-observations.warrant.json
# Markdown SHA-256:   7b10aab605a538a200afe507ae3d6d2707392766d5e919bfc158f1cbc80964a5
# Code AST SHA-256:   accde30646de5df4a167496a9e279211ee596026c3ad052dbc80112556a4e636
# Verified Classes:   TaintLaunderingError, Envelope, TaintRuntime
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when an agent attempts to sign an outbound envelope whose
    declared lineage does not cover the runtime-observed read set."""
    pass


@dataclass(frozen=True)
class Envelope:
    signer: str
    taint: FrozenSet[str]          # provenance edge ids
    derived_from: FrozenSet[str]   # span ids this envelope claims to derive from
    content: str


@dataclass
class TaintRuntime:
    """The runtime, not the agent, observes reads and computes inheritance."""
    observed_reads: dict = field(default_factory=dict)  # agent_id -> set of span ids

    def on_read(self, agent_id: str, envelope: Envelope) -> None:
        self.observed_reads.setdefault(agent_id, set()).update(envelope.derived_from)
        self.observed_reads[agent_id].update(envelope.taint)

    def sign(self, agent_id: str, declared: Envelope) -> Envelope:
        observed = self.observed_reads.get(agent_id, set())
        missing = observed - set(declared.derived_from) - set(declared.taint)
        if missing:
            raise TaintLaunderingError(
                f"agent {agent_id} attempted to sign envelope with clean lineage "
                f"but runtime observed reads from spans {sorted(missing)}; "
                f"re-signing would launder taint. Refusing to sign."
            )
        if declared.signer == agent_id and "self" in declared.derived_from and observed:
            raise TaintLaunderingError(
                f"agent {agent_id} self-declared derived_from='self' while "
                f"runtime observed {len(observed)} inbound spans; "
                f"self-declared lineage is non-authoritative."
            )
        return declared


def propagate(agent_id: str, runtime: TaintRuntime, inbound: Envelope,
              outbound_content: str) -> Envelope:
    runtime.on_read(agent_id, inbound)
    # A correct agent must inherit, not reset, taint.
    candidate = Envelope(
        signer=agent_id,
        taint=inbound.taint,
        derived_from=inbound.derived_from,
        content=outbound_content,
    )
    return runtime.sign(agent_id, candidate)


def propagate_laundered(agent_id: str, runtime: TaintRuntime, inbound: Envelope,
                        outbound_content: str) -> Envelope:
    runtime.on_read(agent_id, inbound)
    # The bug: agent resets taint because it is "just summarizing."
    candidate = Envelope(
        signer=agent_id,
        taint=frozenset(),
        derived_from=frozenset({"self"}),
        content=outbound_content,
    )
    return runtime.sign(agent_id, candidate)  # raises TaintLaunderingError
