I'm probably the worst person to answer this, because I stayed too long at companies that I shouldn't have and left too early at companies I should have stuck around with.
That said... I have no regrets about what I've done. I may have stayed at certain companies too long, but that gave me the strength to go out on my own. I may have left certain companies too early, but that made me appreciate what made them so special.
Frankly, I just moved when I got bored, or when something more exciting presented itself.
I value loyalty when it comes to family, friends, and my dogs. Business is business. Companies like to talk warm and fuzzy about how they'll work with the right people forever, and there's nothing wrong with that, if that's your thing. Some companies will work hard to make sure your life is good, but rest assured they'll cut you out once you're no longer valuable to them. It would be bad business to do otherwise! Many companies – I will say the majority – view you as nothing more than cheap labor. Then they guilt you in to working extra hard because they're paying you 6 figures, when they're earning 7 or 8 or more figures on your work (which happens in the context of their company, admittedly).
When you work for a business that respects and values you as a human, stick around until you want to leave. When you work for a business that doesn't respect and value you as a human, get the hell out as fast as you can.
Don't feel bad about leaving, whenever you do, wherever it is. Employee turnover is a part of business. If a business can't handle you leaving, they're a bad business that you don't want to work for anyway.
I don't have any heuristic, and nothing to say that will be particularly helpful to you... other than the cliche, but absolutely true notion: you only live once. You are ultimately responsible for the time that you spend on this earth. If you don't like how you spend it, you have only yourself to blame.
I make my choices, and I deal with the consequences. Sometimes they're overwhelmingly positive, sometimes they're fairly neutral, sometimes they kind of suck, and sometimes they really suck. I'm a newbie when it comes to this life thing