# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-delegated-agent-credential-be-re-scoped-before-crossing-an-aaif-trust-boundary-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-delegated-agent-credential-be-re-scoped-before-crossing-an-aaif-trust-boundary-hop.warrant.json
# Markdown SHA-256:   48a7e33cb9109430779901b2c09d3b7318fbbe79ac51263aba186cbfe91975e0
# Code AST SHA-256:   61e40b5abe5143a23a7f27d1e5704dc51337d7eceac9564318ff211feb7911f2
# Verified Classes:   DelegationScopeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationScopeError(RuntimeError):
    """Raised when a delegated credential cannot be soundly scoped at a trust-boundary hop."""
    pass


def rescope_at_hop(parent_grant: dict, parent_active_obligation: dict, child_request: dict) -> dict:
    """
    parent_grant:              full set the parent credential permits (e.g. {"perms": {...}, "tenants": {...}})
    parent_active_obligation:  what the parent is actually bound to at this hop (narrower or equal)
    child_request:             what the child asks for

    Intersection against parent_grant is a post-condition, not a derivation.
    Derivation must be against parent_active_obligation.
    """
    # Post-condition: parent_active_obligation must itself be within parent_grant.
    if not _subset(parent_active_obligation, parent_grant):
        raise DelegationScopeError(
            "parent active obligation exceeds its own grant; credential chain is corrupt"
        )

    # Derive against the active obligation, not the grant ceiling.
    derived_perms = set(child_request.get("perms", ())) & set(parent_active_obligation.get("perms", ()))
    derived_tenants = set(child_request.get("tenants", ())) & set(parent_active_obligation.get("tenants", ()))

    # Any requested dimension not satisfiable within the active obligation is a re-scope failure,
    # not a silent narrowing. Widening back to parent_grant is the bug this guards against.
    if set(child_request.get("tenants", ())) - derived_tenants:
        raise DelegationScopeError(
            "child requested tenant outside parent's active obligation; "
            "intersection against grant would silently widen across context"
        )

    if not derived_perms:
        raise DelegationScopeError("derived child scope is empty; refusing to mint")

    child = {
        "perms": sorted(derived_perms),
        "tenants": sorted(derived_tenants),
        "aud": parent_active_obligation.get("aud"),
        "purpose": parent_active_obligation.get("purpose"),
    }

    # Mandatory post-condition: result is a subset of the parent grant.
    if not _subset(child, parent_grant):
        raise DelegationScopeError("derived child scope escapes parent grant")
    return child


def _subset(a: dict, b: dict) -> bool:
    for k, v in a.items():
        if isinstance(v, (set, list, tuple)):
            if not set(v) <= set(b.get(k, ())):
                return False
        else:
            if b.get(k) != v:
                return False
    return True
