@@ -47,13 +47,41 @@ if [ -z "$SESSION_ID" ]; then
4747fi
4848
4949BRANCH=$( cd " $CWD " 2> /dev/null && git branch --show-current 2> /dev/null || echo " unknown" )
50+ REPO=$( resolve_repo_name " $CWD " )
5051
5152EXISTING_ID=" "
52- if [ -n " $CWD " ] && [ -f " $STATE_FILE " ]; then
53- # First: match by branch AND cwd (strongest match — same branch in same worktree)
54- EXISTING_ID=$( jq -r --arg cwd " $CWD " --arg branch " $BRANCH " '
55- [.agents[] | select(.cwd == $cwd and .branch == $branch)] | .[0].id // empty
56- ' " $STATE_FILE " 2> /dev/null)
53+ if [ -f " $STATE_FILE " ]; then
54+ # 1. Match by branch AND cwd (strongest — same branch in same directory)
55+ # Skip protected branches — DeployNOPE stages should never enrich a main/staging/dev agent
56+ if [ -n " $BRANCH " ] && [ " $BRANCH " != " unknown" ]; then
57+ EXISTING_ID=$( jq -r --arg cwd " $CWD " --arg branch " $BRANCH " '
58+ [.agents[] | select(
59+ .cwd == $cwd and .branch == $branch and
60+ ($branch | test("^(main|master|staging|development)$") | not)
61+ )] | .[0].id // empty
62+ ' " $STATE_FILE " 2> /dev/null)
63+ fi
64+ # 2. Match by context against branch name (covers worktrees where cwd differs
65+ # and context may be the branch name e.g. "style-changes")
66+ if [ -z " $EXISTING_ID " ] && [ -n " $CONTEXT " ]; then
67+ EXISTING_ID=$( jq -r --arg ctx " $CONTEXT " '
68+ [.agents[] | select(.branch == $ctx)] | .[0].id // empty
69+ ' " $STATE_FILE " 2> /dev/null)
70+ fi
71+ # 3. Match by repo: find a non-protected, non-complete branch agent in the same repo.
72+ # Covers context changes (e.g. "style-changes" → "2.21.0") and worktree cwd mismatches.
73+ # Excludes completed deployments so we don't hijack a finished workflow.
74+ if [ -z " $EXISTING_ID " ] && [ -n " $REPO " ]; then
75+ EXISTING_ID=$( jq -r --arg repo " $REPO " '
76+ [.agents[] | select(
77+ .repo == $repo and
78+ (.branch // "" | test("^(main|master|staging|development)$") | not) and
79+ ((.deploynope.stage // "" | ascii_downcase) != "complete")
80+ )] |
81+ sort_by(if (.deploynope.active // false) then 0 else 1 end) |
82+ .[0].id // empty
83+ ' " $STATE_FILE " 2> /dev/null)
84+ fi
5785fi
5886
5987if [ -n " $EXISTING_ID " ]; then
@@ -72,8 +100,6 @@ if [ ! -f "$STATE_FILE" ]; then
72100 echo ' {"version":1,"agents":{},"stagingClaim":null,"warnings":[],"activity":[]}' > " $STATE_FILE "
73101fi
74102
75- REPO=$( resolve_repo_name " $CWD " )
76-
77103# ── Branch drift detection ──────────────────────────────────────────────────
78104# Check how many commits the current branch is behind the production branch
79105DRIFT_BEHIND=0
0 commit comments