# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-credential-attenuation-failure-when-an-agent-re-delegates-an-aaif-scope-across-a-trust-domain-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-credential-attenuation-failure-when-an-agent-re-delegates-an-aaif-scope-across-a-trust-domain-boundary.warrant.json
# Markdown SHA-256:   325831ab4dd968c3e8c9d08bdf0b9d8abc3e81a2b5cc8ec04671b007e60c8551
# Code AST SHA-256:   e856f91cc21f9511dfaf29dbf41bafb732f2f32240a15699317652a9dcf92295
# Verified Classes:   ScopeReexpansionError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class ScopeReexpansionError(RuntimeError):
    """Raised when cross-domain attenuation fails to preserve the subset invariant."""
    pass


@dataclass
class Scope:
    resource: str
    bindings: Dict[str, str] = field(default_factory=dict)

    def is_subset_of(self, parent: "Scope") -> bool:
        if self.resource != parent.resource and parent.resource != "*":
            return False
        for key, val in self.bindings.items():
            pval = parent.bindings.get(key)
            if pval is None:
                # parent leaves parameter unbound -> wildcard under tolerant grammar
                continue
            if pval != "*" and pval != val:
                return False
        return True


def resolve_tolerant(scope: Scope) -> Scope:
    """Verifier grammar: unbound parameter is wildcard."""
    return Scope(resource=scope.resource,
                 bindings={k: (v if v != "*" else "*") for k, v in scope.bindings.items()})


def resolve_strict(scope: Scope) -> Scope:
    """Issuer grammar: unbound parameter is constrained by ancestor, not wildcard."""
    return Scope(resource=scope.resource, bindings=dict(scope.bindings))


def attenuate(parent: Scope, requested: Scope, cross_domain: bool) -> Scope:
    if not requested.is_subset_of(parent):
        raise ScopeReexpansionError(
            f"requested scope {requested} exceeds parent {parent}"
        )
    if cross_domain:
        # forbid elision: pin every parent binding explicitly
        merged = dict(parent.bindings)
        merged.update(requested.bindings)
        child = Scope(resource=requested.resource, bindings=merged)
        # verify commutation across grammars
        if not resolve_tolerant(child).is_subset_of(resolve_tolerant(parent)):
            raise ScopeReexpansionError(
                f"cross-domain attenuation non-commutative: child {child} "
                f"resolves outside parent {parent} under verifier grammar"
            )
        return child
    # intra-domain: elision of ancestor-fixed params is safe
    return Scope(resource=requested.resource, bindings=dict(requested.bindings))


def issue_delegated(parent: Scope, requested: Scope, cross_domain: bool) -> Scope:
    child = attenuate(parent, requested, cross_domain)
    # final guard: never emit a child that a tolerant verifier would widen
    if not resolve_tolerant(child).is_subset_of(resolve_tolerant(parent)):
        raise ScopeReexpansionError(
            "post-attenuation re-expansion detected at issuance boundary"
        )
    return child
