From f021e205ea0701c55452b4286a32eea054fe2392 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:06:28 +0100 Subject: [PATCH 1/3] Resolve the task base in one Git fetch Architecture-Review: unchanged; start still verifies the remote base and checks out the exact fetched commit without using shared FETCH_HEAD. Co-Authored-By: Codex --- src/loopzero/worktree.py | 28 +++++++++++++++++++++------- tests/test_worktree.py | 21 ++++++++++++--------- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index aeaa60b2..ef9b8c5a 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -229,13 +229,28 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: if not existing and _branch_exists(repo_root, branch): raise WorktreeError(f"branch already exists: {branch}") remote_ref = f"refs/heads/{base_branch}" - lookup = ("ls-remote", "--refs", "origin", remote_ref) + tracking = f"refs/remotes/origin/{base_branch}" + base = None try: - advertised = _git(repo_root, *lookup) - base, _, ref = advertised.partition("\t") - if ref != remote_ref: - raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}") - _git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base) + valid = run(("git", "check-ref-format", remote_ref), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30) + symbolic = run(("git", "symbolic-ref", "-q", tracking), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30) + if valid.exit_code == 0 and symbolic.exit_code == 1: + fetch = ("git", "fetch", "--porcelain", "--verbose", "--no-tags", "--no-prune", + "--no-write-fetch-head", "--refmap=", "origin", f"+{remote_ref}:{tracking}") + result = run(fetch, cwd=repo_root, env_allowlist=GIT_ENV, timeout=120) + if result.exit_code != 129: # Older Git does not accept --porcelain. + row = result.stdout.removesuffix("\n").rsplit(" ", 2) + if result.exit_code or len(row) != 3 or row[-1] != tracking: + raise GitError(fetch, result.stderr or result.stdout or f"origin did not report {remote_ref}") + base = row[1] + if base is None: + lookup = ("ls-remote", "--refs", "origin", remote_ref) + advertised = _git(repo_root, *lookup) + base, _, ref = advertised.partition("\t") + if ref != remote_ref: + raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}") + _git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base) + _git(repo_root, "update-ref", "--no-deref", tracking, base) except GitError: if "origin" not in _git(repo_root, "remote").splitlines(): raise WorktreeError( @@ -244,7 +259,6 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: "with `git remote rename origin`." ) from None raise - _git(repo_root, "update-ref", "--no-deref", f"refs/remotes/origin/{base_branch}", base) if existing: existing_head = _resumable_head(repo_root, wt, branch) if existing_head is None: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index b180a947..f6a635d5 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -51,27 +51,29 @@ def test_branch_reads_valid_names_and_rejects_detached_head(repo: Path, slug: st worktree.branch(repo) -@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic"]) +@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic", "legacy"]) def test_start_creates_branch_worktree_and_task_file(repo: Path, branch: str | None, monkeypatch) -> None: side = branch or "side" git(repo, "push", "-q", "origin", f"HEAD:refs/heads/{side}") upstream = commit_on_origin(repo, "feature.txt") if branch == "symbolic": git(repo, "symbolic-ref", "refs/remotes/origin/main", "refs/heads/main") - elif branch: + elif branch and branch != "legacy": checkout = repo.parent / "single-branch" origin = (repo.parent / "origin.git").as_uri() git(repo, "clone", "-q", "--single-branch", "--branch", branch, origin, str(checkout)) assert not git(checkout, "for-each-ref", "refs/heads/main", "refs/remotes/origin/main").strip() repo = checkout - invoke, local_head = worktree._git, worktree.head(repo) - def interleave(path, *args, **kwargs): - result = invoke(path, *args, **kwargs) - if args[0] == "fetch": - git(path, "fetch", "-q", "origin", f"refs/heads/{side}") + invoke, local_head = worktree.run, worktree.head(repo) + def interleave(argv, **kwargs): + if branch == "legacy" and argv[:3] == ("git", "fetch", "--porcelain"): + return invoke(("git", "fetch", "--loopzero-unsupported"), **kwargs) + result = invoke(argv, **kwargs) + if argv[1] == "fetch" and result.exit_code == 0: + git(kwargs["cwd"], "fetch", "-q", "origin", f"refs/heads/{side}") return result - monkeypatch.setattr(worktree, "_git", interleave) + monkeypatch.setattr(worktree, "run", interleave) wt = worktree.start(repo, "my-task", "main") assert wt == repo / ".worktrees" / "my-task" assert (wt / "feature.txt").exists(), "fetched origin/main before branching" @@ -200,7 +202,8 @@ def test_start_explains_missing_origin(repo: Path, change: tuple[str, ...]) -> N def test_start_reports_git_failure_with_command(repo: Path) -> None: with pytest.raises(worktree.GitError) as info: worktree.start(repo, "nobase", "does-not-exist") - assert info.value.command[:2] == ("git", "ls-remote") + assert info.value.command[0] == "git" + assert info.value.command[1] in {"fetch", "ls-remote"} assert info.value.tail From faf90bda539de32089089fb84db3f79a0465cfde Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:07:10 +0100 Subject: [PATCH 2/3] Keep base resolution separate from worktree setup Architecture-Review: unchanged; base resolution still validates origin and materializes the exact commit before checkout. Co-Authored-By: Codex --- src/loopzero/worktree.py | 49 ++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index ef9b8c5a..c549c35b 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -216,21 +216,8 @@ def _ensure_excludes(repo_root: Path) -> None: return -def start(repo_root: Path, slug: str, base_branch: str) -> Path: - """Create a task worktree or finish initializing an interrupted start.""" - repo_root = Path(repo_root) - branch = branch_name(repo_root, slug) - wt = worktree_dir(repo_root, slug) - task = task_file(wt) - existing = wt.exists() - refusal = f"worktree directory already exists: {wt}" - if wt.is_symlink() or task.parent.is_symlink() or task.is_symlink() or task.exists(): - raise WorktreeError(refusal) - if not existing and _branch_exists(repo_root, branch): - raise WorktreeError(f"branch already exists: {branch}") - remote_ref = f"refs/heads/{base_branch}" - tracking = f"refs/remotes/origin/{base_branch}" - base = None +def _fetch_base(repo_root: Path, base_branch: str) -> str: + remote_ref, tracking = f"refs/heads/{base_branch}", f"refs/remotes/origin/{base_branch}" try: valid = run(("git", "check-ref-format", remote_ref), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30) symbolic = run(("git", "symbolic-ref", "-q", tracking), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30) @@ -242,15 +229,14 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: row = result.stdout.removesuffix("\n").rsplit(" ", 2) if result.exit_code or len(row) != 3 or row[-1] != tracking: raise GitError(fetch, result.stderr or result.stdout or f"origin did not report {remote_ref}") - base = row[1] - if base is None: - lookup = ("ls-remote", "--refs", "origin", remote_ref) - advertised = _git(repo_root, *lookup) - base, _, ref = advertised.partition("\t") - if ref != remote_ref: - raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}") - _git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base) - _git(repo_root, "update-ref", "--no-deref", tracking, base) + return row[1] + lookup = ("ls-remote", "--refs", "origin", remote_ref) + base, _, ref = _git(repo_root, *lookup).partition("\t") + if ref != remote_ref: + raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}") + _git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base) + _git(repo_root, "update-ref", "--no-deref", tracking, base) + return base except GitError: if "origin" not in _git(repo_root, "remote").splitlines(): raise WorktreeError( @@ -259,6 +245,21 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: "with `git remote rename origin`." ) from None raise + + +def start(repo_root: Path, slug: str, base_branch: str) -> Path: + """Create a task worktree or finish initializing an interrupted start.""" + repo_root = Path(repo_root) + branch = branch_name(repo_root, slug) + wt = worktree_dir(repo_root, slug) + task = task_file(wt) + existing = wt.exists() + refusal = f"worktree directory already exists: {wt}" + if wt.is_symlink() or task.parent.is_symlink() or task.is_symlink() or task.exists(): + raise WorktreeError(refusal) + if not existing and _branch_exists(repo_root, branch): + raise WorktreeError(f"branch already exists: {branch}") + base = _fetch_base(repo_root, base_branch) if existing: existing_head = _resumable_head(repo_root, wt, branch) if existing_head is None: From 3684a7ddeccdcae7e78c8e5545788f54b100c61c Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:10:18 +0100 Subject: [PATCH 3/3] Keep established fetch behavior for initialized submodules Architecture-Review: unchanged; worktrees with initialized submodules keep the previous exact-SHA fetch and its recursion. Co-Authored-By: Codex --- src/loopzero/worktree.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index c549c35b..afd93870 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -221,7 +221,8 @@ def _fetch_base(repo_root: Path, base_branch: str) -> str: try: valid = run(("git", "check-ref-format", remote_ref), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30) symbolic = run(("git", "symbolic-ref", "-q", tracking), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30) - if valid.exit_code == 0 and symbolic.exit_code == 1: + modules = repo_root / _git(repo_root, "rev-parse", "--git-path", "modules", preserve_whitespace=True) + if valid.exit_code == 0 and symbolic.exit_code == 1 and not modules.exists(): fetch = ("git", "fetch", "--porcelain", "--verbose", "--no-tags", "--no-prune", "--no-write-fetch-head", "--refmap=", "origin", f"+{remote_ref}:{tracking}") result = run(fetch, cwd=repo_root, env_allowlist=GIT_ENV, timeout=120) @@ -238,13 +239,12 @@ def _fetch_base(repo_root: Path, base_branch: str) -> str: _git(repo_root, "update-ref", "--no-deref", tracking, base) return base except GitError: - if "origin" not in _git(repo_root, "remote").splitlines(): - raise WorktreeError( - "no Git remote named 'origin'. Add it with `git remote add origin ` " - "using the URL for the repository in `[repo] name`, or rename that remote " - "with `git remote rename origin`." - ) from None - raise + if "origin" in _git(repo_root, "remote").splitlines(): + raise + raise WorktreeError( + "no Git remote named 'origin'. Add it with `git remote add origin ` using the URL for the " + "repository in `[repo] name`, or rename that remote with `git remote rename origin`." + ) from None def start(repo_root: Path, slug: str, base_branch: str) -> Path: