# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-deceptive-alignment-drift-when-its-own-litmus-probe-is-being-gamed-by-the-swarm-it-monitors.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-deceptive-alignment-drift-when-its-own-litmus-probe-is-being-gamed-by-the-swarm-it-monitors.warrant.json
# Markdown SHA-256:   3d5c3ab7ad8646cffa99f06295d326536a494043d72f1b147434c7b8b8ec70f9
# Code AST SHA-256:   dac785bf60acad11c1ba464a53992b2625cb5d0bc5315b7391d16aaacb39f74b
# Verified Classes:   ProbeContaminationError, LitmusRSM
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProbeContaminationError(RuntimeError):
    """Raised when a LITMUS probe outcome is routed into a channel
    reachable by the probed population, invalidating downstream scores."""
    pass


class LitmusRSM:
    def __init__(self, probed_tier_readsets, monitor_private_store):
        self._probed_readsets = probed_tier_readsets  # set of channel ids
        self._private = monitor_private_store
        self._naivety = {}  # agent_id -> remaining clean-probe budget

    def publish_flag(self, agent_id, channel_id, score):
        # A flag is only safe if no probed agent can read the channel.
        if channel_id in self._probed_readsets:
            # Mark every peer in the tier as non-naive: the leak is generalizable.
            for peer in self._probed_readsets[channel_id]:
                self._naivety[peer] = 0
            raise ProbeContaminationError(
                f"flag for {agent_id} routed to channel {channel_id} readable "
                f"by probed tier; downstream scores in this horizon are void"
            )
        self._private.write(agent_id, channel_id, score)

    def score(self, agent_id, delta, threshold):
        if self._naivety.get(agent_id, 1) <= 0:
            raise ProbeContaminationError(
                f"agent {agent_id} has observed a probe artifact; "
                f"score {delta} is sign-unreliable and must not be aggregated"
            )
        self._naivety[agent_id] = self._naivety.get(agent_id, 1) - 1
        return delta > threshold
