Nix-env "No such file or directory", tries to access a stale user

Many commands including nix profile install ..., nix-env --list-generations etc fail with this error:

$ nix-env --list-generations
error: opening lock file '/home/<old user name here>/.local/state/nix/profiles/profile.lock': No such file or directory

I have renamed the user after installing the system by changing

  users.users.<new user name here> = {...}

Then I deleted the old user home directory, but somehow nix-env still points to the old user that no longer has a home directory. What am I doing wrong?

Uhh… how is my system reproducible if there’s some reference somewhere pointing to some stale directory that’s not specified in my configuration.nix?

Anyway. I wanted to just create a new profile in place of the borked one. Apparently in order to create a new profile, you’re expected to switch to a profile that does not exist (and hence should be created):

$ nix-env --switch-profile ~/my-new-profile

this created a new profile and allowed me to run nix-env and nix profile commands again.

Naturally, although nix-env interface is considered deprecated and nix profile commands are supposed to be the way to go, I could not find an alternative to nix-env --switch-profile with nix profile.