How can an observed or desired collective behavior be reverse-engineered into local rules that individuals can embody? In this talk, I present an algorithmic framework that harnesses statistical physics to obtain stochastic distributed algorithms whose long-run collective behaviors can be formally characterized by phase transitions. To bridge this algorithmic theory to the mechanics of physical systems, I demonstrate how the nonequilibrium dynamics of active granular matter can be quantitatively predicted by a stochastic distributed algorithm at equilibrium. I conclude by highlighting how these connections between theory and physical systems suggest new approaches to characterizing emergent phenomena in complex biological and social systems, as in my ongoing work on the dynamics of political polarization.