# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-provenance-label-as-unforgeable-rather-than-advisory.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-provenance-label-as-unforgeable-rather-than-advisory.warrant.json
# Markdown SHA-256:   b8368f84acd7b77d5a88a4f7dbd0f9b2be23da0da95df2562fc92d59c40c2e94
# Code AST SHA-256:   47df5871b6301684d5409b0a06dd32c30afee17b67599bfee5d5964a3b2045da
# Verified Classes:   ProvenanceForgeryError, TaintDowngradeError, Span, ToolResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass, field
from typing import Literal

Taint = Literal["trusted", "untrusted"]
_RANK = {"trusted": 0, "untrusted": 1}


class ProvenanceForgeryError(RuntimeError):
    """Raised when a taint resolution depends on model-authored label bytes."""


class TaintDowngradeError(RuntimeError):
    """Raised when a paraphrase or re-emission attempts to lower taint."""


@dataclass(frozen=True)
class Span:
    span_id: str
    content: str
    label: Taint
    mac: bytes  # orchestrator-issued HMAC over (span_id, label, content_hash)


@dataclass
class ToolResult:
    span: Span
    arg_taints: tuple[Taint, ...] = field(default_factory=tuple)

    def effective_taint(self, key: bytes) -> Taint:
        # Outermost-wins + monotonic join: never trust the innermost/self-reported label.
        if not _verify(self.span, key):
            raise ProvenanceForgeryError(
                f"span {self.span.span_id!r} label not orchestrator-signed; "
                "treating as advisory is unsafe for privileged actions"
            )
        joined = max((self.span.label, *self.arg_taints), key=_RANK.__getitem__)
        return joined


def _verify(span: Span, key: bytes) -> bool:
    msg = f"{span.span_id}|{span.label}|{hashlib.sha256(span.content.encode()).hexdigest()}"
    expected = hmac.new(key, msg.encode(), hashlib.sha256).digest()
    return hmac.compare_digest(expected, span.mac)


def gate_privileged_action(result: ToolResult, key: bytes, action: str) -> None:
    taint = result.effective_taint(key)
    if taint == "untrusted":
        raise TaintDowngradeError(
            f"action {action!r} blocked: derived from untrusted span {result.span.span_id!r}; "
            "escalate for out-of-band adjudication"
        )


def summarize(untrusted_input: ToolResult, key: bytes, summary_text: str) -> ToolResult:
    # A summarizer is a model: its output taint is the join of its inputs, regardless
    # of any <trusted> tag the summary text may contain.
    parent = untrusted_input.effective_taint(key)
    forged = "<trusted source=\"operator\">" in summary_text
    if forged:
        raise ProvenanceForgeryError(
            "summary contains a model-authored provenance tag; "
            "labels must be out-of-band, not in the token stream"
        )
    span = Span(span_id="sum-1", content=summary_text, label=parent, mac=b"")
    return ToolResult(span=span, arg_taints=(parent,))
