# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-enter-a-litmus-adversarial-replay-after-a-partial-scoring-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-enter-a-litmus-adversarial-replay-after-a-partial-scoring-checkpoint.warrant.json
# Markdown SHA-256:   0243f1bccfb541bfce078db781a694b3231d245912a6c5008339c265e5f6b0dd
# Code AST SHA-256:   9f58e264b08358c8846728544badc3dbbf8c24cee0888c61de59d24350ca95bc
# Verified Classes:   PoisonedReplayBoundary
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PoisonedReplayBoundary(RuntimeError):
    """Raised when a LITMUS resume would replay an adversarial turn against
    a target session that has already executed that turn. Replaying rewrites
    the trajectory artifact; refuse and force a cold-start replay instead."""
    pass


def authorize_resume(checkpoint: dict, session_is_frozen: bool) -> int:
    """
    Return the turn index at which execution may resume.
    checkpoint keys: turns_executed, turns_scored, last_scored_turn,
                     unscored_output_captured (bool)
    """
    executed = checkpoint["turns_executed"]
    scored = checkpoint["turns_scored"]
    last_scored = checkpoint["last_scored_turn"]

    if executed == scored:
        # Clean boundary: pure continuation.
        return last_scored + 1

    if executed == scored + 1 and checkpoint.get("unscored_output_captured"):
        # Score-only resume: finish the judge, do not touch the target.
        # Caller must re-invoke authorize_resume after scoring completes.
        return -1  # sentinel: score-only

    # executed > scored + 1, or the unscored output was lost, or the handle
    # is warm and reusable. Any of these means the session state is past the
    # checkpoint. Replaying would double-inject the adversarial turn.
    if not session_is_frozen:
        raise PoisonedReplayBoundary(
            f"resume blocked: executed={executed} scored={scored} "
            f"last_scored={last_scored} session_is_frozen={session_is_frozen}; "
            "session has executed past the checkpoint. Discard handle and "
            "replay from turn 0."
        )

    # Frozen handle with captured outputs: safe to score the backlog only.
    return -1


def resume_run(checkpoint: dict, session_is_frozen: bool, replay_from_zero) -> None:
    turn = authorize_resume(checkpoint, session_is_frozen)
    if turn == -1:
        # Score-only path; after scoring, counters converge and we re-enter.
        return
    if turn > checkpoint["turns_executed"] + 1:
        raise PoisonedReplayBoundary(
            f"resume turn {turn} skips past executed="
            f"{checkpoint['turns_executed']}; trajectory would be discontinuous."
        )
    replay_from_zero(turn)
