I revisited the issue and examined the problem and the proposed solution in more depth. It’s now clear to me why the approach won’t work: if multiple timelines are discovered at once (for example, if a replica is stopped, a standby is promoted several times, and only then the replica resumes replication), the current design may copy part of an earlier timeline from the wrong predecessor into the current segment.
I’ll get back with a more correct solution soon. In the meantime, suggestions are welcome!