# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-across-a-retrieval-to-tool-seam-when-the-label-carrier-itself-is-attacker-writable.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-across-a-retrieval-to-tool-seam-when-the-label-carrier-itself-is-attacker-writable.warrant.json
# Markdown SHA-256:   b6ce30b7b4ea7db44ff6f93ca9094a878a532e88659c40b0cc0fed187d7f865a
# Code AST SHA-256:   f12790baf637268d534ca11dfe3eb8d83c9472b6bff0c1014b2abc47e779b431
# Verified Classes:   TaintViolation, Trust, Channel
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum


class TaintViolation(RuntimeError):
    """Raised when a label-bearing position is authored or copied by model output."""


class Trust(IntEnum):
    UNTRUSTED = 0
    INTERNAL = 1
    PRIVILEGED = 2


@dataclass(frozen=True)
class Channel:
    """A message as the runtime sees it. Labels live here, never in `body`."""
    message_id: str
    body: str
    trust: Trust
    taint: frozenset[str] = field(default_factory=frozenset)


_LABEL_SCHEMA_KEYS = frozenset({"trust", "source", "taint", "origin"})
_SENTINEL = "__IFC_7f3a__"


def derive_hop_output(
    inputs: list[Channel],
    model_output: str,
    *,
    out_message_id: str,
) -> Channel:
    """
    Re-key a model-mediated hop. The model's output is content only; the
    runtime derives trust and taint from provenance, never from the bytes.

    Invariant: out.taint = join(in.taint for all in), and out.trust is the
    minimum trust of any input. A model that emits label-shaped fields or the
    sentinel is treated as an injection attempt, not as a label author.
    """
    if not inputs:
        raise TaintViolation("hop has no provenance; refusing to mint a label")

    # 1. Reject any attempt by the model to author a label position.
    for key in _LABEL_SCHEMA_KEYS:
        if f'"{key}"' in model_output or f"'{key}'" in model_output:
            raise TaintViolation(
                f"model output contains label-bearing key {key!r}; "
                "labels are runtime-derived, not model-authored"
            )
    if _SENTINEL in model_output:
        raise TaintViolation(
            "model output contains the IFC sentinel; treating as injection"
        )

    # 2. Derive trust as the minimum over provenance (monotone, no declass).
    derived_trust = min(ch.trust for ch in inputs)

    # 3. Join taint over provenance, not over lexical overlap. A paraphrase
    #    of tainted content is tainted even if no substring is shared.
    joined_taint: set[str] = set()
    for ch in inputs:
        joined_taint |= ch.taint
        if ch.trust is Trust.UNTRUSTED:
            joined_taint.add(f"untrusted:{ch.message_id}")

    return Channel(
        message_id=out_message_id,
        body=model_output,
        trust=derived_trust,
        taint=frozenset(joined_taint),
    )


def admit_to_privileged_tool(hop: Channel) -> None:
    """Gate a tool call on the runtime-derived label, never on body content."""
    if hop.taint:
        raise TaintViolation(
            f"message {hop.message_id} carries taint {sorted(hop.taint)}; "
            "privileged tool admission requires out-of-band declassification"
        )
    if hop.trust < Trust.PRIVILEGED:
        raise TaintViolation(
            f"message {hop.message_id} has trust {hop.trust.name}; "
            "insufficient for privileged tool"
        )
