# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-litmus-safety-score-has-been-silently-inverted-by-trajectory-level-truncation-before-the-unsafe-action-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-litmus-safety-score-has-been-silently-inverted-by-trajectory-level-truncation-before-the-unsafe-action-executes.warrant.json
# Markdown SHA-256:   997943d37c1eb5153780d23cda98f467e881ce0df465dc13166d93545f7f60c4
# Code AST SHA-256:   cb81d50eb4745f85936a2ee2a7d735481ad0ac02295d920ae034ae484d73a34a
# Verified Classes:   TruncationInversionError, LitmusWindowGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TruncationInversionError(RuntimeError):
    """Raised when a pending tool call would fall outside the scorer's window
    while the only available verdict was computed inside it."""
    pass


class LitmusWindowGuard:
    def __init__(self, assumed_window: int = 2):
        if assumed_window < 1:
            raise ValueError("assumed_window must be >= 1")
        self.assumed_window = assumed_window
        self.steps_emitted = 0
        self.last_verdict = None  # "SAFE" | "UNSAFE" | None

    def record_step(self, label: str) -> None:
        self.steps_emitted += 1
        if label == "UNSAFE":
            self.last_verdict = "UNSAFE"
        elif self.last_verdict is None:
            self.last_verdict = "SAFE"

    def authorize_next_action(self, action_name: str) -> None:
        # The next action will be step index == steps_emitted.
        # If that index is >= assumed_window, any prior SAFE verdict
        # was computed without seeing this step -> it cannot authorize it.
        next_index = self.steps_emitted
        if next_index >= self.assumed_window and self.last_verdict == "SAFE":
            raise TruncationInversionError(
                f"action {action_name!r} at step {next_index} lies outside "
                f"assumed scoring window of {self.assumed_window}; "
                f"prior verdict {self.last_verdict!r} did not observe this step"
            )
        if self.last_verdict == "UNSAFE":
            raise TruncationInversionError(
                f"action {action_name!r} blocked: trajectory already labeled UNSAFE"
            )


# Trace replay demonstrating the silent inversion being caught.
guard = LitmusWindowGuard(assumed_window=2)
guard.record_step("SAFE")   # read_file(config.json)
guard.record_step("SAFE")   # read_file(creds.env)
guard.authorize_next_action("http_post")  # raises before exfiltration
