# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-longitudinal-misuse-detection-harnesses-from-laundering-poisoned-episodes-through-the-litmus-resume-path.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-longitudinal-misuse-detection-harnesses-from-laundering-poisoned-episodes-through-the-litmus-resume-path.warrant.json
# Markdown SHA-256:   5bd6754621027ce3322ae791f5fd9da3f90157766316b0df44711c4ccf8163f8
# Code AST SHA-256:   657fa597302c26262feb0cff4933d5625b1de11530d4fb3f8f0d8b83e6b028fb
# Verified Classes:   EvidenceIntegrityViolation, RiskRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Iterable


class EvidenceIntegrityViolation(RuntimeError):
    """Raised when a checkpointed risk-state cannot be reconciled with its evidence."""


@dataclass(frozen=True)
class RiskRecord:
    episode_id: int
    source_digest: str
    status: str
    vector: dict


def digest_prefix(transcript_turns: Iterable[dict]) -> str:
    h = hashlib.sha256()
    for turn in transcript_turns:
        h.update(json.dumps(turn, sort_keys=True).encode("utf-8"))
    return h.hexdigest()


def is_strict_prefix_extension(old_turns: list, new_turns: list) -> bool:
    return len(new_turns) > len(old_turns) and new_turns[: len(old_turns)] == old_turns


def resume_episode(
    record: RiskRecord,
    on_disk_turns: list,
    recorded_prefix_len: int,
    recompute,
    invalidate_downstream,
) -> RiskRecord:
    """
    Enforce the evidence/derivation invariant on resume.

    - Digest match           -> accept.
    - Strict prefix extension -> recompute + transitively invalidate.
    - Anything else           -> halt with EvidenceIntegrityViolation.
    """
    if record.status != "distilled":
        raise EvidenceIntegrityViolation(
            f"episode {record.episode_id}: unexpected status {record.status!r} at resume"
        )

    actual_digest = digest_prefix(on_disk_turns[:recorded_prefix_len])
    if actual_digest == record.source_digest:
        return record

    recorded_prefix = on_disk_turns[:recorded_prefix_len]
    if is_strict_prefix_extension(recorded_prefix, on_disk_turns):
        # Append-only reconciliation: safe to recompute, unsafe to accept.
        fresh = recompute(on_disk_turns)
        fresh = RiskRecord(
            episode_id=record.episode_id,
            source_digest=digest_prefix(on_disk_turns),
            status="distilled",
            vector=fresh,
        )
        invalidate_downstream(record.episode_id)
        return fresh

    raise EvidenceIntegrityViolation(
        f"episode {record.episode_id}: transcript is not a prefix-extension "
        f"(recorded_len={recorded_prefix_len}, on_disk_len={len(on_disk_turns)}); "
        f"evidence was rewritten or truncated — refusing to launder memory"
    )
