Like any other useful adaptation, the dam-building clockwork in the brain must have evolved by Darwinian selection of genes. There must have been genetic variations in the wiring of the brain which affected dam-building. Those genetic variants that resulted in improved dams were more likely to survive in beaver gene pools. It is the same story as for all Darwinian adaptations.