From 09c806671d51f961be8c6367f93a1b60dc7edb79 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:25:28 +0100 Subject: [PATCH 1/4] Make an interrupted worktree checkout retryable Architecture-Review: unchanged; the existing Git path and task-state checks still guard checkout recovery. Co-Authored-By: Codex --- src/loopzero/_proc.py | 21 +++++++++++------ src/loopzero/worktree.py | 51 ++++++++++++++++++++++++++++++---------- tests/test_worktree.py | 33 ++++++++++++++++++++++---- 3 files changed, 81 insertions(+), 24 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index a7db463d..88104495 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -167,6 +167,7 @@ def run( encoding: str | None = None, preserve_newlines: bool = False, tail_chars: int | None = None, + graceful_interrupt: bool = False, pass_fds: tuple[int, ...] = (), ) -> Completed: """Run `argv` (never through a shell) with an environment stripped to the allowlist. @@ -198,13 +199,19 @@ def run( stdout, stderr = (proc.communicate(stdin, timeout=timeout) if tail_chars is None else (_read_output_tail(proc, tail_chars, timeout), "")) except BaseException: - 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 f71e1ded..2bc72155 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -16,7 +16,7 @@ from select import select from uuid import uuid4 -from loopzero._proc import build_env, run, run_git_paths +from loopzero._proc import build_env, defer_sigterm, run, run_git_paths 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,13 +59,16 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None: super().__init__(f"{' '.join(command)} failed: {tail.strip()[-400:]}") -def _git(cwd: Path, *args: str, timeout: float = 120, - preserve_whitespace: bool = False, preserve_newlines: bool = False) -> str: +def _git( + cwd: Path, *args: str, timeout: float = 120, + preserve_whitespace: bool = False, preserve_newlines: bool = False, graceful_interrupt: bool = False, +) -> str: argv = ("git", *args) if preserve_whitespace: done = run_git_paths(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout) else: - done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, preserve_newlines=preserve_newlines) + done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, + preserve_newlines=preserve_newlines, graceful_interrupt=graceful_interrupt) if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) return done.stdout if preserve_newlines or preserve_whitespace else done.stdout.strip() @@ -245,36 +248,58 @@ 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 " f"origin/{base_branch} at {base}; run loopzero start with a new slug" ) _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) + _prepare_checkout(repo_root, wt, branch, base, existing=existing, detached=detached) _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 _prepare_checkout(repo_root: Path, wt: Path, branch: str, base: str, *, existing: bool, detached: bool) -> None: + if not existing: + wt.parent.mkdir(parents=True, exist_ok=True) + # 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) + + +def _resumable_checkout(repo_root: Path, wt: Path, expected_branch: str) -> tuple[str, bool] | None: registered = _git(repo_root, "worktree", "list", "--porcelain", "-z", preserve_whitespace=True).split("\0\0") path_field = f"worktree {wt.resolve()}\0" fields = next((item for item in registered if item.startswith(path_field)), "").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 common = _git(repo_root, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) - if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or branch(wt, native=True) != expected_branch: + if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common: + 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)): + return None + elif branch(wt, native=True) != expected_branch: return None current_head = head(wt) - return current_head if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None + return (current_head, detached) if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None def _initialize_task(task: Path, text: str) -> None: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index b180a947..53d8f395 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 @@ -90,7 +92,7 @@ def interleave(path, *args, **kwargs): assert base_section.strip().splitlines() == [f"main @ {upstream}", f"Base: {upstream}"] -@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): repo = repo.rename(repo.with_name("repo\rreturn")) base = commit_on_origin(repo, "base-change") @@ -99,7 +101,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] == ("worktree", "add"): + interrupted_step = ("worktree", "add") if state == "detached" else ("switch", "--quiet") + if args[:2] == interrupted_step: raise KeyboardInterrupt return output @@ -108,9 +111,10 @@ 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), worktree.head(wt)) == ("lz/my-task", base) + current_branch = git(wt, "branch", "--show-current").strip() + assert (current_branch, worktree.head(wt)) == ("" if state == "detached" else "lz/my-task", base) assert not task.exists() - if state == "same-base": + if state in {"same-base", "detached"}: assert worktree.start(repo, "my-task", "main") == wt assert worktree.base_sha(wt) == base text = task.read_text() @@ -303,3 +307,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): + (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 5e2355d714f229d142d0994f1b975d6537f395e8 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:10:24 +0100 Subject: [PATCH 2/4] Allow ignored artifacts in verified merge cleanup Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 ++- src/loopzero/worktree.py | 30 +++++++++++++++++++----------- tests/test_worktree.py | 36 +++++++++++++++++++++++++++++++----- 3 files changed, 52 insertions(+), 17 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ebb2a162..c78f0dd5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -323,7 +323,8 @@ Git configuration so URL rewrites cannot change its destination. After confirmed remote deletion or absence, cleanup deletes the matching `origin/lz/` tracking ref only if it still points to the merged head. An already-merged PR can resume cleanup from its task worktree. Local removal -requires a clean worktree with no ignored user files. A Git ref lock keeps the +allows ignored files in a clean worktree and refuses to remove nested worktrees. +Git removal stays non-forced. A Git ref lock keeps the worktree at the merged PR head during removal. Cleanup then deletes the branch only if it still points at that head. Hosted eligibility trusts the configured publisher's projection and live identity, diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index aeaa60b2..b1728f0a 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -368,19 +368,27 @@ def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None] transaction.terminate() -def _require_no_ignored_user_files(wt: Path) -> None: - ignored = _git( - wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True - ) - for path in ignored.split("\0")[:-1]: - if not ((path in {".loopzero/task.md", ".loopzero/checks.json"} - or re.fullmatch(r"\.loopzero/review(?:er-output)?-[0-9a-f]{12}-(primary|delta)\.json", path)) - and not (wt / path).is_symlink()): - raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}") +def _require_no_nested_worktree(wt: Path, git_dir: Path) -> None: + root = wt.resolve() + records = _git(git_dir, f"--git-dir={git_dir}", "worktree", "list", "--porcelain", "-z", + preserve_whitespace=True) + for field in records.split("\0"): + if field.startswith("worktree "): + path = Path(field.removeprefix("worktree ")) + if path != root and path.is_relative_to(root): + raise WorktreeError(f"nested worktree {path}, refusing to remove: {wt}") + + def fail_scan(exc: OSError) -> None: + raise WorktreeError(f"could not inspect nested worktrees in {wt}: {exc}") from exc + + # Other repositories' linked worktrees are absent from this Git registry. + for path, _, files in root.walk(on_error=fail_scan): + if path != root and ".git" in files: + raise WorktreeError(f"nested Git worktree at {path}, refusing to remove: {wt}") def cleanup(wt: Path, expected_head: str) -> None: - """Remove a clean merged worktree and its branch if it has no local user files.""" + """Remove a clean verified worktree and its branch, preserving nested worktrees.""" wt = Path(wt).absolute() if not wt.exists(): raise WorktreeError(f"no such worktree: {wt}") @@ -394,7 +402,7 @@ def cleanup(wt: Path, expected_head: str) -> None: raise WorktreeError("local branch changed during merge cleanup") if is_dirty(wt): raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") - _require_no_ignored_user_files(wt) + _require_no_nested_worktree(wt, gd) _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z", preserve_whitespace=True) if f"branch {ref}" in worktrees.split("\0"): diff --git a/tests/test_worktree.py b/tests/test_worktree.py index b180a947..5fe21aa2 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -255,14 +255,40 @@ def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None: assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list") -@pytest.mark.parametrize("file", ["scratch.txt", "local.env", ".loopzero/user-notes.md"]) -def test_cleanup_preserves_user_files(repo: Path, file: str) -> None: +def test_cleanup_removes_ignored_artifacts(repo: Path) -> None: + (repo / ".git/info/exclude").write_text(".venv/\n") + wt = worktree.start(repo, "cached", "main") + (wt / ".venv").mkdir() + (wt / ".venv/dependency").write_text("generated") + worktree.cleanup(wt, worktree.head(wt)) + assert not wt.exists() + assert not git(repo, "branch", "--list", "lz/cached") + + +def test_cleanup_preserves_untracked_work_with_ignored_artifacts(repo: Path) -> None: (repo / ".git/info/exclude").write_text("local.env\n") wt = worktree.start(repo, "dirty", "main") - (wt / file).write_text("x") - with pytest.raises(worktree.WorktreeError, match="worktree is dirty" if file == "scratch.txt" else "ignored file"): + (wt / "local.env").write_text("ignored") + (wt / "scratch.txt").write_text("keep my work") + with pytest.raises(worktree.WorktreeError, match="worktree is dirty"): + worktree.cleanup(wt, worktree.head(wt)) + assert (wt / "scratch.txt").read_text() == "keep my work" + assert (wt / "local.env").read_text() == "ignored" + assert "lz/dirty" in git(repo, "branch", "--list", "lz/dirty") + + +@pytest.mark.parametrize("other_repo", [False, True]) +def test_cleanup_preserves_ignored_nested_worktrees(repo: Path, tmp_path: Path, other_repo: bool) -> None: + (repo / ".git/info/exclude").write_text("nested/\n") + wt = worktree.start(repo, "parent", "main") + source = init_git_repo(tmp_path / "other") if other_repo else repo + nested = wt / "nested" + git(source, "worktree", "add", "--detach", str(nested)) + assert not worktree.is_dirty(wt) + with pytest.raises(worktree.WorktreeError, match=r"nested (Git )?worktree"): worktree.cleanup(wt, worktree.head(wt)) - assert (wt / file).read_text() == "x" and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty") + assert (nested / ".git").is_file() + assert "lz/parent" in git(repo, "branch", "--list", "lz/parent") def test_cleanup_missing_worktree(repo: Path) -> None: From 842008542568e7e2061529c7b9e871aeb68216b0 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:18:24 +0100 Subject: [PATCH 3/4] Point work-issue at draft CI activation before triage Closes #1966 Co-Authored-By: Codex --- core/skills/work-issue/SKILL.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/skills/work-issue/SKILL.md b/core/skills/work-issue/SKILL.md index 4ec3d9ff..183ce438 100644 --- a/core/skills/work-issue/SKILL.md +++ b/core/skills/work-issue/SKILL.md @@ -21,7 +21,10 @@ Before publication, inspect the issue and links for its lifecycle blueprint and include required completion in the closing delivery. A child does not own its parent's blueprint. Recheck collisions, live acceptance, prior delivery and ownership before publication and merge. Reconcile changes before proceeding. -On approval, run readiness at the approved head and defer optional changes. +Defer optional changes after approval. With a current passing receipt, follow +[contract Step 5](../../CONTRACT.md#the-six-steps) at the approved head before +investigating missing or skipped draft checks. Use its scheduling guidance if +checks remain missing after activation. Before queueing, check the candidate merged with the current base against every repository size cap, including the combined effect of any batch. Verify the replacement is installed and works before retiring a deployment workaround. From 15473c731d5240e2caf03cc9fd1490f2bc82c2d0 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:19:02 +0100 Subject: [PATCH 4/4] Preserve ignored standalone Git checkouts during cleanup Architecture-Review: unchanged; the nested checkout safeguard applies to linked and standalone Git checkouts. Co-Authored-By: Codex --- src/loopzero/worktree.py | 6 +++--- tests/test_worktree.py | 13 ++++++++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index b1728f0a..767e2606 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -381,9 +381,9 @@ def _require_no_nested_worktree(wt: Path, git_dir: Path) -> None: def fail_scan(exc: OSError) -> None: raise WorktreeError(f"could not inspect nested worktrees in {wt}: {exc}") from exc - # Other repositories' linked worktrees are absent from this Git registry. - for path, _, files in root.walk(on_error=fail_scan): - if path != root and ".git" in files: + # Other repositories' checkouts are absent from this Git registry. + for path, directories, files in root.walk(on_error=fail_scan): + if path != root and (".git" in files or ".git" in directories): raise WorktreeError(f"nested Git worktree at {path}, refusing to remove: {wt}") diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 5fe21aa2..c6570d73 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -277,17 +277,20 @@ def test_cleanup_preserves_untracked_work_with_ignored_artifacts(repo: Path) -> assert "lz/dirty" in git(repo, "branch", "--list", "lz/dirty") -@pytest.mark.parametrize("other_repo", [False, True]) -def test_cleanup_preserves_ignored_nested_worktrees(repo: Path, tmp_path: Path, other_repo: bool) -> None: +@pytest.mark.parametrize("kind", ["same repo", "other repo", "clone"]) +def test_cleanup_preserves_ignored_nested_worktrees(repo: Path, tmp_path: Path, kind: str) -> None: (repo / ".git/info/exclude").write_text("nested/\n") wt = worktree.start(repo, "parent", "main") - source = init_git_repo(tmp_path / "other") if other_repo else repo nested = wt / "nested" - git(source, "worktree", "add", "--detach", str(nested)) + if kind == "clone": + git(repo, "clone", str(repo), str(nested)) + else: + source = init_git_repo(tmp_path / "other") if kind == "other repo" else repo + git(source, "worktree", "add", "--detach", str(nested)) assert not worktree.is_dirty(wt) with pytest.raises(worktree.WorktreeError, match=r"nested (Git )?worktree"): worktree.cleanup(wt, worktree.head(wt)) - assert (nested / ".git").is_file() + assert (nested / ".git").exists() assert "lz/parent" in git(repo, "branch", "--list", "lz/parent")