Skip to content
Closed
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
3 changes: 2 additions & 1 deletion core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,8 @@ the failure. Exit 2 covers invalid arguments and sandbox unavailability in
`check` or fresh `review`.

Exit 3 means waiting or timeout. Review exits 4 when independent review is
unavailable and 5 when changes are requested. Interruption exits 130.
unavailable and 5 when changes are requested. SIGINT exits 130. SIGTERM is
re-raised, yielding shell status 143 and subprocess return code `-15`.

**Never pipe `loopzero`, even with pipefail**, because it can hide the verdict.
Redirect stdout and stderr (e.g. `loopzero check >check.log 2>&1`) and read the
Expand Down
11 changes: 10 additions & 1 deletion src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
import selectors
import signal
import subprocess
import sys
import threading
import time
from collections.abc import Mapping, Sequence
from contextlib import contextmanager, suppress
from dataclasses import dataclass
from dataclasses import dataclass, replace
from pathlib import Path

from .types import LoopZeroError
Expand Down Expand Up @@ -146,6 +147,14 @@ def append(chunk: str) -> None:
return suffix


def run_git_paths(argv: Sequence[str], *, cwd: Path, env_allowlist: Sequence[str], timeout: float,
extra_env: Mapping[str, str] | None = None) -> Completed:
"""Read Git path records, removing the final LF from line-terminated output."""
done = run(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=timeout, extra_env=extra_env,
preserve_newlines=True, encoding=sys.getfilesystemencoding())
return replace(done, stdout=done.stdout.removesuffix("\n"))


def run(
argv: Sequence[str],
*,
Expand Down
13 changes: 5 additions & 8 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,8 @@ def review_marker(head: str, kind: str, source: str = "model") -> str:

def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False,
extra_env: dict[str, str] | None = None) -> str:
done = _proc.run(
["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, extra_env=extra_env,
preserve_newlines=paths, encoding=sys.getfilesystemencoding() if paths else None,
)
run = _proc.run_git_paths if paths else _proc.run
done = run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, extra_env=extra_env)
if done.exit_code != 0:
raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}")
return done.stdout if paths else done.stdout.strip()
Expand Down Expand Up @@ -109,7 +107,7 @@ def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None:


def _toplevel() -> Path:
return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True).removesuffix("\n"))
return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True))


def _repo_root(wt: Path) -> Path:
Expand All @@ -118,8 +116,7 @@ def _repo_root(wt: Path) -> Path:
if not first.startswith("worktree "):
raise CliError("Git did not identify the primary worktree; refusing cleanup")
root = Path(first.removeprefix("worktree "))
common = _git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True)
common = Path(common.removesuffix("\n")).resolve()
common = Path(_git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True)).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
Expand Down Expand Up @@ -784,7 +781,7 @@ def _lock_review(run_review: Callable[[argparse.Namespace, Path, Config], int]):
@wraps(run_review)
def locked(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
git_dir = _git(wt, "rev-parse", "--absolute-git-dir")
git_dir = _git(wt, "rev-parse", "--absolute-git-dir", paths=True)
fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY)
try:
try:
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,13 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, re
if fetched.exit_code != 0:
raise ConfigError(f"could not refresh origin/{branch}. {hint}")
directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else []
resolved = _proc.run(
resolved = _proc.run_git_paths(
["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if resolved.exit_code != 0:
raise ConfigError(f"{source} has no remote-tracking base commit. {hint}")
common_dir, _, revision = resolved.stdout.rstrip("\n").rpartition("\n")
common_dir, _, revision = resolved.stdout.rpartition("\n")
if (previous is not None and previous.base_branch == branch and previous.trusted_base_revision == revision
and common_dir and not _has_replacement_refs(Path(common_dir))):
return previous, revision
Expand Down
18 changes: 8 additions & 10 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,25 +318,23 @@ def _review_config(family: str, binary: Path, ro_paths: tuple[str, ...]) -> Conf


def _git_dir(cwd: Path, flag: str, env_allowlist: tuple[str, ...]) -> Path:
raw = _review_git(cwd, env_allowlist, f"rev-parse {flag}", "rev-parse", flag)
return (cwd / raw.strip()).resolve()
return (cwd / _review_git(cwd, env_allowlist, f"rev-parse {flag}", "rev-parse", flag, paths=True)).resolve()


def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str) -> str:
done = _proc.run(["git", *args], cwd=cwd, env_allowlist=allowlist, timeout=30)
def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str, paths: bool = False) -> str:
run = _proc.run_git_paths if paths else _proc.run
done = run(["git", *args], cwd=cwd, env_allowlist=allowlist, timeout=30)
if done.exit_code != 0:
raise RunnerBadOutput(f"git {label} exited {done.exit_code}", _tail(done.stderr))
return done.stdout


def _git_dirs(cwd: Path, env_allowlist: tuple[str, ...]) -> tuple[Path, Path]:
argv = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir", "--git-dir"]
done = _proc.run(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30)
paths = done.stdout.removesuffix("\n").split("\n")
if done.exit_code == 0 and len(paths) == 2:
common_dir, git_dir = map(Path, paths)
if common_dir.is_absolute() and git_dir.is_absolute():
return common_dir.resolve(), git_dir.resolve()
done = _proc.run_git_paths(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30)
paths = [Path(path) for path in done.stdout.split("\n")]
if done.exit_code == 0 and len(paths) == 2 and all(path.is_absolute() for path in paths):
return paths[0].resolve(), paths[1].resolve()
# A path may contain a newline, which makes the combined output ambiguous.
return _git_dir(cwd, "--git-common-dir", env_allowlist), _git_dir(cwd, "--git-dir", env_allowlist)

Expand Down
44 changes: 18 additions & 26 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
missing, preparations = (None, ()) if _resolved else _preflight(config, worktree)
results = [missing] if missing else []
commands = () if missing else (*preparations, *config.checks)
for index, command in enumerate(commands):
for ordinal, command in enumerate(commands, 1):
if progress:
progress(command)
key = _input_key(config, worktree, command, "" if dirty else base,
Expand All @@ -138,19 +138,22 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
if status:
status(f"reused {(old.reused_from or head)[:8]}")
else:
with _stage_status(status, index + 1, len(commands)):
with _stage_status(status, ordinal, len(commands)):
result = (_dispatch_one(config, worktree, head, base, command, timeout)
if config.check_runner else _run_one(config, worktree, prefix, command, timeout))
if key:
result = replace(result, input_key=key)
if index >= len(preparations) or result.exit_code:
result = replace(result, input_key=key)
if ordinal > len(preparations) or result.exit_code:
results.append(result)
_checkpoint_success(
checkpoint, CheckReport(head, dirty, tuple(results), settings_sha256),
previous, commands[index + 1:],
)
if checkpoint is not None and result.input_key and result.exit_code == 0:
# The receipt stays nonpassing until final validation.
incomplete = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "")
unvisited = (
previous[stage] for stage in commands[ordinal:] if stage in previous
)
checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete),
settings_sha256))
if status:
status(f"stage {index + 1}/{len(commands)}: exit {result.exit_code} "
status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} "
f"({result.duration_s:.1f}s)")
if result.exit_code != 0:
break
Expand All @@ -173,17 +176,6 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
INCOMPLETE_CHECK_COMMAND = "<checks incomplete>"


def _checkpoint_success(checkpoint: Callable[[CheckReport], None] | None,
report: CheckReport, previous: dict[str, CheckResult],
remaining: tuple[str, ...]) -> None:
stage = report.results[-1]
if checkpoint is not None and stage.input_key and stage.exit_code == 0:
# Even the last stage leaves a nonpassing receipt until final validation.
incomplete = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "")
unvisited = tuple(previous[command] for command in remaining if command in previous)
checkpoint(replace(report, results=(*report.results, *unvisited, incomplete)))


def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
if _git(config, worktree, "ls-files", "--", ".loopzero"):
return {}
Expand Down Expand Up @@ -550,8 +542,9 @@ def bwrap_argv(
return argv


def _git(config: Config, worktree: Path, *args: str) -> str:
done = _proc.run(
def _git(config: Config, worktree: Path, *args: str, paths: bool = False) -> str:
run = _proc.run_git_paths if paths else _proc.run
done = run(
["git", *args], cwd=worktree, env_allowlist=config.env_allowlist, timeout=GIT_TIMEOUT
)
if done.exit_code != 0:
Expand All @@ -562,8 +555,7 @@ def _git(config: Config, worktree: Path, *args: str) -> str:


def _git_dir(config: Config, worktree: Path, flag: str) -> Path:
raw = Path(_git(config, worktree, "rev-parse", flag).strip())
return (raw if raw.is_absolute() else worktree / raw).resolve()
return (worktree / _git(config, worktree, "rev-parse", flag, paths=True)).resolve()


def _stage_unchanged(config: Config, worktree: Path, head: str) -> bool:
Expand Down Expand Up @@ -640,7 +632,7 @@ def _dispatch_one(
raise ValueError("Worktree changed before fallback")
local = run_checks(replace(config, check_runner=(), checks=(command,), inputs={}),
worktree, timeout=timeout, _resolved=True)
if local.dirty or not local.results:
if local.dirty:
raise ValueError("Local fallback failed")
return local.results[-1]
return CheckResult(command, frame["exit_code"], frame["duration_s"],
Expand Down
34 changes: 15 additions & 19 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@
import os
import re
import subprocess
import sys
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager, suppress
from pathlib import Path
from select import select

from loopzero._proc import build_env, run
from loopzero._proc import build_env, 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")
Expand Down Expand Up @@ -62,14 +61,13 @@ def _git(
preserve_whitespace: bool = False, preserve_newlines: bool = False,
) -> str:
argv = ("git", *args)
done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout,
preserve_newlines=preserve_newlines or preserve_whitespace,
encoding=sys.getfilesystemencoding() if preserve_whitespace else None)
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)
if done.exit_code != 0:
raise GitError(argv, done.stderr or done.stdout)
if preserve_newlines and not preserve_whitespace:
return done.stdout
return done.stdout.removesuffix("\n") if preserve_whitespace else done.stdout.strip()
return done.stdout if preserve_newlines or preserve_whitespace else done.stdout.strip()


def branch_name(repo_root: Path, slug: str) -> str:
Expand Down Expand Up @@ -177,19 +175,17 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path:


def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | 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")
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}"
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:
common = _git(repo_root, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or 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 if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None


def _initialize_task(task: Path, text: str) -> None:
Expand Down Expand Up @@ -224,8 +220,8 @@ def head(wt: Path) -> str:


def is_linked_checkout(wt: Path) -> bool:
git_dir = _git(wt, "rev-parse", "--absolute-git-dir")
common_dir = _git(wt, *_ABSOLUTE_COMMON_DIR)
git_dir = _git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True)
common_dir = _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)
return git_dir != common_dir


Expand Down Expand Up @@ -326,7 +322,7 @@ def cleanup(wt: Path, expected_head: str) -> None:
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
_require_no_ignored_user_files(wt)
_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")
worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z", preserve_whitespace=True)
if f"branch {ref}" in worktrees.split("\0"):
raise WorktreeError(f"local branch {name!r} is checked out in another worktree")
try:
Expand Down
4 changes: 2 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,10 +725,10 @@ def dispatch(_config, _wt, _head, _base, command, _timeout):
raise KeyboardInterrupt
return CheckResult(command, 0, 0.0, "")

def check_git(config, path, *args):
def check_git(config, path, *args, **kwargs):
if interrupt and len(calls) == 2 and args == ("rev-parse", "HEAD"):
raise KeyboardInterrupt
return original_git(config, path, *args)
return original_git(config, path, *args, **kwargs)

monkeypatch.setattr(cli, "_context", context)
monkeypatch.setattr(cli.sandbox, "_dispatch_one", dispatch)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ def test_reviewer_does_not_bind_missing_auth_paths(repo, fake_bin, tmp_path, fak
assert all(destination == SANDBOX_HOME for _, destination in _pairs(_bwrap_argv(fake_bwrap), "--bind"))


@pytest.mark.parametrize("repo_name", ["repo", "repo\ncommon"], ids=["ordinary", "newline"])
@pytest.mark.parametrize("repo_name", ["repo", "repo\ncommon", "repo\rcommon"], ids=["ordinary", "newline", "carriage-return"])
def test_linked_worktree_and_git_directory_are_read_only(
git_repo: Path, tmp_path: Path, fake_bin: Path, monkeypatch, repo_name: str,
) -> None:
Expand All @@ -624,6 +624,7 @@ def test_linked_worktree_and_git_directory_are_read_only(

def record(config, cwd, home, common_dir, git_dir, **kwargs):
assert (common_dir, git_dir) == (common, common / "worktrees" / linked.name)
assert sandbox._git_dir(config, cwd, "--git-common-dir") == common
argv = bwrap_argv(config, cwd, home, common_dir, git_dir, **kwargs)
captured.extend(argv)
return argv
Expand All @@ -632,8 +633,7 @@ def record(config, cwd, home, common_dir, git_dir, **kwargs):
_fake_review(fake_bin, "claude")
assert _review("claude", linked).verdict == "approve"
binds = _pairs(captured, "--ro-bind")
assert (str(linked.resolve()),) * 2 in binds
assert (str(common),) * 2 in binds
assert all((str(path),) * 2 in binds for path in (linked.resolve(), common))


@pytest.mark.parametrize("family", ["claude", "codex"])
Expand Down
4 changes: 2 additions & 2 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ def interleave(path, *args, **kwargs):

@pytest.mark.parametrize("state", ["same-base", "dirty", "moved-base"])
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")
wt = repo / ".worktrees" / "my-task"
run_git = worktree._git
Expand Down Expand Up @@ -127,8 +128,7 @@ def interrupt_after_add(cwd, *args, **kwargs):
worktree.start(repo, "my-task", "main")
for detail in (base, "origin/main", current_base, "new slug"):
assert detail in str(error.value)
assert worktree.branch(wt) == "lz/my-task"
assert worktree.head(wt) == base
assert (worktree.branch(wt), worktree.head(wt)) == ("lz/my-task", base)
assert not task.exists()
return

Expand Down
Loading