# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-authorization-scope-when-a-delegated-aaif-warrant-is-re-signed-across-a-three-hop-chain-and-the-middle-agent-s-capability-se.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-authorization-scope-when-a-delegated-aaif-warrant-is-re-signed-across-a-three-hop-chain-and-the-middle-agent-s-capability-se.warrant.json
# Markdown SHA-256:   083ce84dfa47d264145f82441fb1976eb15086be15938e087175b14966a855a1
# Code AST SHA-256:   d5339bc9108da14db8fe50ea49c4a82fb7f60fb9e2bc971b8480580bc111e560
# Verified Classes:   ScopeReexpansionError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ScopeReexpansionError(RuntimeError):
    """Raised when a re-minted warrant re-expands a scope that an intermediate
    hop had legitimately downscoped, without a denial nonce binding it to the
    triggering denial. This is the strict-subset re-expansion boundary."""
    pass


def verify_warrant_chain(
    chain: list[dict],
    root_scope: frozenset[str],
    denial_nonces: frozenset[str],
) -> None:
    """Verify a multi-hop AAIF warrant chain under the intent-preserving posture.

    Each hop is a dict with keys: issuer, subject, scope (frozenset),
    attenuation (frozenset), denial_nonce (str | None).

    Raises ScopeReexpansionError if a hop's scope exceeds its immediate
    delegator's scope in a way that re-expands a prior downscope without a
    denial nonce, or if any hop exceeds the root scope.
    """
    if not chain:
        raise ScopeReexpansionError("empty warrant chain")

    for i, hop in enumerate(chain):
        scope = hop["scope"]
        atten = hop["attenuation"]

        # Authorization check: cannot grant more than you hold.
        if not scope <= atten:
            raise ScopeReexpansionError(
                f"hop {i}: scope {sorted(scope)} exceeds issuer attenuation "
                f"{sorted(atten)}"
            )

        # Intent check: no hop may exceed the originator's root grant.
        if not scope <= root_scope:
            raise ScopeReexpansionError(
                f"hop {i}: scope {sorted(scope)} exceeds root_scope "
                f"{sorted(root_scope)}"
            )

        # Strict-subset re-expansion check: if a previous hop downscoped
        # below this hop's scope, the re-expansion must be nonce-bound to
        # the denial that triggered it.
        if i > 0:
            prev_scope = chain[i - 1]["scope"]
            if not scope <= prev_scope:
                nonce = hop.get("denial_nonce")
                if nonce is None or nonce not in denial_nonces:
                    raise ScopeReexpansionError(
                        f"hop {i}: scope {sorted(scope)} re-expands past "
                        f"hop {i-1} scope {sorted(prev_scope)} without a "
                        f"valid denial nonce"
                    )


def mint_remint(
    delegator_scope: frozenset[str],
    denied_warrant_scope: frozenset[str],
    requested_scope: frozenset[str],
    denial_nonce: str,
    denial_nonces: frozenset[str],
) -> dict:
    """Mint a re-signed warrant after a denial, enforcing the escalation guard."""
    if denial_nonce not in denial_nonces:
        raise ScopeReexpansionError(
            f"denial nonce {denial_nonce!r} not recognized by the gate"
        )
    if not requested_scope <= delegator_scope:
        raise ScopeReexpansionError(
            f"requested {sorted(requested_scope)} exceeds delegator "
            f"{sorted(delegator_scope)}"
        )
    if not requested_scope <= denied_warrant_scope:
        # Escalation: re-mint grants more than the denied warrant held.
        # Under the intent-preserving posture this requires out-of-band
        # originator approval, which is not present here.
        raise ScopeReexpansionError(
            f"re-mint escalates past denied warrant: requested "
            f"{sorted(requested_scope)} vs denied {sorted(denied_warrant_scope)}"
        )
    return {
        "issuer": "<delegator>",
        "subject": "<worker>",
        "scope": requested_scope,
        "attenuation": delegator_scope,
        "denial_nonce": denial_nonce,
    }
