From 2eae6c8da5b5731059afc6e4cae65b96afc73910 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:14:35 +0100 Subject: [PATCH 01/10] Checkpoint recorded check stages in the check loop Co-Authored-By: Codex --- src/loopzero/sandbox.py | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 5edb2449..20c7b104 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -126,7 +126,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, @@ -137,19 +137,23 @@ 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: + 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 @@ -172,17 +176,6 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO INCOMPLETE_CHECK_COMMAND = "" -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 {} @@ -632,7 +625,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"], From b31c94b16784814457a51545b81e343f81d75ae5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:21:06 +0100 Subject: [PATCH 02/10] Revert "Checkpoint recorded check stages in the check loop" This reverts commit 2eae6c8da5b5731059afc6e4cae65b96afc73910. --- src/loopzero/sandbox.py | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 20c7b104..5edb2449 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -126,7 +126,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 ordinal, command in enumerate(commands, 1): + for index, command in enumerate(commands): if progress: progress(command) key = _input_key(config, worktree, command, "" if dirty else base, @@ -137,23 +137,19 @@ 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, ordinal, len(commands)): + with _stage_status(status, index + 1, 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 ordinal > len(preparations) or result.exit_code: + if index >= len(preparations) or result.exit_code: results.append(result) - 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)) + _checkpoint_success( + checkpoint, CheckReport(head, dirty, tuple(results), settings_sha256), + previous, commands[index + 1:], + ) if status: - status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} " + status(f"stage {index + 1}/{len(commands)}: exit {result.exit_code} " f"({result.duration_s:.1f}s)") if result.exit_code != 0: break @@ -176,6 +172,17 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO INCOMPLETE_CHECK_COMMAND = "" +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 {} @@ -625,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: + if local.dirty or not local.results: raise ValueError("Local fallback failed") return local.results[-1] return CheckResult(command, frame["exit_code"], frame["duration_s"], From 8916b1a6c0b4e9a4ed3ad384ede4eed49db76807 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:21:37 +0100 Subject: [PATCH 03/10] Keep the check loop within its branch budget Co-Authored-By: Codex --- src/loopzero/sandbox.py | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 5edb2449..56745094 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -126,7 +126,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, @@ -137,19 +137,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 @@ -172,17 +175,6 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO INCOMPLETE_CHECK_COMMAND = "" -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 {} @@ -632,7 +624,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"], From ecf426db3ccb39578f2a4a6f557c0fe5be29b043 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:37:26 +0100 Subject: [PATCH 04/10] Preserve carriage returns in Git checkout and metadata paths Architecture-Review: unchanged; Git still owns path discovery and the existing subprocess boundary now preserves its path records. Co-Authored-By: Codex --- src/loopzero/_proc.py | 15 ++++++++++++++- src/loopzero/cli.py | 2 +- src/loopzero/runners.py | 2 +- src/loopzero/sandbox.py | 2 +- tests/test_runners.py | 6 +++--- tests/test_worktree.py | 4 ++-- 6 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index a3a81567..7c767408 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -8,6 +8,7 @@ import selectors import signal import subprocess +import sys import threading import time from collections.abc import Mapping, Sequence @@ -146,6 +147,17 @@ def append(chunk: str) -> None: return suffix +def _output_mode(argv: list[str], preserve_newlines: bool, encoding: str | None) -> tuple[bool, str | None]: + # Git path records use filesystem bytes, including literal carriage returns. + if ( + argv == ["git", "worktree", "list", "--porcelain", "-z"] + or argv[:2] == ["git", "rev-parse"] + and {"--git-dir", "--git-common-dir", "--absolute-git-dir"}.intersection(argv[2:]) + ): + return True, encoding or sys.getfilesystemencoding() + return preserve_newlines, encoding + + def run( argv: Sequence[str], *, @@ -170,9 +182,10 @@ def run( newlines on completion and retaining them for timeout diagnostics. Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise. """ + argv = [str(part) for part in argv] + preserve_newlines, encoding = _output_mode(argv, preserve_newlines, encoding) if tail_chars is not None and (not merge_output or preserve_newlines or input is not None or tail_chars <= 0): raise ValueError("bounded tails require merged text output, no input and a positive length") - argv = [str(part) for part in argv] started = time.monotonic() raw_encoding = encoding or "utf-8" stdin = input.encode(raw_encoding) if preserve_newlines and input is not None else input diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f3c59c09..b9c25e62 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -766,7 +766,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).removesuffix("\n") fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY) try: try: diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 9f9cc584..71eaec56 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -314,7 +314,7 @@ 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 / raw.removesuffix("\n")).resolve() def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str) -> str: diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 5edb2449..404deaab 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -554,7 +554,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()) + raw = Path(_git(config, worktree, "rev-parse", flag).removesuffix("\n")) return (raw if raw.is_absolute() else worktree / raw).resolve() diff --git a/tests/test_runners.py b/tests/test_runners.py index e14ccdba..f0e9c584 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -612,7 +612,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"]) def test_linked_worktree_and_git_directory_are_read_only( git_repo: Path, tmp_path: Path, fake_bin: Path, monkeypatch, repo_name: str, ) -> None: @@ -626,6 +626,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 @@ -634,8 +635,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"]) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index b1323269..86ab2d18 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -97,6 +97,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 @@ -126,8 +127,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 From e4d6bc08625e86b68167502d14152ac7100fa784 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:42:00 +0100 Subject: [PATCH 05/10] Select the shared Git path reader explicitly Architecture-Review: unchanged; callers select the shared Git path reader through the existing subprocess boundary. Co-Authored-By: Codex --- src/loopzero/_proc.py | 19 +++++++------------ src/loopzero/cli.py | 12 +++++------- src/loopzero/runners.py | 13 +++++++------ src/loopzero/sandbox.py | 7 ++++--- src/loopzero/worktree.py | 25 ++++++++++++------------- tests/test_runners.py | 2 +- 6 files changed, 36 insertions(+), 42 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 7c767408..8a2aae39 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -13,7 +13,7 @@ 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 @@ -147,15 +147,11 @@ def append(chunk: str) -> None: return suffix -def _output_mode(argv: list[str], preserve_newlines: bool, encoding: str | None) -> tuple[bool, str | None]: - # Git path records use filesystem bytes, including literal carriage returns. - if ( - argv == ["git", "worktree", "list", "--porcelain", "-z"] - or argv[:2] == ["git", "rev-parse"] - and {"--git-dir", "--git-common-dir", "--absolute-git-dir"}.intersection(argv[2:]) - ): - return True, encoding or sys.getfilesystemencoding() - return preserve_newlines, encoding +def run_git_paths(argv: Sequence[str], *, cwd: Path, env_allowlist: Sequence[str], timeout: float) -> Completed: + """Read Git path records, removing the final LF from line-terminated output.""" + done = run(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=timeout, + preserve_newlines=True, encoding=sys.getfilesystemencoding()) + return replace(done, stdout=done.stdout.removesuffix("\n")) def run( @@ -182,10 +178,9 @@ def run( newlines on completion and retaining them for timeout diagnostics. Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise. """ - argv = [str(part) for part in argv] - preserve_newlines, encoding = _output_mode(argv, preserve_newlines, encoding) if tail_chars is not None and (not merge_output or preserve_newlines or input is not None or tail_chars <= 0): raise ValueError("bounded tails require merged text output, no input and a positive length") + argv = [str(part) for part in argv] started = time.monotonic() raw_encoding = encoding or "utf-8" stdin = input.encode(raw_encoding) if preserve_newlines and input is not None else input diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b9c25e62..743751fa 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -74,10 +74,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) -> 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, - ) + run = _proc.run_git_paths if paths else _proc.run + done = run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout) 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() @@ -107,7 +105,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: @@ -117,7 +115,7 @@ def _repo_root(wt: Path) -> Path: 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(common).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 @@ -766,7 +764,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", paths=True).removesuffix("\n") + git_dir = _git(wt, "rev-parse", "--absolute-git-dir", paths=True) fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY) try: try: diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 71eaec56..b170c0c2 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -313,12 +313,13 @@ 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.removesuffix("\n")).resolve() + raw = _review_git(cwd, env_allowlist, f"rev-parse {flag}", "rev-parse", flag, paths=True) + return (cwd / raw).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 @@ -326,8 +327,8 @@ def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str) - 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") + done = _proc.run_git_paths(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30) + paths = done.stdout.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(): diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 404deaab..910de28b 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -542,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: @@ -554,7 +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).removesuffix("\n")) + raw = Path(_git(config, worktree, "rev-parse", flag, paths=True)) return (raw if raw.is_absolute() else worktree / raw).resolve() diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 2ecc8cf3..9f2ec416 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -6,7 +6,6 @@ import re import stat import subprocess -import sys import tempfile from collections.abc import Iterator from contextlib import contextmanager @@ -14,7 +13,7 @@ from select import select from uuid import uuid4 -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") @@ -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: @@ -178,14 +176,15 @@ 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") + registered = _git(repo_root, "worktree", "list", "--porcelain", "-z", preserve_whitespace=True).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}" 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): @@ -225,8 +224,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 @@ -327,7 +326,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: diff --git a/tests/test_runners.py b/tests/test_runners.py index f0e9c584..d1d33cc8 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -612,7 +612,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", "repo\rcommon"]) +@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: From efbaf0bfd4e57abaf6e8d332769803c2a1796f38 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:46:02 +0100 Subject: [PATCH 06/10] Read trusted workflow Git metadata paths losslessly Architecture-Review: unchanged; trusted workflow reuse still checks the common Git directory and now uses the shared path reader. Co-Authored-By: Codex --- src/loopzero/config.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 81388cfa..74da0ae3 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -112,13 +112,13 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." 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"refs/remotes/origin/{branch}^{{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 From e837ed14c7b3b1f9f1f9246ec5b40cbbfc426479 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:17:29 +0100 Subject: [PATCH 07/10] Forward Git path output through checkpoint test doubles Co-Authored-By: Codex --- tests/test_cli.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index f679c279..9af6452e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -579,10 +579,10 @@ def dispatch(_config, _wt, _head, _base, command, _timeout): original_git = cli.sandbox._git - def check_git(config, path, *args): + def check_git(config, path, *args, **kwargs): if interrupt and cut == "final validation" 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) From 8356adb95e31df8299a7f028ee4fef26dada2066 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:25:03 +0100 Subject: [PATCH 08/10] Fit lossless path handling within the current source budget Architecture-Review: unchanged; Git path output still uses one shared reader and callers resolve the same directories. Co-Authored-By: Codex --- src/loopzero/cli.py | 3 +-- src/loopzero/runners.py | 8 +++----- src/loopzero/sandbox.py | 3 +-- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e4a53333..7cfbc51c 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -116,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).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 diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index c5a09173..d2196ea0 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -333,11 +333,9 @@ def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str, p 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_git_paths(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30) - paths = done.stdout.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() + 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) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index ac98c47c..3d004f53 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -561,8 +561,7 @@ def _git(config: Config, worktree: Path, *args: str, paths: bool = False) -> str def _git_dir(config: Config, worktree: Path, flag: str) -> Path: - raw = Path(_git(config, worktree, "rev-parse", flag, paths=True)) - 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: From 4556422681414f68136bafaeaeb83905e14e8559 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:26:00 +0100 Subject: [PATCH 09/10] Keep Git path handling flat against the source cap Architecture-Review: unchanged; worktree registration and review metadata checks retain their existing matching and fallback behavior. Co-Authored-By: Codex --- src/loopzero/runners.py | 3 +-- src/loopzero/worktree.py | 9 +++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index d2196ea0..ff8f8ae1 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -318,8 +318,7 @@ 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, paths=True) - return (cwd / raw).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, paths: bool = False) -> str: diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index d05d3470..fe421d6d 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -176,9 +176,8 @@ 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", preserve_whitespace=True).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") + 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 @@ -186,9 +185,7 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No 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: From a4be1202d78c4eda3eb538abe711a615e222b8a5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:28:56 +0100 Subject: [PATCH 10/10] Distinguish SIGINT and SIGTERM exit status Architecture-Review: unchanged; This correction documents existing cancellation behavior without changing delivery or process handling. Co-Authored-By: Codex --- core/CONTRACT.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 6390ec10..01dce362 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -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