# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-harness-s-own-turn-assembly-layer-as-an-adversarial-principal-rather-than-as-trusted-scaffolding.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-harness-s-own-turn-assembly-layer-as-an-adversarial-principal-rather-than-as-trusted-scaffolding.warrant.json
# Markdown SHA-256:   613690d18c52d84d874201e0a9d1dedcb962ce34d635ec47632c3e0f0266030c
# Code AST SHA-256:   197b24031960c79c7d936083d977d3bbc3bf8d89fa62cdccabfb352202185768
# Verified Classes:   ContinuityViolation, Turn, HarnessRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

class ContinuityViolation(RuntimeError):
    """Raised when the harness mutates a turn the target already checkpointed."""
    pass

@dataclass
class Turn:
    index: int
    role: Literal["user", "assistant"]
    content: str
    checkpointed_by_target: bool = False

@dataclass
class HarnessRecord:
    turns: list[Turn] = field(default_factory=list)
    mutations: list[dict] = field(default_factory=list)

def repair_turn(record: HarnessRecord, index: int, new_content: str) -> None:
    """Harness-side continuity repair. Must fail closed if the target has
    already checkpointed the turn it would overwrite."""
    target_turn = next((t for t in record.turns if t.index == index), None)
    if target_turn is None:
        raise ContinuityViolation(f"no turn at index {index} to repair")
    if target_turn.checkpointed_by_target:
        # The target's memory store already contains the original turn.
        # Overwriting here would make the harness a second adversarial
        # principal and collapse distinct safety labels.
        raise ContinuityViolation(
            f"turn {index} was checkpointed by target; repair would diverge "
            f"record from served transcript. Fork a branch instead."
        )
    record.mutations.append({
        "index": index,
        "prior": target_turn.content,
        "replacement": new_content,
        "kind": "repair",
    })
    target_turn.content = new_content

def serve_turn(record: HarnessRecord, turn: Turn) -> None:
    """Append a turn to the served transcript. Append-only; never reorders."""
    if record.turns and turn.index <= record.turns[-1].index:
        raise ContinuityViolation(
            f"turn {turn.index} would reorder transcript (last={record.turns[-1].index})"
        )
    record.turns.append(turn)

def checkpoint(record: HarnessRecord, index: int) -> None:
    """Target's checkpoint hook. Marks the turn as already seen by the target."""
    for t in record.turns:
        if t.index == index:
            t.checkpointed_by_target = True
            return
    raise ContinuityViolation(f"cannot checkpoint missing turn {index}")
