# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-forgery-in-its-own-memory-write-log-when-the-poisoning-adversary-controls-the-tool-outputs-that-seed-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-forgery-in-its-own-memory-write-log-when-the-poisoning-adversary-controls-the-tool-outputs-that-seed-provenance.warrant.json
# Markdown SHA-256:   1daaf051bb671757fb000e758aedc9b4a0aa00df5b4ab93e54acd58ff9acbb4f
# Code AST SHA-256:   d93e6428215d82a28d85a81c82b49522e9a3c4b9a19cdc5935de166c7d301112
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write would promote adversary-influenceable content to recall-eligible tier."""
    pass


INSTRUCTION_THRESHOLD = 0.6
ADVERSARY_INFLUENCEABLE_CHANNELS = {"web_fetch", "doc_retrieval", "peer_agent_msg"}


def classify_write(content: str, provenance: dict, instruction_score: float) -> dict:
    channel = provenance.get("source")
    tier = provenance.get("tier")

    if channel in ADVERSARY_INFLUENCEABLE_CHANNELS and instruction_score > INSTRUCTION_THRESHOLD:
        # Channel tier is authentic but content is instructional: demote to quarantine.
        return {**provenance, "tier": "T1q", "quarantine_reason": "instruction_likeness"}

    if channel in ADVERSARY_INFLUENCEABLE_CHANNELS and tier in ("T0", "T1"):
        # Tier inflation attempt: a channel cannot self-assign above its registry tier.
        raise ProvenanceLaunderingError(
            f"channel {channel!r} attempted tier {tier!r}; registry caps at T1q for this channel"
        )

    return provenance


def recall_gate(records: list[dict], require_corroboration: bool = True) -> list[dict]:
    eligible = [r for r in records if r["tier"] in ("T0", "T1")]
    quarantined = [r for r in records if r["tier"] == "T1q"]

    if require_corroboration and quarantined and not eligible:
        # A quarantine-only recall hit is not permitted to satisfy the query.
        raise ProvenanceLaunderingError(
            f"recall blocked: {len(quarantined)} quarantined record(s) with no corroborating T0/T1 support"
        )
    return eligible
