# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-taint-a-value-that-arrived-through-a-tool-return-whose-label-was-silently-laundered-by-a-schema-normalizing-serializer.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-taint-a-value-that-arrived-through-a-tool-return-whose-label-was-silently-laundered-by-a-schema-normalizing-serializer.warrant.json
# Markdown SHA-256:   29f00e15b3398ddc29a652a552557d834011268d8ac881c9767809961cca4bc5
# Code AST SHA-256:   27f59b68cf09161ea85b69c4cfaf44e56624d72a282ac18a6a00b46dfbd08142
# Verified Classes:   LabelContinuityError, TaintStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any

TRUSTED, UNTRUSTED, DERIVED_UNTRUSTED = "TRUSTED", "UNTRUSTED", "DERIVED_UNTRUSTED"


class LabelContinuityError(RuntimeError):
    """Raised when a labeled value crosses a boundary and its label cannot be
    re-established without a trust promotion that the manifest did not authorize."""


@dataclass
class TaintStore:
    # Keyed on identity AND exact serialized form; both must agree on lookup.
    by_id: dict[int, str] = field(default_factory=dict)
    by_hash: dict[str, str] = field(default_factory=dict)

    def label(self, v: Any) -> str:
        h = repr(v)
        id_label = self.by_id.get(id(v))
        hash_label = self.by_hash.get(h)
        if id_label is None and hash_label is None:
            return None  # miss
        if id_label != hash_label:
            # identity and content disagree: a reconstruction happened
            return "CONFLICT"
        return id_label

    def tag(self, v: Any, label: str) -> None:
        self.by_id[id(v)] = label
        self.by_hash[repr(v)] = label


def cross_tool_boundary(
    store: TaintStore,
    value: Any,
    tool_manifest_trust: str,
    input_was_tainted: bool,
    normalizer_applied: bool,
) -> str:
    """Determine the label a value carries as it exits a tool boundary.

    Fails closed: a lookup miss on a value derived from tainted input, or a
    normalizer that reconstructed the value without a derivation event, is a
    continuity violation — never a silent promotion to TRUSTED.
    """
    observed = store.label(value)

    if observed == "CONFLICT":
        raise LabelContinuityError(
            "identity/content label conflict: value was reconstructed after labeling"
        )

    if observed is None:
        if input_was_tainted and normalizer_applied:
            raise LabelContinuityError(
                f"laundering serializer: tool declared trust={tool_manifest_trust!r}, "
                "but output was reconstructed from tainted input with no derivation event"
            )
        if input_was_tainted:
            # derived but unlabeled: fail closed, do not promote
            return DERIVED_UNTRUSTED
        return TRUSTED

    if input_was_tainted and observed == TRUSTED and tool_manifest_trust == "pure":
        raise LabelContinuityError(
            "trust promotion on tainted derivation: manifest 'pure' cannot clear taint"
        )

    return observed
