# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-credential-whose-issuer-chain-re-roots-mid-task-the-aaif-delegation-depth-reset-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-credential-whose-issuer-chain-re-roots-mid-task-the-aaif-delegation-depth-reset-invariant.warrant.json
# Markdown SHA-256:   db250b4989fc02d9e5d20eed540f97b660e7d435c50b9c9a1c7a984cdc594482
# Code AST SHA-256:   127b00b22fd7251fb4baa82e01d3640e4328642495e89fcc6dc2c3116fd59534
# Verified Classes:   DelegationRerootError, Credential, TaskLedger
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationRerootError(RuntimeError):
    """Raised when a delegated credential's ancestry changes mid-task."""


@dataclass(frozen=True)
class Credential:
    root_id: str
    chain_epoch: int
    depth: int
    task_warrant_hash: str
    sub: str
    scope: frozenset


@dataclass(frozen=True)
class TaskLedger:
    task_id: str
    root_id: str
    chain_epoch: int
    depth: int
    task_warrant_hash: str
    scope: frozenset


def verify_reissuance(
    ledger: TaskLedger,
    presented: Credential,
    amendment: Optional[dict] = None,
) -> None:
    """Enforce the AAIF delegation-depth reset invariant.

    Accepts a refreshed credential; rejects re-rooting, depth regression,
    epoch reset, and unamended scope substitution.
    """
    if presented.sub != ledger.task_id and presented.sub != ledger.task_id:
        # sub must match the task's bound identity
        raise DelegationRerootError(
            f"sub {presented.sub!r} does not match task {ledger.task_id!r}"
        )

    rerooted = presented.root_id != ledger.root_id
    epoch_regressed = presented.chain_epoch <= ledger.chain_epoch
    depth_regressed = presented.depth < ledger.depth
    warrant_changed = presented.task_warrant_hash != ledger.task_warrant_hash

    if rerooted and epoch_regressed and amendment is None:
        raise DelegationRerootError(
            f"canonical re-root: root {ledger.root_id!r} -> {presented.root_id!r} "
            f"with chain_epoch {ledger.chain_epoch} -> {presented.chain_epoch} "
            f"and no warrant_amendment"
        )

    if rerooted and amendment is None:
        raise DelegationRerootError(
            f"re-root to {presented.root_id!r} requires explicit warrant_amendment "
            f"naming both roots and the scope delta"
        )

    if depth_regressed:
        raise DelegationRerootError(
            f"depth regression within stable root: {ledger.depth} -> {presented.depth}"
        )

    if warrant_changed and amendment is None:
        raise DelegationRerootError(
            f"task_warrant_hash changed without amendment: "
            f"{ledger.task_warrant_hash!r} -> {presented.task_warrant_hash!r}"
        )

    if not presented.scope.issubset(ledger.scope) and amendment is None:
        raise DelegationRerootError(
            f"scope widening without amendment: "
            f"added {presented.scope - ledger.scope!r}"
        )

    if amendment is not None:
        if amendment.get("from_root") != ledger.root_id or \
           amendment.get("to_root") != presented.root_id:
            raise DelegationRerootError(
                "warrant_amendment does not name the observed root transition"
            )
