When and how did galaxies form and their metals accumulate? Over the last decade, this has moved from an archeological question to a live investigation: there is now a broad picture of the evolution of galaxies in dark matter halos: their masses, stars, metals and supermassive blackholes. Galaxies have been found and studied in which these formation processes are taking place most vigorously, all the way back in cosmic time to when the intergalactic medium (IGM) was still largely neutral. However, the details of how and why the interstellar medium (ISM) in distant galaxies cools, is processed, recycled and enriched in metals by stars, and fuels active galactic nuclei (AGNs) remain uncertain. In particular, the cooling of gas to fuel star formation, and the chemistry and physics of the most intensely active regions is hidden from view at optical wavelengths, but can be seen and diagnosed at mid- & far-infrared (IR) wavelengths. Rest-frame IR observations are important first to identify the most luminous, interesting and important galaxies, secondly to quantify accurately their total luminosity, and finally to use spectroscopy to trace the conditions in the molecular and atomic gas out of which stars form. In order to map out these processes over the full range of environments and large-scale structures found in the universe - from the densest clusters of galaxies to the emptiest voids - we require tools for deep, large area surveys, of millions of galaxies out to z~5, and for detailed follow-up spectroscopy. The necessary tools can be realized technically. Here, we outline the requirements for gathering the crucial information to build, validate and challenge models of galaxy evolution.