You don't need recursion. You just need to careful apply-templates to siblings.
The code below is an adaptation from the solution in your other (referred) question.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:strip-space elements="*" />
<xsl:output indent="yes" />
<xsl:key name="key" match="*[@gr]" use="@gr" />
<xsl:template match="*[*/@gr]">
<xsl:copy>
<xsl:apply-templates select="*[not(@into)]"/><!--start by most top-level ones-->
</xsl:copy>
</xsl:template>
<xsl:template match="*[@gr]"/>
<xsl:template match="*[@gr][generate-id() = generate-id(key('key', @gr)[1])]">
<fold>
<xsl:for-each select="key('key', @gr)">
<xsl:call-template name="identity" />
</xsl:for-each>
<xsl:apply-templates select="following-sibling::*[@into = current()/@gr]"/>
</fold>
</xsl:template>
<xsl:template match="node()|@*" name="identity" >
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>