# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-a-delegated-aaif-chain-when-an-intermediate-agent-attenuates-a-warrant-without-rebinding-the-subject.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-a-delegated-aaif-chain-when-an-intermediate-agent-attenuates-a-warrant-without-rebinding-the-subject.warrant.json
# Markdown SHA-256:   12d9840bf3c63afe62fe483e0763eb1133791059a0872447f90f54864167f9ec
# Code AST SHA-256:   40681fa2b3c584d47cf34cc6e382d0fc673f69ad8b5c784a324ecfae924cd5a7
# Verified Classes:   AAIFDomainRebindError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class AAIFDomainRebindError(RuntimeError):
    """Raised when an attenuator rebinds a warrant subject outside the parent's delegation domain."""
    pass


def attenuate_warrant(parent: dict, child_subject_key: str, narrowed_grant: dict) -> dict:
    """
    Produce a child AAIF warrant from `parent`, bound to `child_subject_key`,
    with `narrowed_grant` as the attenuated capability set.

    Enforces the subject-preservation-or-domain-membership invariant:
    if the child subject differs from the parent subject, the child subject
    MUST be a member of parent['delegation_domain'], and the child's domain
    MUST be intersected forward with the parent's.
    """
    parent_subject = parent["subject"]
    parent_domain = parent.get("delegation_domain")  # None means singleton {parent_subject}

    rebinding = child_subject_key != parent_subject

    if rebinding:
        # Absent domain on the parent means NO rebinding is permitted.
        if parent_domain is None:
            raise AAIFDomainRebindError(
                f"parent warrant for subject {parent_subject!r} carries no "
                f"delegation_domain; rebinding to {child_subject_key!r} is forbidden"
            )
        if child_subject_key not in parent_domain:
            raise AAIFDomainRebindError(
                f"child subject {child_subject_key!r} is not a member of parent "
                f"delegation_domain {sorted(parent_domain)!r}; refusing to attenuate"
            )

    # Grant monotonicity: child grant must be a subset of parent grant.
    if not _grant_is_subset(narrowed_grant, parent["grant"]):
        raise AAIFDomainRebindError(
            "narrowed_grant is not a subset of the parent grant; "
            "attenuation cannot widen authority"
        )

    # Depth decrement.
    if parent["depth"] <= 0:
        raise AAIFDomainRebindError(
            "delegation depth exhausted; cannot attenuate further"
        )

    # Forward-intersect the domain: the child may only name subjects the
    # parent could itself name, restricted to those reachable from the new subject.
    if rebinding:
        child_domain = set(parent_domain) | {child_subject_key}
    else:
        child_domain = set(parent_domain) if parent_domain is not None else {parent_subject}

    return {
        "subject": child_subject_key,
        "grant": narrowed_grant,
        "depth": parent["depth"] - 1,
        "expiry": min(parent["expiry"], narrowed_grant.get("expiry", parent["expiry"])),
        "delegation_domain": child_domain,
        "parent_signature": parent["signature"],
    }


def verify_chain(chain: list[dict]) -> None:
    """Verify an AAIF chain hop-by-hop, re-checking domain membership per rebinding hop."""
    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]
        if child["subject"] != parent["subject"]:
            parent_domain = parent.get("delegation_domain")
            if parent_domain is None or child["subject"] not in parent_domain:
                raise AAIFDomainRebindError(
                    f"hop {i}: subject rebinding {parent['subject']!r} -> "
                    f"{child['subject']!r} violates parent delegation_domain"
                )
        if not _grant_is_subset(child["grant"], parent["grant"]):
            raise AAIFDomainRebindError(f"hop {i}: grant widened across attenuation")
        if child["depth"] < 0:
            raise AAIFDomainRebindError(f"hop {i}: negative delegation depth")


def _grant_is_subset(child: dict, parent: dict) -> bool:
    """Capability-set subset check: every child capability must be covered by the parent."""
    for cap, scope in child.items():
        if cap not in parent:
            return False
        if not _scope_is_subset(scope, parent[cap]):
            return False
    return True


def _scope_is_subset(child_scope, parent_scope) -> bool:
    if isinstance(child_scope, str) and isinstance(parent_scope, str):
        return parent_scope == "*" or child_scope == parent_scope or child_scope.startswith(parent_scope.rstrip("*"))
    return child_scope == parent_scope
