# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-adversarial-litmus-probe-pass-ci-while-the-same-probe-fails-at-eval-time-the-context-ordering-nondeterminism-boundary-in-sa.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-adversarial-litmus-probe-pass-ci-while-the-same-probe-fails-at-eval-time-the-context-ordering-nondeterminism-boundary-in-sa.warrant.json
# Markdown SHA-256:   868e60648276234562a26acb0ad98c5a15420a967a7164834200a03f117429b4
# Code AST SHA-256:   2126e5a2be0604ff06fc7776454e279fcdb00eeb01494c9e6a6d35329a998759
# Verified Classes:   ContextOrderViolation, ProbeContext
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class ContextOrderViolation(RuntimeError):
    """Raised when a LITMUS probe's assembled context is not order-invariant."""


@dataclass(frozen=True)
class ProbeContext:
    system_prompt: str
    warmup_turns: Sequence[str]
    payload: str
    token_budget: int


def assemble_and_validate(ctx: ProbeContext, truncation_policy: str = "tail") -> int:
    """Assemble a probe context and return the payload token offset.

    Enforces the context-order invariance required for CI gating.
    Raises ContextOrderViolation instead of silently truncating.
    """
    if truncation_policy != "tail":
        raise ContextOrderViolation(
            f"truncation policy {truncation_policy!r} may evict the system prompt; "
            "only 'tail' is admissible for LITMUS gating"
        )

    # Rough token proxy; real harness uses the model tokenizer.
    def toks(s: str) -> int:
        return max(1, len(s) // 4)

    sys_t = toks(ctx.system_prompt)
    warm = [toks(t) for t in ctx.warmup_turns]
    pay_t = toks(ctx.payload)

    total = sys_t + sum(warm) + pay_t
    if total > ctx.token_budget:
        raise ContextOrderViolation(
            f"assembled context {total} tokens exceeds budget {ctx.token_budget}; "
            "refusing to truncate—fix the probe, do not shrink the context"
        )

    # Payload must never be adjacent to the truncation boundary.
    headroom = ctx.token_budget - total
    if headroom < 64:
        raise ContextOrderViolation(
            f"only {headroom} tokens of headroom; probe is boundary-adjacent and "
            "verdict is not order-invariant"
        )

    return sys_t + sum(warm)


def gate_verdict(offsets: Sequence[int], verdicts: Sequence[bool], k: int = 5) -> bool:
    """Gate a probe only if it is context-order invariant across replays."""
    if len(verdicts) < k:
        raise ContextOrderViolation(
            f"need {k} replays for invariance check, got {len(verdicts)}"
        )
    if len(set(offsets)) != 1:
        raise ContextOrderViolation(
            f"payload offset varied across replays: {sorted(set(offsets))}; "
            "harness injected nondeterminism"
        )
    if len(set(verdicts)) != 1:
        raise ContextOrderViolation(
            "verdict flips under fixed ordering; probe is high-variance, quarantine it"
        )
    return verdicts[0]
