From e2df91b7a9db720b0f997f9330098590f099c6de Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:52:58 +0100 Subject: [PATCH 1/5] Keep finding resolution compatible with legacy encodings Architecture-Review: unchanged; stdout escaping preserves the existing resolution and eligibility sequence. Co-Authored-By: Codex --- src/loopzero/cli.py | 6 +++--- tests/test_cli.py | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b4c64c5f..9c8cd541 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1818,11 +1818,11 @@ def _version() -> str: def main(argv: list[str] | None = None) -> int: - # Progress lines must precede the stderr verdict when both go to one file. - if isinstance(sys.stdout, io.TextIOWrapper): - sys.stdout.reconfigure(line_buffering=True) parser = build_parser() args = parser.parse_args(argv) + # Preserve output order and escape characters a legacy stream cannot write during resolve. + if isinstance(sys.stdout, io.TextIOWrapper): + sys.stdout.reconfigure(line_buffering=True, errors="backslashreplace" if args.command == "resolve" else None) if args.command == "resolve" and args.finding is not None and not args.reply.strip(): parser.error('expected resolve [ ""] with a nonblank reply for a finding') if args.command == "review" and args.repost: diff --git a/tests/test_cli.py b/tests/test_cli.py index fda149c0..12e37de2 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4016,25 +4016,25 @@ def finding_pr(wt, gh, head): @pytest.mark.parametrize("outcome", ["refreshed", "remaining", "dispatch failed"]) def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, outcome) -> None: - listing = threads_json(finding_pr) - remaining = listing if outcome == "remaining" else threads_json() - gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, remaining) + sys.stdout.reconfigure(encoding="ascii" if outcome == "refreshed" else "utf-8", errors="strict") + finding_pr["comments"]["nodes"][0]["body"] = finding_pr["comments"]["nodes"][0]["body"].replace("Off by one", "Łódź") + listing = threads_json({**finding_pr, "path": "src/Łódź.py"}) + gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, + listing if outcome == "remaining" else threads_json()) gh.respond("api -X", "", exit=int(outcome == "dispatch failed"), stderr="HTTP 403") - + title = r"\u0141\xf3d\u017a" if outcome == "refreshed" else "Łódź" code, out, err = run(capsys, "resolve") - assert (code, err) == (0, "") and out == "0b9b59e7 important src/a.py:3 Off by one\n" + assert (code, err) == (0, "") and out == f"0b9b59e7 important src/{title}.py:3 {title}\n" assert not any("eligibility.yml/dispatches" in " ".join(c["argv"]) for c in gh.calls) - code, out, err = run(capsys, "resolve", "0b9b59e7", "Fixed in abc1234: loop bound corrected.") - assert out.splitlines()[0] == "resolved 0b9b59e7: Off by one" + assert out.splitlines()[0] == f"resolved 0b9b59e7: {title}" calls = [c["argv"] for c in gh.calls if c["argv"][:2] == ["api", "graphql"]][2:] assert "addPullRequestReviewThreadReply" in calls[0][3] and "resolveReviewThread" in calls[1][3] assert "body=Fixed in abc1234: loop bound corrected." in calls[0] and "thread=THREAD_1" in calls[1] endpoint = f"repos/{REPO}/actions/workflows/eligibility.yml/dispatches" dispatches = [c["argv"] for c in gh.calls if endpoint in c["argv"]] if outcome == "remaining": - assert (code, err, dispatches) == (0, "", []) - assert len(out.splitlines()) == 1 + assert (code, err, dispatches, len(out.splitlines())) == (0, "", [], 1) else: assert dispatches == [["api", "-X", "POST", endpoint, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]] if outcome == "refreshed": From a3deb601b14ac21cc68654269c1ecbfd6e76e312 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:05:59 +0100 Subject: [PATCH 2/5] Escape finding text at the resolve output boundary Architecture-Review: unchanged; escaping is scoped to the existing finding output and leaves resolution and eligibility sequencing intact. Co-Authored-By: Codex --- src/loopzero/cli.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 9c8cd541..c165e4f6 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1667,15 +1667,15 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None: def cmd_resolve(args: argparse.Namespace) -> int: - """List open blocking findings, or reply to one with what changed and resolve its thread.""" + encoding = getattr(sys.stdout, "encoding", None) or "utf-8" wt, config = _context(args) pr = _require_pr(config, worktree.branch(wt)) if not args.finding: for marker_id, _thread, f in github.open_findings(config.repo, pr.number): - print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}") + print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}".encode(encoding, "backslashreplace").decode(encoding)) return 0 finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply) - print(f"resolved {args.finding}: {finding.title}") + print(f"resolved {args.finding}: {finding.title}".encode(encoding, "backslashreplace").decode(encoding)) try: with github.api_error_diagnostics(): remaining = github.open_blocking_findings(config.repo, pr.number) @@ -1818,11 +1818,11 @@ def _version() -> str: def main(argv: list[str] | None = None) -> int: + # Progress lines must precede the stderr verdict when both go to one file. + if isinstance(sys.stdout, io.TextIOWrapper): + sys.stdout.reconfigure(line_buffering=True) parser = build_parser() args = parser.parse_args(argv) - # Preserve output order and escape characters a legacy stream cannot write during resolve. - if isinstance(sys.stdout, io.TextIOWrapper): - sys.stdout.reconfigure(line_buffering=True, errors="backslashreplace" if args.command == "resolve" else None) if args.command == "resolve" and args.finding is not None and not args.reply.strip(): parser.error('expected resolve [ ""] with a nonblank reply for a finding') if args.command == "review" and args.repost: From 2caa6acaa6458180e1631a9594fee3903e50464b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:56:38 +0100 Subject: [PATCH 3/5] Promote shared Codex entries without replacing the destination Architecture-Review: unchanged; account mirroring retains its lock and layout while refusing concurrent destination replacement. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 18 ++++++++++++++++-- tests/test_ai_accounts.py | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 5c4c901d..f2757abc 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -46,7 +46,9 @@ from __future__ import annotations import argparse import base64 +import ctypes import datetime as dt +import errno from email.utils import parsedate_to_datetime import fcntl import hashlib @@ -200,6 +202,18 @@ def sync_codex_home(home: Path, *, create: bool = False) -> None: _sync_codex_home(home) +def _rename_noreplace(source: Path, target: Path) -> None: + """Publish a shared entry atomically, including directories.""" + libc = ctypes.CDLL(None, use_errno=True) + renameat2 = getattr(libc, "renameat2", None) + if renameat2 is None: + raise OSError(errno.ENOSYS, "atomic no-replace promotion requires renameat2") + at_fdcwd, rename_noreplace = -100, 1 + if renameat2(at_fdcwd, os.fsencode(source), at_fdcwd, os.fsencode(target), rename_noreplace): + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), source, None, target) + + def _sync_codex_home(home: Path) -> None: """Mirror shared Codex files while holding the home lock.""" for entry in home.iterdir(): @@ -207,8 +221,8 @@ def _sync_codex_home(home: Path) -> None: if shared(entry) and not entry.is_symlink() and not target.exists() \ and not target.is_symlink(): try: - os.rename(entry, target) - except FileNotFoundError: + _rename_noreplace(entry, target) + except (FileExistsError, FileNotFoundError): pass for src in CODEX_MAIN.iterdir(): dst = home / src.name diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index c161c052..e02de851 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -593,3 +593,26 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): with pytest.raises(OSError), helper._locked(".codex-sync.lock"): pytest.fail("redirected lock opened") assert lock.read_text() == "preserve" + + +def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch): + home = helper.codex_home("extra") + home.mkdir(parents=True) + helper.CODEX_MAIN.mkdir() + source = home / "sessions" + source.mkdir() + (source / "old").write_text("keep local") + (home / "notes").write_text("promote") + rename = helper._rename_noreplace + + def create_destination(entry, target): + if entry == source: + target.mkdir() + rename(entry, target) + + monkeypatch.setattr(helper, "_rename_noreplace", create_destination) + helper.sync_codex_home(home) + assert (source / "old").read_text() == "keep local" + assert list((helper.CODEX_MAIN / "sessions").iterdir()) == [] + assert (home / "notes").is_symlink() + assert (home / "notes").read_text() == "promote" From a6a2a19b89ded73aac7d7b4ff3bf51a4c02661a5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:58:57 +0100 Subject: [PATCH 4/5] Keep mirroring when no-replace promotion is unsupported Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 8 ++++++-- tests/test_ai_accounts.py | 8 +++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index f2757abc..f7702dc8 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -208,6 +208,7 @@ def _rename_noreplace(source: Path, target: Path) -> None: renameat2 = getattr(libc, "renameat2", None) if renameat2 is None: raise OSError(errno.ENOSYS, "atomic no-replace promotion requires renameat2") + renameat2.argtypes = (ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint) at_fdcwd, rename_noreplace = -100, 1 if renameat2(at_fdcwd, os.fsencode(source), at_fdcwd, os.fsencode(target), rename_noreplace): error = ctypes.get_errno() @@ -222,8 +223,11 @@ def _sync_codex_home(home: Path) -> None: and not target.is_symlink(): try: _rename_noreplace(entry, target) - except (FileExistsError, FileNotFoundError): - pass + except OSError as exc: + # A competing writer or unsupported no-replace operation leaves the source local. + if exc.errno not in {errno.EEXIST, errno.ENOENT, errno.ENOSYS, errno.EINVAL, + errno.EOPNOTSUPP, errno.EXDEV}: + raise for src in CODEX_MAIN.iterdir(): dst = home / src.name if shared(src) and not dst.exists() and not dst.is_symlink(): diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index e02de851..2464d7a2 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -595,7 +595,8 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): assert lock.read_text() == "preserve" -def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch): +@pytest.mark.parametrize("unsupported", [None, "ENOSYS", "EINVAL"]) +def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch, unsupported): home = helper.codex_home("extra") home.mkdir(parents=True) helper.CODEX_MAIN.mkdir() @@ -608,11 +609,12 @@ def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monk def create_destination(entry, target): if entry == source: target.mkdir() + if unsupported: + raise OSError(getattr(helper.errno, unsupported), "no-replace unsupported") rename(entry, target) monkeypatch.setattr(helper, "_rename_noreplace", create_destination) helper.sync_codex_home(home) assert (source / "old").read_text() == "keep local" assert list((helper.CODEX_MAIN / "sessions").iterdir()) == [] - assert (home / "notes").is_symlink() - assert (home / "notes").read_text() == "promote" + assert (home / "notes").is_symlink() and (home / "notes").read_text() == "promote" From 58ef6f26f6b5eea49da8f2256f8c33ac7c11afa7 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:18:14 +0100 Subject: [PATCH 5/5] Deduplicate CLI checks, waits and diagnostics Architecture-Review: unchanged; the cut preserves command output, receipt handling, safety checks and read and write ordering. Co-Authored-By: Codex --- src/loopzero/cli.py | 173 ++++++++++++++++++-------------------------- 1 file changed, 71 insertions(+), 102 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 3ac7a1c5..b4f8febc 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -21,6 +21,7 @@ import tempfile import time from collections.abc import Callable, Iterator +from contextlib import suppress from datetime import UTC, datetime from functools import partial, wraps from pathlib import Path @@ -107,8 +108,8 @@ def _toplevel() -> Path: return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True)) -def _repo_root(wt: Path) -> Path: - """The verified primary checkout or bare repository owning this linked worktree.""" +def _repo_root(wt: Path) -> None: + """Verify the primary checkout or bare repository owns this linked worktree.""" first = _git(wt, "worktree", "list", "--porcelain", "-z", paths=True).split("\0", 1)[0] if not first.startswith("worktree "): raise CliError("Git did not identify the primary worktree; refusing cleanup") @@ -116,19 +117,16 @@ def _repo_root(wt: Path) -> Path: 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 def _load_config( args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None, refresh: bool = False, ) -> Config: - path = args.config or root / "workflow.toml" - if not pin_checks: - return config_mod.load(path) - if args.config: - print("checks are unpinned because --config was provided") - return config_mod.load(path) + if not pin_checks or args.config: + if pin_checks: + print("checks are unpinned because --config was provided") + return config_mod.load(args.config or root / "workflow.toml") config = config_mod.load_trusted(root, previous=previous, refresh=refresh, read_timeout=github._read_timeout) if args.command == "check": if not config.checks: @@ -408,14 +406,12 @@ def _require_receipt(wt: Path, config: Config, head: str) -> None: def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: """Best-effort transcript identity; never authority or environment attestation.""" - try: + with suppress(Exception): content = _git(wt, "rev-parse", f"{report.head}^{{tree}}").strip() commands = json.dumps([r.command for r in report.results], separators=(",", ":")) digest = hashlib.sha256(commands.encode()).hexdigest() print(f"receipt {action}: head={report.head} content={content} " f"config=commands-sha256:{digest} environment=unknown") - except Exception: # output must never affect the verdict - return def _save_report(wt: Path, report: CheckReport) -> str | None: @@ -479,19 +475,16 @@ def _pr_body(wt: Path, head: str, config: Config, existing: str | None = None) - """Refresh only generated checks; the live body owns existing PR prose.""" body = (existing if existing is not None else worktree.task_text(wt)).replace("\r\n", "\n") block = f"{_CHECKS_START}\n{_validation_section(wt, head, config)}\n{_CHECKS_END}" - pattern = re.compile(r"^## (?:Validation|Checks)\n(.*?)(?=^## |\Z)", - re.DOTALL | re.MULTILINE) - match = pattern.search(body) + match = re.search(r"^## (?:Validation|Checks)\n(.*?)(?=^## |\Z)", body, re.DOTALL | re.MULTILINE) if match is None: return _validate_pr_body_size(f"{body.rstrip()}\n\n## Validation\n{block}\n") content = match.group(1) - if _CHECKS_START in content or _CHECKS_END in content: - if (content.count(_CHECKS_START) != 1 or content.count(_CHECKS_END) != 1 - or content.index(_CHECKS_START) > content.index(_CHECKS_END)): + before, start, after = content.partition(_CHECKS_START) + if start or _CHECKS_END in content: + _, end, suffix = after.partition(_CHECKS_END) + if not end or _CHECKS_END in before or _CHECKS_END in suffix or _CHECKS_START in after: raise CliError("malformed loopzero checks block in PR Validation; repair its markers") - start = content.index(_CHECKS_START) - end = content.index(_CHECKS_END) + len(_CHECKS_END) - content = content[:start] + block + content[end:] + content = before + block + suffix else: # Migrate our old report/placeholder only, retaining behavioral evidence. content = _LEGACY_CHECKS.sub("", content) @@ -520,16 +513,13 @@ def _sync_task_narrative(wt: Path, existing: str) -> str: existing = existing.replace("\r\n", "\n") owned = {m.group(1): m.group() for m in pattern.finditer(task) if m.group(1) not in {"Validation", "Checks", "Review"}} - first = pattern.search(existing) - task_first = pattern.search(task) - prefix = task[:task_first.start()] if task_first else task - content = existing[first.start():] if first else "" + content = existing[first.start():] if (first := pattern.search(existing)) else "" + prefix = task[:first.start()] if (first := pattern.search(task)) else task def replace(match: re.Match[str]) -> str: - replacement = owned.pop(match.group(1), None) - if replacement is None: - return match.group() - trailing = match.group()[len(match.group().rstrip()):] + section = match.group() + replacement = owned.pop(match.group(1), section) + trailing = section[len(section.rstrip()):] return replacement.rstrip() + trailing content = pattern.sub(replace, content) @@ -677,18 +667,17 @@ def cmd_pr(args: argparse.Namespace) -> int: _require_clean(wt) _require_pr_details(wt) pr = github.merged_pr_for_branch(config.repo, branch) - if pr is None: - pr = github.pr_for_branch(config.repo, branch, open_only=True) - if pr is not None and pr.state == "MERGED": + if pr is not None: raise CliError( f"task branch {branch} already merged as PR #{pr.number} ({pr.url}); " "run `loopzero start ` for a new task" ) + pr = github.pr_for_branch(config.repo, branch, open_only=True) 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 push = ["push", "-u", "origin"] - if pr is not None and pr.state == "OPEN": + if pr is not None: known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}") if known.exit_code != 0: raise CliError( @@ -705,7 +694,7 @@ def cmd_pr(args: argparse.Namespace) -> int: 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": + if pr is not None: with worktree.lock_local_state(wt): live = github.pr_view(config.repo, pr.number) if live.state != "OPEN": @@ -885,8 +874,7 @@ def _refresh_publisher_token(token: str, publisher: str) -> str: def _review_verdict(result: ReviewResult) -> int: - counts = {s: sum(1 for f in result.findings if f.severity == s) for s in runners.SEVERITIES} - summary = ", ".join(f"{n} {s}" for s, n in counts.items()) + summary = ", ".join(f"{sum(f.severity == s for f in result.findings)} {s}" for s in runners.SEVERITIES) print(f"{result.kind} review by {result.family} on {result.head[:12]}: {result.verdict} ({summary})") return 0 if result.verdict == "approve" else 5 # the exit code is the verdict, as for check @@ -928,19 +916,17 @@ def _has_recoverable_review( try: result, _ = _load_review(wt, head, kind, publication=publication) candidates, excluded = _repost_reviewer_families(wt, config, head, result) - if result.fallback and not _published_fallback(result.fallback, candidates, excluded): - return False - return _matches_publication(result, publication) + fallback_valid = not result.fallback or _published_fallback(result.fallback, candidates, excluded) + return fallback_valid and _matches_publication(result, publication) except (CliError, runners.RunnerBadOutput): return False def _repost_prefix(result: ReviewResult) -> str: sessions = result.provenance["session_ids"] - return review_marker(result.head, result.kind, "repost") + "\n" + ( - "Reposted from runner session" + ("s" if len(sessions) != 1 else "") - + ": " + ", ".join(f"`{session}`" for session in sessions) - ) + label = "session" if len(sessions) == 1 else "sessions" + ids = ", ".join(f"`{session}`" for session in sessions) + return f"{review_marker(result.head, result.kind, 'repost')}\nReposted from runner {label}: {ids}" def _recover_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult, @@ -1134,8 +1120,7 @@ def _review_failure(family: str, exc: Exception) -> tuple[str, str, str]: login = "claude auth login" if family == "claude" else "codex login" return lines[0], detail + f"\nFix: run `{login}`.", _FALLBACK_REASONS[0] if isinstance(exc, runners.RunnerUsageLimit): - fix = "\nFix: wait for the limit to reset or switch this reviewer's account." - return lines[0], detail + fix, _FALLBACK_REASONS[1] + return lines[0], detail + "\nFix: wait for the limit to reset or switch this reviewer's account.", _FALLBACK_REASONS[1] if isinstance(exc, runners.RunnerMissing): package = "@anthropic-ai/claude-code" if family == "claude" else "@openai/codex" return lines[0], detail + f"\nFix: install it with `npm install -g {package}`.", _FALLBACK_REASONS[2] @@ -1160,9 +1145,8 @@ def _review_file(wt: Path, head: str, kind: str) -> Path: def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None) -> None: - path = _review_file(wt, result.head, result.kind) data = dataclasses.asdict(result) | ({"publication": publication} if publication is not None else {}) - worktree.write_local_state(wt, path.name, json.dumps(data, indent=2) + "\n", private=True) + worktree.write_local_state(wt, _review_file(wt, result.head, result.kind).name, json.dumps(data, indent=2) + "\n", private=True) def _load_review( @@ -1202,10 +1186,9 @@ def _pr_readiness( _require_task_branch(config, branch) pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True) _require_pushed(pr, head) - if pr.state == "MERGED": - return pr, None - return pr, _readiness(wt, config, pr, head, workflow_wait=workflow_wait, - announce_receipt=True) + readiness = None if pr.state == "MERGED" else _readiness( + wt, config, pr, head, workflow_wait=workflow_wait, announce_receipt=True) + return pr, readiness CLEANUP_RETRY = "; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup" @@ -1301,6 +1284,8 @@ def cmd_ready(args: argparse.Namespace) -> int: waiting = _draft_checks_waiting(config, pr, readiness) kicked = bool(waiting) started = time.monotonic() + wait = partial(_wait_with_deadline, wt, config, timeout=args.wait, started=started, + args=args, allow_skipped=True, initial_read_time=started - read_started) if waiting: _require_receipt(wt, config, pr.head_sha) github.mark_ready(config.repo, pr.number) @@ -1312,26 +1297,20 @@ def cmd_ready(args: argparse.Namespace) -> int: if args.wait is not None and ( waiting or _pending_checks(config, pr, readiness, allow_skipped=not pr.is_draft) ): - waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=kicked, started=started, - shown=readiness.reasons if kicked else (), args=args, - allow_skipped=True, initial=None if kicked else readiness, - initial_read_time=started - read_started) + waited = wait(pr, kicked=kicked, shown=readiness.reasons if kicked else (), + initial=None if kicked else readiness) if waited is None: return 3 pr, readiness, kicked = waited - assert readiness is not None _prequeue_size_budget(wt, config, pr, readiness) if readiness.ready and pr.is_draft and not kicked: _require_receipt(wt, config, pr.head_sha) github.mark_ready(config.repo, pr.number) if args.wait is not None: - waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started, - args=args, allow_skipped=True, - initial_read_time=started - read_started) + waited = wait(pr, kicked=True) if waited is None: return 3 pr, readiness, kicked = waited - assert readiness is not None for reason in _readiness_messages(pr, readiness): print(f"not ready: {reason}") if not readiness.ready: @@ -1426,11 +1405,10 @@ def _poll_until( def _wait_with_deadline( wt: Path, config: Config, pr: github.PR, timeout: float, *, kicked: bool, - started: float | None = None, shown: tuple[str, ...] = (), args: argparse.Namespace, + started: float, shown: tuple[str, ...] = (), args: argparse.Namespace, allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None, initial_read_time: float = 0.0, ) -> tuple[github.PR, github.Readiness | None, bool] | None: - started = time.monotonic() if started is None else started wait = partial(_wait_for_checks, wt, config, pr, timeout, kicked=kicked, started=started, shown=shown, args=args, allow_merged=allow_merged, allow_skipped=allow_skipped, initial=initial) @@ -1466,13 +1444,11 @@ def _print_check_wait_timeout(pr: github.PR, args: argparse.Namespace | None) -> def _verify_wait_snapshot( args: argparse.Namespace | None, wt: Path, config: Config, head: str, current_head: str, - previous: Config | None = None, + previous: Config, ) -> Config: if current_head != head: raise CliError(f"PR head changed while waiting: {head[:12]} to {current_head[:12]}") - if args is None: - return config - latest = _load_config(args, wt, pin_checks=True, previous=previous or config, refresh=True) + latest = config if args is None else _load_config(args, wt, pin_checks=True, previous=previous, refresh=True) if latest == config: return latest retry = "retry with the current settings" if _current_check_report(wt, latest, head) else "run loopzero check and retry" @@ -1586,10 +1562,9 @@ def _mergify_timeout_detail( config: Config, pr: github.PR, queue: str, state: mergify.Membership | None, ) -> str: if state is None: - try: + report = None + with suppress(github.GhError): _, _, report = mergify.request_status(config.repo, pr.number, pr.head_sha, queue) - except github.GhError: - report = None return f"waiting for admission to Mergify queue {queue}. " + ( f"Mergify report: {report}" if report else "Check the PR for Mergify's admission report." ) @@ -1619,23 +1594,6 @@ def _mergify_timeout_detail( ) -def _mergify_departure_hint(report: mergify.Departure | None, base: str) -> str: - if report is None: - return f"{MERGIFY_DEQUEUE_HINT} {MERGIFY_REQUEUE}" - detail = f"Mergify report: {report.url}." - if report.attribution == "base_conflict": - return (f"The PR conflicts with {base}. Run `git fetch origin {base}` and resolve the base " - f"integration according to the PR's review state. Requeue only after resolving the " - f"conflict. {detail} {MERGIFY_REQUEUE}") - if report.checks: - detail += " Failing checks: " + ", ".join(repr(check) for check in report.checks) + "." - guidance = { - "stacked": "Mergify tested a stack and could not attribute the failure. Inspect the candidate in the report or requeue after the earlier PRs clear.", - "isolated": "Mergify tested this PR alone. Inspect or fix the failed check before requeueing unless it is a known flake.", - } - return f"{detail} {guidance.get(report.attribution, MERGIFY_DEQUEUE_HINT)} {MERGIFY_REQUEUE}" - - def _mergify_departure( config: Config, pr: github.PR, queue: str, closed: list[github.GhError], confirmed: bool, ) -> str | None: @@ -1643,11 +1601,25 @@ def _mergify_departure( if not confirmed and report is None: return None sha = _landed(config, pr, closed) - if not sha and not closed: - raise CliError( - f"PR #{pr.number} left Mergify queue {queue} unmerged. {_mergify_departure_hint(report, pr.base_ref)}" - ) - return sha + if sha or closed: + return sha + detail = MERGIFY_DEQUEUE_HINT + if report is not None: + detail = f"Mergify report: {report.url}." + if report.attribution == "base_conflict": + base = pr.base_ref + detail = (f"The PR conflicts with {base}. Run `git fetch origin {base}` and resolve the base " + f"integration according to the PR's review state. Requeue only after resolving the " + f"conflict. {detail}") + else: + if report.checks: + detail += " Failing checks: " + ", ".join(repr(check) for check in report.checks) + "." + guidance = { + "stacked": "Mergify tested a stack and could not attribute the failure. Inspect the candidate in the report or requeue after the earlier PRs clear.", + "isolated": "Mergify tested this PR alone. Inspect or fix the failed check before requeueing unless it is a known flake.", + } + detail += " " + guidance.get(report.attribution, MERGIFY_DEQUEUE_HINT) + raise CliError(f"PR #{pr.number} left Mergify queue {queue} unmerged. {detail} {MERGIFY_REQUEUE}") def _wait_for_mergify( @@ -1787,14 +1759,14 @@ def cmd_merge(args: argparse.Namespace) -> int: return 3 _require_receipt(wt, config, pr.head_sha) sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha) - if sha is None and args.wait is not None: + if sha is None: + if args.wait is None: + print(f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}") + return 0 sha = _wait_for_merge(config, pr, max(0.0, deadline - time.monotonic())) if sha is None: print(f"timed out waiting for the merge queue to land PR #{pr.number}") return 3 - if sha is None: - print(f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}") - return 0 _cleanup_remote_refs(wt, config, branch, pr.head_sha) _cleanup(wt, pr) print(sha) @@ -1893,14 +1865,13 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi assert queue is not None requested, confirmed, report = mergify.request_status(config.repo, pr.number, pr.head_sha, queue) state = mergify.membership(config.repo, pr.number, queue) + label = "not admitted" if state: label = "confirmed" elif confirmed: label = "ejected" elif requested or (readiness.ready and report): label = "waiting for admission" - else: - label = "not admitted" print(f"mergify: {label} ({queue})") if label == "waiting for admission" and report: print(f" Mergify report: {report}") @@ -1917,15 +1888,13 @@ def _run(args: argparse.Namespace) -> int: except IndependentReviewerUnavailable as exc: print(f"loopzero {args.command}: {exc}", file=sys.stderr) return 4 - except HANDLED as exc: + except HANDLED + UNEXPECTED as exc: if isinstance(exc, sandbox.SandboxUnavailable) and args.command in {"check", "review"}: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 message = str(exc) if isinstance(exc, ReviewersUnavailable) else _one_line(exc) - print(f"loopzero {args.command}: {message}", file=sys.stderr) - return 1 - except UNEXPECTED as exc: - print(f"loopzero {args.command}: unexpected response: {_one_line(exc)}", file=sys.stderr) + prefix = "unexpected response: " if isinstance(exc, UNEXPECTED) else "" + print(f"loopzero {args.command}: {prefix}{message}", file=sys.stderr) return 1 except KeyboardInterrupt: print(f"loopzero {args.command}: interrupted", file=sys.stderr)