From 8c05177fec1af6eb5eb45929fca51e3eb915f100 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:57:30 +0100 Subject: [PATCH 1/4] Preserve Git checkout paths during merge cleanup Architecture-Review: unchanged; merge still verifies the PR and removes the invoking task worktree; Git path reads now retain the invoking path exactly. Co-Authored-By: Codex --- src/loopzero/cli.py | 16 ++++++++++------ src/loopzero/worktree.py | 9 ++++++--- tests/test_cli.py | 28 ++++++++++++++-------------- 3 files changed, 30 insertions(+), 23 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b4c64c5f..200ca848 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -70,11 +70,14 @@ def review_marker(head: str, kind: str, source: str = "model") -> str: # --------------------------------------------------------------------------- git / context -def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str: - done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout) +def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False) -> str: + done = _proc.run( + ["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, + preserve_newlines=paths, encoding=sys.getfilesystemencoding() if paths else None, + ) if done.exit_code != 0: raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}") - return done.stdout.strip() + return done.stdout if paths else done.stdout.strip() def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None: @@ -89,16 +92,17 @@ def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None: def _toplevel() -> Path: - return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel")) + return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True).removesuffix("\n")) def _repo_root(wt: Path) -> Path: """The verified primary checkout or bare repository owning this linked worktree.""" - first = _git(wt, "worktree", "list", "--porcelain", "-z").split("\0", 1)[0] + first = _git(wt, "worktree", "list", "--porcelain", "-z", paths=True).split("\0", 1)[0] if not first.startswith("worktree "): raise CliError("Git did not identify the primary worktree; refusing cleanup") root = Path(first.removeprefix("worktree ")) - common = Path(_git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve() + common = _git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True) + common = Path(common.removesuffix("\n")).resolve() if root.resolve() == wt.resolve() or common not in (root.resolve(), (root / ".git").resolve()): raise CliError("primary repository does not own this linked worktree; refusing cleanup") return root diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 008a7cde..edc51f1e 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -5,6 +5,7 @@ import errno import re import stat +import sys import tempfile from pathlib import Path from uuid import uuid4 @@ -57,10 +58,11 @@ def _git( ) -> str: argv = ("git", *args) done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, - preserve_newlines=preserve_newlines) + preserve_newlines=preserve_newlines, + encoding=sys.getfilesystemencoding() if preserve_newlines and preserve_whitespace else None) if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) - if preserve_newlines: + if preserve_newlines and not preserve_whitespace: return done.stdout return done.stdout.removesuffix("\n") if preserve_whitespace else done.stdout.strip() @@ -266,7 +268,8 @@ def cleanup(wt: Path) -> None: raise WorktreeError(f"no such worktree: {wt}") if is_dirty(wt): raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") - name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve() + common = _git(wt, "rev-parse", "--git-common-dir", preserve_whitespace=True, preserve_newlines=True) + name, gd = branch(wt), (wt / common).resolve() _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout try: _git(gd, f"--git-dir={gd}", "branch", "-D", name) diff --git a/tests/test_cli.py b/tests/test_cli.py index fda149c0..3f5a7a30 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3251,9 +3251,9 @@ def test_merged_bare_primary_cleans_only_clean_linked_worktree( if state == "dirty": (linked / "README.md").write_text("uncommitted work\n") original, cwds = cli._git, [] # #439: no cleanup git in a primary checkout - monkeypatch.setattr(cli, "_git", lambda cwd, *args: cwds.append(Path(cwd).resolve()) or ( + monkeypatch.setattr(cli, "_git", lambda cwd, *args, **kwargs: cwds.append(Path(cwd).resolve()) or ( f"worktree {repo}\0" if state == "wrong_primary" and args == ("worktree", "list", "--porcelain", "-z") - else original(cwd, *args))) + else original(cwd, *args, **kwargs))) code, out, err = run(capsys, "merge") assert {primary.resolve(), repo.resolve()}.isdisjoint(cwds) @@ -3841,21 +3841,21 @@ def test_review_and_ready_refuse_closed_pr(wt: Path, gh: FakeGh, capsys) -> None @pytest.mark.parametrize("changed", [False, True]) def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up( - wt: Path, repo: Path, gh: FakeGh, capsys, changed + wt: Path, repo: Path, gh: FakeGh, capsys, changed, monkeypatch ) -> None: - arm_pr(gh, head_of(wt), state="MERGED", isDraft=False) - gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='e' * 40)) - gh.respond("api -X", "") + collision, wt = wt, wt.with_name(wt.name + " ") + git(repo, "worktree", "move", str(collision), str(wt)) + git(repo, "worktree", "add", "-qb", "lz/other", str(collision), "lz/t1") + monkeypatch.chdir(wt) + for branch, number in (("lz/t1", 7), ("lz/other", 8)): + arm_pr(gh, head_of(wt), branch=branch, number=number, state="MERGED", isDraft=False) + gh.append(f"api repos/{REPO}/pulls/{number}", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='e' * 40)) code, out, err = run(capsys, "merge") + assert (code, collision.exists(), wt.exists()) == (int(changed), True, changed) if changed: - assert code == 1 and "head changed" in err and wt.exists() - assert all(c["argv"][:2] != ["api", "-X"] for c in gh.calls) - return - assert (code, err) == (0, "") - assert out.splitlines()[-1] == "e" * 40 - assert f"PR #7 was already merged as {'e' * 12}" in out and "e" * 40 in out - assert not wt.exists() - assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls) + assert "head changed" in err + else: + assert not err and f"PR #7 was already merged as {'e' * 12}" in out and out.endswith("e" * 40 + "\n") def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None: From 94e40dc19c8a240b014fc7539ef7aa9f5f9de13f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:49:40 +0100 Subject: [PATCH 2/4] Reject non-advancing GitHub review-thread cursors Architecture-Review: unchanged; review and readiness use the existing read errors when pagination cannot advance. Co-Authored-By: Codex --- src/loopzero/github.py | 15 +++++++++++++-- tests/test_github.py | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 874b79fa..f2ec21f6 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1044,11 +1044,21 @@ def open_findings(repo: str, number: int, """ +def _next_thread_cursor(page: dict, seen: set[str]) -> str: + cursor = page.get("endCursor") + if not isinstance(cursor, str) or not cursor.strip() or cursor in seen: + raise GhError(("gh", "api", "graphql"), "missing or repeated review thread cursor") + seen.add(cursor) + return cursor + + def _has_thread_reply(node: dict, reply: str) -> bool: page = node["comments"].get("pageInfo", {}) + seen: set[str] = set() while page.get("hasNextPage"): + cursor = _next_thread_cursor(page, seen) data = _gh_json("api", "graphql", "-f", f"query={_THREAD_REPLIES_QUERY}", - "-F", f"thread={node['id']}", "-f", f"after={page['endCursor']}") + "-F", f"thread={node['id']}", "-f", f"after={cursor}") try: comments = data["data"]["node"]["comments"] page = comments["pageInfo"] @@ -1137,6 +1147,7 @@ def _unresolved_threads(repo: str, number: int) -> list[dict]: def _review_threads(repo: str, number: int, *, include_resolved: bool = False) -> list[dict]: owner, name = repo.split("/", 1) after: str | None = None + seen: set[str] = set() found: list[dict] = [] while True: args = [ @@ -1153,7 +1164,7 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) - found += [node for node in nodes if include_resolved or not node.get("isResolved")] if not page["hasNextPage"]: return found - after = page["endCursor"] + after = _next_thread_cursor(page, seen) except (KeyError, TypeError) as exc: raise _not_found(number, exc) from exc diff --git a/tests/test_github.py b/tests/test_github.py index 3066bfb7..4e264dd5 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -870,6 +870,23 @@ def test_open_blocking_findings_paginates(gh: FakeGh) -> None: assert "after=C1" not in gh.argv(0) and "after=C1" in gh.argv(1) +@pytest.mark.parametrize("cursors", [(None,), ("C1", "C1"), ("C1", "C2", "C1")]) +def test_open_blocking_findings_rejects_invalid_cursor(gh: FakeGh, cursors) -> None: + gh.respond("api graphql", *(threads_json(has_next=True, cursor=c) for c in cursors)) + with pytest.raises(github.GhError, match="missing or repeated review thread cursor"): + github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) + assert len(gh.calls) == len(cursors) + + +def test_thread_reply_read_rejects_repeated_cursor(gh: FakeGh) -> None: + page = {"hasNextPage": True, "endCursor": "C1"} + gh.respond("api graphql", {"data": {"node": {"comments": {"pageInfo": page, "nodes": []}}}}) + node = {"id": "T1", "comments": {"pageInfo": page}} + with pytest.raises(github.GhError, match="missing or repeated review thread cursor"): + github._has_thread_reply(node, "reply") + assert len(gh.calls) == 1 and "after=C1" in gh.argv(0) + + # --- checks -------------------------------------------------------------------------------- From 8c5f9046b5bf5678e5b0107e477af888c6c587d7 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:52:14 +0100 Subject: [PATCH 3/4] Clean up GitHub API payloads when staging fails Architecture-Review: unchanged; GitHub keeps the existing request staging boundary and scopes the temporary file to the operation. Co-Authored-By: Codex --- src/loopzero/github.py | 18 ++++++------------ tests/test_gh_contract.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 874b79fa..99692359 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -496,13 +496,6 @@ def _paged(endpoint: str, key: str = "check_runs") -> list: return list(_iter_paged(endpoint, key)) -def _with_file(content: str) -> Path: - fd, name = tempfile.mkstemp(suffix=".loopzero", text=True) - with open(fd, "w", encoding="utf-8") as handle: - handle.write(content) - return Path(name) - - def api_get(endpoint: str) -> object: """`gh api ` parsed as JSON (None on an empty body).""" return _gh_json("api", endpoint) @@ -530,11 +523,12 @@ def _not_found(number: int, exc: Exception) -> GhError: def _api(endpoint: str, payload: dict, method: str = "POST", token: str | None = None) -> object: - path = _with_file(json.dumps(payload)) - try: - return _gh_json("api", endpoint, "--method", method, "--input", str(path), token=token) - finally: - path.unlink(missing_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", suffix=".loopzero", encoding="utf-8", delete_on_close=False + ) as handle: + handle.write(json.dumps(payload)) + handle.close() + return _gh_json("api", endpoint, "--method", method, "--input", handle.name, token=token) def merge_hold(number: int, labels: tuple[str, ...]) -> str | None: diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index 9f31898a..53182069 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -7,6 +7,7 @@ import re import shutil import subprocess +import sys from pathlib import Path import pytest @@ -27,6 +28,38 @@ REAL_GH = shutil.which("gh") +def test_api_removes_payload_when_staging_fails(tmp_path): + script = """ +import errno +import resource +import signal +import tempfile + +from loopzero import github + +def unexpected_dispatch(*args, **kwargs): + raise AssertionError("failed payload must not be dispatched") + +github._gh_json = unexpected_dispatch +tempfile.gettempdir() +signal.signal(signal.SIGXFSZ, signal.SIG_IGN) +_, hard = resource.getrlimit(resource.RLIMIT_FSIZE) +resource.setrlimit(resource.RLIMIT_FSIZE, (0, hard)) +try: + github._api("repos/example/project/issues", {"body": "synthetic"}) +except OSError as exc: + assert exc.errno == errno.EFBIG +else: + raise AssertionError("payload staging should fail") +""" + done = subprocess.run( + [sys.executable, "-c", script], env={**os.environ, "TMPDIR": str(tmp_path)}, + capture_output=True, text=True, check=False, + ) + assert done.returncode == 0, done.stderr + assert not list(tmp_path.glob("*.loopzero")) + + @pytest.fixture(scope="module") def captured_argv(tmp_path_factory: pytest.TempPathFactory) -> list[dict]: """Drive every public operation through production code and retain its exact argv.""" From 24105f1e851ad61469b4ef49a5997976d28a6597 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:02:52 +0100 Subject: [PATCH 4/4] Keep the staging failure regression within the test budget Co-Authored-By: Codex --- tests/test_gh_contract.py | 47 ++++++++++++++------------------------- 1 file changed, 17 insertions(+), 30 deletions(-) diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index 53182069..2869e0df 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -2,12 +2,15 @@ from __future__ import annotations +import errno import json import os import re +import resource import shutil +import signal import subprocess -import sys +import tempfile from pathlib import Path import pytest @@ -28,35 +31,19 @@ REAL_GH = shutil.which("gh") -def test_api_removes_payload_when_staging_fails(tmp_path): - script = """ -import errno -import resource -import signal -import tempfile - -from loopzero import github - -def unexpected_dispatch(*args, **kwargs): - raise AssertionError("failed payload must not be dispatched") - -github._gh_json = unexpected_dispatch -tempfile.gettempdir() -signal.signal(signal.SIGXFSZ, signal.SIG_IGN) -_, hard = resource.getrlimit(resource.RLIMIT_FSIZE) -resource.setrlimit(resource.RLIMIT_FSIZE, (0, hard)) -try: - github._api("repos/example/project/issues", {"body": "synthetic"}) -except OSError as exc: - assert exc.errno == errno.EFBIG -else: - raise AssertionError("payload staging should fail") -""" - done = subprocess.run( - [sys.executable, "-c", script], env={**os.environ, "TMPDIR": str(tmp_path)}, - capture_output=True, text=True, check=False, - ) - assert done.returncode == 0, done.stderr +def test_api_removes_payload_when_staging_fails(tmp_path, monkeypatch): + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + monkeypatch.setattr(github, "_gh_json", lambda *args, **kwargs: pytest.fail("unexpected dispatch")) + original_limit = resource.getrlimit(resource.RLIMIT_FSIZE) + handler = signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (0, original_limit[1])) + with pytest.raises(OSError) as failure: + github._api("repos/example/project/issues", {"body": "synthetic"}) + finally: + resource.setrlimit(resource.RLIMIT_FSIZE, original_limit) + signal.signal(signal.SIGXFSZ, handler) + assert failure.value.errno == errno.EFBIG assert not list(tmp_path.glob("*.loopzero"))