You're looking for [drupal_build_css_cache](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_build_css_cache/7) & [drupal_build_js_cache](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_build_js_cache/7). The building happens when the file doesn't exist or when the combination of files used in the aggregate is different than before.

Looking at [drupal_clear_css_cache](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_clear_css_cache/7) & [drupal_clear_js_cache](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_clear_js_cache/7) the variable gets removed & any file older than 30 days gets deleted. By removing the variable, drupal will then check to see if the contents of the file has changed, if yes a new aggregate will be build. So the file name is build by using a hash of the files content and the quick lookup is built by a hash of the file names used.

If you want something that's a little smarter than core, doesn't cause a stamped of writes to the variables table on a cache clear, and keeps files around based upon usage instead of a 30 day window give [Advanced CSS/JS Aggregation](https://www.drupal.org/project/advagg) a try.