Looks like the function version works.
Interestingly, swapping `\after \duration $A \volta 2 \fine` with `\volta 2 \after \duration $A \fine` causes the unfolded music to be missing the AA part. I’ve noticed a tricky interplay between `\after` and `\volta x` previously.
\version "2.24.0"
duration =
#(define-scheme-function (x) (duration-or-music?)
(if (ly:duration? x)
x
(make-duration-of-length (ly:music-length x))))
AABAify =
#(define-music-function
(A B) (ly:music? ly:music?)
#{
\repeat segno 2 {
\after \duration $A \volta 2 \fine
<<
\volta #'() {
\repeat volta 2 $A
}
\unfolded {
\volta 1 \repeat volta 2 $A
\volta 2 $A
}
>>
\volta 1 $B
}
#})
A = {
\repeat unfold 8 { a'4 a' a' a' | }
\section
}
B = { \repeat unfold 8 { b'2 b' | }
\section
}
AABA = \AABAify \A \B
\score {
\AABA
}
\score {
\unfoldRepeats \AABA
}