# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-episodic-write-when-the-rollback-target-itself-was-authored-by-the-same-compromised-instance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-episodic-write-when-the-rollback-target-itself-was-authored-by-the-same-compromised-instance.warrant.json
# Markdown SHA-256:   8260778f65322e1c11e4e5a534ef5abbd4e7b69edf2970ac76c9f1f8909e1dc1
# Code AST SHA-256:   73e4e1b13dfde925b9804c29f3716fc0780e68e64ecc6e7afa3c0f10b4198690
# Verified Classes:   UntrustedRollbackAnchor, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UntrustedRollbackAnchor(RuntimeError):
    """Raised when a checkpoint cannot be used as a rollback target because its
    provenance chain is not independently anchored (self-validated or store-derived)."""
    pass


@dataclass(frozen=True)
class Checkpoint:
    task_id: str
    epoch: int
    author: str
    validator: Optional[str]
    validator_attestation_hash: Optional[str]  # must come from an out-of-band source
    store_derived_validation: bool              # True if validator checked against the store itself


def select_rollback_anchor(
    checkpoints: list[Checkpoint],
    requesting_instance: str,
) -> Checkpoint:
    """Walk checkpoints newest-to-oldest and return the first one whose provenance
    chain terminates in an independent anchor. Refuse to fall back silently."""
    ordered = sorted(checkpoints, key=lambda c: c.epoch, reverse=True)

    for cp in ordered:
        if cp.validator is None:
            continue  # no validator recorded: not a rollback candidate
        if cp.validator == cp.author:
            continue  # self-attestation: laundered
        if cp.validator == requesting_instance:
            continue  # requester validating its own resume target: not independent
        if cp.store_derived_validation:
            continue  # circular: validated against the substrate it lives in
        if not cp.validator_attestation_hash:
            continue  # no out-of-band anchor present
        return cp

    raise UntrustedRollbackAnchor(
        f"No independently-anchored checkpoint for task {ordered[0].task_id if ordered else '<none>'}; "
        f"refusing rollback. Cold-start from human-authored seed required."
    )


def resume_from_latest(task_id: str, checkpoints: list[Checkpoint], instance: str) -> Checkpoint:
    anchor = select_rollback_anchor(checkpoints, instance)
    if anchor.validator_attestation_hash is None:
        # Defensive: select_rollback_anchor already filters this, but guard the invariant.
        raise UntrustedRollbackAnchor(
            f"Anchor epoch {anchor.epoch} for {task_id} lacks attestation hash; "
            f"cannot resume {instance} on unverified state."
        )
    return anchor
