# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-probe-injection-as-a-state-mutating-event-rather-than-a-read-only-evaluation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-probe-injection-as-a-state-mutating-event-rather-than-a-read-only-evaluation.warrant.json
# Markdown SHA-256:   fa8ba01eebe2aa60a0c080db3939ec1d1fa71f3cf13ce712ca2a88aed11c7e09
# Code AST SHA-256:   f3b6883bb431ffa19162541384ff592b77b76cce5594b11cb8d70358cf541c62
# Verified Classes:   ProbeStateContamination, AgentState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProbeStateContamination(RuntimeError):
    """Raised when a LITMUS probe mutated agent state it was meant to observe."""
    pass


@dataclass
class AgentState:
    memory_store: list = field(default_factory=list)
    tool_session: dict = field(default_factory=dict)
    context_buffer: list = field(default_factory=list)

    def fingerprint(self) -> str:
        blob = repr((self.memory_store, self.tool_session, self.context_buffer))
        return hashlib.sha256(blob.encode()).hexdigest()


def emit_probe(state: AgentState, probe_text: str, forkable: bool,
               barrier_active: bool, persistent_tool: bool) -> dict:
    pre = state.fingerprint()

    if forkable:
        # Probe-as-sensor: score against a fork, live state untouched.
        return {"mode": "sensor", "score_target": probe_text}

    if persistent_tool:
        raise ProbeStateContamination(
            f"Probe {probe_text!r} would invoke a persistent tool; "
            "non-forkable context cannot isolate side effects."
        )

    if not barrier_active:
        raise ProbeStateContamination(
            f"Probe {probe_text!r} injected into live buffer without a write "
            "barrier; deferred distillation will persist probe text."
        )

    # Barrier active: probe may enter buffer, but distillation is suppressed.
    state.context_buffer.append(probe_text)
    post = state.fingerprint()
    if post != pre and not barrier_active:
        raise ProbeStateContamination(
            "Post-probe state delta detected with no barrier; quarantining episode."
        )
    return {"mode": "sensor_with_barrier", "pre": pre, "post": post}
