# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-at-the-second-hop-when-aaif-capability-tokens-carry-attenuated-scope-but-the-warrant-chain-is-re-signed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-at-the-second-hop-when-aaif-capability-tokens-carry-attenuated-scope-but-the-warrant-chain-is-re-signed.warrant.json
# Markdown SHA-256:   dd44b03450ed35de9ef51789ffd28d650229c7580afc7135ef1872e0757249c3
# Code AST SHA-256:   7cd961c29e09e6ed7328385035e2692e5e16e259a1d9aa13e216e3a080a06cf5
# Verified Classes:   WarrantLineageError, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class WarrantLineageError(RuntimeError):
    """Raised when a delegation would break issuer/lineage continuity."""
    pass


@dataclass
class CapabilityToken:
    issuer: str
    subject: str
    scope: frozenset
    expires_at: int
    parent_warrant_hash: Optional[str]
    reissue_authorization: Optional[dict] = None
    signature: str = ""

    def canonical(self) -> bytes:
        return repr((
            self.issuer, self.subject, sorted(self.scope),
            self.expires_at, self.parent_warrant_hash,
            self.reissue_authorization,
        )).encode()

    def content_hash(self) -> str:
        return hashlib.sha256(self.canonical()).hexdigest()


def delegate(
    parent: CapabilityToken,
    delegator_key_id: str,
    subject: str,
    requested_scope: frozenset,
    expires_at: int,
    delegation_mode: str,
) -> CapabilityToken:
    # Invariant 1: scope monotonicity — always enforced.
    if not requested_scope.issubset(parent.scope):
        raise WarrantLineageError(
            f"scope escalation: {requested_scope} not subset of {parent.scope}"
        )

    # Invariant 2: temporal monotonicity — always enforced.
    if expires_at > parent.expires_at:
        raise WarrantLineageError(
            f"temporal escalation: child expires_at {expires_at} > parent {parent.expires_at}"
        )

    if delegation_mode == "attenuate":
        # Correct path: child inherits parent's issuer; parent-hash links chain.
        return CapabilityToken(
            issuer=parent.issuer,
            subject=subject,
            scope=requested_scope,
            expires_at=expires_at,
            parent_warrant_hash=parent.content_hash(),
            reissue_authorization=None,
            signature=f"sig({parent.issuer})",
        )

    if delegation_mode == "reissue":
        # The dangerous path. Must be gated by an explicit reissue grant.
        grant = parent.reissue_authorization
        if grant is None:
            raise WarrantLineageError(
                f"agent {delegator_key_id} attempted reissue on lineage "
                f"issued by {parent.issuer} without a reissue_authorization segment; "
                f"lineage would break at this hop"
            )
        if not requested_scope.issubset(frozenset(grant["subtree"])):
            raise WarrantLineageError(
                f"reissue scope {requested_scope} outside granted subtree {grant['subtree']}"
            )
        if grant.get("max_depth", 0) <= 0:
            raise WarrantLineageError(
                "reissue depth exhausted; delegator must attenuate, not reissue"
            )
        return CapabilityToken(
            issuer=delegator_key_id,
            subject=subject,
            scope=requested_scope,
            expires_at=expires_at,
            parent_warrant_hash=parent.content_hash(),
            reissue_authorization={
                "subtree": list(grant["subtree"]),
                "max_depth": grant["max_depth"] - 1,
                "attested_by": parent.issuer,
            },
            signature=f"sig({delegator_key_id})",
        )

    raise WarrantLineageError(f"unknown delegation_mode: {delegation_mode!r}")


def verify_chain(token: CapabilityToken, trusted_roots: set) -> bool:
    """Strict verifier: requires issuer continuity unless an attested grant exists."""
    if token.issuer in trusted_roots:
        return True
    grant = token.reissue_authorization
    if grant is None or grant.get("attested_by") not in trusted_roots:
        # No grant, and issuer is not a root: lineage is broken.
        return False
    return True
