# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-taint-aware-tool-gating-fail-when-provenance-labels-decohere-across-a-re-plan-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-taint-aware-tool-gating-fail-when-provenance-labels-decohere-across-a-re-plan-boundary.warrant.json
# Markdown SHA-256:   a40feefed47cdbd195e5c10a68ec940991042e2391614dbdf272aed9e5df197a
# Code AST SHA-256:   056efc96f7240837e1bc05acbf152614c388299112b69f6fccf2036cb8fa6e5f
# Verified Classes:   Taint, TaintContinuityError, LabeledValue, ExecutorStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1
    SECRET = 2


def join(*labels: Taint) -> Taint:
    return Taint(max(labels, default=Taint.TRUSTED))


class TaintContinuityError(RuntimeError):
    """Raised when a re-planned argument cannot be proven label-continuous."""


@dataclass
class LabeledValue:
    handle: str
    text: str
    label: Taint


@dataclass
class ExecutorStore:
    values: dict[str, LabeledValue] = field(default_factory=dict)

    def put(self, handle: str, text: str, label: Taint) -> None:
        self.values[handle] = LabeledValue(handle, text, label)

    def live_labels(self) -> Iterable[Taint]:
        return (v.label for v in self.values.values())


def gate_replanned_argument(
    store: ExecutorStore,
    arg_name: str,
    *,
    handle: str | None = None,
    literal: str | None = None,
    sink_requires: Taint = Taint.UNTRUSTED,
) -> Taint:
    """
    Gate one argument of a re-planned tool call.

    Invariant: the argument's effective label must be >= the join of all
    live labels in the planner's context if the argument is a literal,
    and must equal the handle's label if it is a handle reference.
    """
    if handle is not None and literal is not None:
        raise TaintContinuityError(
            f"argument {arg_name!r} is both a handle and a literal; ambiguous provenance"
        )

    if handle is not None:
        if handle not in store.values:
            raise TaintContinuityError(
                f"argument {arg_name!r} references dead handle {handle!r}; "
                "label continuity broken (handle evicted before re-plan)"
            )
        effective = store.values[handle].label
    elif literal is not None:
        # Re-plan laundering guard: a literal emitted while labeled values are
        # live must inherit the join of those labels, not the bottom.
        live = list(store.live_labels())
        if live:
            effective = join(*live)
        else:
            effective = Taint.TRUSTED
    else:
        raise TaintContinuityError(
            f"argument {arg_name!r} has neither handle nor literal"
        )

    if effective > sink_requires:
        raise TaintContinuityError(
            f"argument {arg_name!r} carries {effective.name} > sink allows "
            f"{sink_requires.name}; re-plan did not preserve label continuity"
        )
    return effective


# --- reproduction of the observed failure ---
store = ExecutorStore()
store.put("v7", "<fetched page body>", Taint.UNTRUSTED)
store.put("v9", "<summary of v7>", Taint.UNTRUSTED)

# Safe re-plan: handle preserved.
assert gate_replanned_argument(store, "body", handle="v9") == Taint.UNTRUSTED

# Observed failure: re-plan inlined v9 as a literal. Under the naive gate this
# passed; under the continuity gate it must be rejected.
try:
    gate_replanned_argument(store, "body", literal="<summary of v7>")
except TaintContinuityError as exc:
    print(f"blocked: {exc}")
else:
    raise TaintContinuityError("laundering re-plan was admitted; gate is unsound")
