# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-aaif-delegation-token-s-sub-act-chain-as-a-continuity-invariant-rather-than-a-per-hop-authorization-check.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-aaif-delegation-token-s-sub-act-chain-as-a-continuity-invariant-rather-than-a-per-hop-authorization-check.warrant.json
# Markdown SHA-256:   e26d676a06a472c0eb6bda25e971de1e33d31eebd2ad56fdec2e8520175be2d3
# Code AST SHA-256:   1a5b492dd896f68cdc0105260c3cae2d0f0d55d421c733b493fd03d4975afa9a
# Verified Classes:   DelegationChainError, ActFrame, DelegatedToken, AgentTokenState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when a token exchange would violate the append-only act-chain invariant."""
    pass


@dataclass(frozen=True)
class ActFrame:
    agent_id: str


@dataclass(frozen=True)
class DelegatedToken:
    sub: str                      # root principal
    act: tuple[ActFrame, ...]     # append-only actor chain
    scope: str
    exp: int
    jti: str


@dataclass
class AgentTokenState:
    # Durable state: must survive checkpoint/restart. If absent, refresh is impossible.
    inbound: Optional[DelegatedToken] = None
    issued_frames: dict[str, str] = field(default_factory=dict)  # task_id -> agent_id already appended


def extend_chain(
    state: AgentTokenState,
    self_id: str,
    task_id: str,
    requested_scope: str,
    now: int,
) -> DelegatedToken:
    """Chain-extension exchange. Refuses to mint a re-rooted token."""
    if state.inbound is None:
        # Cold start / eviction: we cannot preserve the chain prefix.
        raise DelegationChainError(
            f"agent {self_id} has no inbound chain for task {task_id}; "
            "refresh impossible, escalate to root principal for re-delegation"
        )

    inbound = state.inbound
    if not inbound.act or inbound.act[-1].agent_id != self_id:
        raise DelegationChainError(
            f"inbound act-chain terminal frame {inbound.act[-1] if inbound.act else None} "
            f"!= caller identity {self_id}; token not issued to this agent"
        )

    if requested_scope != inbound.scope:
        raise DelegationChainError(
            f"scope escalation/change {inbound.scope!r} -> {requested_scope!r} "
            "requires re-delegation from root, not refresh"
        )

    # Idempotent append: reuse existing frame for this task rather than duplicating.
    if task_id in state.issued_frames:
        if state.issued_frames[task_id] != self_id:
            raise DelegationChainError(
                f"task {task_id} already delegated to {state.issued_frames[task_id]}, "
                f"not {self_id}"
            )
        appended = inbound.act
    else:
        appended = inbound.act + (ActFrame(self_id),)
        state.issued_frames[task_id] = self_id

    return DelegatedToken(
        sub=inbound.sub,
        act=appended,
        scope=inbound.scope,
        exp=now + 1800,
        jti=f"{task_id}:{self_id}:{now}",
    )


def reauthorize_from_root(
    root_principal: str,
    self_id: str,
    task_id: str,
    scope: str,
    now: int,
) -> tuple[DelegatedToken, AgentTokenState]:
    """Explicit re-delegation path after chain loss. New chain, new task authorization."""
    new_token = DelegatedToken(
        sub=root_principal,
        act=(ActFrame(self_id),),
        scope=scope,
        exp=now + 1800,
        jti=f"reauth:{task_id}:{self_id}:{now}",
    )
    state = AgentTokenState(inbound=new_token, issued_frames={task_id: self_id})
    return new_token, state
