# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-a-memory-write-round-trip-but-not-a-tool-output-re-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-a-memory-write-round-trip-but-not-a-tool-output-re-serialization.warrant.json
# Markdown SHA-256:   f7d7d3871091c58b4ca820500b30bb41e7996081d57b134c04ab0ec6cae7259c
# Code AST SHA-256:   6990e2ef2e7d438161ca24bf24811209276268ee29f60bbb780932590f8b319f
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

memory.write(key="scrape_2026_11_14", value=summary_dict)

class TaintLaunderingError(RuntimeError):
    """Raised when tainted content would be persisted without declassification."""
    pass


TRUSTED_PROVENANCE = frozenset({"self:reasoning", "user:direct", "system:config"})


def guard_memory_write(key: str, value, provenance: str, labels: frozenset[str],
                       declassify_token: str | None = None) -> dict:
    """
    Gate a memory write. A write is permitted only if:
      - provenance is trusted, OR
      - every label is in TRUSTED_PROVENANCE, OR
      - an explicit declassify_token is supplied AND the caller acknowledges
        the union of input labels (no silent laundering through summarization).

    Summarization does NOT declassify. An LLM that paraphrases tainted text
    produces a new object whose labels MUST be the union of its inputs.
    """
    untrusted = frozenset(
        l for l in labels if l not in TRUSTED_PROVENANCE
    ) | (frozenset() if provenance in TRUSTED_PROVENANCE else frozenset({provenance}))

    if untrusted and declassify_token is None:
        raise TaintLaunderingError(
            f"refusing memory write key={key!r}: untrusted labels {sorted(untrusted)} "
            f"would be dropped by serialization. Supply declassify_token to override, "
            f"or write with provenance=untrusted and trust_on_read=False."
        )

    if untrusted and declassify_token is not None:
        if not _verify_declassify_token(declassify_token, key, untrusted):
            raise TaintLaunderingError(
                f"declassify_token for key={key!r} does not cover labels "
                f"{sorted(untrusted)}; token scope mismatch."
            )
        return {
            "key": key,
            "value": value,
            "provenance": provenance,
            "taint": sorted(untrusted),
            "declassified": True,
        }

    return {
        "key": key,
        "value": value,
        "provenance": provenance,
        "taint": [],
        "declassified": False,
    }


def _verify_declassify_token(token: str, key: str, labels: frozenset[str]) -> bool:
    # Placeholder: real implementation verifies an HMAC over (key, sorted(labels))
    # against a token minted by an authorized declassifier (e.g., a user approval).
    return token.startswith("declass:") and key in token


# --- Example: the laundering path that this gate blocks ---
def write_scrape_summary(memory, scrape_output: str, labels: frozenset[str]) -> dict:
    summary = {"text": scrape_output[:500], "source": "web_scrape"}
    # The summarizer is NOT an authorized declassifier; labels propagate.
    return guard_memory_write(
        key="scrape_2026_11_14",
        value=summary,
        provenance="untrusted:web_scrape",
        labels=labels,
    )
    # -> raises TaintLaunderingError unless the caller supplies a declassify_token
