diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 5575666c..8c3223bc 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -201,9 +201,9 @@ version. Loop-zero serves internal projects only and does not target tamper resistance for outside users. Freeze new work on Codex evidence projections. Simplify or delete them when they break or obstruct delivery. -- One primary and at most one delta per PR. The delta reads only - changes since the primary; unresolved primary findings still count under - Blockers. +- One primary and at most one delta per PR. After a base merge, the delta covers first-parent topic changes and + edits to each automatic remerge. The reviewed commit must be on the first-parent history, and merged parents + must come from the verified base. Unresolved primary findings still count under Blockers. - Default: one writing model family per PR, including delegates and repairs; another may advise read-only and review independently. Before committing imported work, record every actual writing delegate in truthful diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 57956e14..e0999f09 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -45,8 +45,11 @@ The CLI also writes a head-bound checks receipt and saved review output in `.loopzero/` for local readiness and reposting. They do not form a second authoritative delivery history; new Codex native audit receipts have the restricted retention requirement described below. Local readiness requires its current successful check receipt; hosted eligibility evaluates GitHub -review evidence using trusted base configuration. Losing local artifacts may -require rerunning checks or review, and never creates a hosted approval. +review evidence using trusted base configuration. Local readiness and merge fetch +the configured origin base once at startup before loading its publisher policy. +A receipt bound to the base may require a new check after that base advances. +Losing local artifacts may require rerunning checks or review, and never creates +a hosted approval. Saved runner artifacts also retain the repository, PR and actual request publisher before publication. A lost POST reply triggers a read-only reconciliation bounded by one 30-second transport deadline, with no read retries. Recovery regenerates @@ -76,8 +79,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con source sandbox. It inventories Git object stores only when alternates may be present. Its simple-command preflight catches missing local scripts, prepares recognized uv dependency groups offline in that sandbox and prints - progress before each command, metadata-only stage heartbeats every 30 seconds - (including silent children), and exit code/duration immediately after each stage. + progress before each command, a metadata-only heartbeat after 30 seconds and every + five minutes thereafter, and exit code/duration immediately after each stage. Heartbeats stop on completion or cancellation and never supply a verdict. Local stages drain merged child output and retain a bounded diagnostic tail. Trusted-base commands remain authoritative; @@ -103,6 +106,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con the PR-wide cap of one primary and one delta across head rewrites, and the [owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception), which changes neither the selector nor the budget. + The delta requires the reviewed commit on the current head's first-parent + history and verifies merged parents against the live configured base. The + runner receives topic patches in first-parent order and the difference + between each automatic remerge and its recorded tree. Isolated Git verifies + the history and builds the patch, excluding unrelated base changes. 5. `ready` derives readiness from the current head, its check receipt, an eligible review at that head or an eligible review covering an ancestor, blocking findings (unresolved threads a review publisher opened with a head-bound marker line), diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 9179e09e..d0c17b22 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -324,7 +324,7 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: } deadline = time.monotonic() + _TREE_SECONDS - def git(*args: str, command_env: dict[str, str] = env) -> str: + def git(*args: str, command_env: dict[str, str] = env, preserve_newlines: bool = False) -> str: with (root / "output").open("w+b") as output: process = subprocess.Popen( [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), @@ -353,6 +353,8 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish output.seek(0) result = output.read(_TREE_OUTPUT + 1) _require(len(result) <= _TREE_OUTPUT, "Git object/output bound exceeded") + if preserve_newlines: + return result.decode("utf-8", errors="surrogateescape") return result.decode().strip() finally: if process.poll() is None: diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 6c99472e..4ddfa0a4 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -127,6 +127,7 @@ def _repo_root(wt: Path) -> Path: 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: @@ -134,7 +135,7 @@ def _load_config( if args.config: print("checks are unpinned because --config was provided") return config_mod.load(path) - config = config_mod.load_trusted(root, previous=previous) + config = config_mod.load_trusted(root, previous=previous, refresh=refresh) if args.command == "check": if not config.checks: raise config_mod.ConfigError( @@ -147,7 +148,9 @@ def _load_config( def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Path, Config]: wt = _toplevel() - return wt, _load_config(args, wt, pin_checks=pin_checks) + return wt, _load_config( + args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"}, + ) def _is_ancestor(wt: Path, sha: str, head: str) -> bool: @@ -626,6 +629,20 @@ def cmd_start(args: argparse.Namespace) -> int: return 0 +def _check_failure_preview(tail: str, limit: int = 1536) -> str: + if len(tail.encode()) <= limit: + return tail + edge = limit // 8 + lines = (line.encode() for line in tail.splitlines()) + preview = b"\n".join( + line if len(line) <= 2 * edge else line[:edge] + b" [...] " + line[-edge:] + for line in lines + ) + if len(preview) > limit: + preview = b"[...]\n" + preview[6 - limit:] + return preview.decode(errors="ignore") + + def cmd_check(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) if not config.checks: @@ -639,32 +656,30 @@ def cmd_check(args: argparse.Namespace) -> int: except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 + shortened = False for result in report.results: if result.exit_code != 0: print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr) tail = _proc.tail(result.tail) - print(tail, file=sys.stderr) + preview = _check_failure_preview(tail) + shortened |= preview != tail + print(preview, file=sys.stderr) if not config.network and (result.command.startswith("uv sync --offline --locked") or OFFLINE_FAILURE_RE.search(tail)): - env = { - **sandbox.SANDBOX_ENV, - **_proc.build_env(config.env_allowlist), - **dict(config.env), - } + env = sandbox.SANDBOX_ENV | _proc.build_env(config.env_allowlist) | dict(config.env) print( "\nThe sandbox has no network because `[checks] network = false`; " f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. " - "To prepare offline, run UV_CACHE_DIR= uv sync --group dev " - "(use the groups your checks require) on the host, or the same commands, so the cache " - "under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to " - "that cache.", - file=sys.stderr, + "Run UV_CACHE_DIR= uv sync --group dev on the host " + "(use the required groups) so the cache under `[checks] writable` is warm, " + "or set `[checks] env` UV_CACHE_DIR to a warm cache.", file=sys.stderr, ) - current_head = _save_report(wt, report) - if current_head is not None: + if (current_head := _save_report(wt, report)) is not None: print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}", file=sys.stderr) return 1 + if shortened: + print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr) if report.ok and report.settings_sha256 is None: print("check stages passed but the receipt is unverified; rerun loopzero check from the task " "worktree with a stable, readable configured runner before running ready", file=sys.stderr) @@ -835,11 +850,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: # Exact read-back above may confirm an older published note; a new post needs the current form. if result.fallback and not _published_fallback(result.fallback, candidates, excluded): raise CliError("saved fallback note is not in the published form; run without --repost") - allowed, _ = _decide_kind( + allowed, reviewed = _decide_kind( _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head ) if allowed != kind: raise CliError("saved review kind differs from the remaining review budget") + _delta_patch(wt, config, reviewed, head, pr.number) else: if args.model is None and args.effort is None and _has_recoverable_review( wt, config, head, kind, publication_context, @@ -1035,12 +1051,27 @@ def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResul return True -def _delta_merge_recovery(wt: Path, reviewed: str, merge: str) -> str: - pre_merge = _git(wt, "rev-parse", f"{merge}^1") - if not _is_ancestor(wt, reviewed, pre_merge): - return f"replay the fixes on the reviewed head {reviewed[:12]}" - return (f"save the current tip on a backup branch, use `git reset --hard {pre_merge}`, " - "and cherry-pick any later fixes from the backup") +def _delta_patch(wt: Path, config: Config, since: str | None, head: str, number: int | None) -> bytes: + if since is None: + return b"" + if not _is_ancestor(wt, since, head): + raise CliError( + f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original tip with `git reflog`. " + "Back up your branch, reset to that tip and replay later fixes. To publish the restored head, " + f"run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR" + ) + if not worktree.merges_since(wt, since): + return worktree.diff_since(wt, since) + patch = (eligibility.base_merge_material(config.repo, number, since, head, config.base_branch, clean=False) + if number is not None else None) + if patch is None: + raise CliError( + f"could not verify merge history: {since[:12]} must be on the first-parent history and " + f"merged parents must come from {config.base_branch}. Save your work, then replay the fixes " + f"on the reviewed head {since[:12]}, including resolution edits. Push with `loopzero pr` " + "and run `loopzero review`, or open a new PR" + ) + return patch def _run_review( @@ -1050,23 +1081,8 @@ def _run_review( ) -> ReviewResult: lineage_base = _primary_base(wt, config) since = reviewed if kind == "delta" else lineage_base - if kind == "delta" and not _is_ancestor(wt, since, head): - raise CliError( - f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original " - "branch tip with `git reflog`. Save the current tip on a backup branch, then use " - "`git reset --hard ` and replay any later fixes. To publish the restored " - f"head, run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR " - "from the current branch" - ) - if kind == "delta" and (merges := worktree.merges_since(wt, since)): - recovery = _delta_merge_recovery(wt, since, merges[0]) - raise CliError( - f"merge commit {merges[0][:12]} since the reviewed head {since[:12]} would put the " - f"merged-in changes in the delta material. To recover, {recovery}. " - f"To publish the recovered head, run `loopzero pr`, then `loopzero review` " - f"before merging {config.base_branch} again" - ) - patch = worktree.diff_since(wt, since) + patch = (_delta_patch(wt, config, since, head, publication[1] if publication else None) + if kind == "delta" else worktree.diff_since(wt, since)) diff = runners.render_patch(patch) task = worktree.task_text(wt) authors = runners.author_families(wt, head, lineage_base) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 81388cfa..a6f72af2 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -108,12 +108,21 @@ def _has_replacement_refs(common_dir: Path) -> bool: return b" refs/replace/" in packed -def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]: +def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, refresh: bool) -> tuple[Config, str]: source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." + ref = f"refs/remotes/origin/{branch}" + if refresh: + fetched = _proc.run( + ["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", + "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"], + cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, + ) + if fetched.exit_code != 0: + raise ConfigError(f"could not refresh origin/{branch}. {hint}") directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] resolved = _proc.run( - ["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"], + ["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, ) if resolved.exit_code != 0: @@ -140,7 +149,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu raise ConfigError(f"{source}: {exc}. {hint}") from None -def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: +def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> Config: """Select delivery policy using Git's origin default and its trusted workflow.""" prefix = "refs/remotes/origin/" default = _proc.run( @@ -154,10 +163,10 @@ def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: "or supply --config for bootstrap or an override." ) branch = ref.removeprefix(prefix) - policy, revision = _remote_workflow(worktree, branch, previous) + policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh) if policy.base_branch == branch: return replace(policy, trusted_base_revision=revision) - base, revision = _remote_workflow(worktree, policy.base_branch, previous) + base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh) if base.base_branch != policy.base_branch: raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") return replace(base, trusted_base_revision=revision) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 3f2ab78a..88677c77 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -9,6 +9,7 @@ import json import re import sys +from collections.abc import Callable from pathlib import Path from loopzero import candidate, config, github, runners @@ -95,36 +96,52 @@ def eligible_review(reviews: list[dict], head: str, publishers: tuple[str, ...], return latest if verdict else None -def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_branch: str) -> bool: - """Prove each intervening first-parent commit is an unmodified merge from the base.""" +def _verified_merge(git: Callable[..., str], merge: str, first: str, second: str, + base: str, *, clean: bool) -> bool: + git("merge-base", "--is-ancestor", second, base) + merge_bases = git("merge-base", "--all", first, second).splitlines() + # A shallow root outside the known merge bases could hide another base. + if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases): + return False + return not clean or git("merge-tree", "--write-tree", first, second) == git("rev-parse", f"{merge}^{{tree}}") + + +def base_merge_material( + repo: str, number: int, reviewed: str, head: str, base_branch: str, *, clean: bool, +) -> bytes | None: + """Return a verified delta patch, or empty bytes for proven clean inheritance.""" try: pr = github.api_get(f"repos/{repo}/pulls/{number}") base = pr["base"]["sha"] if (pr["head"]["sha"] != head or pr["base"]["ref"] != base_branch or not re.fullmatch(r"[0-9a-f]{40}", base)): - return False + return None with candidate.fetched_git(repo, [reviewed, head, base]) as git: history = git("rev-list", "--first-parent", "--parents", f"{reviewed}..{head}") cursor = head + row_lengths = {3} if clean else {2, 3} for row in history.splitlines(): commits = row.split() - if len(commits) != 3 or commits[0] != cursor: - return False - merge, first, second = commits - git("merge-base", "--is-ancestor", second, base) - merge_bases = git("merge-base", "--all", first, second).splitlines() - # A shallow root outside the known merge bases could hide another base. - if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases): - return False - tree = git("merge-tree", "--write-tree", first, second) - if tree != git("rev-parse", f"{merge}^{{tree}}"): - return False - cursor = first - return cursor == reviewed + if len(commits) not in row_lengths or commits[0] != cursor: + return None + cursor = commits[1] + if len(commits) == 2: + continue + if not _verified_merge(git, *commits, base, clean=clean): + return None + if cursor != reviewed: + return None + if clean: + return b"" + patch = git("log", "--first-parent", "--reverse", "--remerge-diff", "-p", "--format=", + "--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--ignore-submodules=none", "--submodule=short", + f"{reviewed}..{head}", preserve_newlines=True) + return patch.encode("utf-8", errors="surrogateescape") except github.GhUnavailable: raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): - return False + return None def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...], *, @@ -158,7 +175,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...] return None elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}): return None - if not _clean_base_merges(repo, number, reviewed, head, base_branch): + if base_merge_material(repo, number, reviewed, head, base_branch, clean=True) is None: return None return latest diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 6f725e28..663784be 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -31,7 +31,8 @@ TIMEOUT_EXIT = 124 CHECK_SHELL = ("/bin/bash", "--posix", "-o", "pipefail", "-c") CHECK_TAIL_BYTES = 16 * 1024 -HEARTBEAT_INTERVAL = 30.0 +FIRST_HEARTBEAT_DELAY = 30.0 +HEARTBEAT_INTERVAL = 300.0 SANDBOX_HOME = "/tmp/home" # Only these system directories are exposed read-only by default; home tool paths # require explicit `[checks] ro_paths`. Host homes, sockets and processes stay hidden. @@ -325,9 +326,11 @@ def _stage_status(status: Callable[[str], None] | None, ordinal: int, total: int started = time.monotonic() def heartbeat(): - while not stopped.wait(HEARTBEAT_INTERVAL): + delay = FIRST_HEARTBEAT_DELAY + while not stopped.wait(delay): status(f"stage {ordinal}/{total}: running " f"({time.monotonic() - started:.1f}s elapsed)") + delay = HEARTBEAT_INTERVAL reporter = threading.Thread(target=heartbeat, daemon=True) if status else None if reporter: diff --git a/tests/test_cli.py b/tests/test_cli.py index 5e41347f..28a77a46 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -194,6 +194,21 @@ def head_of(path: Path) -> str: return git(path, "rev-parse", "HEAD").strip() +@pytest.fixture +def isolated_git(wt, monkeypatch, fake_tool): + """Use real isolated Git fetches against the test worktree.""" + fake_tool("prlimit", "exit 127\n") + popen = subprocess.Popen + + def fetch_from_worktree(argv, **kwargs): + if "fetch" in argv: + argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv] + return popen(argv, **kwargs) + + monkeypatch.setenv("GH_TOKEN", "test-token") + monkeypatch.setattr(subprocess, "Popen", fetch_from_worktree) + + @pytest.fixture def head(wt: Path) -> str: return head_of(wt) @@ -611,6 +626,67 @@ def test_malformed_live_markers_do_not_mask_check_verdict( assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["exit_code"] == 0 +@pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"]) +def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt): + tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n' + tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 + monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( + "a" * 40 if receipt == "head moved" else head, False, + (CheckResult("apply migrations", 7, 0.1, tail),), + )) + if receipt == "write failed": + monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2500 + assert code == 1 and "apply migrations (exit 7)" in err + assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) + assert "uv sync --group dev" in err + if receipt == "saved": + assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err + assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail + else: + assert ".loopzero/checks.json" not in err + assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err + + +def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): + sandbox = cli.sandbox + clock = poll_clock(monkeypatch) + deadline = 0.0 + + def wait(seconds): + clock.now += seconds + return clock.now >= deadline + + monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) + monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) + + def run_checks(cfg, path, *, progress, status, checkpoint, workflow): + nonlocal deadline + results = [] + for ordinal in range(1, 25): + command = f"run tool {ordinal:02d}" + duration = 3600.0 if ordinal == 1 else 0.1 + deadline = clock.now + duration + progress(command) + with sandbox._stage_status(status, ordinal, 24): + pass + status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") + results.append(CheckResult(command, 0, duration, "")) + return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) + + monkeypatch.setattr(sandbox, "run_checks", run_checks) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2400 + assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") + assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out + assert out.count("running: run tool") == 24 + assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( + range(30, 3600, 300) + ) + assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") + + @pytest.mark.parametrize("command,exit_code,tail", [ ("echo no; exit 3", 3, "no\n"), ("seq 1 50; exit 1", 1, "".join(f"{i}\n" for i in range(11, 51)))]) @@ -1475,13 +1551,14 @@ def test_review_runtime_paths_use_only_verified_base( def test_runtime_pinning_requires_trusted_workflow( wt: Path, gh: FakeGh, fake_bin: Path, capsys, command: str, missing: str, ) -> None: + origin = Path(git(wt, "remote", "get-url", "origin").strip()) if missing == "default": git(wt, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD") - elif missing == "remote": - git(wt, "update-ref", "-d", "refs/remotes/origin/main") else: - git(wt, "update-ref", "refs/remotes/origin/main", - git(wt, "rev-list", "--max-parents=0", "HEAD").strip()) + options = ("-d",) if missing == "remote" else () + revision = () if options else (git(wt, "rev-list", "--max-parents=0", "HEAD").strip(),) + for checkout, ref in ((wt, "refs/remotes/origin/main"), (origin, "refs/heads/main")): + git(checkout, "update-ref", *options, ref, *revision) prepare_review(wt, gh, fake_bin) code, out, err = run(capsys, command) assert "reviewer paths" not in out + err @@ -1821,35 +1898,74 @@ def test_review_delta_diffs_since_primary(wt: Path, gh: FakeGh, fake_bin: Path, assert marker(head, "delta") in payload["body"] -def test_review_delta_refuses_base_merge_since_primary(wt, repo, gh, fake_bin, capsys) -> None: - reviewed = head_of(wt) # intelflo#8393: primary-reviewed head, a merge of main, the delta - (repo / "upstream.py").write_text("y = 1\n") - git(repo, "add", "upstream.py") - git(repo, "commit", "-q", "-m", "landed on main") - git(wt, "merge", "-q", "--no-edit", "main") - merge = head_of(wt) - git(wt, "commit", "-q", "--allow-empty", "-m", "fix after review") - prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) - code, out, err = run(capsys, "review") - assert code != 0 and out == "" and not (fake_bin / "claude.stdin").exists() - assert f"merge commit {merge[:12]} since the reviewed head {reviewed[:12]}" in err - assert f"`git reset --hard {reviewed}`" in err - assert "cherry-pick any later fixes" in err - assert "run `loopzero pr`, then `loopzero review` before merging main again" in err +def conflict_merge(wt, repo): + (wt / "README.md").write_text("branch edit\n") + git(wt, "commit", "-qam", "edit on branch") + reviewed = head_of(wt) + (repo / "README.md").write_text("base edit\n") + (repo / "upstream.py").write_text("upstream = 1\n") + git(repo, "add", "README.md", "upstream.py") + git(repo, "commit", "-qm", "landed on main") + with pytest.raises(subprocess.CalledProcessError) as exc: + git(wt, "merge", "--no-edit", "main") + assert "CONFLICT" in exc.value.stdout + (wt / "README.md").write_text("distinct resolution\n") + git(wt, "commit", "-qam", "resolve base merge") + return reviewed + + +@pytest.mark.parametrize("verified", [True, False]) +def test_review_delta_after_conflict_merge(wt, repo, gh, fake_bin, capsys, isolated_git, verified): + reviewed = conflict_merge(wt, repo) + (wt / ".gitmodules").write_text('[submodule "dep"]\npath = dep\nurl = ../dep\nignore = all\n') + git(wt, "add", ".gitmodules") + git(wt, "update-index", "--add", "--cacheinfo", f"160000,{reviewed},dep") + commit_file(wt, "topic.py", "topic = 2\n", "topic repair") + history = [rev(reviewed, "primary")] + head = prepare_review(wt, gh, fake_bin, history=history) + detail = rest_pr_json(pr_json(headRefOid=head, isDraft=False)) + detail["base"]["sha"] = git(repo, "rev-parse", "main" if verified else "main^").strip() + gh.respond(f"api repos/{REPO}/pulls/7", detail) + + code, _, err = run(capsys, "review") + + if not verified: + assert code == 1 and not (fake_bin / "claude.stdin").exists() + assert "could not verify merge history" in err and "including resolution edits" in err + return + assert code == 0, err + header, diff = (fake_bin / "claude.stdin").read_bytes().split(b"\n", 1) + assert json.loads(header)["head"] == head + assert b"+distinct resolution" in diff and b"+topic = 2" in diff and b"upstream.py" not in diff + assert f"+Subproject commit {reviewed}".encode() in diff and diff.endswith(b"+topic = 2\n") + posted = posted_review(gh) + assert posted["commit_id"] == head and marker(head, "delta") in posted["body"] + + exact = rev(head, "delta") + exact["body"] = posted["body"] + for reviews, ready in ((history, False), ([*history, exact], True)): + arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=reviews, isDraft=False) + gh.respond(f"api repos/{REPO}/pulls/7", detail) + assert run(capsys, "ready")[0] == (0 if ready else 1) + assert cli.eligibility.evaluate(REPO, 7, head, "main", (LOGIN,)).ready is ready def test_review_delta_replays_fixes_when_reviewed_head_is_second_parent( - wt: Path, gh: FakeGh, fake_bin: Path, capsys + wt: Path, gh: FakeGh, fake_bin: Path, capsys, isolated_git ) -> None: reviewed = head_of(wt) git(wt, "reset", "--hard", "main") git(wt, "commit", "-q", "--allow-empty", "-m", "independent branch work") git(wt, "merge", "-q", "--no-edit", reviewed) - prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) + head = prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) + detail = rest_pr_json(pr_json(headRefOid=head)) + detail["base"]["sha"] = reviewed # Even a verified base parent cannot substitute for the first parent. + gh.respond(f"api repos/{REPO}/pulls/7", detail) _fake_codex(fake_bin, json.dumps(APPROVE)) _, err = expect_cli(capsys, 1, "review") - assert f"replay the fixes on the reviewed head {reviewed[:12]}" in err + assert f"{reviewed[:12]} must be on the first-parent history" in err + assert f"on the reviewed head {reviewed[:12]}, including resolution edits" in err assert "git reset --hard" not in err assert not (fake_bin / "claude.stdin").exists() assert not (fake_bin / "codex.stdin").exists() @@ -2181,7 +2297,7 @@ def test_ready_after_reviewed_head( popen = subprocess.Popen def isolated_fetch(argv, **kwargs): - if "fetch" in argv: + if "fetch" in argv and f"https://github.com/{REPO}.git" in argv: if history == "missing history": raise cli.eligibility.candidate.CandidateError("history unavailable") argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv] @@ -2222,7 +2338,7 @@ def test_ready_marks_draft_ready(wt: Path, gh: FakeGh, capsys, head, branch, git gh.respond("pr ready", "") git_calls.clear() code, out, err = run(capsys, "ready") - assert_git_cost(git_calls, 7, 1) + assert_git_cost(git_calls, 8, 1) assert (code, err) == (0, "") and out.endswith(f"ready: {URL}\n") assert ["pr", "ready", "7", "--repo", REPO] in [c["argv"] for c in gh.calls] @@ -3147,6 +3263,7 @@ def test_merged_bare_primary_cleans_only_clean_linked_worktree( repo: Path, gh: FakeGh, capsys, monkeypatch, state ) -> None: primary = repo.parent / "origin.git" + git(primary, "remote", "add", "origin", str(primary)) linked = repo.parent / "linked task" git(primary, "worktree", "add", "-q", "-b", "lz/bare", str(linked), "main") monkeypatch.chdir(linked) @@ -3676,7 +3793,7 @@ def test_commands_refuse_base_branch(wt: Path, gh: FakeGh, capsys, base) -> None git(wt, "checkout", "-q", "--ignore-other-worktrees", base) else: publish_workflow(wt, workflow.read_text()) - git(wt, "update-ref", f"refs/remotes/origin/{base}", "refs/remotes/origin/main") + git(wt, "push", "-q", "origin", f"origin/main:refs/heads/{base}") git(wt, "checkout", "-q", "-b", base) for command in ("pr", "review", "ready", "merge"): code, out, err = run(capsys, command) @@ -4171,12 +4288,25 @@ def test_hosted_eligibility_uses_publisher_not_token(wt, gh, state, verdict, exp @pytest.mark.parametrize("publisher", ["stranger", "lz-bot"]) -def test_ready_pins_review_publishers_to_base(wt, gh, capsys, publisher, head): - (wt / "workflow.toml").write_text(WORKFLOW + f'\nreview_publishers = ["{publisher}"]\n') +def test_ready_pins_review_publishers_to_base(wt, repo, gh, capsys, monkeypatch, publisher, head): + policy = WORKFLOW.replace('required_ci = ["checks"]', 'required_ci = ["checks", "Loop-zero Eligibility"]') + publish_workflow(wt, policy + '\nreview_publishers = ["stranger"]\n') + commit_file(repo, "workflow.toml", policy + f'\nreview_publishers = ["{LOGIN}"]\n', "rotate publisher") + git(repo, "push", str(repo.parent / "origin.git"), "main") # preserve the retired local publisher + (wt / "workflow.toml").write_text(policy + f'\nreview_publishers = ["{publisher}"]\n') arm_approved_pr_with_check_result( gh, head, wt, "success", review_login=publisher, isDraft=False ) + gh.respond(f"api repos/{REPO}/commits/{head}/statuses", [{"context": "Loop-zero Eligibility", "state": "success"}]) assert run(capsys, "ready")[0] == (0 if publisher == LOGIN else 1) + event = repo / "event.json" + event.write_text(json.dumps({"inputs": {"pr": "7"}})) + monkeypatch.chdir(repo) + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + assert hosted.main() == 0 + assert json.loads(gh.calls[-1]["--input"])["state"] == ("success" if publisher == LOGIN else "pending") def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch): diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index b8ea47f6..08e388cd 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -533,7 +533,7 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: @pytest.fixture def heartbeat_log(monkeypatch): - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 0.03) observed, events, reporters = Event(), [], set() def status(message): @@ -591,7 +591,6 @@ def run_stage(config, worktree, prefix, stage_command, timeout): def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch): - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 30.0) events = [] report = sandbox.run_checks( make_config(checks=("echo secret; exit 17", "echo never")), git_repo, @@ -676,7 +675,7 @@ def status(message): if mode == "blocked-heartbeat": threading.Event().wait() -sandbox.HEARTBEAT_INTERVAL = 0.03 +sandbox.FIRST_HEARTBEAT_DELAY = 0.03 repo = Path.cwd() command = "echo complete" if mode in {"dispatch", "removal"} else "exec sleep 30" report = sandbox.run_checks(make_config(checks=(command,)), repo, status=status)