Capturing the superorganism: a formal theory of group adaptation