# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-propagate-a-litmus-adversarial-score-across-a-tool-result-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-propagate-a-litmus-adversarial-score-across-a-tool-result-boundary.warrant.json
# Markdown SHA-256:   f4a72d96d76a5ad0442799bfe10236c651fc65149c479ca452d1d2c17db3641b
# Code AST SHA-256:   650f649cf70d794ed01cec24c4e6935ac74b298b049704c189b218c9db6fccd4
# Verified Classes:   ScoreDomainError, ObjectClass, LitmusScore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class ScoreDomainError(RuntimeError):
    """Raised when a LITMUS score is applied outside its calibration domain."""


class ObjectClass(Enum):
    PROPOSAL = "proposal"      # a candidate tool call / drafted action
    OBSERVATION = "observation"  # a tool result / retrieved document
    HANDOFF = "handoff"        # a message passed across an instance boundary


@dataclass(frozen=True)
class LitmusScore:
    value: float
    object_class: ObjectClass
    object_id: str
    context_epoch: str
    probe_version: str

    def require_proposal_for(self, proposal_id: str, current_epoch: str) -> float:
        """Return the score only if it is a valid, epoch-current proposal score."""
        if self.object_class is not ObjectClass.PROPOSAL:
            raise ScoreDomainError(
                f"score for {self.object_id} is class={self.object_class.value}; "
                f"cannot gate proposal {proposal_id}. Re-probe required."
            )
        if self.context_epoch != current_epoch:
            raise ScoreDomainError(
                f"score epoch {self.context_epoch} != current {current_epoch}; "
                f"stale score cannot gate {proposal_id}."
            )
        return self.value


def gate_tool_call(
    proposal_id: str,
    proposal_args: dict,
    candidate_score: Optional[LitmusScore],
    current_epoch: str,
    threshold: float = 0.5,
) -> bool:
    """
    Gate a pending tool call. The candidate_score must be a fresh proposal
    score for THIS proposal in THIS epoch. Observation and handoff scores
    are rejected by construction.
    """
    if candidate_score is None:
        # Unmeasured is not low. Refuse to proceed silently.
        raise ScoreDomainError(
            f"no proposal score for {proposal_id}; refusing to execute unscored action."
        )
    score = candidate_score.require_proposal_for(proposal_id, current_epoch)
    if score >= threshold:
        raise ScoreDomainError(
            f"proposal {proposal_id} scored {score:.2f} >= {threshold}; blocked."
        )
    return True


def on_tool_result(
    observation_id: str,
    observation_text: str,
    prior_scores: list[LitmusScore],
) -> None:
    """
    A tool result arrived. Any prior score is now stale (epoch advanced).
    The observation is routed to a content filter, NOT to the LITMUS probe,
    and prior scores are invalidated rather than inherited.
    """
    for s in prior_scores:
        if s.object_class is ObjectClass.PROPOSAL:
            # epoch has advanced; this score can no longer gate anything
            continue
        if s.object_class is ObjectClass.OBSERVATION:
            raise ScoreDomainError(
                f"observation score {s.object_id} present in proposal cache; "
                f"domain confusion detected at {observation_id}."
            )
    # observation_text goes to adversarial-content filter, not LITMUS
