# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-ephemeral-workload-identity-mid-handoff-under-per-task-mtls.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-ephemeral-workload-identity-mid-handoff-under-per-task-mtls.warrant.json
# Markdown SHA-256:   d66b8b4dddc34758f1d8f65f24ddda66c80788d738f364115b1980f57d681e9a
# Code AST SHA-256:   df3c2a6fabb0e19b6398f4d3e9bff8b88d32649811665baaaca4c0ccf8f29cd7
# Verified Classes:   IdentityContinuityViolation, TaskClaim
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class IdentityContinuityViolation(RuntimeError):
    """Raised when a rotated workload identity breaks task-lineage invariants."""
    pass


@dataclass(frozen=True)
class TaskClaim:
    task_id: str
    hop_index: int
    lineage: str  # hash chain over prior hop serials
    serial: str


def rotate_identity(
    current: TaskClaim,
    next_hop: int,
    new_serial: str,
) -> TaskClaim:
    """Task-phase-triggered rotation. Refuses to silently reset hop state."""
    if next_hop < current.hop_index:
        raise IdentityContinuityViolation(
            f"hop regression on rotation: task={current.task_id} "
            f"current_hop={current.hop_index} requested_hop={next_hop}"
        )
    if next_hop == current.hop_index:
        raise IdentityContinuityViolation(
            f"rotation without hop advance: task={current.task_id} "
            f"hop={next_hop}; time-triggered rotation is not permitted "
            f"under lineage-enforcing policy"
        )
    new_lineage = hashlib.sha256(
        f"{current.lineage}:{current.serial}".encode()
    ).hexdigest()
    return TaskClaim(
        task_id=current.task_id,
        hop_index=next_hop,
        lineage=new_lineage,
        serial=new_serial,
    )


def verify_inbound(
    presented: TaskClaim,
    expected_task_id: str,
    expected_hop: int,
    hop_high_water: dict[str, int],
) -> None:
    """Verifier-side enforcement of hop monotonicity and lineage presence."""
    if presented.task_id != expected_task_id:
        raise IdentityContinuityViolation(
            f"task mismatch: presented={presented.task_id} "
            f"expected={expected_task_id}"
        )
    if presented.hop_index != expected_hop:
        raise IdentityContinuityViolation(
            f"hop mismatch: task={presented.task_id} "
            f"presented_hop={presented.hop_index} expected_hop={expected_hop}"
        )
    prior = hop_high_water.get(presented.task_id, -1)
    if presented.hop_index <= prior:
        raise IdentityContinuityViolation(
            f"replay of prior hop identity: task={presented.task_id} "
            f"hop={presented.hop_index} high_water={prior}"
        )
    if not presented.lineage:
        raise IdentityContinuityViolation(
            f"empty lineage on hop {presented.hop_index} "
            f"for task {presented.task_id}; rotation dropped chain"
        )
    hop_high_water[presented.task_id] = presented.hop_index
