# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-litmus-benchmark-harness-contamination-when-a-continuous-red-team-agent-s-probe-corpus-silently-overlaps-with-its-own-at.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-litmus-benchmark-harness-contamination-when-a-continuous-red-team-agent-s-probe-corpus-silently-overlaps-with-its-own-at.warrant.json
# Markdown SHA-256:   ee7b80cef3b5df1c16fa30bb02b65d1536606d5de0c4c3dcf499a126c5322257
# Code AST SHA-256:   0b236b1039d82dbcfec8efdd2fe30631e4ea3aa028d58a9720f0841f1b025d37
# Verified Classes:   ProbeContaminationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProbeContaminationError(RuntimeError):
    """Raised when a probe submitted to the LITMUS harness is a semantic
    paraphrase-descendant of a success-labeled entry in the red-team agent's
    attack memory for the same target instance."""
    pass


def admit_probe(
    probe: dict,
    attack_memory: list[dict],
    target_id: str,
    frame_classifier,
) -> str:
    """
    Gate a probe before submission to the LITMUS harness.

    probe: {"text": str, "derived_from_frame_id": str | None}
    attack_memory: entries {"frame_id", "target_id", "success_label", "parent_frame_id"}
    frame_classifier: callable(text) -> frame_id, calibrated on target's paraphrase behavior

    Returns "admit" | "quarantine" | "reject".
    Raises ProbeContaminationError if provenance is missing or the gate
    cannot be evaluated.
    """
    if "text" not in probe or "derived_from_frame_id" not in probe:
        raise ProbeContaminationError(
            f"probe missing provenance fields: {probe!r}"
        )

    frame_id = frame_classifier(probe["text"])
    if frame_id is None:
        raise ProbeContaminationError(
            f"frame_classifier returned None for probe {probe['text'][:60]!r}; "
            "cannot evaluate contamination gate"
        )

    # Walk the frame ancestry in attack memory for this target.
    success_frames = {
        e["frame_id"]
        for e in attack_memory
        if e["success_label"] == 1 and e["target_id"] == target_id
    }
    other_target_frames = {
        e["frame_id"]
        for e in attack_memory
        if e["success_label"] == 1 and e["target_id"] != target_id
    }

    ancestor = probe["derived_from_frame_id"]
    seen = set()
    while ancestor is not None and ancestor not in seen:
        seen.add(ancestor)
        if ancestor in success_frames:
            return "quarantine"  # paraphrase-descendant of a same-target win
        if ancestor in other_target_frames:
            return "reject"      # cross-target success; not valid here
        parent = next(
            (e["parent_frame_id"] for e in attack_memory if e["frame_id"] == ancestor),
            None,
        )
        ancestor = parent

    if frame_id in success_frames:
        # Classifier caught an overlap the provenance chain missed.
        raise ProbeContaminationError(
            f"frame {frame_id!r} matches success-labeled memory for target "
            f"{target_id!r} but provenance chain did not: probe {probe['text'][:60]!r}"
        )

    return "admit"
