# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-delegated-aaif-credential-chain-has-been-silently-re-rooted-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-delegated-aaif-credential-chain-has-been-silently-re-rooted-mid-execution.warrant.json
# Markdown SHA-256:   546111f9f860842c9387d2bcbf42cb778e275a2283da23fc80902af4cdfa97ed
# Code AST SHA-256:   67b5b1c0d0eac6b08cf7cb0ae797e6ccd52680c4f2e5385404fe1a1a55cdd77e
# Verified Classes:   ReRootedChainError, ChainPath
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Sequence


class ReRootedChainError(RuntimeError):
    """Raised when a delegated AAIF chain's path-to-root changes mid-task.

    Distinct from a cryptographic verification failure: the presented chain
    may verify perfectly against a trusted root. The error means the root
    (or an intermediate delegator) is not the one the task started under.
    """


@dataclass(frozen=True)
class ChainPath:
    root_principal_id: str
    root_issuer_key_id: str
    delegation_path_principal_ids: tuple[str, ...]

    def fingerprint(self) -> str:
        # Fingerprint covers the FULL path to root, not the leaf token.
        # Leaf rotation (new exp/jti) must not perturb this value.
        material = json.dumps(
            {
                "root": self.root_principal_id,
                "root_key": self.root_issuer_key_id,
                "path": list(self.delegation_path_principal_ids),
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(material).hexdigest()


def assert_root_continuity(
    task_start_path: ChainPath,
    checkpoint_path: ChainPath,
) -> None:
    """Enforce the root-continuity invariant at a task checkpoint.

    Called after standard AAIF verification has already PASSED. This function
    does not re-check signatures or scopes; it checks identity of authority.
    """
    start_fp = task_start_path.fingerprint()
    now_fp = checkpoint_path.fingerprint()

    if start_fp == now_fp:
        return  # same authority, leaf rotation is a non-event

    # Build a precise diff so the operator can see WHICH element moved.
    diffs: list[str] = []
    if task_start_path.root_principal_id != checkpoint_path.root_principal_id:
        diffs.append(
            f"root_principal_id: {task_start_path.root_principal_id!r} "
            f"-> {checkpoint_path.root_principal_id!r}"
        )
    if task_start_path.root_issuer_key_id != checkpoint_path.root_issuer_key_id:
        diffs.append(
            f"root_issuer_key_id: {task_start_path.root_issuer_key_id!r} "
            f"-> {checkpoint_path.root_issuer_key_id!r}"
        )
    if (
        task_start_path.delegation_path_principal_ids
        != checkpoint_path.delegation_path_principal_ids
    ):
        diffs.append(
            f"delegation_path: {task_start_path.delegation_path_principal_ids!r} "
            f"-> {checkpoint_path.delegation_path_principal_ids!r}"
        )

    raise ReRootedChainError(
        "AAIF chain re-rooted mid-task; standard verification passed but "
        "authority identity changed. Halting task; require out-of-band "
        "re-authorization. Diff: " + "; ".join(diffs)
    )


def checkpoint_guard(
    task_start_path: ChainPath,
    presented_chain_paths: Sequence[ChainPath],
) -> None:
    """Checkpoint entry point. Verifies every presented chain against the
    task-start root path. Any divergence is terminal."""
    for idx, path in enumerate(presented_chain_paths):
        try:
            assert_root_continuity(task_start_path, path)
        except ReRootedChainError as exc:
            # Re-raise with position context; never downgrade to a warning.
            raise ReRootedChainError(
                f"checkpoint chain[{idx}] failed root continuity: {exc}"
            ) from exc
