# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-capability-token-whose-scope-narrows-only-on-paper-the-attenuation-inversion-boundary-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-capability-token-whose-scope-narrows-only-on-paper-the-attenuation-inversion-boundary-i.warrant.json
# Markdown SHA-256:   3dee0ee64118999cdb20bbce3080338f15fa716b0d6e104294f8b258498d9d51
# Code AST SHA-256:   aeafe9231674d9b160f84fb196c452fa1baeb0bd34f088bfdcd4fc140ca2d2f2
# Verified Classes:   AttenuationInversionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class AttenuationInversionError(RuntimeError):
    """Raised when a delegated AAIF token's declared scope is a syntactic
    subset of its parent but its effective authorization set is not."""
    pass


IDENTITY_BINDINGS = ("$SUBJECT", "$CALLER", "$DELEGATOR")


def _is_closed_world(term: str) -> bool:
    # A term is closed-world only if it names a concrete resource or a finite
    # enumeration. Wildcards, tags, attribute predicates, and time windows are
    # open-world and cannot be statically attenuated.
    open_markers = ("*", "tag:", "attr:", "window:", "owner==")
    return not any(m in term for m in open_markers)


def _has_identity_binding(term: str) -> bool:
    return any(b in term for b in IDENTITY_BINDINGS)


def _rewrite_to_root_subject(term: str, root_subject: str) -> str:
    for b in IDENTITY_BINDINGS:
        term = term.replace(b, root_subject)
    return term


def validate_delegation(
    child_scope: list[str],
    parent_scope: list[str],
    root_subject: str,
    tool_manifest: dict[str, dict],
    invoked_tools: list[str],
) -> list[str]:
    """Return the effective child scope after root-pinned rewriting, or raise
    AttenuationInversionError if the delegation cannot be statically bounded."""
    parent_set = set(parent_scope)
    effective: list[str] = []

    for term in child_scope:
        if _has_identity_binding(term):
            rewritten = _rewrite_to_root_subject(term, root_subject)
            if not _is_closed_world(rewritten):
                raise AttenuationInversionError(
                    f"scope term {term!r} binds identity and remains open-world "
                    f"after rewrite to root subject {root_subject!r}; "
                    f"use-time re-binding would widen authorization"
                )
            if rewritten not in parent_set:
                raise AttenuationInversionError(
                    f"rewritten term {rewritten!r} not covered by parent scope "
                    f"{sorted(parent_set)!r}"
                )
            effective.append(rewritten)
            continue

        if not _is_closed_world(term):
            raise AttenuationInversionError(
                f"scope term {term!r} is open-world; syntactic subset check is "
                f"inconclusive and no use-time gate was supplied"
            )

        if term not in parent_set:
            raise AttenuationInversionError(
                f"scope term {term!r} not in parent scope {sorted(parent_set)!r}"
            )
        effective.append(term)

    for tool in invoked_tools:
        manifest = tool_manifest.get(tool)
        if manifest is None:
            raise AttenuationInversionError(
                f"invoked tool {tool!r} absent from capability manifest"
            )
        if not manifest.get("non_reentrant", False):
            raise AttenuationInversionError(
                f"tool {tool!r} may re-enter authorization with the delegated "
                f"token (confused-deputy vector); mark non_reentrant or exchange "
                f"for a tool-scoped token at the boundary"
            )

    return effective
