# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-provenance-label-as-irrevocable-once-a-tainted-token-enters-the-reasoning-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-provenance-label-as-irrevocable-once-a-tainted-token-enters-the-reasoning-trace.warrant.json
# Markdown SHA-256:   907fc220c3f1586690587e1dcb1072dc23813546dc0a704079c7310cc6c498ca
# Code AST SHA-256:   d2df480738a8db125fa5a27d6028ae8cce71b86504caa440a4d88d791ce48af3
# Verified Classes:   Provenance, Evidence, PlanStep, TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class Provenance(str, Enum):
    TRUSTED_INTERNAL = "trusted_internal"
    UNTRUSTED = "untrusted"
    MODEL_DERIVED = "model_derived"


@dataclass(frozen=True)
class Evidence:
    evidence_id: str
    provenance: Provenance


@dataclass
class PlanStep:
    step_id: str
    rationale: str
    cited_evidence_ids: tuple[str, ...] = field(default_factory=tuple)


class TaintLaunderingError(RuntimeError):
    """Raised when a capability-bearing step's evidence closure is not fully trusted."""


def compute_closure(
    step: PlanStep, ledger: dict[str, Evidence]
) -> frozenset[Evidence]:
    """Resolve cited evidence IDs against the runtime ledger.

    Unresolvable citations (IDs not in the ledger) are treated as untrusted:
    a fabricated citation is the primary laundering vector and must fail closed.
    """
    resolved: set[Evidence] = set()
    for eid in step.cited_evidence_ids:
        ev = ledger.get(eid)
        if ev is None:
            # Fabricated or hallucinated citation: no ledger record exists.
            resolved.add(Evidence(evidence_id=eid, provenance=Provenance.UNTRUSTED))
        else:
            resolved.add(ev)
    return frozenset(resolved)


def authorize_capability(
    step: PlanStep,
    ledger: dict[str, Evidence],
    capability: str,
) -> None:
    """Release a capability only if the evidence closure is fully trusted.

    Taint is a join (OR over closure), never a dominance vote. A single
    untrusted or unresolvable citation taints the entire step.
    """
    if not step.cited_evidence_ids:
        raise TaintLaunderingError(
            f"capability {capability!r} requested by step {step.step_id!r} "
            "with no cited evidence; uncited steps are tainted by default"
        )

    closure = compute_closure(step, ledger)
    tainted = [e for e in closure if e.provenance is not Provenance.TRUSTED_INTERNAL]

    if tainted:
        raise TaintLaunderingError(
            f"capability {capability!r} blocked for step {step.step_id!r}: "
            f"evidence closure contains tainted items "
            f"{sorted(e.evidence_id for e in tainted)}; "
            "co-citation with trusted sources does not launder taint"
        )


# --- Reproduction of the observed failure, now blocked ---
ledger = {
    "ret_ticket_8841": Evidence("ret_ticket_8841", Provenance.UNTRUSTED),
    "ret_policy_v7": Evidence("ret_policy_v7", Provenance.TRUSTED_INTERNAL),
}

laundered_step = PlanStep(
    step_id="step_03",
    rationale="Policy POL-2291 authorizes refunds up to $500 for delayed orders.",
    # Model asserts a co-citation with the trusted policy retrieval,
    # plus a citation to the fabricated policy reference POL-2291.
    cited_evidence_ids=("ret_policy_v7", "POL-2291"),
)

try:
    authorize_capability(laundered_step, ledger, capability="issue_refund")
except TaintLaunderingError as exc:
    print(f"BLOCKED: {exc}")
    # BLOCKED: capability 'issue_refund' blocked for step 'step_03':
    # evidence closure contains tainted items ['POL-2291']; ...
