# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-agent-instance-refuse-to-propagate-a-taint-label-across-a-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-agent-instance-refuse-to-propagate-a-taint-label-across-a-tool-boundary.warrant.json
# Markdown SHA-256:   8a8031dad421b1e0d7a30e565747bf3354480af3e426628732280833bc189d79
# Code AST SHA-256:   74b7dd044097d6a090551e458e484cd699b68826052fd40b2db696be518e52e9
# Verified Classes:   TaintBoundaryError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintBoundaryError(RuntimeError):
    """Raised when a label cannot be safely propagated across a tool boundary."""
    pass


TRUST_ORDER = {"external_untrusted": 0, "internal": 1, "trusted": 2}


def join_labels(*labels: str) -> str:
    if not labels:
        return "external_untrusted"
    return max(labels, key=lambda l: TRUST_ORDER[l])


def propagate_across_boundary(
    inbound_label: str | None,
    tool_manifest_trust: str | None,
    payload_declared_trust: str | None,
) -> str:
    # Rule 1: absence of a label slot is untrusted, never trusted.
    effective_inbound = inbound_label if inbound_label is not None else "external_untrusted"

    # Rule 2: a trust claim inside the payload is itself tainted input.
    if payload_declared_trust is not None:
        raise TaintBoundaryError(
            f"tool declared trust={payload_declared_trust!r} inside payload; "
            "trust claims must be pinned in the manifest, not self-asserted"
        )

    if tool_manifest_trust is None:
        # Rule 3: no pinned trust -> cannot prove non-downgrade -> reject.
        raise TaintBoundaryError(
            "tool has no pinned manifest trust; cannot prove label was not downgraded"
        )

    joined = join_labels(effective_inbound, tool_manifest_trust)

    # Rule 4: monotonicity — never allow the join to fall below inbound.
    if TRUST_ORDER[joined] < TRUST_ORDER[effective_inbound]:
        raise TaintBoundaryError(
            f"label downgrade: {effective_inbound!r} -> {joined!r} across tool boundary"
        )
    return joined


def evaluate_tool_result(
    inbound_label: str | None,
    tool_manifest_trust: str | None,
    payload: dict,
) -> str:
    try:
        return propagate_across_boundary(
            inbound_label,
            tool_manifest_trust,
            payload.get("_provenance"),
        )
    except TaintBoundaryError as exc:
        # Reject the call rather than proceed with a best-effort label.
        raise TaintBoundaryError(f"tool call rejected at taint boundary: {exc}") from exc
