# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-after-a-tool-call-mutates-the-very-object-it-was-authorized-against.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-after-a-tool-call-mutates-the-very-object-it-was-authorized-against.warrant.json
# Markdown SHA-256:   8eefdebd030cd64f7750aec244d9994b782b7bed73886eccf2abb6fdf9eefeb7
# Code AST SHA-256:   8ee328254e6113dcdddb389342b1a27c71c4a3838a4be3aacbf75015c03f8e40
# Verified Classes:   TaintLaunderingError, LabelStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Hashable

TAINT_ORDER = {"TRUSTED": 0, "INTERNAL": 1, "UNTRUSTED": 2}

class TaintLaunderingError(RuntimeError):
    """Raised when a mutating tool call would lower an object's taint below
    the join of its pre-call label and the taint of all inputs that flowed
    into the write. This is a hard failure at the write boundary, not a
    downstream authorization failure."""
    pass

@dataclass
class LabelStore:
    labels: dict[Hashable, str] = field(default_factory=dict)

    def get(self, obj: Hashable) -> str:
        return self.labels.get(obj, "TRUSTED")

    def snapshot(self, objs) -> dict[Hashable, str]:
        return {o: self.get(o) for o in objs}

    def join(self, *labels: str) -> str:
        return max(labels, key=lambda l: TAINT_ORDER[l])

def enforce_mutating_call(
    store: LabelStore,
    tool_name: str,
    write_targets: list[Hashable],
    input_taints: list[str],
    declared_output_label: str,
) -> None:
    # Snapshot BEFORE the tool writes, or the re-derivation reads its own effect.
    pre = store.snapshot(write_targets)
    input_join = store.join(*input_taints) if input_taints else "TRUSTED"
    required = store.join(input_join, declared_output_label)

    for obj in write_targets:
        post = store.get(obj)  # tool has already written; store reflects new label
        floor = store.join(pre[obj], required)
        if TAINT_ORDER[post] < TAINT_ORDER[floor]:
            raise TaintLaunderingError(
                f"tool={tool_name} target={obj!r} "
                f"pre={pre[obj]} input_join={input_join} "
                f"declared={declared_output_label} post={post} "
                f"required_floor={floor}: write lowered taint below data-flow join"
            )
        # Commit the floor, never the tool's self-reported label.
        store.labels[obj] = floor
