# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-collapse-when-an-aaif-agent-re-mints-a-verifiable-credential-mid-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-collapse-when-an-aaif-agent-re-mints-a-verifiable-credential-mid-delegation-chain.warrant.json
# Markdown SHA-256:   fd80729c17447d05baaae972af05309010134faa498a96567ea152294f95ca71
# Code AST SHA-256:   5722b2194d698143c0975b197873335757f78688d5e344b2dcd04751cb9160d9
# Verified Classes:   DelegationInvariantError, AgentCredential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationInvariantError(RuntimeError):
    """Raised when a re-minted agent credential violates AAIF delegation invariants."""


@dataclass(frozen=True)
class AgentCredential:
    subject: str
    scopes: FrozenSet[str]
    cnf_thumbprint: str          # must chain to root principal
    delegation_depth: int
    root_thumbprint: str


def canonicalize(raw_scopes) -> FrozenSet[str]:
    if isinstance(raw_scopes, str):
        raw_scopes = raw_scopes.split()
    return frozenset(s.strip() for s in raw_scopes if s.strip())


def remint_child(
    parent: AgentCredential,
    child_subject: str,
    requested_scopes,
    child_cnf_thumbprint: str,
    max_depth: int = 3,
) -> AgentCredential:
    child_scopes = canonicalize(requested_scopes)

    # Invariant 1: canonical subset relation, not string comparison.
    if not child_scopes.issubset(parent.scopes):
        raise DelegationInvariantError(
            f"scope escalation: {child_scopes - parent.scopes} not in parent"
        )

    # Invariant 2: cnf chain continuity — child must bind to root, not to parent.
    if child_cnf_thumbprint != parent.root_thumbprint:
        raise DelegationInvariantError(
            f"cnf rebind: child cnf {child_cnf_thumbprint} != root "
            f"{parent.root_thumbprint}; delegation chain broken"
        )

    # Invariant 3: atomic depth decrement bounded by policy.
    next_depth = parent.delegation_depth + 1
    if next_depth > max_depth:
        raise DelegationInvariantError(
            f"delegation depth {next_depth} exceeds max {max_depth}"
        )

    return AgentCredential(
        subject=child_subject,
        scopes=child_scopes,
        cnf_thumbprint=child_cnf_thumbprint,
        delegation_depth=next_depth,
        root_thumbprint=parent.root_thumbprint,
    )


def handle_resource_server_error(err_code: str, parent: AgentCredential) -> str:
    if err_code == "invalid_chain":
        # Must escalate; narrowing scope cannot fix a broken cnf chain.
        raise DelegationInvariantError(
            "invalid_chain received; halting re-mint to prevent silent scope collapse"
        )
    if err_code == "insufficient_scope":
        return "narrow_within_verified_subset"
    raise DelegationInvariantError(f"unclassified error {err_code}; refusing to retry")
