# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-output-sanitization-as-a-non-idempotent-transform-that-invalidates-the-instruction-hierarchy.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-output-sanitization-as-a-non-idempotent-transform-that-invalidates-the-instruction-hierarchy.warrant.json
# Markdown SHA-256:   b0e5bd7a07b02099b8b535ed103ab87519aa1079afc0b0f4afb9c991131d1062
# Code AST SHA-256:   e97fae171f690066ea75c7ea8bd612c0ffa5c635d8e1ec612536801110466141
# Verified Classes:   ProvenanceLaunderingError, ContextObject
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, replace


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a transform drops or downgrades provenance on tool-derived content."""


@dataclass(frozen=True)
class ContextObject:
    text: str
    provenance: str          # e.g. "tool:payments", "peer:auditor", "assistant", "system"
    tainted: bool            # lineage-derived; only declassify() may clear
    tier: str                # "DATA" | "INSTRUCTION"


_TRUSTED_ORIGINS = {"system", "assistant"}


def sanitize(obj: ContextObject, strip_markers: tuple[str, ...]) -> ContextObject:
    """Non-idempotent-safe sanitizer: strips markers but MUST preserve lineage."""
    if not isinstance(obj, ContextObject):
        raise ProvenanceLaunderingError("sanitize() received bare text; provenance lost at call site")
    stripped = obj.text
    for m in strip_markers:
        stripped = stripped.replace(m, "")
    # Taint is monotonic: a strip is NOT evidence of safety.
    return replace(obj, text=stripped, tainted=obj.tainted)


def declassify(obj: ContextObject, reason: str) -> ContextObject:
    """Explicit, audited declassification. Only legal path to clear taint."""
    if obj.provenance.split(":")[0] not in _TRUSTED_ORIGINS and not reason.startswith("typed-parse:"):
        raise ProvenanceLaunderingError(
            f"cannot declassify untrusted origin {obj.provenance!r} without typed-parse reason"
        )
    return replace(obj, tainted=False)


def promote_to_instruction(obj: ContextObject) -> ContextObject:
    """Distillation / resume path. Promotion firewall lives here."""
    origin = obj.provenance.split(":")[0]
    if origin in ("tool", "peer") and obj.tainted:
        raise ProvenanceLaunderingError(
            f"refusing to promote tainted {obj.provenance!r} content to INSTRUCTION tier"
        )
    if obj.provenance not in _TRUSTED_ORIGINS and obj.provenance.split(":")[0] not in _TRUSTED_ORIGINS:
        raise ProvenanceLaunderingError(
            f"promotion of {obj.provenance!r} would violate instruction hierarchy"
        )
    return replace(obj, tier="INSTRUCTION")


def resume_from_scratchpad(entries: list[ContextObject]) -> list[ContextObject]:
    """Checkpoint reload. Rejects any entry whose provenance was laundered to bare text."""
    out = []
    for e in entries:
        if not isinstance(e, ContextObject):
            raise ProvenanceLaunderingError("scratchpad entry lacks provenance; laundering suspected")
        if e.tier == "INSTRUCTION" and e.provenance.split(":")[0] in ("tool", "peer"):
            raise ProvenanceLaunderingError(
                f"resumed entry {e.provenance!r} already promoted across trust boundary"
            )
        out.append(e)
    return out
