Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ Git configuration so URL rewrites cannot change its destination.
After confirmed remote deletion or absence, cleanup deletes the matching
`origin/lz/<slug>` 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 at the merged PR head.
requires a clean worktree at the merged PR head with no ignored user files.
Hosted eligibility trusts the configured publisher's projection and live identity,
state, head and latest ordering. It cannot recompute private raw or defeat a
coherent forgery by a trusted publisher/editor; native claims do not attest the
Expand Down
13 changes: 12 additions & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,23 @@ def merges_since(wt: Path, sha: str) -> list[str]:


def cleanup(wt: Path) -> None:
"""Remove the worktree and its branch. Refuses when the worktree is dirty."""
"""Remove the worktree and branch if there are no local user files."""
wt = Path(wt).absolute()
if not wt.exists():
raise WorktreeError(f"no such worktree: {wt}")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
ignored = _git(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Ignored build/dependency caches now block cleanup and are fully enumerated

ls-files --others --ignored without --directory walks into every ignored tree, such as .venv/, node_modules/ or __pycache__/. Two effects: (a) any developer who ran tests or installed dependencies in the task worktree now gets a refusal that names only the first file, and (b) the listing can be very large and slow under the git timeout. Refusing on these files matches the stated goal, but the warning only says "fix the cause" (cli.py:1162). Consider reporting the top-level ignored directory, or a count of ignored files, so the user can decide quickly. Also consider documenting that build caches have to be removed before cleanup.

wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True
)
for path in ignored.split("\0")[:-1]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Leftover atomic-write temp files permanently block cleanup

_write_json_atomically (cli.py:384) and _initialize_task (worktree.py:190) create temp files inside .loopzero/ named .checks.json-*, .review-…json-* and .task.md-*. If the process is killed before the temp file is unlinked, it stays behind as an unknown ignored file. Cleanup then refuses on every loopzero merge rerun until the user finds and deletes it by hand. Refusing is the safe choice, but these are loop-zero's own artifacts. Consider allowing those exact temp-name prefixes, or have the error message say that .loopzero/.*-XXXX temp files are safe to delete.

if (
(path in {".loopzero/task.md", ".loopzero/checks.json"}
or re.fullmatch(r"\.loopzero/review-[0-9a-f]{12}-(primary|delta)\.json", path))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Receipt filename allowlist duplicates the naming in cli._review_file and runners

The new regex \.loopzero/review-[0-9a-f]{12}-(primary|delta)\.json and the literals .loopzero/task.md and .loopzero/checks.json repeat naming that is also defined in three other places: cli._review_file (cli.py:1103), cli.CHECKS_FILE (cli.py:30) and the receipt-path strings in runners.py:672/1003. If a receipt name or review kind changes, cleanup will start refusing to remove every merged worktree. The only symptom is a warning, so the drift would go unnoticed. Smallest fix: define the receipt-name pattern once in worktree.py, next to task_file, and use it from cli/runners. Alternatively, add a test that builds the receipts through the real writers (cli._save_report / cli._save_review) and then calls worktree.cleanup, so drift fails CI.

and not (wt / path).is_symlink()
):
continue
raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}")
name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve()
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout
try:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4715,7 +4715,7 @@ def interrupt(staged, dest):


def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head):
(wt / ".loopzero" / "review-existing.json").write_text("{broken")
cli._review_file(wt, head, "primary").write_text("{broken")
arm_pr(gh, head, isDraft=False, state="MERGED")
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state="MERGED", head=head, sha="c" * 40))
ref = f"api repos/{REPO}/git/ref/heads/lz/t1"
Expand Down
14 changes: 7 additions & 7 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,11 @@ def interrupt_after_add(cwd, *args, **kwargs):

def test_start_excludes_worktrees_and_task_dir(repo: Path) -> None:
exclude = repo / ".git" / "info" / "exclude"
exclude.parent.mkdir(parents=True, exist_ok=True)
exclude.write_text("*.log") # no trailing newline on purpose
old_inode = exclude.stat().st_ino
wt = worktree.start(repo, "t1", "main")
assert exclude.stat().st_ino != old_inode
lines = exclude.read_text().splitlines()
assert lines == ["*.log", ".worktrees/", ".loopzero/"]
assert exclude.read_text().splitlines() == ["*.log", ".worktrees/", ".loopzero/"]
assert not worktree.is_dirty(wt), "fresh worktree with task.md is clean"
assert git(repo, "status", "--porcelain") == ""
installed = exclude.stat()
Expand Down Expand Up @@ -238,12 +236,14 @@ 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")


def test_cleanup_refuses_dirty(repo: Path) -> None:
@pytest.mark.parametrize("file", ["scratch.txt", "local.env", ".loopzero/user-notes.md"])
def test_cleanup_preserves_user_files(repo: Path, file: str) -> None:
(repo / ".git/info/exclude").write_text("local.env\n")
wt = worktree.start(repo, "dirty", "main")
(wt / "scratch.txt").write_text("x")
with pytest.raises(worktree.WorktreeError, match="dirty"):
(wt / file).write_text("x")
with pytest.raises(worktree.WorktreeError, match="worktree is dirty" if file == "scratch.txt" else "ignored file"):
worktree.cleanup(wt)
assert wt.exists() and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty")
assert (wt / file).read_text() == "x" and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty")


def test_cleanup_missing_worktree(repo: Path) -> None:
Expand Down
Loading