From d42a3989b1509445b19cbb59951306b488a93268 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:36:16 +0100 Subject: [PATCH 1/3] Preserve UTF-8 across GitHub, Git and task reads Architecture-Review: unchanged; machine text is decoded at existing process and file boundaries without changing delivery state or authority. Co-Authored-By: Codex --- src/loopzero/cli.py | 10 +++++----- src/loopzero/github.py | 2 +- src/loopzero/worktree.py | 4 ++-- tests/test_cli.py | 26 +++++++++++++------------- tests/test_github.py | 14 +++++++------- tests/test_worktree.py | 4 ++-- 6 files changed, 30 insertions(+), 30 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 48a64159..b06eb8e0 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -71,7 +71,8 @@ def review_marker(head: str, kind: str, source: str = "model") -> str: def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str: - done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout) + done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, + encoding=sys.getfilesystemencoding(), preserve_newlines=True) if done.exit_code != 0: raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}") return done.stdout.strip() @@ -1692,10 +1693,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}") + if isinstance(sys.stdout, io.TextIOWrapper): + sys.stdout.reconfigure(errors="backslashreplace") + print(f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}") 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 45fb8ce2..57347984 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -338,7 +338,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) if scope else timeout) + timeout=_read_timeout(timeout) if scope else timeout, 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 diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 008a7cde..84162a4e 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -57,7 +57,7 @@ def _git( ) -> str: argv = ("git", *args) done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, - preserve_newlines=preserve_newlines) + encoding="utf-8", preserve_newlines=preserve_newlines) if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) if preserve_newlines: @@ -235,7 +235,7 @@ def task_text(wt: Path) -> str: "or recreate the file using the handoff template at " "https://github.com/feder-positronics/loop-zero/blob/main/core/HANDOFF.md" ) - return task.read_text() + return task.read_text(encoding="utf-8") def base_sha(wt: Path) -> str: diff --git a/tests/test_cli.py b/tests/test_cli.py index b5536583..8ebbfa6d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -173,8 +173,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) @@ -1060,12 +1060,12 @@ def test_pr_replaces_closed_never_merged_pr(wt: Path, gh: FakeGh, capsys) -> Non assert run(capsys, "pr") == (0, URL + "\n", "") -def test_pr_title_prefers_human_heading(wt: Path, gh: FakeGh, capsys) -> None: - task = wt / ".loopzero" / "task.md" - task.write_text("## Objective\nx\n\n# Add the feature flag\n") - assert cli._pr_title(wt, "lz/t1") == "Add the feature flag" - task.write_text("## Objective\nonly sections\n") - assert cli._pr_title(wt, "lz/t1") == "lz/t1" +def test_pr_title_prefers_human_heading(wt: Path) -> None: + for heading, title in [("# Dodaj Łódź", "Dodaj Łódź"), ("only sections", "lz/t1")]: + (wt / ".loopzero/task.md").write_text(f"## Objective\nx\n\n{heading}\n", encoding="utf-8") + command = "from loopzero.cli import _pr_title; from pathlib import Path; print(ascii(_pr_title(Path.cwd(), 'lz/t1')))" + env = {**os.environ, "LC_ALL": "C", "PYTHONCOERCECLOCALE": "0"} + assert subprocess.check_output([sys.executable, "-X", "utf8=0", "-c", command], env=env, text=True).strip() == ascii(title) @pytest.mark.parametrize("name,value", [ @@ -3686,13 +3686,13 @@ def test_status_explains_detached_head(wt: Path, capsys) -> None: assert err == "loopzero status: HEAD is detached. Switch to a branch and retry.\n" -def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls) -> None: - head = head_of(wt) +@pytest.mark.parametrize("wt", ["Łódź"], indirect=True) +def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls, head, monkeypatch) -> None: + monkeypatch.setattr(subprocess, "_text_encoding", lambda: "ascii") gh.respond_pr_list([]) code, out, _ = run(capsys, "status") - assert code == 0 - assert "branch: lz/t1" in out and f"head: {head}" in out and "dirty: no" in out - assert "pr: none (commit changes and pass `loopzero check` before `loopzero pr`)" in out + assert (code, out.splitlines()[:3]) == (0, [f"worktree: {wt}", "branch: lz/t1", f"head: {head}"]) + assert "dirty: no" in out and "pr: none (commit changes and pass `loopzero check` before `loopzero pr`)" in out arm_approved_pr_with_check_result(gh, head, wt, "pending") (wt / "scratch").write_text("x") git_calls.clear() diff --git a/tests/test_github.py b/tests/test_github.py index c961f43e..16937c05 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 @@ -719,13 +720,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 230adc02..7a63f29e 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -34,10 +34,10 @@ def commit_on_origin(repo: Path, name: str) -> str: return git(clone, "rev-parse", "HEAD").strip() -def test_branch_preserves_unicode_whitespace(repo: Path) -> None: +def test_branch_preserves_unicode_whitespace(repo: Path, monkeypatch) -> None: name = worktree.branch_name(repo, "zażółć\u00a0") git(repo, "switch", "-c", name) - + monkeypatch.setattr(subprocess, "_text_encoding", lambda: "ascii") assert worktree.branch(repo) == "lz/zażółć\u00a0" From 3aec211b421c0f0ba392c846cc89b8b5357bc6ea Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:40:38 +0100 Subject: [PATCH 2/3] Round-trip native Git paths and refs under legacy locales Architecture-Review: unchanged; local Git commands retain native filesystem bytes and GitHub branch names use UTF-8. Co-Authored-By: Codex --- src/loopzero/cli.py | 6 +++--- src/loopzero/worktree.py | 18 +++++++++--------- tests/test_worktree.py | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b06eb8e0..adaea575 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -79,8 +79,8 @@ def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str: def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None: - done = _proc.run(["git", *args], cwd=wt, env_allowlist=worktree.GIT_ENV, - extra_env={"LC_ALL": "C"}, timeout=PUSH_TIMEOUT) + argv = ["git", *(os.fsdecode(arg.encode("utf-8", "surrogateescape")) for arg in args)] + done = _proc.run(argv, cwd=wt, env_allowlist=worktree.GIT_ENV, extra_env={"LC_ALL": "C"}, timeout=PUSH_TIMEOUT) if done.exit_code != 0: detail = _proc.tail(done.stderr)[-2000:] if force_lease and any(line.startswith("!\t") and line.endswith("\t[rejected] (stale info)") @@ -1650,7 +1650,7 @@ 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) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 84162a4e..1a08fd88 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -3,10 +3,12 @@ from __future__ import annotations import errno +import os import re import stat import tempfile from pathlib import Path +from sys import getfilesystemencoding from uuid import uuid4 from loopzero._proc import run @@ -51,13 +53,11 @@ 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) done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, - encoding="utf-8", preserve_newlines=preserve_newlines) + encoding=None if preserve_newlines else getfilesystemencoding(), preserve_newlines=True) if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) if preserve_newlines: @@ -175,7 +175,7 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No or not (wt / ".git").is_file()): return None common_dir = ("rev-parse", "--path-format=absolute", "--git-common-dir") - if _git(wt, *common_dir) != _git(repo_root, *common_dir) or branch(wt) != expected_branch: + if _git(wt, *common_dir) != _git(repo_root, *common_dir) or branch(wt, native=True) != expected_branch: return None current_head = head(wt) if fields[1] != f"HEAD {current_head}" or is_dirty(wt): @@ -220,11 +220,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: @@ -266,7 +266,7 @@ def cleanup(wt: Path) -> None: raise WorktreeError(f"no such worktree: {wt}") if is_dirty(wt): raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") - name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve() + name, gd = branch(wt, native=True), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve() _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout try: _git(gd, f"--git-dir={gd}", "branch", "-D", name) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 7a63f29e..bf7c7402 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -231,11 +231,11 @@ 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)) worktree.cleanup(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") def test_cleanup_refuses_dirty(repo: Path) -> None: From 7f671a4978b80d726b527468a651bed36459e896 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:51:56 +0100 Subject: [PATCH 3/3] Keep guarded remote ref deletion byte-exact Architecture-Review: unchanged; the existing force-with-lease still guards deletion with the same remote SHA. Co-Authored-By: Codex --- src/loopzero/github.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 57347984..4235f72a 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1440,7 +1440,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}")