# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-transitive-tool-invocation-graphs-when-provenance-is-re-asserted-at-each-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-transitive-tool-invocation-graphs-when-provenance-is-re-asserted-at-each-hop.warrant.json
# Markdown SHA-256:   897af080390b9289c6ecd76c71272d148d2956975993800833d32a9aeefbc111
# Code AST SHA-256:   da3bce932fe91f2fae1218bf4151fb8e7ae80b0e729a91e655e379eed3cd4590
# Verified Classes:   TaintLaunderingError, Taint, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a node with agency receives content whose origin chain
    cannot be reconstructed, or when a sink call would exceed clearance."""


@dataclass(frozen=True)
class Taint:
    origin: str            # e.g. "untrusted:web", "trusted:internal"
    chain: tuple[str, ...] # ordered hop ids, oldest first

    def meet(self, other: "Taint") -> "Taint":
        # Taint only accumulates: the weaker origin wins, chains concatenate.
        weaker = self.origin if self.origin.startswith("untrusted") else other.origin
        return Taint(origin=weaker, chain=self.chain + other.chain)


@dataclass
class Envelope:
    value: Any
    taint: Taint | None  # None == provenance was dropped at some hop


def emit_tool_call(node_id: str, can_emit: bool, arg: Envelope,
                   sink_clearance: str) -> Envelope:
    if can_emit and arg.taint is None:
        # Fail closed: a node with agency must not default to caller trust.
        raise TaintLaunderingError(
            f"node {node_id} has agency but argument provenance is absent; "
            f"refusing to re-derive trust from caller identity"
        )
    effective = arg.taint.origin if arg.taint else "untrusted:unknown"
    if effective.startswith("untrusted") and sink_clearance != "untrusted-ok":
        raise TaintLaunderingError(
            f"node {node_id} would route taint {effective} "
            f"(chain={arg.taint.chain if arg.taint else '?'}) "
            f"into sink with clearance {sink_clearance}"
        )
    return arg


def detect_discontinuity(sink_arg: Envelope, ingested_hashes: dict[str, str],
                         content_hash: str) -> None:
    claimed = sink_arg.taint.origin if sink_arg.taint else "trusted:implicit"
    true_origin = ingested_hashes.get(content_hash)
    if true_origin and true_origin.startswith("untrusted") and claimed.startswith("trusted"):
        raise TaintLaunderingError(
            f"provenance discontinuity: content matches {true_origin} "
            f"but envelope claims {claimed}"
        )
