Dear stata list,

I am running survival time analyses and my goal is to create a survival time variable that indicates the total of data collection points that one has survived in his/her first management position. For this, I need to know in what year a person reported not be holding a management position for the very first time.
Below you can see the code that I used to create this variable. Specifically, this variable detects the very first year of not having a management position that follows a year or years of holding a management position for the very first time (marked blue).

by idcode (year), sort: egen test = min(cond(job == 0 | job ==., year, .)) if job[_n-1]==1

idcode year job failmanager test
4 1996 1 .
4 1997 1 .
4 1998 0 1 .
4 2000 1 1 .
4 2001 0 1 2001
4 2003 1 1 .
4 2004 1 1 2001
4 2006 0 1 2001
4 2007 0 1 .
4 2008 0 1 .
4 2009 0 1 .
4 2010 0 1 .
4 2011 0 1 .
4 2013 0 1 .
4 2015 0 1 .

However, this variable does not detect observations that enter a management position for the very first time and are not coded with 0 (holding a non-management position) at later points of data collection. See two examples below:

idcode year job failmanager test
1752 1996 1
1752 1997 1
1752 1998 1
1752 2000 0 1
1752 2001 0 1
1752 2003 0 1
1752 2004 0 1
1752 2006 0 1
1752 2007 0 1
1752 2008 0 1
1752 2009 0 1
1752 2010 0 1
1752 2011 0 1
1752 2013 0 1
1752 2015 1 1

idcode year job failmanager test
2074 1996 1
2074 1997 1
2074 1998 0 1
2074 2000 0 1
2074 2001 0 1
2074 2003 0 1
2074 2004 0 1
2074 2006 0 1
2074 2007 0 1
2074 2008 0 1
2074 2009 0 1
2074 2010 0 1
2074 2011 1 1
2074 2013 1 1
2074 2015 1 1

Do you have some ideas about how I could adjust my code in order to include these observations?
Thank you very much in advance!
Best Anna