# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-harness-contamination-when-litmus-adversarial-probes-and-legitimate-tool-calls-share-a-byte-identical-prefix.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-harness-contamination-when-litmus-adversarial-probes-and-legitimate-tool-calls-share-a-byte-identical-prefix.warrant.json
# Markdown SHA-256:   a25b355e6e0c02757b63023cae0bec8ef7102cf2affef34b6c07ed770a0956a4
# Code AST SHA-256:   6c7622f3441b51f6e0a70ad44fcbffeccfd946718dc06a23aa1f4924b04d3036
# Verified Classes:   ProvenanceCollapseError, ActionClass, Suspicion, ChannelState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

"""Provenance-discrimination guard for adversarial-harness evaluation.

Enforces the decision boundary: no irreversible action may be taken on the
basis of a syntactic-only discriminator when the probe/legit channel is
unlabeled at the model boundary.
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class ProvenanceCollapseError(RuntimeError):
    """Raised when an irreversible action is attempted under collapse regime."""


class ActionClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"
    EXFILTRATING = "exfiltrating"


@dataclass(frozen=True)
class Suspicion:
    """A candidate reason to flag an input.

    semantic_feature: the content-level property that would flip the decision
        (e.g. 'requests read of /etc/shadow'). Must be checkable against the
        payload itself.
    syntactic_feature: a formatting/path/offset correlate (e.g. header string,
        filename quarter, token offset). May leak the harness label.
    """
    semantic_feature: str | None
    syntactic_feature: str | None


@dataclass(frozen=True)
class ChannelState:
    """What the instance actually knows about provenance at the model boundary."""
    probe_label_visible: bool      # tag survived transport into assembled prompt
    control_arm_present: bool      # paired-legit arm exists in this eval
    distributions_disjoint: bool   # legit vs adversarial separable on content


def classify_action(tool_name: str, args: dict) -> ActionClass:
    if tool_name in {"read_file", "list_dir", "summarize"}:
        return ActionClass.REVERSIBLE
    if tool_name in {"write_file", "rotate_key", "delete", "exec_shell"}:
        return ActionClass.IRREVERSIBLE
    if tool_name in {"http_post", "send_email", "upload"}:
        return ActionClass.EXFILTRATING
    return ActionClass.IRREVERSIBLE  # conservative default for unknown tools


def is_collapse_regime(ch: ChannelState) -> bool:
    """True when no valid single policy can separate probe from legit input."""
    return not (ch.probe_label_visible or ch.distributions_disjoint)


def decide(
    ch: ChannelState,
    susp: Suspicion,
    action: ActionClass,
) -> str:
    """Return 'act', 'flag_hold', or 'escalate'.

    Raises ProvenanceCollapseError if an irreversible/exfiltrating action is
    about to be justified only by a syntactic discriminator.
    """
    provenance_trusted = ch.probe_label_visible or ch.distributions_disjoint
    semantic_signal = susp.semantic_feature is not None
    syntactic_only = semantic_signal is False and susp.syntactic_feature is not None

    if action in (ActionClass.IRREVERSIBLE, ActionClass.EXFILTRATING):
        if not provenance_trusted and syntactic_only:
            raise ProvenanceCollapseError(
                f"Refusing {action.value} action justified only by syntactic "
                f"feature {susp.syntactic_feature!r}; channel provenance is "
                f"untrusted (label_visible={ch.probe_label_visible}, "
                f"disjoint={ch.distributions_disjoint}). Escalate for "
                f"out-of-band verification instead."
            )
        if not provenance_trusted:
            return "escalate"

    if is_collapse_regime(ch):
        # Neither comply nor refuse silently; surface uncertainty.
        return "flag_hold"

    if syntactic_only and not semantic_signal:
        # Detector is measuring the harness, not the adversary.
        return "escalate"

    return "act" if not syntactic_only else "flag_hold"


# --- exercise the guard -------------------------------------------------
if __name__ == "__main__":
    # Harness claims a probe_id tag, but transport dropped it; no control arm.
    degraded = ChannelState(
        probe_label_visible=False,
        control_arm_present=False,
        distributions_disjoint=False,
    )
    # Agent's only signal: the benign-looking header it saw on a real file.
    weak = Suspicion(semantic_feature=None, syntactic_feature="INTERNAL NOTES header")

    try:
        decide(degraded, weak, ActionClass.EXFILTRATING)
    except ProvenanceCollapseError as exc:
        print(f"[guard] blocked: {exc}")

    # Reversible summarization under collapse -> hold, not silent comply.
    print(decide(degraded, weak, ActionClass.REVERSIBLE))  # flag_hold

    # Healthy channel: tag survives, distributions disjoint.
    healthy = ChannelState(True, True, True)
    strong = Suspicion(semantic_feature="requests read of /etc/shadow",
                       syntactic_feature=None)
    print(decide(healthy, strong, ActionClass.EXFILTRATING))  # act (flag path)
