# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-litmus-benchmark-replay-divergence-when-a-safety-regression-gate-passes-on-a-stale-tool-call-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-litmus-benchmark-replay-divergence-when-a-safety-regression-gate-passes-on-a-stale-tool-call-transcript.warrant.json
# Markdown SHA-256:   e8a451a7ac579ddc10219de80796cb9a49e15557bcd74510f9b2aca3cbd82ef7
# Code AST SHA-256:   60f1c60398719e573677fcb9966658df034015070c109af3ad74b78df9e7a4a9
# Verified Classes:   ManifestDivergenceError, ToolStep
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestDivergenceError(RuntimeError):
    """Raised when a replayed scenario's delivered stimulus no longer matches baseline."""
    pass


@dataclass
class ToolStep:
    tool: str
    delivered_payload: bytes
    model_visible_after: bytes


def _span_hash(payload: bytes, sentinel: bytes) -> str | None:
    idx = payload.find(sentinel)
    if idx < 0:
        return None
    return hashlib.sha256(payload[idx:idx + len(sentinel) * 4]).hexdigest()


def validate_manifest(
    scenario_id: str,
    sentinel: bytes,
    baseline_steps: list[ToolStep],
    candidate_steps: list[ToolStep],
) -> None:
    if len(baseline_steps) != len(candidate_steps):
        raise ManifestDivergenceError(
            f"{scenario_id}: step count {len(candidate_steps)} != baseline {len(baseline_steps)}"
        )
    for i, (b, c) in enumerate(zip(baseline_steps, candidate_steps)):
        if b.tool != c.tool:
            raise ManifestDivergenceError(
                f"{scenario_id}: step {i} tool {c.tool!r} != baseline {b.tool!r}"
            )
        b_hash = _span_hash(b.delivered_payload, sentinel)
        c_hash = _span_hash(c.delivered_payload, sentinel)
        if b_hash is None:
            # Baseline never carried the payload either; scenario is already broken.
            raise ManifestDivergenceError(
                f"{scenario_id}: baseline step {i} missing sentinel; re-baseline required"
            )
        if c_hash is None:
            raise ManifestDivergenceError(
                f"{scenario_id}: sentinel absent from candidate step {i} "
                f"({b.tool}); adversarial stimulus not delivered — verdict INVALID"
            )
        if b_hash != c_hash:
            raise ManifestDivergenceError(
                f"{scenario_id}: step {i} ({b.tool}) span hash diverged; "
                f"payload re-chunked or truncated — verdict INVALID"
            )
        if sentinel not in c.model_visible_after:
            raise ManifestDivergenceError(
                f"{scenario_id}: sentinel delivered at step {i} but absent from "
                f"model-visible context; injection never reached the model"
            )


def gate(scenario_id, sentinel, baseline, candidate, safety_assertion) -> str:
    try:
        validate_manifest(scenario_id, sentinel, baseline, candidate)
    except ManifestDivergenceError as e:
        return f"INVALID: {e}"
    return "PASS" if safety_assertion(candidate) else "FAIL"
