From 267938c4bf9c252c6b298127bc4d1541a56c0a78 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:12:59 +0100 Subject: [PATCH 1/3] Drop transient Codex launcher paths before running loop-zero Architecture-Review: unchanged; existing account selection and sandbox environment boundaries are preserved. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 4 ++++ tests/test_ai_accounts.py | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index b7871bae..75828558 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -1085,6 +1085,10 @@ def cmd_shim(name: str, args: list[str]) -> int: dirs = os.environ.get("PATH", "").split(os.pathsep) shim_dirs = [d for d in dirs if is_shim_dir(d)] rest = [d for d in dirs if d not in shim_dirs] + if name == "loopzero": + # Codex's transient launcher shims are hidden in the check sandbox. + arg0 = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "tmp/arg0-linux" + rest = [d for d in rest if Path(d).parent != arg0 or not Path(d).name.startswith("codex-arg0")] real = next((str(c) for d in rest if (c := Path(d or ".") / name).is_file() and os.access(c, os.X_OK)), None) if real is None: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 05b5ef02..9db4ab49 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -455,7 +455,10 @@ def test_shim_prefers_verified_codex_only_for_loopzero(helper, tmp_path, monkeyp codex = pin / 'codex' codex.write_text('#!/bin/sh\nexit 0\n') codex.chmod(0o755 if pin_state != 'nonexecutable' else 0o644) - monkeypatch.setenv('PATH', f'{shims}:{binaries}') + codex_home = tmp_path / 'codex-home' + arg0 = codex_home / 'tmp/arg0-linux/codex-arg0ABC123' + monkeypatch.setenv('CODEX_HOME', str(codex_home)) + monkeypatch.setenv('PATH', f'{shims}:{arg0}:{binaries}') monkeypatch.setattr(helper.sys, 'argv', [str(shims / name)]) calls = [] monkeypatch.setattr(helper.os, 'execve', lambda *args: calls.append(args)) @@ -471,7 +474,7 @@ def test_shim_prefers_verified_codex_only_for_loopzero(helper, tmp_path, monkeyp expected.insert(0, str(pin)) assert env['PATH'].split(helper.os.pathsep) == expected else: - assert env['PATH'] == f'{shims}:{binaries}' + assert env['PATH'] == f'{shims}:{arg0}:{binaries}' @pytest.mark.parametrize('provider,email,shown', [ From 028e9d058d2e649a73d4e69e82669764d12d205e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:14:21 +0100 Subject: [PATCH 2/3] Reject invalid UTF-8 in trusted workflow blobs Architecture-Review: unchanged; Git still resolves the same trusted ref. Decoder failures report the existing source label. Co-Authored-By: Codex --- src/loopzero/config.py | 6 ++++-- tests/test_cli.py | 18 +++++++++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 6563d33b..81388cfa 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -124,12 +124,14 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu return previous, revision shown = _proc.run( ["git", "show", f"{revision}:workflow.toml"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, + cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, preserve_newlines=True, encoding="utf-8", ) if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") try: - data = tomllib.loads(shown.stdout) + data = tomllib.loads(shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8")) + except UnicodeDecodeError as exc: + raise ConfigError(f"{source}: {exc}") from exc except tomllib.TOMLDecodeError as exc: raise ConfigError(f"{source}: invalid TOML: {exc}. {hint}") from None try: diff --git a/tests/test_cli.py b/tests/test_cli.py index 81376235..f9470c70 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -695,15 +695,23 @@ def test_config_flag_overrides_root(wt: Path, tmp_path: Path, capsys, bootstrap) assert out.startswith("checks are unpinned because --config was provided\n") -def test_invalid_workflow_utf8_names_file(wt, capsys): - filename = "broken-workflow.toml" - (wt / filename).write_bytes(bytes([255])) - args = ["--config", filename, "status"] +@pytest.mark.parametrize("trusted", [False, True]) +def test_invalid_workflow_utf8_names_file(wt, capsys, trusted): + data = WORKFLOW.encode().replace(b"echo ok", b"echo \xff") + filename = "origin/main:workflow.toml" if trusted else "broken-workflow.toml" + if trusted: + (wt / "workflow.toml").write_bytes(data) + git(wt, "add", "workflow.toml") + git(wt, "commit", "-qm", "invalid workflow bytes") + git(wt, "update-ref", "refs/remotes/origin/main", "HEAD") + else: + (wt / filename).write_bytes(data) + args = ["status"] if trusted else ["--config", filename, "status"] code, _, err = run(capsys, *args) assert code == 1 - assert filename in err and "utf-8" in err.lower() and "position 0" in err + assert filename in err and "utf-8" in err.lower() and "position " in err assert "Traceback" not in err From 9527586085d0355fa0f7bc2901c495f094df8082 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:15:45 +0100 Subject: [PATCH 3/3] Bind PR publication to its destination and task branch history Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 5 ++++- src/loopzero/cli.py | 19 ++++++++++++++++++- tests/test_cli.py | 39 ++++++++++++++++++++++++++++++--------- 3 files changed, 52 insertions(+), 11 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 462bb23c..deef845e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -94,7 +94,10 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con newer duplicate exists. If the head commit cannot prove completion, the pull-list fallback also checks earlier commits of the branch. Failed, malformed, repeated or truncated history blocks publication, with a limit of - 100 pages. An unfinished branch creates or refreshes a draft PR. + 100 pages. An unfinished branch creates or refreshes a draft PR. Publication + checks that every effective origin push URL targets the configured GitHub + repository. A leased rewrite also requires the PR head in the task branch's + local history. 4. `review` publishes one native review of the exact authored SHA. The contract's [review budget](../core/CONTRACT.md#review-budget) owns contributor exclusion, the PR-wide cap of one primary and one delta across head rewrites, and the diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index a0890dd2..715ed33e 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -80,6 +80,18 @@ def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str: return done.stdout.strip() +def _require_push_target(wt: Path, repo: str) -> None: + urls = _git(wt, "remote", "get-url", "--push", "--all", "origin").splitlines() + github_url = re.compile( + r"(?:https://(?:[a-z0-9._~%:+-]+@)?github\.com(?::443)?/" + r"|git@github\.com:|ssh://git@github\.com(?::22)?/|ssh://git@ssh\.github\.com:443/)" + + re.escape(repo) + r"(?:\.git)?/?", + re.IGNORECASE | re.ASCII, + ) + if not urls or any(not github_url.fullmatch(url) for url in urls): + raise CliError(f"origin push URL does not target {repo}; correct the Git remote before running pr") + + 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) @@ -666,7 +678,6 @@ def cmd_pr(args: argparse.Namespace) -> int: force_lease = False push = ["push", "-u", "origin"] if pr is not None and pr.state == "OPEN": - # Only rewrite history this worktree has seen; an unknown remote head is someone else's. known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) if known.exit_code != 0: @@ -675,8 +686,14 @@ def cmd_pr(args: argparse.Namespace) -> int: ) force_lease = not _is_ancestor(wt, pr.head_sha, head) if force_lease: + previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{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) + _require_push_target(wt, config.repo) _git_push(wt, push, force_lease=force_lease) if pr is not None and pr.state == "OPEN": with _lock_task_state(wt): diff --git a/tests/test_cli.py b/tests/test_cli.py index 81376235..cafe7cea 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -108,7 +108,14 @@ def repo(git_seed: Path, tmp_path: Path, fake_tool, monkeypatch, request: pytest shutil.copytree(git_seed / seed_checkout, checkout) origin = shutil.copytree(git_seed / "origin.git", tmp_path / "origin.git") git(checkout, "remote", "set-url", "origin", str(origin)) - run_command = github.run + run_command, git_command = github.run, cli._git + + def local_push_url(cwd, *args, **kwargs): + output = git_command(cwd, *args, **kwargs) + if args == ("remote", "get-url", "--push", "--all", "origin"): + return "\n".join(f"https://github.com/{REPO}.git" if url == str(origin) else url + for url in output.splitlines()) + return output def local_transport(argv, **kwargs): if argv[0] == "git" and "push" in argv: @@ -120,6 +127,7 @@ def local_transport(argv, **kwargs): return run_command(argv, **kwargs) monkeypatch.setattr(github, "run", local_transport) + monkeypatch.setattr(cli, "_git", local_push_url) fake_tool("bwrap", FAKE_BWRAP.format(log=tmp_path / "bwrap.argv")) return checkout @@ -1194,16 +1202,20 @@ def test_pr_aborts_on_missing_remote_head(wt, gh, fake_tool, tmp_path, capsys): assert all("--method" not in call["argv"] for call in gh.calls) -@pytest.mark.parametrize("hook_fails", [False, True]) +@pytest.mark.parametrize("case", ["rewrite", "hook-fails", "wrong-destination"]) def test_pr_uses_lease_for_rewritten_open_pr( - wt: Path, repo: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, hook_fails: bool + wt: Path, repo: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, case: str ) -> None: old = head_of(wt) git(wt, "push", "-q", "-u", "origin", "lz/t1") git(wt, "reset", "-q", "--soft", "HEAD~1") git(wt, "commit", "-q", "-m", "rebased feature") head = head_of(wt) - if hook_fails: + origin, other = repo.parent / "origin.git", tmp_path / "other.git" + if case == "wrong-destination": + shutil.copytree(origin, other) + git(wt, "remote", "set-url", "--push", "origin", str(other)) + if case == "hook-fails": hook = fake_tool("pre-push", "echo 'lint failed in widget.py' >&2\nexit 1\n") git(wt, "config", "core.hooksPath", str(hook.parent)) pushes = trace_pushes(fake_tool, tmp_path) @@ -1212,7 +1224,12 @@ def test_pr_uses_lease_for_rewritten_open_pr( code, out, err = run(capsys, "pr") - if hook_fails: + if case == "wrong-destination": + assert (code, out) == (1, "") and "origin push URL does not target" in err + assert not pushes.exists() + assert all(git(remote, "rev-parse", "refs/heads/lz/t1").strip() == old for remote in (origin, other)) + return + if case == "hook-fails": assert (code, out) == (1, "") and "lint failed in widget.py" in err assert "remote moved" not in err and all("PATCH" not in call["argv"] for call in gh.calls) else: @@ -1220,11 +1237,12 @@ def test_pr_uses_lease_for_rewritten_open_pr( assert pushes.read_text().strip() == ( f"push -u origin --porcelain --force-with-lease=lz/t1:{old} lz/t1" ) - assert git(repo.parent / "origin.git", "rev-parse", "refs/heads/lz/t1").strip() == (old if hook_fails else head) + assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == (old if case == "hook-fails" else head) +@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 + wt: Path, repo: Path, gh: FakeGh, tmp_path: Path, capsys, shared_object: bool ) -> None: old = head_of(wt) origin = repo.parent / "origin.git" @@ -1237,11 +1255,14 @@ def test_pr_reports_rejected_lease_without_overwriting_remote( commit_file(mover, "remote.txt", "moved\n", "remote move") git(mover, "push", "-q", "origin", "lz/t1") moved = git(origin, "rev-parse", "refs/heads/lz/t1").strip() - gh.respond_pr_list([pr_json(headRefOid=old)]) + if shared_object: + git(repo, "fetch", "-q", "origin", "lz/t1") + gh.respond_pr_list([pr_json(headRefOid=moved if shared_object else old)]) code, out, err = run(capsys, "pr") - assert code == 1 and out == "" and "remote moved" in err + diagnostic = "absent from this task branch's history" if shared_object else "remote moved" + assert code == 1 and out == "" and diagnostic in err assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == moved