# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-authorization-chains-have-silently-collapsed-in-aaif-token-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-authorization-chains-have-silently-collapsed-in-aaif-token-exchange.warrant.json
# Markdown SHA-256:   2d3127b8450d7a8281f89b689c6310625e6d18662bb57dee10c2d0d4db5df82f
# Code AST SHA-256:   577e1dfda788f8f8727870855dbf9a851e636cdd46af915ac78017c3b1d569f7
# Verified Classes:   DelegationChainCollapse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationChainCollapse(RuntimeError):
    """Raised when an AAIF-exchanged token's actor chain is structurally
    inconsistent with its parent (flattened, inflated, or unauditable)."""
    pass


def validate_attenuation(parent: dict, child: dict, attenuation_log: dict) -> None:
    """Enforce the strict-extension invariant on an exchanged token.

    parent/child are decoded AAIF claims; attenuation_log maps child jti ->
    parent jti for tokens actually produced by attenuation (not re-mint).
    """
    parent_depth = _act_depth(parent.get("act"))
    child_depth = _act_depth(child.get("act"))

    # Clause 1: structural extension, not replacement.
    if child_depth != parent_depth + 1:
        raise DelegationChainCollapse(
            f"actor chain flattened: parent depth {parent_depth}, "
            f"child depth {child_depth} (expected {parent_depth + 1}); "
            f"exchange re-minted instead of attenuating"
        )

    # Clause 2: scope must be a subset.
    if not set(child.get("scope", [])) <= set(parent.get("scope", [])):
        raise DelegationChainCollapse(
            f"scope escalation: child {child.get('scope')} not subset of "
            f"parent {parent.get('scope')}"
        )

    # Clause 3: expiry must not be inflated beyond parent.
    if child.get("exp", 0) > parent.get("exp", 0):
        raise DelegationChainCollapse(
            f"TTL inflation: child exp {child.get('exp')} exceeds parent "
            f"exp {parent.get('exp')}; token outlives its grant"
        )

    # Clause 4: provenance must resolve to a logged attenuation of the parent.
    logged_parent = attenuation_log.get(child.get("jti"))
    if logged_parent != parent.get("jti"):
        raise DelegationChainCollapse(
            f"unauditable chain: child jti {child.get('jti')} does not resolve "
            f"to attenuation of parent jti {parent.get('jti')} "
            f"(resolved: {logged_parent}); token was minted, not attenuated"
        )


def _act_depth(act) -> int:
    depth = 0
    while isinstance(act, dict):
        depth += 1
        act = act.get("act")
    return depth
