The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(worktree): keep a local slash-named branch local
kshitijk4poore3fffd8c173a
diff --git a/apps/desktop/electron/git-worktree-ops.test.ts b/apps/desktop/electron/git-worktree-ops.test.tsindex 053ee5369a7..885b381a69c 100644--- a/apps/desktop/electron/git-worktree-ops.test.ts+++ b/apps/desktop/electron/git-worktree-ops.test.ts@@ -322,48 +322,6 @@ test('addWorktree: base origin/main does not set up upstream tracking', async ()}})-test('addWorktree: base origin/main resolves on a tag-pinned narrow clone', async () => {- // `--single-branch --branch <tag>` maps remote.origin.fetch to the tag only.- // A by-name `git fetch origin main` writes FETCH_HEAD and never origin/main.- const remoteDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-narrow-remote-'))- const cloneDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-narrow-clone-'))- const ident = ['-c', 'user.email=hermes@localhost', '-c', 'user.name=Hermes']-- try {- execFileSync('git', ['init', '-q', '-b', 'main', remoteDir])- execFileSync('git', ['-C', remoteDir, ...ident, 'commit', '-q', '--allow-empty', '-m', 'init'])- execFileSync('git', ['-C', remoteDir, 'tag', 'v0'])- execFileSync('git', ['-C', remoteDir, ...ident, 'commit', '-q', '--allow-empty', '-m', 'tip'])- const tip = execFileSync('git', ['-C', remoteDir, 'rev-parse', 'HEAD']).toString().trim()-- execFileSync('git', ['clone', '-q', '--single-branch', '--branch', 'v0', remoteDir, cloneDir])-- const result = await addWorktree(- cloneDir,- { base: 'origin/main', branch: 'from-main', name: 'from-main' },- 'git'- )-- const head = execFileSync('git', ['-C', result.path, 'rev-parse', 'HEAD']).toString().trim()-- assert.equal(head, tip)- assert.equal(result.branch, 'from-main')-- let hasUpstream = true-- try {- execFileSync('git', ['-C', cloneDir, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', 'from-main@{u}'])- } catch {- hasUpstream = false- }-- assert.equal(hasUpstream, false)- } finally {- fs.rmSync(remoteDir, { recursive: true, force: true })- fs.rmSync(cloneDir, { recursive: true, force: true })- }-})-// A tag-pinned narrow clone (`--single-branch --branch v0`), the shape older// installers made: remote.origin.fetch maps only the tag, so no branch has a// tracking ref. The remote has `main` and `feature` one commit past the tag.@@ -385,6 +343,29 @@ function seedNarrowClone(label) {return { cloneDir, remoteDir, tip }}+test('addWorktree: base origin/main resolves on a tag-pinned narrow clone', async () => {+ // A by-name `git fetch origin main` on a tag-only refspec writes FETCH_HEAD+ // and never origin/main.+ const { cloneDir, remoteDir, tip } = seedNarrowClone('narrow-base')++ try {+ const result = await addWorktree(cloneDir, { base: 'origin/main', branch: 'from-main', name: 'from-main' }, 'git')++ const head = execFileSync('git', ['-C', result.path, 'rev-parse', 'HEAD']).toString().trim()++ assert.equal(head, tip)+ assert.equal(result.branch, 'from-main')+ assert.throws(() =>+ execFileSync('git', ['-C', cloneDir, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', 'from-main@{u}'], {+ stdio: 'ignore'+ })+ )+ } finally {+ fs.rmSync(remoteDir, { recursive: true, force: true })+ fs.rmSync(cloneDir, { recursive: true, force: true })+ }+})+const fetchConfig = cloneDir =>execFileSync('git', ['-C', cloneDir, 'config', '--get-all', 'remote.origin.fetch']).toString().trim()@@ -443,6 +424,30 @@ test('addWorktree: converting a remote branch on a normal clone adds no fetch re}})+test('addWorktree: a local slash branch named like a remote branch stays local', async () => {+ // Without this, "origin/feature" (a local branch) became a new `feature`+ // tracking the remote branch of the same name, after a network fetch.+ const { cloneDir, remoteDir, tip } = seedNarrowClone('narrow-local-slash')++ try {+ execFileSync('git', ['-C', cloneDir, 'branch', 'origin/feature'])+ const local = execFileSync('git', ['-C', cloneDir, 'rev-parse', 'refs/heads/origin/feature']).toString().trim()++ assert.notEqual(local, tip)++ const result = await addWorktree(cloneDir, { existingBranch: 'origin/feature' }, 'git')+ const head = execFileSync('git', ['-C', result.path, 'rev-parse', 'HEAD']).toString().trim()+ const remoteRefs = execFileSync('git', ['-C', cloneDir, 'for-each-ref', 'refs/remotes']).toString().trim()++ assert.equal(result.branch, 'origin/feature')+ assert.equal(head, local)+ assert.equal(remoteRefs, '')+ } finally {+ fs.rmSync(remoteDir, { recursive: true, force: true })+ fs.rmSync(cloneDir, { recursive: true, force: true })+ }+})+test('addWorktree: a glob base is not turned into a fetch of every branch', async () => {const { cloneDir, remoteDir } = seedNarrowClone('narrow-glob')diff --git a/apps/desktop/electron/git-worktree-ops.ts b/apps/desktop/electron/git-worktree-ops.tsindex d70ee853ff2..3fa3774a525 100644--- a/apps/desktop/electron/git-worktree-ops.ts+++ b/apps/desktop/electron/git-worktree-ops.ts@@ -258,11 +258,15 @@ async function addExistingBranchWorktree(gitBin, root, name) {let remote = await remoteOfRef(gitBin, root, requested)let fetched = false- if (!remote && requested.includes('/')) {+ if (+ !remote &&+ requested.includes('/') &&+ !(await gitOk(gitBin, ['show-ref', '--verify', '--quiet', `refs/heads/${requested}`], root))+ ) {// A tag-pinned narrow clone has no tracking ref for any branch, so the// ref-based reading above misreads "origin/feature" as a local branch. When- // the remote carries the branch, fetching it creates the ref; otherwise- // keep the local-branch reading and its error.+ // no such local branch exists and the remote carries the branch, fetching+ // it creates the ref; otherwise keep the local-branch reading and its error.const maybeRemote = requested.slice(0, requested.indexOf('/'))if (diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.pyindex b5c4ddf8a41..8dbd9069102 100644--- a/hermes_cli/web_git.py+++ b/hermes_cli/web_git.py@@ -615,10 +615,11 @@ def _worktree_for_existing(root: str, raw_name: str) -> dict:# #81724)remote = _remote_of_ref(root, requested)fetched = False- if not remote and "/" in requested:+ if not remote and "/" in requested and not _ref_exists(root, f"refs/heads/{requested}"):# A tag-pinned narrow clone has no tracking ref for any branch, so the ref-based reading- # above misreads "origin/feature" as a local branch. When the remote carries the branch,- # fetching it creates the ref; otherwise keep the local-branch reading and its error.+ # above misreads "origin/feature" as a local branch. When no such local branch exists+ # and the remote carries the branch, fetching it creates the ref; otherwise keep the+ # local-branch reading and its error.maybe_remote, maybe_branch = requested.split("/", 1)if _git_line(root, ["remote", "get-url", maybe_remote]) and _fetch_tracking_ref(root, maybe_remote, maybe_branch@@ -630,19 +631,18 @@ def _worktree_for_existing(root: str, raw_name: str) -> dict:return {"path": root, "branch": existing, "repoRoot": root}target = _unique_dir(os.path.join(root, ".worktrees", _slugify(existing)))if remote:- ref = f"{remote}/{existing}"# Best-effort freshness: on failure (offline, branch gone) the last known ref is still# there to branch from.fetched = fetched or _fetch_tracking_ref(root, remote, existing)- if _git(root, ["worktree", "add", "--track", "-b", existing, target, ref])[0] != 0:+ if _git(root, ["worktree", "add", "--track", "-b", existing, target, requested])[0] != 0:# `--track` needs remote.<remote>.fetch to map the ref back to a remote branch; a# narrow clone maps only its tag. Branch untracked, then register the branch and# wire upstream, but only for a branch the fetch just proved exists: a configured# refspec whose source is gone makes every later plain `git fetch` fail.- _git_ok(root, ["worktree", "add", "-b", existing, target, ref])+ _git_ok(root, ["worktree", "add", "-b", existing, target, requested])if fetched:_git(root, ["remote", "set-branches", "--add", remote, existing])- _git(root, ["branch", f"--set-upstream-to={ref}", existing])+ _git(root, ["branch", f"--set-upstream-to={requested}", existing])else:_git_ok(root, ["worktree", "add", target, existing])return {"path": target, "branch": existing, "repoRoot": root}diff --git a/tests/hermes_cli/test_web_server_git.py b/tests/hermes_cli/test_web_server_git.pyindex 58df45f6013..3b48c1f56c5 100644--- a/tests/hermes_cli/test_web_server_git.py+++ b/tests/hermes_cli/test_web_server_git.py@@ -269,152 +269,87 @@ def test_worktree_add_from_origin_base_does_not_track(client, repo_with_remote):assert probe.returncode != 0-def test_worktree_add_from_origin_base_on_tag_pinned_clone(tmp_path):- """A tag-only fetch refspec must still materialize origin/main (#125686).-- ``git clone --single-branch --branch <tag>`` maps ``remote.origin.fetch`` to- the tag. ``git fetch origin main`` then writes FETCH_HEAD and leaves- ``origin/main`` missing, so ``worktree add`` dies with invalid reference.- """- origin = tmp_path / "origin"- origin.mkdir()-- def git(*args, cwd):- subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)-- git("init", "-q", "-b", "main", cwd=origin)- git("-c", "[email protected]", "-c", "user.name=Test", "commit", "-q", "--allow-empty", "-m", "init", cwd=origin)- git("tag", "v0", cwd=origin)- git("-c", "[email protected]", "-c", "user.name=Test", "commit", "-q", "--allow-empty", "-m", "tip", cwd=origin)- tip = subprocess.run(- ["git", "rev-parse", "HEAD"], cwd=origin, check=True, capture_output=True, text=True,- ).stdout.strip()+def _out(cwd, *args):+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()- clone = tmp_path / "clone"- subprocess.run(- ["git", "clone", "-q", "--single-branch", "--branch", "v0", str(origin), str(clone)],- check=True, capture_output=True, text=True,- )- missing = subprocess.run(- ["git", "show-ref", "--verify", "--quiet", "refs/remotes/origin/main"],- cwd=clone, capture_output=True,- )- assert missing.returncode != 0- from hermes_cli.web_git import worktree_add-- added = worktree_add(str(clone), {"base": "origin/main", "name": "x"})- head = subprocess.run(- ["git", "rev-parse", "HEAD"], cwd=added["path"], check=True, capture_output=True, text=True,- ).stdout.strip()- assert head == tip- upstream = subprocess.run(- ["git", "rev-parse", "--abbrev-ref", f"{added['branch']}@{{upstream}}"],- cwd=clone, capture_output=True, text=True,- )- assert upstream.returncode != 0---def _narrow_clone(tmp_path, *, seed_tracking_ref=False):- """A tag-pinned narrow clone (bare origin + --single-branch --branch <tag>) whose- remote.origin.fetch maps only the tag — the shape older installers made."""+def _seed_origin(tmp_path):+ """A bare origin whose `main` and `feature` sit one commit past tag `v0`."""origin = tmp_path / "origin.git"origin.mkdir()-- def og(*args):- subprocess.run(["git", *args], cwd=origin, check=True, capture_output=True, text=True)-- og("init", "-q", "-b", "main", "--bare")- work = tmp_path / "worktree-src"+ _git(origin, "init", "-q", "-b", "main", "--bare")+ work = tmp_path / "seed"work.mkdir()+ _git(work, "init", "-q", "-b", "main")+ ident = ("-c", "[email protected]", "-c", "user.name=Test")+ _git(work, *ident, "commit", "-q", "--allow-empty", "-m", "c1")+ _git(work, "tag", "v0")+ _git(work, *ident, "commit", "-q", "--allow-empty", "-m", "c2")+ _git(work, "branch", "feature")+ _git(work, "push", "-q", str(origin), "main", "feature", "v0")+ return origin, _out(work, "rev-parse", "HEAD")- def wg(*args):- subprocess.run(["git", *args], cwd=work, check=True, capture_output=True, text=True)-- wg("init", "-q", "-b", "main")- wg("-c", "[email protected]", "-c", "user.name=Test", "commit", "-q", "--allow-empty", "-m", "c1")- wg("tag", "v0")- wg("branch", "feature")- wg("-c", "[email protected]", "-c", "user.name=Test", "commit", "-q", "--allow-empty", "-m", "c2")- tip = subprocess.run(["git", "rev-parse", "feature"], cwd=work, check=True,- capture_output=True, text=True).stdout.strip()- wg("push", "-q", str(origin), "main", "feature", "v0")+def _narrow_clone(tmp_path, *, seed_tracking_ref=False):+ """A tag-pinned narrow clone (--single-branch --branch <tag>) whose remote.origin.fetch+ maps only the tag, the shape older installers made (#125686)."""+ origin, tip = _seed_origin(tmp_path)clone = tmp_path / "clone"- subprocess.run(["git", "clone", "-q", "--single-branch", "--branch", "v0", str(origin), str(clone)],- check=True, capture_output=True, text=True)+ _git(tmp_path, "clone", "-q", "--single-branch", "--branch", "v0", str(origin), str(clone))if seed_tracking_ref:- subprocess.run(["git", "fetch", "-q", "origin",- "+refs/heads/feature:refs/remotes/origin/feature"],- cwd=clone, check=True, capture_output=True, text=True)+ _git(clone, "fetch", "-q", "origin", "+refs/heads/feature:refs/remotes/origin/feature")return clone, tip-def test_worktree_add_existing_branch_materializes_missing_tracking_ref(client, tmp_path):- """On a tag-pinned narrow clone the tracking ref never exists, so `origin/feature` used to- be read as a local branch name and worktree creation died with `invalid reference`."""- clone, tip = _narrow_clone(tmp_path)+def _normal_clone(tmp_path):+ origin, tip = _seed_origin(tmp_path)+ clone = tmp_path / "normal"+ _git(tmp_path, "clone", "-q", str(origin), str(clone))+ return clone, tip- added = client.post(- "/api/git/worktree/add",- json={"path": str(clone), "existingBranch": "origin/feature"},- ).json()- assert added["branch"] == "feature"- head = subprocess.run(- ["git", "rev-parse", "HEAD"], cwd=added["path"], check=True, capture_output=True, text=True,- ).stdout.strip()- assert head == tip # branched from the remote feature, not the tag- upstream = subprocess.run(- ["git", "rev-parse", "--abbrev-ref", "feature@{upstream}"],- cwd=added["path"], capture_output=True, text=True,- ).stdout.strip()- assert upstream == "origin/feature"+def _fetch_config(clone):+ return _out(clone, "config", "--get-all", "remote.origin.fetch")-def test_worktree_add_existing_branch_tracks_when_refspec_cannot_reverse_map(client, tmp_path):- """With the tracking ref present, `worktree add --track` still cannot wire upstream on a- narrow clone (remote.origin.fetch maps only the tag); the mirror must set it explicitly."""- clone, tip = _narrow_clone(tmp_path, seed_tracking_ref=True)+def test_worktree_add_from_origin_base_on_tag_pinned_clone(tmp_path):+ """``git fetch origin main`` on a tag-only refspec writes FETCH_HEAD and leaves+ ``origin/main`` missing, so ``worktree add`` died with invalid reference."""+ clone, tip = _narrow_clone(tmp_path)+ from hermes_cli.web_git import worktree_add- added = client.post(- "/api/git/worktree/add",- json={"path": str(clone), "existingBranch": "origin/feature"},- ).json()+ added = worktree_add(str(clone), {"base": "origin/main", "name": "x"})- assert added["branch"] == "feature"- head = subprocess.run(- ["git", "rev-parse", "HEAD"], cwd=added["path"], check=True, capture_output=True, text=True,- ).stdout.strip()- assert head == tip+ assert _out(added["path"], "rev-parse", "HEAD") == tipupstream = subprocess.run(- ["git", "rev-parse", "--abbrev-ref", "feature@{upstream}"],- cwd=added["path"], capture_output=True, text=True,- ).stdout.strip()- assert upstream == "origin/feature"+ ["git", "rev-parse", "--abbrev-ref", f"{added['branch']}@{{upstream}}"],+ cwd=clone, capture_output=True, text=True,+ )+ assert upstream.returncode != 0-def _fetch_config(clone):- return subprocess.run(- ["git", "config", "--get-all", "remote.origin.fetch"],- cwd=clone, check=True, capture_output=True, text=True,- ).stdout+ "seed_tracking_ref", [False, True], ids=["tracking-ref-missing", "tracking-ref-present"],+)+def test_worktree_add_existing_branch_on_tag_pinned_clone_tracks_remote(client, tmp_path, seed_tracking_ref):+ """Missing ref: "origin/feature" used to be read as a local branch name. Present ref:+ `--track` still cannot wire upstream through a tag-only fetch refspec."""+ clone, tip = _narrow_clone(tmp_path, seed_tracking_ref=seed_tracking_ref)+ added = client.post(+ "/api/git/worktree/add", json={"path": str(clone), "existingBranch": "origin/feature"},+ ).json()-def _normal_clone(tmp_path):- """The narrow fixture's origin, cloned the normal way (wildcard fetch refspec)."""- _narrow_clone(tmp_path)- clone = tmp_path / "normal"- subprocess.run(["git", "clone", "-q", str(tmp_path / "origin.git"), str(clone)],- check=True, capture_output=True, text=True)- return clone+ assert added["branch"] == "feature"+ assert _out(added["path"], "rev-parse", "HEAD") == tip # the remote feature, not tag v0+ assert _out(added["path"], "rev-parse", "--abbrev-ref", "feature@{upstream}") == "origin/feature"[email protected]("shape", ["narrow", "normal"])-def test_worktree_add_missing_remote_branch_leaves_fetch_config_alone(client, tmp_path, shape):[email protected]("clone_of", [_narrow_clone, _normal_clone], ids=["narrow", "normal"])+def test_worktree_add_missing_remote_branch_leaves_fetch_config_alone(client, tmp_path, clone_of):"""A configured refspec whose source is missing makes every later plain `git fetch`fail, so a typo'd "origin/<branch>" must never be registered on the remote."""- clone = _narrow_clone(tmp_path)[0] if shape == "narrow" else _normal_clone(tmp_path)+ clone, _ = clone_of(tmp_path)before = _fetch_config(clone)resp = client.post(@@ -423,11 +358,11 @@ def test_worktree_add_missing_remote_branch_leaves_fetch_config_alone(client, tmassert resp.status_code != 200assert _fetch_config(clone) == before- subprocess.run(["git", "fetch", "-q"], cwd=clone, check=True, capture_output=True)+ _git(clone, "fetch", "-q")def test_worktree_add_existing_branch_on_normal_clone_adds_no_fetch_refspec(client, tmp_path):- clone = _normal_clone(tmp_path)+ clone, _ = _normal_clone(tmp_path)before = _fetch_config(clone)added = client.post(@@ -438,6 +373,23 @@ def test_worktree_add_existing_branch_on_normal_clone_adds_no_fetch_refspec(clieassert _fetch_config(clone) == before+def test_worktree_add_local_slash_branch_named_like_a_remote_stays_local(client, tmp_path):+ """A local "origin/feature" branch must be checked out as itself, not swapped for a+ new `feature` tracking the remote branch of the same name."""+ clone, tip = _narrow_clone(tmp_path)+ _git(clone, "branch", "origin/feature")+ local = _out(clone, "rev-parse", "origin/feature")+ assert local != tip++ added = client.post(+ "/api/git/worktree/add", json={"path": str(clone), "existingBranch": "origin/feature"},+ ).json()++ assert added["branch"] == "origin/feature"+ assert _out(added["path"], "rev-parse", "HEAD") == local+ assert _out(clone, "for-each-ref", "refs/remotes") == "" # never went to the network++def test_worktree_add_glob_base_is_not_fetched(tmp_path):"""`base` comes from the API; inside a refspec "origin/*" would fetch every branch."""clone, _ = _narrow_clone(tmp_path)@@ -446,6 +398,4 @@ def test_worktree_add_glob_base_is_not_fetched(tmp_path):with pytest.raises(RuntimeError):worktree_add(str(clone), {"base": "origin/*", "name": "glob"})- refs = subprocess.run(["git", "for-each-ref", "refs/remotes"], cwd=clone,- check=True, capture_output=True, text=True).stdout- assert refs == ""+ assert _out(clone, "for-each-ref", "refs/remotes") == ""