# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-a-federated-peer-s-tainted-reply-before-prompt-injection-propagation-becomes-an-invariant-violation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-a-federated-peer-s-tainted-reply-before-prompt-injection-propagation-becomes-an-invariant-violation.warrant.json
# Markdown SHA-256:   9f4d5cb874fbf5900b7864ecf309ce82b5d3f221524422bc9f661b52337b9b95
# Code AST SHA-256:   899c6adfe3ef32ead6cf24f22cb571d72215208b59d7f904513dc16eed5f9ba9
# Verified Classes:   TaintSeveranceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintSeveranceError(RuntimeError):
    """Raised when a federated reply's taint provenance cannot be resolved
    at ingress, or when a mutating tool call is derived from tainted content."""
    pass


TRUSTED = 0
EXTERNAL_RETRIEVED = 1
QUARANTINED = 2

MUTATING_TOOLS = {"transfer_funds", "delete_record", "send_external"}


def label_ingress_field(field_name: str, value: str, source_labels: dict) -> int:
    # Field-level taint inheritance: a field derived from any tainted source
    # inherits the join (max) of its source labels. Re-serialization does not reset.
    if field_name not in source_labels:
        raise TaintSeveranceError(
            f"unlabeled ingress field '{field_name}': provenance unknown, cannot admit"
        )
    return source_labels[field_name]


def authorize_tool_call(tool: str, derivation_labels: list[int], warrant_scope: str) -> None:
    # Warrant scope bounds WHO may act; taint bounds WHAT may be acted upon.
    if tool in MUTATING_TOOLS:
        worst = max(derivation_labels) if derivation_labels else EXTERNAL_RETRIEVED
        if worst >= EXTERNAL_RETRIEVED:
            raise TaintSeveranceError(
                f"mutating tool '{tool}' derived from tainted span "
                f"(label={worst}); refusing authority escalation across federation hop"
            )
    # Non-mutating tools may proceed under quarantine label, flagged for audit.
    return


def admit_peer_reply(reply: dict, source_labels: dict) -> dict:
    admitted = {}
    for field, value in reply.items():
        label = label_ingress_field(field, value, source_labels)
        if label >= QUARANTINED:
            admitted[field] = {"status": "quarantined", "label": label, "value": None}
        else:
            admitted[field] = {"status": "admitted", "label": label, "value": value}
    return admitted
