# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-authority-inflation-in-chained-aaif-delegated-credentials-when-scope-conjunction-is-evaluated-per-hop-rather-than-at-the.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-authority-inflation-in-chained-aaif-delegated-credentials-when-scope-conjunction-is-evaluated-per-hop-rather-than-at-the.warrant.json
# Markdown SHA-256:   9af3b8df0c98486037e2fc1a4a46d45b0f6193ff5f37c9c5c16f1206ae554344
# Code AST SHA-256:   5b5c511e416a2a99093c8bff476c4a190d1a7f81e535eedee404ec5b31bf54ea
# Verified Classes:   AuthorityInflationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AuthorityInflationError(RuntimeError):
    """Raised when a chained AAIF credential's effective scope exceeds the
    conjunction of all ancestor asserted scopes, or when asserted and
    effective scope fields diverge at any hop."""
    pass


def verify_chain_conjunction(chain):
    # chain: list of Credential, ordered root -> leaf.
    # Each Credential exposes .asserted_scope and .effective_scope as frozensets.
    if not chain:
        raise AuthorityInflationError("empty credential chain")

    # 1. Per-hop narrowing must hold on the asserted field.
    for i in range(1, len(chain)):
        parent = chain[i - 1].asserted_scope
        child = chain[i].asserted_scope
        if not child.issubset(parent):
            raise AuthorityInflationError(
                f"hop {i} asserts {child - parent} not granted by hop {i-1}"
            )

    # 2. Asserted and effective fields must agree at every hop.
    for i, cred in enumerate(chain):
        if cred.effective_scope != cred.asserted_scope:
            residual = cred.effective_scope - cred.asserted_scope
            raise AuthorityInflationError(
                f"hop {i} carries latent residual {residual} "
                f"not present in asserted scope"
            )

    # 3. Terminal conjunction: leaf effective scope must be bounded by
    #    the intersection of ALL ancestors, not just the immediate parent.
    conjunction = chain[0].asserted_scope
    for cred in chain[1:]:
        conjunction = conjunction & cred.asserted_scope

    leaf_effective = chain[-1].effective_scope
    if not leaf_effective.issubset(conjunction):
        raise AuthorityInflationError(
            f"leaf effective scope {leaf_effective - conjunction} "
            f"exceeds full-chain conjunction {conjunction}"
        )

    return conjunction


def authorize_action(chain, action):
    granted = verify_chain_conjunction(chain)
    if action not in granted:
        raise AuthorityInflationError(
            f"action {action!r} not in full-chain conjunction {granted}"
        )
    return True
