From 421a1eb4d2ac8d3a7bff9aa8359119b0649265b4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:45:14 +0100 Subject: [PATCH 1/2] Let Git clean up an interrupted worktree checkout Architecture-Review: unchanged; start still owns a single branch and linked worktree at the resolved base. Co-Authored-By: Codex --- src/loopzero/_proc.py | 5 +++++ src/loopzero/worktree.py | 41 +++++++++++++++++++++++++++++----------- tests/test_worktree.py | 25 +++++++++++++++++++++++- 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index a3a81567..3d3d3440 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -158,6 +158,7 @@ def run( encoding: str | None = None, preserve_newlines: bool = False, tail_chars: int | None = None, + graceful_interrupt: bool = False, ) -> Completed: """Run `argv` (never through a shell) with an environment stripped to the allowlist. @@ -194,6 +195,10 @@ def run( else: stdout, stderr = _read_output_tail(proc, tail_chars, timeout), "" except BaseException: + if graceful_interrupt and os.name == "posix": + with suppress(ProcessLookupError, subprocess.TimeoutExpired): + os.killpg(proc.pid, signal.SIGTERM) + proc.wait(timeout=5) if os.name == "posix": with suppress(ProcessLookupError): os.killpg(proc.pid, signal.SIGKILL) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 755f8e79..746f054e 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -14,7 +14,7 @@ from pathlib import Path from select import select -from loopzero._proc import build_env, run +from loopzero._proc import build_env, defer_sigterm, run GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK") _ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir") @@ -59,10 +59,10 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None: def _git( cwd: Path, *args: str, timeout: float = 120, - preserve_whitespace: bool = False, preserve_newlines: bool = False, + preserve_whitespace: bool = False, preserve_newlines: bool = False, graceful_interrupt: bool = False, ) -> str: argv = ("git", *args) - done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, + done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, graceful_interrupt=graceful_interrupt, preserve_newlines=preserve_newlines or preserve_whitespace, encoding=sys.getfilesystemencoding() if preserve_whitespace else None) if done.exit_code != 0: @@ -158,10 +158,12 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: ) from None raise _git(repo_root, "update-ref", "--no-deref", f"refs/remotes/origin/{base_branch}", base) + detached = not existing if existing: - existing_head = _resumable_head(repo_root, wt, branch) - if existing_head is None: + checkout = _resumable_checkout(repo_root, wt, branch) + if checkout is None: raise WorktreeError(refusal) + existing_head, detached = checkout if existing_head != base: raise WorktreeError( f"cannot resume start at {wt}: existing HEAD {existing_head} does not match " @@ -170,26 +172,43 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: _ensure_excludes(repo_root) if not existing: wt.parent.mkdir(parents=True, exist_ok=True) - _git(repo_root, "worktree", "add", "--quiet", "-b", branch, str(wt), base) + # Let Git clean up the interrupted checkout before creating the final branch. + _git(repo_root, "worktree", "add", "--quiet", "--detach", str(wt), base, graceful_interrupt=True) + if detached: + with defer_sigterm(): + _git(wt, "switch", "--quiet", "-c", branch, graceful_interrupt=True) _initialize_task(task, _TASK_TEMPLATE.format( title=title_from_slug(slug), base_branch=base_branch, base=base)) return wt -def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | None: +def _resumable_checkout(repo_root: Path, wt: Path, expected_branch: str) -> tuple[str, bool] | None: registered = _git(repo_root, "worktree", "list", "--porcelain", "-z").split("\0\0") path_field = f"worktree {wt.resolve()}" entry = next((item for item in registered if item.startswith(f"{path_field}\0")), "") fields = entry.split("\0") - if (len(fields) != 3 or fields[2] != f"branch refs/heads/{expected_branch}" + if (len(fields) != 3 or fields[2] not in ("detached", f"branch refs/heads/{expected_branch}") or not (wt / ".git").is_file()): return None - if _git(wt, *_ABSOLUTE_COMMON_DIR) != _git(repo_root, *_ABSOLUTE_COMMON_DIR) or branch(wt) != expected_branch: + if _git(wt, *_ABSOLUTE_COMMON_DIR) != _git(repo_root, *_ABSOLUTE_COMMON_DIR): + return None + detached = fields[2] == "detached" + if detached: + admin = Path(_git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True)) + try: + backlink = os.fsdecode((admin / "gitdir").read_bytes().removesuffix(b"\n")) + except OSError: + return None + if ((wt / ".git").is_symlink() or (admin / backlink).resolve() != (wt / ".git").resolve() + or _branch_exists(repo_root, expected_branch) + or _git(wt, "branch", "--show-current")): + return None + elif branch(wt) != expected_branch: return None current_head = head(wt) if fields[1] != f"HEAD {current_head}" or is_dirty(wt): return None - return current_head + return current_head, detached def _initialize_task(task: Path, text: str) -> None: @@ -244,7 +263,7 @@ def task_text(wt: Path) -> str: "or recreate the file using the handoff template at " "https://github.com/feder-positronics/loop-zero/blob/main/core/HANDOFF.md" ) - return task.read_text(encoding="utf-8") + return task.read_text() def base_sha(wt: Path) -> str: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 3b65536d..d27b6c94 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -2,7 +2,9 @@ from __future__ import annotations +import shlex import subprocess +import sys from pathlib import Path import pytest @@ -104,7 +106,7 @@ def test_start_retries_after_git_creates_worktree(repo, monkeypatch, state): def interrupt_after_add(cwd, *args, **kwargs): output = run_git(cwd, *args, **kwargs) - if args[:2] == ("worktree", "add"): + if args[:2] == ("switch", "--quiet"): raise KeyboardInterrupt return output @@ -334,3 +336,24 @@ def test_abandoned_worktree_guide(repo: Path, tmp_path: Path, state: str) -> Non assert git(repo, "ls-remote", "origin", "refs/heads/lz/abandoned").split() == [ head, "refs/heads/lz/abandoned" ] + + +def test_start_retries_after_git_checkout_interrupt(repo, tmp_path, monkeypatch): + (repo / ".gitattributes").write_text("README.md filter=paused\n") + (repo / "workflow.toml").write_text('[repo]\nname="owner/repo"\n') + git(repo, "add", ".gitattributes", "workflow.toml") + git(repo, "commit", "-qm", "add checkout barrier") + git(repo, "push", "-q", "origin", "main") + pid_file, entered = tmp_path / "starter.pid", tmp_path / "checkout-entered" + git(repo, "config", "filter.paused.smudge", + f'cat >/dev/null; : > {shlex.quote(str(entered))}; ' + f'kill -INT "$(cat {shlex.quote(str(pid_file))})"; exec sleep 30') + start = ("import os, sys; from pathlib import Path; from loopzero.cli import main; " + "Path(sys.argv[1]).write_text(str(os.getpid())); sys.exit(main(['start', 'paused']))") + command = [sys.executable, "-c", start, str(pid_file)] + first = subprocess.run(command, cwd=repo, capture_output=True, timeout=8, check=False) + assert entered.exists() and first.returncode in (-2, 130) + git(repo, "config", "--unset", "filter.paused.smudge") + resumed = subprocess.run(command, cwd=repo, capture_output=True, timeout=8, check=False) + assert resumed.returncode == 0, resumed.stderr + assert worktree.task_file(worktree.worktree_dir(repo, "paused")).is_file() From 53d35d2298510389dcb545831836a9a814a324db Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:49:40 +0100 Subject: [PATCH 2/2] Keep UTF-8 task reads and reap interrupted checkout processes Architecture-Review: unchanged; task handoffs continue to use UTF-8 and checkout signals still unwind before ownership is published. Co-Authored-By: Codex --- src/loopzero/_proc.py | 24 +++++++++++++----------- src/loopzero/worktree.py | 5 ++--- tests/test_worktree.py | 8 +++++--- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 3d3d3440..66a86568 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -195,17 +195,19 @@ def run( else: stdout, stderr = _read_output_tail(proc, tail_chars, timeout), "" except BaseException: - if graceful_interrupt and os.name == "posix": - with suppress(ProcessLookupError, subprocess.TimeoutExpired): - os.killpg(proc.pid, signal.SIGTERM) - proc.wait(timeout=5) - if os.name == "posix": - with suppress(ProcessLookupError): - os.killpg(proc.pid, signal.SIGKILL) - else: - proc.kill() - # Popen's context exit can skip reaping after KeyboardInterrupt. - proc.wait() + try: + if graceful_interrupt and os.name == "posix": + with suppress(ProcessLookupError, subprocess.TimeoutExpired): + os.killpg(proc.pid, signal.SIGTERM) + proc.wait(timeout=5) + finally: + if os.name == "posix": + with suppress(ProcessLookupError): + os.killpg(proc.pid, signal.SIGKILL) + else: + proc.kill() + # Popen's context exit can skip reaping after KeyboardInterrupt. + proc.wait() raise except FileNotFoundError as exc: if exc.filename == str(cwd): diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 746f054e..30eb39ce 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -200,8 +200,7 @@ def _resumable_checkout(repo_root: Path, wt: Path, expected_branch: str) -> tupl except OSError: return None if ((wt / ".git").is_symlink() or (admin / backlink).resolve() != (wt / ".git").resolve() - or _branch_exists(repo_root, expected_branch) - or _git(wt, "branch", "--show-current")): + or _branch_exists(repo_root, expected_branch)): return None elif branch(wt) != expected_branch: return None @@ -263,7 +262,7 @@ def task_text(wt: Path) -> str: "or recreate the file using the handoff template at " "https://github.com/feder-positronics/loop-zero/blob/main/core/HANDOFF.md" ) - return task.read_text() + return task.read_text(encoding="utf-8") def base_sha(wt: Path) -> str: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index d27b6c94..ce28f70b 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -98,7 +98,7 @@ def interleave(path, *args, **kwargs): assert "lz/my-task" in git(repo, "branch", "--list", "lz/my-task") -@pytest.mark.parametrize("state", ["same-base", "dirty", "moved-base"]) +@pytest.mark.parametrize("state", ["same-base", "dirty", "moved-base", "detached"]) def test_start_retries_after_git_creates_worktree(repo, monkeypatch, state): base = commit_on_origin(repo, "base-change") wt = repo / ".worktrees" / "my-task" @@ -106,7 +106,8 @@ def test_start_retries_after_git_creates_worktree(repo, monkeypatch, state): def interrupt_after_add(cwd, *args, **kwargs): output = run_git(cwd, *args, **kwargs) - if args[:2] == ("switch", "--quiet"): + interrupted_step = ("worktree", "add") if state == "detached" else ("switch", "--quiet") + if args[:2] == interrupted_step: raise KeyboardInterrupt return output @@ -115,7 +116,8 @@ def interrupt_after_add(cwd, *args, **kwargs): with pytest.raises(KeyboardInterrupt): worktree.start(repo, "my-task", "main") task = worktree.task_file(wt) - assert worktree.branch(wt) == "lz/my-task" and worktree.head(wt) == base + assert git(wt, "branch", "--show-current").strip() == ("" if state == "detached" else "lz/my-task") + assert worktree.head(wt) == base assert not task.exists() if state == "dirty": (wt / "untracked").write_text("work in progress")