From 6b64e2dc0d7d21624c91f8eddf4af1806e9f5c0d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:23:08 +0100 Subject: [PATCH 1/5] Preserve Git ref bytes and GitHub Unicode under legacy locales Architecture-Review: unchanged; filesystem paths and refs round-trip native Git bytes and GitHub keeps its UTF-8 transport. Co-Authored-By: Codex --- src/loopzero/cli.py | 18 ++++++++-------- src/loopzero/github.py | 4 ++-- src/loopzero/worktree.py | 19 ++++++++--------- tests/test_cli.py | 46 ++++++++++++++++++++++++++++++++++++++-- tests/test_github.py | 18 ++++++++-------- tests/test_worktree.py | 4 ++-- 6 files changed, 75 insertions(+), 34 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2ae035b3..ae0d1777 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -697,6 +697,7 @@ def cmd_pr(args: argparse.Namespace) -> int: existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None body = _pr_body(wt, head, config, existing) force_lease = False + git_branch = os.fsdecode(branch.encode("utf-8", "surrogateescape")) push = ["push", "-u", "origin"] if pr is not None and pr.state == "OPEN": known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}") @@ -706,13 +707,13 @@ def cmd_pr(args: argparse.Namespace) -> int: ) force_lease = pr.head_sha != head and not _is_ancestor(wt, pr.head_sha, head) if force_lease: - previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{branch}").splitlines() + previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{git_branch}").splitlines() if not any(_is_ancestor(wt, pr.head_sha, previous) for previous in previous_heads): raise CliError( f"PR head {pr.head_sha[:12]} is absent from this task branch's history; integrate it first" ) - push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}")) - push.append(branch) + push.extend(("--porcelain", f"--force-with-lease={git_branch}:{pr.head_sha}")) + push.append(git_branch) _require_push_target(wt, config.repo) _git_push(wt, push, force_lease=force_lease) if pr is not None and pr.state == "OPEN": @@ -1826,10 +1827,10 @@ def _cleanup_remote_refs(wt: Path, config: Config, branch: str, expected_head: s def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None: if not branch.startswith("lz/") or branch.count("/") != 1: return - ref = f"refs/remotes/origin/{branch}" + ref = os.fsdecode(f"refs/remotes/origin/{branch}".encode("utf-8", "surrogateescape")) try: _repo_root(wt) - current = _git(wt, "for-each-ref", "--format=%(objectname) %(refname) %(symref)", ref) + current = _git(wt, "for-each-ref", "--format=%(objectname) %(refname) %(symref)", ref, paths=True).rstrip(" ") if current == f"{expected_head} {ref}": _git(wt, "update-ref", "--no-deref", "-d", ref, expected_head) except (CliError, OSError, _proc.ProcTimeout) as exc: @@ -1872,10 +1873,9 @@ def cmd_status(args: argparse.Namespace) -> int: wt = _toplevel() config = _load_config(args, wt, pin_checks=True) branch, head = worktree.branch(wt), worktree.head(wt) - print(f"worktree: {wt}") - print(f"branch: {branch}") - print(f"head: {head}") - print(f"base: {config.base_branch}") + encoding = getattr(sys.stdout, "encoding", None) or "utf-8" + identity = f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}" + print(identity.encode(encoding, "backslashreplace").decode(encoding)) print(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}") pr = github.pr_for_branch(config.repo, branch) if pr is None: diff --git a/src/loopzero/github.py b/src/loopzero/github.py index ba49032d..2e61383f 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -375,7 +375,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, try: done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV, extra_env={"GH_TOKEN": selected} if selected else None, - timeout=_read_timeout(timeout, scoped=read_only)) + timeout=_read_timeout(timeout, scoped=read_only), encoding="utf-8") except ToolMissing as exc: raise GhMissing(argv, str(exc), token=selected, guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc @@ -1465,7 +1465,7 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool: current = _remote_branch_head(endpoint) if current != expected_head: return current is None - ref = f"refs/heads/{branch}" + ref = os.fsdecode(f"refs/heads/{branch}".encode("utf-8", "surrogateescape")) argv = ("git", "-c", "credential.helper=!gh auth git-credential", "push", f"--force-with-lease={ref}:{expected_head}", f"https://github.com/{repo}.git", f":{ref}") diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 4d38c4de..d6381b83 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -58,10 +58,8 @@ 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) -> str: argv = ("git", *args) if preserve_whitespace: done = run_git_paths(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout) @@ -262,7 +260,7 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No 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) != expected_branch: + if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or 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 @@ -292,11 +290,11 @@ def is_linked_checkout(wt: Path) -> bool: return git_dir != common_dir -def branch(wt: Path) -> str: +def branch(wt: Path, *, native: bool = False) -> str: name = _git(Path(wt), "branch", "--show-current", preserve_whitespace=True) if not name: raise WorktreeError("HEAD is detached. Switch to a branch and retry.") - return name + return name if native else os.fsencode(name).decode("utf-8", "surrogateescape") def task_text(wt: Path) -> str: @@ -343,7 +341,8 @@ def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None] ) as transaction: assert transaction.stdin is not None and transaction.stdout is not None try: - transaction.stdin.write(f"option no-deref\nverify {ref} {expected_head}\nprepare\n") + wire_ref = os.fsencode(ref).decode("utf-8", "surrogateescape") + transaction.stdin.write(f"option no-deref\nverify {wire_ref} {expected_head}\nprepare\n") transaction.stdin.flush() if not select([transaction.stdout], [], [], 30)[0]: raise GitError(argv, "timed out verifying the merged branch") @@ -379,11 +378,11 @@ def cleanup(wt: Path, expected_head: str) -> None: raise WorktreeError(f"no such worktree: {wt}") if head(wt) != expected_head: raise WorktreeError("local HEAD differs from merged PR head") - name = branch(wt) + name = branch(wt, native=True) gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)) ref = f"refs/heads/{name}" with _lock_verified_ref(wt, ref, expected_head): - if branch(wt) != name: + if branch(wt, native=True) != name: raise WorktreeError("local branch changed during merge cleanup") if is_dirty(wt): raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") diff --git a/tests/test_cli.py b/tests/test_cli.py index aab7989a..1437b78d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -187,8 +187,8 @@ def run(argv, *, cwd, env_allowlist, extra_env=None, **kwargs): @pytest.fixture -def wt(repo: Path, git_seed: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - path = cli.worktree.worktree_dir(repo, "t1") +def wt(repo: Path, git_seed: Path, monkeypatch: pytest.MonkeyPatch, request) -> Path: + path = cli.worktree.worktree_dir(repo, getattr(request, "param", "t1")) git(repo, "worktree", "add", "-q", str(path), "lz/t1") shutil.copytree(git_seed / ".loopzero", cli.worktree.task_file(path).parent) monkeypatch.chdir(path) @@ -1335,6 +1335,48 @@ def test_pr_uses_lease_for_rewritten_open_pr( assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == (old if case == "hook-fails" else head) +@pytest.mark.parametrize("wt", ["Łódź"], indirect=True) +def test_legacy_locale_status_reflog_push_and_cleanup(wt, repo, gh, monkeypatch, rewritten_branch): + branch, head = "lz/Łódź", head_of(wt) + ref, origin = f"refs/heads/{branch}", repo.parent / "origin.git" + git(wt, "branch", "-m", branch) + git(origin, "update-ref", ref, rewritten_branch) + assert git(wt, "remote", "get-url", "origin").strip() == str(origin) + monkeypatch.chdir(repo) + + def legacy_python(program): + return subprocess.run( + [sys.executable, "-X", "utf8=0", "-c", program], cwd=wt, + env={**os.environ, "LC_ALL": "C", "PYTHONCOERCECLOCALE": "0", "PYTHONIOENCODING": "ascii:strict"}, + capture_output=True, encoding="ascii", + ) + + gh.respond_pr_list([], branch=branch) + status = legacy_python("from loopzero.cli import main; raise SystemExit(main(['status']))") + assert status.returncode == 0, status.stderr + assert f"branch: {branch.encode('ascii', 'backslashreplace').decode('ascii')}" in status.stdout + assert any(pr_list_key(branch).removeprefix("api ") in call["argv"] for call in gh.calls) + + gh.respond(branch_history_key(branch=branch), []) + gh.respond_pr_list([pr_json(headRefOid=rewritten_branch)], branch=branch) + gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) + pushed = legacy_python(""" +from pathlib import Path +from loopzero import cli, worktree + +# The fixture verifies and uses a local bare remote. +cli._require_push_target = lambda *_: None +assert cli.main(["pr"]) == 0 +wt = Path.cwd() +head = worktree.head(wt) +cli._delete_tracking_ref(wt, worktree.branch(wt), head) +worktree.cleanup(wt, head) +""") + assert pushed.returncode == 0, pushed.stderr + assert git(origin, "rev-parse", ref).strip() == head + assert not wt.exists() and not git(repo, "branch", "-a", "--list", f"*{branch}") + + @pytest.mark.parametrize("shared_object", [False, True]) def test_pr_reports_rejected_lease_without_overwriting_remote( wt: Path, repo: Path, gh: FakeGh, tmp_path: Path, capsys, shared_object: bool, rewritten_branch diff --git a/tests/test_github.py b/tests/test_github.py index d92af20d..6bba5edf 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -4,6 +4,7 @@ import hashlib import json +import subprocess import sys from dataclasses import replace from pathlib import Path @@ -28,8 +29,8 @@ def pr_list_key(branch: str = "lz/t1", state: str = "open") -> str: return (f"api repos/{REPO}/pulls?state={state}&head={head}" "&sort=created&direction=desc&per_page=1") -def branch_history_key(page: int = 1) -> str: - head = quote(f"{REPO.split('/')[0]}:lz/t1", safe="") +def branch_history_key(page: int = 1, *, branch: str = "lz/t1") -> str: + head = quote(f"{REPO.split('/')[0]}:{branch}", safe="") return (f"api repos/{REPO}/pulls?state=closed&head={head}" f"&sort=created&direction=desc&per_page=100&page={page}") @@ -716,13 +717,12 @@ def test_pr_for_branch_missing_key_is_gh_error(gh: FakeGh) -> None: github.pr_for_branch(REPO, "lz/x") -def test_api_get_and_login_helpers(gh: FakeGh) -> None: - gh.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}}) - gh.respond("api repos/acme/widgets", {"default_branch": "main"}) - assert github.api_get("repos/acme/widgets") == {"default_branch": "main"} - assert gh.argv(0) == ["api", "repos/acme/widgets", "--include"] - assert github.login() == "bot-user" - gh.respond("api graphql viewer", {"data": {"viewer": {}}}) +def test_api_get_and_login_helpers(gh: FakeGh, monkeypatch) -> None: + monkeypatch.setattr(subprocess, "_text_encoding", lambda: "ascii") + gh.respond("api graphql viewer", '{"data":{"viewer":{"login":"Łódź"}}}', {"data": {"viewer": {}}}) + gh.respond("api repos/acme/widgets", '{"default_branch":"Łódź"}') + assert (github.api_get("repos/acme/widgets"), gh.argv(0)) == ({"default_branch": "Łódź"}, ["api", "repos/acme/widgets", "--include"]) + assert github.login() == "Łódź" with pytest.raises(github.GhError, match="no login"): github.login() diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 13db9bb1..0313aa4d 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -248,12 +248,12 @@ def test_task_helpers_errors(repo: Path) -> None: def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None: - wt, calls, real = worktree.start(repo, "done", "main"), [], worktree._git + wt, calls, real = worktree.start(repo, "zażółć", "main"), [], worktree._git monkeypatch.setattr(worktree, "_git", lambda d, *a, **k: calls.append((d, a)) or real(d, *a, **k)) (wt / f".loopzero/reviewer-output-{worktree.head(wt)[:12]}-primary.json").write_text("{}") worktree.cleanup(wt, worktree.head(wt)) # #439: no cleanup git runs in (or -C) the primary checkout assert calls and all(Path(d).resolve() != repo.resolve() and "-C" not in a for d, a in calls) - assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list") + assert not wt.exists() and not git(repo, "branch", "--list", "lz/zażółć") and "zażółć" not in git(repo, "worktree", "list") @pytest.mark.parametrize("file", ["scratch.txt", "local.env", ".loopzero/user-notes.md"]) From 098b63bbe1576bb9bb6339955e11c1d81a07c625 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:46:49 +0100 Subject: [PATCH 2/5] Reuse one legacy interpreter for status, push, and cleanup Co-Authored-By: Codex --- tests/test_cli.py | 30 +++++++++++++----------------- tests/test_worktree.py | 4 ++-- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 80a7ed50..eef5618d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1344,26 +1344,14 @@ def test_legacy_locale_status_reflog_push_and_cleanup(wt, repo, gh, monkeypatch, assert git(wt, "remote", "get-url", "origin").strip() == str(origin) monkeypatch.chdir(repo) - def legacy_python(program): - return subprocess.run( - [sys.executable, "-X", "utf8=0", "-c", program], cwd=wt, - env={**os.environ, "LC_ALL": "C", "PYTHONCOERCECLOCALE": "0", "PYTHONIOENCODING": "ascii:strict"}, - capture_output=True, encoding="ascii", - ) - - gh.respond_pr_list([], branch=branch) - status = legacy_python("from loopzero.cli import main; raise SystemExit(main(['status']))") - assert status.returncode == 0, status.stderr - assert f"branch: {branch.encode('ascii', 'backslashreplace').decode('ascii')}" in status.stdout - assert any(pr_list_key(branch).removeprefix("api ") in call["argv"] for call in gh.calls) - gh.respond(branch_history_key(branch=branch), []) - gh.respond_pr_list([pr_json(headRefOid=rewritten_branch)], branch=branch) + gh.respond_pr_list([], [pr_json(headRefOid=rewritten_branch)], branch=branch) gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) - pushed = legacy_python(""" + program = """ from pathlib import Path from loopzero import cli, worktree +assert cli.main(["status"]) == 0 # The fixture verifies and uses a local bare remote. cli._require_push_target = lambda *_: None assert cli.main(["pr"]) == 0 @@ -1371,8 +1359,16 @@ def legacy_python(program): head = worktree.head(wt) cli._delete_tracking_ref(wt, worktree.branch(wt), head) worktree.cleanup(wt, head) -""") - assert pushed.returncode == 0, pushed.stderr +""" + result = subprocess.run( + [sys.executable, "-X", "utf8=0", "-c", program], cwd=wt, + env={**os.environ, "LC_ALL": "C", "PYTHONCOERCECLOCALE": "0", "PYTHONIOENCODING": "ascii:strict"}, + capture_output=True, encoding="ascii", + ) + assert result.returncode == 0, result.stderr + escaped = branch.encode("ascii", "backslashreplace").decode("ascii") + assert f"branch: {escaped}" in result.stdout + assert any(pr_list_key(branch).removeprefix("api ") in call["argv"] for call in gh.calls) assert git(origin, "rev-parse", ref).strip() == head assert not wt.exists() and not git(repo, "branch", "-a", "--list", f"*{branch}") diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 0313aa4d..13db9bb1 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -248,12 +248,12 @@ def test_task_helpers_errors(repo: Path) -> None: def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None: - wt, calls, real = worktree.start(repo, "zażółć", "main"), [], worktree._git + wt, calls, real = worktree.start(repo, "done", "main"), [], worktree._git monkeypatch.setattr(worktree, "_git", lambda d, *a, **k: calls.append((d, a)) or real(d, *a, **k)) (wt / f".loopzero/reviewer-output-{worktree.head(wt)[:12]}-primary.json").write_text("{}") worktree.cleanup(wt, worktree.head(wt)) # #439: no cleanup git runs in (or -C) the primary checkout assert calls and all(Path(d).resolve() != repo.resolve() and "-C" not in a for d, a in calls) - assert not wt.exists() and not git(repo, "branch", "--list", "lz/zażółć") and "zażółć" not in git(repo, "worktree", "list") + 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"]) From ddd1ad4435b5b58c6f743b8e5709c6d11f85f8d1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:12:09 +0100 Subject: [PATCH 3/5] Share sandbox reporting and candidate transport test setup Co-Authored-By: Codex --- tests/test_candidate.py | 69 +++++++++++++--------------------- tests/test_sandbox.py | 83 +++++++++++++++-------------------------- 2 files changed, 56 insertions(+), 96 deletions(-) diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 91bd0bfc..d1f2b0d0 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -17,6 +17,7 @@ from itertools import cycle from os import environ from shutil import copytree +from unittest.mock import Mock import pytest @@ -158,10 +159,9 @@ def test_attests_nested_candidate_and_transitive_parent_sources() -> None: ) def test_rejects_forged_bot_or_prefix(mutation, message: str) -> None: candidate_event = event() - original_payloads = payloads(candidate_event) mutation(candidate_event) with pytest.raises(CandidateError, match=message): - run_attestation(candidate_event=candidate_event, github_payloads=original_payloads) + run_attestation(candidate_event=candidate_event, github_payloads=payloads(event())) @pytest.mark.parametrize("case,diagnostic", [ @@ -243,8 +243,21 @@ def commit(name, content): return git("rev-parse", "HEAD") popen = subprocess.Popen + observed_transport = set() def isolated_fetch(argv, **kwargs): + if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080" and "git" in argv: + env = kwargs["env"] + transport = {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} + if "fetch" in argv: + observed_transport.add("fetch") + assert env["HTTPS_PROXY"] == environ["HTTPS_PROXY"] + assert (env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"]) == ("1", "http.extraHeader") + header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ") + assert base64.b64decode(header) == b"x-access-token:secret-token" + else: + observed_transport.add("plumbing") + assert not transport & env.keys() assert not any(arg.startswith("--as") for arg in argv) # arm64 Git exceeds RLIMIT_AS if "fetch" in argv: assert "https://github.com/owner/repo.git" in argv @@ -294,47 +307,24 @@ def get(path): if base_branch != "main": run = partial(run, base_branch=base_branch) - return run_attestation(candidate_event, github_get=get, status_reads=[queue], - source_policy=policy, run=run) + sources = run_attestation(candidate_event, github_get=get, status_reads=[queue], + source_policy=policy, run=run) + if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080": + assert observed_transport == {"fetch", "plumbing"} + return sources return attest, git, commit, base, parent, source, candidate_sha @pytest.mark.parametrize("base_branch", ["main", "trunk"]) -def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch): +def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch, monkeypatch): + monkeypatch.setenv("HTTPS_PROXY", "http://proxy.invalid:8080") attest, _, _, _, _, source, _ = tree_candidate seen = [] assert attest(base_branch=base_branch, policy=lambda n, _: seen.append(n)) == expected_sources((102, source)) assert seen == [102] -def test_candidate_transport_configuration_is_scoped_to_fetch(tree_candidate, monkeypatch): - attest, _, _, _, _, source, _ = tree_candidate - popen = subprocess.Popen - seen = set() - proxy = "http://proxy.invalid:8080" - monkeypatch.setenv("HTTPS_PROXY", proxy) - - def check_environment(argv, **kwargs): - if "git" in argv: - env = kwargs["env"] - if "fetch" in argv: - seen.add("fetch") - assert env["HTTPS_PROXY"] == proxy - assert env["GIT_CONFIG_COUNT"] == "1" - assert env["GIT_CONFIG_KEY_0"] == "http.extraHeader" - header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ") - assert base64.b64decode(header) == b"x-access-token:secret-token" - else: - seen.add("non-fetch") - assert not {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} & env.keys() - return popen(argv, **kwargs) - - monkeypatch.setattr(subprocess, "Popen", check_environment) - assert attest() == expected_sources((102, source)) - assert seen == {"fetch", "non-fetch"} - - @pytest.mark.parametrize("mutation,diagnostic", [ ("replaced", "tree mismatch"), ("withdrawn", "tree mismatch"), ("extra", "tree mismatch|objects unavailable"), ("tampered", "tree mismatch"), ("missing", "objects unavailable"), @@ -403,10 +393,7 @@ def run(event, *, github_get, mergify_status, source_policy): @pytest.fixture(params=["loopzero", "intelflo"]) def candidate_policy(request): - - if request.param == "intelflo": - return request.getfixturevalue("intelflo_policy") - return candidate, attest_candidate + return request.getfixturevalue("intelflo_policy") if request.param == "intelflo" else (candidate, attest_candidate) @pytest.mark.parametrize("case", [ @@ -566,10 +553,7 @@ def test_nonrace_failure_does_not_retry(monkeypatch, failure, reread): live["batches"].pop(0) values["/repos/owner/repo/git/ref/heads/main"] = {"object": {"sha": "b" * 40}} - def mismatch(*_): - raise CandidateError("candidate tree mismatch") - - monkeypatch.setattr(candidate, "_verify_tree", mismatch) + monkeypatch.setattr(candidate, "_verify_tree", Mock(side_effect=CandidateError("candidate tree mismatch"))) def get(path): if path == "/apps/mergify": @@ -583,10 +567,7 @@ def get(path): return deepcopy(reread) return result - def policy(*_): - if failure == "policy": - raise expected - + policy = Mock(side_effect=expected if failure == "policy" else None) monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) with pytest.raises(CandidateError) as caught: run_attestation(github_get=get, status_reads=[live], source_policy=policy) diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 06a99753..851f17ae 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -148,11 +148,15 @@ def test_check_pipeline_verdict(git_repo, bwrap_log, monkeypatch, capsys, comman assert capsys.readouterr().out.splitlines()[-1] == ("FAIL" if stage_exit else "PASS") -def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): +@pytest.mark.parametrize("limited", [False, True], ids=["default", "constrained"]) +def test_bwrap_flags(git_repo, bwrap_log, monkeypatch, limited): + options = {"limits": ResourceLimits(memory_mb=64, file_mb=3)} if limited else {} + if limited: + monkeypatch.setattr(resource, "getrlimit", lambda _: (0, 32 * 1024 * 1024)) monkeypatch.setenv("LZ_KEEP", "kept") monkeypatch.setenv("LZ_DROP", "dropped") values = 'printf "%s\\n" "$PATH" "$LZ_KEEP" "${LZ_DROP-unset}" "$UV_CACHE_DIR" "$PYTHONDONTWRITEBYTECODE"' - (result,) = sandbox.run_checks(make_config(checks=(values,)), git_repo).results + (result,) = sandbox.run_checks(make_config(checks=(values,), **options), git_repo).results argv = argv_of(bwrap_log) head, tail = argv[: argv.index("--")], argv[argv.index("--") + 1 :] for flag in ("--die-with-parent", "--new-session", "--unshare-all", "--clearenv"): @@ -183,9 +187,11 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): assert sandbox.run_checks(make_config(), git_repo).dirty is False # /tmp tmpfs comes before the worktree bind so a worktree under /tmp stays visible. assert head.index("--tmpfs") < head.index(str(git_repo)) - assert tail == ["prlimit", f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", - f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", - "--", *sandbox.CHECK_SHELL, values] + limits = ["--as=33554432", "--fsize=3145728"] if limited else [ + f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", + f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", + ] + assert tail == ["prlimit", *limits, "--", *sandbox.CHECK_SHELL, values] @pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) @@ -272,17 +278,6 @@ def test_timeout_is_recorded_with_drained_output(git_repo, bwrap_log): assert len(result.tail.encode()) == 16 * 1024 -def test_configured_resource_limits_are_converted_to_bytes(git_repo, bwrap_log, monkeypatch): - limits = ResourceLimits(memory_mb=64, file_mb=3) - monkeypatch.setattr(resource, "getrlimit", lambda _: (0, 32 * 1024 * 1024)) - sandbox.run_checks(make_config(limits=limits), git_repo) - argv = argv_of(bwrap_log) - assert argv[argv.index("--") + 1:] == [ - "prlimit", "--as=33554432", "--fsize=3145728", - "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", "echo hello", - ] - - def test_linked_worktree_binds_common_git_dir(git_repo, bwrap_log, tmp_path): linked = tmp_path / "linked" git(git_repo, "worktree", "add", "-q", str(linked), "-b", "feature") @@ -323,10 +318,7 @@ def test_bwrap_missing_or_probe_failure(git_repo, fake_bin, fake_tool, monkeypat def test_probe_timeout_reports_only_the_timeout(git_repo, monkeypatch): - def timed_out(*args, **kwargs): - raise sandbox._proc.ProcTimeout("private probe diagnostic") - - monkeypatch.setattr(sandbox._proc, "run", timed_out) + monkeypatch.setattr(sandbox._proc, "run", Mock(side_effect=sandbox._proc.ProcTimeout("private probe diagnostic"))) with pytest.raises(sandbox.SandboxUnavailable) as info: sandbox.probe(make_config(), git_repo, ["bwrap", "--"]) @@ -428,12 +420,8 @@ def test_real_sandbox_denies_writes(self, git_repo): report = sandbox.run_checks(make_config(checks=(command,)), git_repo) assert report.results[0].exit_code != 0, report assert not escaped.exists() - checks = ( - "echo x > \"$HOME/ok\" && cat \"$HOME/ok\" && test ! -e /tmp/repo", - "test \"$(pwd)\" = \"$PWD\" && env | grep -c '^LZ_' ; true", - ) - report = sandbox.run_checks(make_config(checks=checks), git_repo) - assert [r.exit_code for r in report.results] == [0, 0], report + allowed = 'echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo' + assert sandbox.run_checks(make_config(checks=(allowed,)), git_repo).ok def test_real_sandbox_memory_limit_fails_check_and_preserves_report(self, git_repo): command = "/usr/bin/perl -e '$x = \"x\" x (64 * 1024 * 1024); print length($x)'" @@ -534,15 +522,16 @@ def wait(): return events, reporters, status, wait -@pytest.mark.parametrize("exit_code", [0, 7]) -def test_silent_stage_reports_live_metadata_then_completion( +@pytest.mark.parametrize("exit_code", [0, 7, 17], ids=["pass", "failure", "early-failure"]) +def test_stage_reports_metadata_then_completion( git_repo, bwrap_log, monkeypatch, heartbeat_log, exit_code ): import re events, _, status, wait_for_heartbeat = heartbeat_log + early = exit_code == 17 monkeypatch.setenv("LZ_KEEP", "credential-value") - command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' + command = "echo secret; exit 17" if early else f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' cfg = make_config(checks=(command, "echo next")) run_one = sandbox._run_one @@ -551,11 +540,18 @@ def run_stage(config, worktree, prefix, stage_command, timeout): wait_for_heartbeat() return run_one(config, worktree, prefix, stage_command, timeout) - monkeypatch.setattr(sandbox, "_run_one", run_stage) - report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status) + if early: + monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 30.0) + else: + monkeypatch.setattr(sandbox, "_run_one", run_stage) + report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=events.append if early else status) assert report.results[0].exit_code == exit_code - assert report.results[0].tail == "credential-value\nprivate-stderr" + assert report.results[0].tail == ("secret" if early else "credential-value\nprivate-stderr") statuses = [event for event in events if event not in cfg.checks] + if early: + assert len(statuses) == 1 and statuses[0].startswith("stage 1/2: exit 17 (") + assert len(report.results) == 1 and not report.ok + return heartbeats = [event for event in statuses if "running" in event] assert heartbeats and all(re.fullmatch( r"stage [12]/2: running \([0-9]+\.[0-9]s elapsed\)", event @@ -574,17 +570,6 @@ def run_stage(config, worktree, prefix, stage_command, timeout): assert statuses[-1].startswith("stage 2/2: exit 0") -def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch): - events = [] - report = sandbox.run_checks( - make_config(checks=("echo secret; exit 17", "echo never")), git_repo, - status=events.append, - ) - assert len(events) == 1 and events[0].startswith("stage 1/2: exit 17 (") - assert report.results[0].tail == "secret" and len(report.results) == 1 - assert not report.ok - - def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch, heartbeat_log): events, _, status, wait_for_heartbeat = heartbeat_log inject_check_timeout(monkeypatch, b"private\n", wait_for_heartbeat) @@ -803,10 +788,7 @@ def test_input_diagnostic_failure_does_not_block_dirty_check( git_repo, bwrap_log, fetched_base, monkeypatch, path, ): if path == "README.md": - def timed_out(*args): - raise sandbox._proc.ProcTimeout("input lookup timed out") - - monkeypatch.setattr(sandbox, "_input_blobs", timed_out) + monkeypatch.setattr(sandbox, "_input_blobs", Mock(side_effect=sandbox._proc.ProcTimeout("input lookup timed out"))) (git_repo / "README.md").write_text("dirty\n") command = 'test "$(cat README.md)" = dirty' config = make_config(checks=(command,), inputs={command: (path,)}) @@ -861,7 +843,6 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe command = f"echo '{marker}'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) original = sandbox.run_checks(config, git_repo) - assert original.ok legacy = replace(original.results[0], tail=f"{'x' * 20_000}\n{marker}") _save_report(git_repo, replace(original, results=(legacy,))) @@ -881,8 +862,7 @@ def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkey command = "echo stage ran" config = make_config(checks=(command,), inputs={command: ("README.md",)}) original = cache_check(config, clean=True, verify_reuse=True) - assert original.results[0].input_key - assert original.head == fetched_base + assert original.results[0].input_key and original.head == fetched_base run = sandbox._proc.run @@ -969,9 +949,8 @@ def write_runner(path, exit_code): write_runner(original, 0) runner.symlink_to(original) config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) - report = cache_check(config) + report = cache_check(config, verify_reuse=True) assert _current_check_report(git_repo, config, report.head) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head if change == "target": replacement = tmp_path / "runner-b" From 9bcf2c6322c996de4f88533c51615cc4ffbeef7c Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:34:36 +0100 Subject: [PATCH 4/5] Retain literal shell and stage assertions in deduped tests Co-Authored-By: Codex --- tests/test_candidate.py | 6 ++---- tests/test_sandbox.py | 10 ++++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/test_candidate.py b/tests/test_candidate.py index d1f2b0d0..b9d42e37 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -126,10 +126,8 @@ def run_attestation( run=attest_candidate, ): candidate_event = candidate_event or event() - reads, values = ( - cycle(status_reads or [status()]), - github_payloads or payloads(candidate_event), - ) + reads = cycle(status_reads or [status()]) + values = github_payloads or payloads(candidate_event) return run( candidate_event, github_get=github_get or (lambda path: deepcopy(values[path])), diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 851f17ae..3dea2ef0 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -191,7 +191,7 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch, limited): f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", ] - assert tail == ["prlimit", *limits, "--", *sandbox.CHECK_SHELL, values] + assert tail == ["prlimit", *limits, "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", values] @pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) @@ -420,8 +420,10 @@ def test_real_sandbox_denies_writes(self, git_repo): report = sandbox.run_checks(make_config(checks=(command,)), git_repo) assert report.results[0].exit_code != 0, report assert not escaped.exists() - allowed = 'echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo' - assert sandbox.run_checks(make_config(checks=(allowed,)), git_repo).ok + checks = ('echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo', + 'test "$(pwd)" = "$PWD" && env | grep -c "^LZ_" ; true') + report = sandbox.run_checks(make_config(checks=checks), git_repo) + assert [r.exit_code for r in report.results] == [0, 0], report def test_real_sandbox_memory_limit_fails_check_and_preserves_report(self, git_repo): command = "/usr/bin/perl -e '$x = \"x\" x (64 * 1024 * 1024); print length($x)'" @@ -852,7 +854,7 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe receipt = json.loads(receipt_path.read_text()) assert receipt["head"] == git(git_repo, "rev-parse", "HEAD").strip() [result] = receipt["results"] - assert result["reused_from"] == original.head + assert original.ok and result["reused_from"] == original.head assert marker in result["tail"].splitlines() assert len(result["tail"].encode("utf-8")) <= 16 * 1024 From 75c9f70b265445f6ccf2ae4ab27e0513c03a5f82 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:01:52 +0100 Subject: [PATCH 5/5] Keep all status output printable under legacy locales Architecture-Review: unchanged; display encoding preserves the existing status and resolution interfaces. Co-Authored-By: Codex --- src/loopzero/cli.py | 32 +++++++++++++++++--------------- tests/test_cli.py | 5 ++++- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 7c849fbe..5f903b3f 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1860,8 +1860,12 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None: print(f"warning: merged but tracking ref cleanup failed for {ref}: {exc}", file=sys.stderr) -def cmd_resolve(args: argparse.Namespace) -> int: +def _print_display(text: str) -> None: encoding = getattr(sys.stdout, "encoding", None) or "utf-8" + print(text.encode(encoding, "backslashreplace").decode(encoding)) + + +def cmd_resolve(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR pr = _require_pr(config, worktree.branch(wt)) if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base @@ -1869,10 +1873,10 @@ def cmd_resolve(args: argparse.Namespace) -> int: publishers = config.review_publishers or (github.login(),) if not args.finding: for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers): - print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}".encode(encoding, "backslashreplace").decode(encoding)) + _print_display(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}") return 0 finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers) - print(f"resolved {args.finding}: {finding.title}".encode(encoding, "backslashreplace").decode(encoding)) + _print_display(f"resolved {args.finding}: {finding.title}") try: with github.api_error_diagnostics(): remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers) @@ -1896,26 +1900,24 @@ def cmd_status(args: argparse.Namespace) -> int: wt = _toplevel() config = _load_config(args, wt, pin_checks=True) branch, head = worktree.branch(wt), worktree.head(wt) - encoding = getattr(sys.stdout, "encoding", None) or "utf-8" - identity = f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}" - print(identity.encode(encoding, "backslashreplace").decode(encoding)) - print(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}") + _print_display(f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}") + _print_display(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}") pr = github.pr_for_branch(config.repo, branch) if pr is None: - print("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)") + _print_display("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)") return 0 - print(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})") + _print_display(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})") reviews = _pr_reviews(config.repo, pr.number) markers = _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number) if markers: latest = markers[-1] - print(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})") + _print_display(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})") else: - print("review: none on this PR") + _print_display("review: none on this PR") readiness = _readiness(wt, config, pr, head, reviews, diagnostics=True) - print(f"ready: {'yes' if readiness.ready else 'no'}") + _print_display(f"ready: {'yes' if readiness.ready else 'no'}") for reason in readiness.reasons: - print(f" - {reason}") + _print_display(f" - {reason}") if config.merge_strategy == "mergify" and pr.state == "OPEN" and pr.head_sha == head: _print_mergify_status(config, pr, readiness) return 0 @@ -1933,9 +1935,9 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi label = "ejected" elif requested or (readiness.ready and report): label = "waiting for admission" - print(f"mergify: {label} ({queue})") + _print_display(f"mergify: {label} ({queue})") if label == "waiting for admission" and report: - print(f" Mergify report: {report}") + _print_display(f" Mergify report: {report}") def main(argv: list[str] | None = None) -> int: diff --git a/tests/test_cli.py b/tests/test_cli.py index 89ea9bcf..f98e8bdd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1354,12 +1354,14 @@ def test_legacy_locale_status_reflog_push_and_cleanup(wt, repo, gh, monkeypatch, monkeypatch.chdir(repo) gh.respond(branch_history_key(branch=branch), []) - gh.respond_pr_list([], [pr_json(headRefOid=rewritten_branch)], branch=branch) + gh.respond_pr_list([pr_json(headRefOid=rewritten_branch)], branch=branch) + gh.respond(reviews_key(), []) gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) program = """ from pathlib import Path from loopzero import cli, worktree +cli._readiness = lambda *_, **__: cli.github.Readiness(False, ("check \\u0141 is pending",)) assert cli.main(["status"]) == 0 # The fixture verifies and uses a local bare remote. cli._require_push_target = lambda *_: None @@ -1377,6 +1379,7 @@ def test_legacy_locale_status_reflog_push_and_cleanup(wt, repo, gh, monkeypatch, assert result.returncode == 0, result.stderr escaped = branch.encode("ascii", "backslashreplace").decode("ascii") assert f"branch: {escaped}" in result.stdout + assert r"check \u0141 is pending" in result.stdout assert any(pr_list_key(branch).removeprefix("api ") in call["argv"] for call in gh.calls) assert git(origin, "rev-parse", ref).strip() == head assert not wt.exists() and not git(repo, "branch", "-a", "--list", f"*{branch}")