# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-escalate-scope-when-a-delegated-capability-token-is-re-minted-across-a-trust-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-escalate-scope-when-a-delegated-capability-token-is-re-minted-across-a-trust-hop.warrant.json
# Markdown SHA-256:   25f66b0e2728d6ebc237c40d4639f57a6839b850b1094171599ba3cad0819dcb
# Code AST SHA-256:   5920aa3c717eaa7cad77e82049521bb0461fc33b247dbd305ac5c542b6922d7a
# Verified Classes:   AttenuationInvariantViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AttenuationInvariantViolation(RuntimeError):
    """Raised when a delegated capability token's effective scope is not a
    strict subset of its parent's recomputed scope, or when the signer's
    ambient authority has leaked into the child token."""
    pass


def verify_delegation_chain(
    root_token,
    child_token,
    audit_log,
    signer_ambient_scopes,
):
    """
    Enforce: child.scopes subset-of parent.scopes subset-of ... subset-of root.scopes,
    with parent scopes recomputed from the audit log's *requested* field,
    not from the parent token's self-declared scopes.
    """
    # 1. Recompute the parent's effective scope from intent, not from claims.
    audit_entry = audit_log.lookup(child_token.parent_hash)
    if audit_entry is None:
        raise AttenuationInvariantViolation(
            f"no audit entry for parent_hash={child_token.parent_hash!r}; "
            "cannot recompute parent scope"
        )

    recomputed_parent = frozenset(audit_entry.requested_scopes)

    # 2. Ambient-authority leak check: the signer's own scopes must not
    #    appear in the child unless they were explicitly requested and
    #    are within the recomputed parent ceiling.
    leaked = frozenset(child_token.scopes) & frozenset(signer_ambient_scopes)
    leaked -= recomputed_parent
    if leaked:
        raise AttenuationInvariantViolation(
            f"ambient authority leaked into child token: {sorted(leaked)}"
        )

    # 3. Subset invariant, element-wise against recomputed parent.
    if not frozenset(child_token.scopes) <= recomputed_parent:
        extra = frozenset(child_token.scopes) - recomputed_parent
        raise AttenuationInvariantViolation(
            f"child scope {sorted(child_token.scopes)} exceeds parent "
            f"{sorted(recomputed_parent)}; offending: {sorted(extra)}"
        )

    # 4. Countersignature: the delegator, not the signer, must have
    #    authorized the requested scope.
    if audit_entry.countersigner != child_token.delegator_id:
        raise AttenuationInvariantViolation(
            f"audit countersigner {audit_entry.countersigner!r} does not match "
            f"delegator {child_token.delegator_id!r}"
        )

    return True
