diff --git a/README.md b/README.md index 58f85992..f2cbf0fe 100644 --- a/README.md +++ b/README.md @@ -31,9 +31,8 @@ ownership and the contributor routine that keeps documentation current. For a picture of the whole flow, see the [workflow diagrams](docs/WORKFLOW.md). -`loopzero status` prints where the current branch is in that sequence. It -requires authenticated access to the configured GitHub repository even before -a PR exists. +`loopzero status` reports the branch stage and can exit 0 with `ready: no`. +It requires authenticated GitHub access even before a PR exists. `loopzero resolve` lists the open blocking findings with their ids; `loopzero resolve ""` replies in that thread and resolves it. diff --git a/core/CONTRACT.md b/core/CONTRACT.md index a70b9875..878373f8 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -192,9 +192,9 @@ version. - Findings live only in PR review threads, expire at merge, and must not be copied into files, issues or backlogs. -- Blocking marker: +- Blocking marker, as the first line of a thread a review publisher opened: `` - (or `important`). + (or `important`). Other threads never block. - `critical`: wrong or unsafe; must fix. `important`: ships a bug or breaks acceptance; must fix. `suggestion`: never counted or blocking. - Missing diff or required evidence: return one `critical` finding; never @@ -285,8 +285,8 @@ meta-directives; reviewers load no instruction files or skills from the reviewed Fail closed on missing tools and command errors, preserve the failing command and output tail, and keep a short, safe detail about the cause or stage when operator-facing code wraps an error. Stop on terminal failures or quota errors. -Exit 3 means waiting: rerun the bounded waiter. Exit 5 means changes requested, -not a crash. +Exit 3 means waiting or timeout. Review exits 4 when independent review is +unavailable and 5 when changes are requested. Interruption exits 130. **Never pipe a `loopzero` command, even with `set -o pipefail`: the pipeline can report the filter's exit code in place of the command's verdict.** Redirect diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 462bb23c..55e9eb0d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -101,7 +101,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con [owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception), which changes neither the selector nor the budget. 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, + head or an eligible review covering an ancestor, blocking findings + (unresolved threads a review publisher opened with a head-bound marker line), target branch and required CI. The receipt must record a clean passing run at that head with the current commands and check settings digest. A settings change or an older receipt without the digest requires a fresh check. The @@ -281,7 +282,7 @@ Git configuration so URL rewrites cannot change its destination. After confirmed remote deletion or absence, cleanup deletes the matching `origin/lz/` tracking ref only if it still points to the merged head. An already-merged PR can resume cleanup from its task worktree. Local removal -requires a clean worktree at the merged PR head. +requires a clean worktree at the merged PR head with no ignored user files. Hosted eligibility trusts the configured publisher's projection and live identity, state, head and latest ordering. It cannot recompute private raw or defeat a coherent forgery by a trusted publisher/editor; native claims do not attest the diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index aed8f2c9..29829078 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -286,6 +286,7 @@ def _readiness( workflow_wait and review_age is not None and -MAX_REVIEW_CLOCK_SKEW <= review_age < STALE_VERDICT_GRACE ), + publishers=publishers, ) report = _load_report(wt) receipt_problem = _check_report_problem(report, wt, config, head) @@ -1704,17 +1705,20 @@ 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.""" - wt, config = _context(args) + wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR pr = _require_pr(config, worktree.branch(wt)) + if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base + raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}") + publishers = config.review_publishers or (github.login(),) if not args.finding: - for marker_id, _thread, f in github.open_findings(config.repo, pr.number): + for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers): print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}") return 0 - finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply) + finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers) print(f"resolved {args.finding}: {finding.title}") try: with github.api_error_diagnostics(): - remaining = github.open_blocking_findings(config.repo, pr.number) + remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers) except (github.GhError, _proc.ProcTimeout, OSError) as exc: retry = shlex.join(("gh", *github.eligibility_dispatch_args( config.repo, pr.number, config.base_branch, diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 41de7f3c..6cd10e1d 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -152,7 +152,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...] verdict = summary.partition(": **")[2] state = latest.get("state") if verdict.startswith("request_changes** (") and state in {"CHANGES_REQUESTED", "COMMENTED"}: - if github.open_blocking_findings(repo, number, reviewed): + if github.open_blocking_findings(repo, number, reviewed, publishers): return None elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}): return None @@ -182,7 +182,8 @@ def evaluate(repo: str, number: int, head: str, base: str, page += 1 review = readiness_review(reviews, head, publishers, repo=repo, number=number, base_branch=base) result = github.readiness(repo, pr, base, (), head if review else None, allow_behind=True, - ancestor_review=review is not None and review["commit_id"] != head) + ancestor_review=review is not None and review["commit_id"] != head, + publishers=publishers) if github.pr_view(repo, number).head_sha != head: return github.Readiness(False, ("source head changed during eligibility refresh",)) return result diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 171efcb9..53aba75a 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -28,9 +28,8 @@ _app_token_cache = ("", 0.0) MISSING_REVIEW_REASON = "no review recorded for the current head" MARKER_RE = re.compile( - r"" + r"" ) PAGE = 100 PR_FILE_LIMIT = 3_000 @@ -50,7 +49,9 @@ pageInfo { hasNextPage endCursor } nodes { id isResolved isOutdated path line - comments(first: 1) { nodes { body } pageInfo { hasNextPage endCursor } } + comments(first: 1) { + nodes { body author { __typename login } } pageInfo { hasNextPage endCursor } + } } } } @@ -965,22 +966,29 @@ def _title_of(text: str) -> str: return re.sub(r"^\*\*\w+:\s*|\*\*$", "", title_line).strip() -def _parse_thread(node: dict, current_head: str | None) -> Finding | None: +def _thread_marker(node: dict, publishers: tuple[str, ...]) -> re.Match[str] | None: + """The v=1 marker opening a thread's first comment, if a review publisher wrote it.""" comments = node.get("comments", {}).get("nodes") or [] if not comments: return None - first = comments[0] - body = first.get("body") or "" - match = MARKER_RE.search(body) + author = comments[0].get("author") or {} + login = str(author.get("login") or "") + # GraphQL names an App's bot account without REST's "[bot]" suffix. + if author.get("__typename") == "Bot": + login += "[bot]" + if not login or login.casefold() not in {p.casefold() for p in publishers}: + return None + # The publisher writes the marker as the whole first line, exactly as finding_marker does. + return MARKER_RE.fullmatch((comments[0].get("body") or "").partition("\n")[0]) + + +def _parse_thread(node: dict, current_head: str | None, + publishers: tuple[str, ...]) -> Finding | None: + match = _thread_marker(node, publishers) if not match or match.group("severity") not in BLOCKING: return None - version = match.group("version") + body = node["comments"]["nodes"][0]["body"] marker_head = match.group("head") - marker_id = match.group("id") - if version and (not marker_head or not marker_id): - return None - if not version and marker_id: - return None if current_head is not None and marker_head != current_head and node.get("isOutdated"): return None severity = match.group("severity") @@ -998,12 +1006,13 @@ def _parse_thread(node: dict, current_head: str | None) -> Finding | None: ) -def open_findings(repo: str, number: int) -> list[tuple[str, str, Finding]]: +def open_findings(repo: str, number: int, + publishers: tuple[str, ...]) -> list[tuple[str, str, Finding]]: """(marker id, thread id, finding) for every unresolved blocking thread, any head.""" return [ - (MARKER_RE.search(node["comments"]["nodes"][0]["body"]).group("id") or node["id"], node["id"], f) + (_thread_marker(node, publishers).group("id"), node["id"], f) for node in _unresolved_threads(repo, number) - if (f := _parse_thread(node, None)) + if (f := _parse_thread(node, None, publishers)) ] @@ -1037,16 +1046,16 @@ def _has_thread_reply(node: dict, reply: str) -> bool: return False -def resolve_finding(repo: str, number: int, finding_id: str, reply: str) -> Finding: +def resolve_finding(repo: str, number: int, finding_id: str, reply: str, + publishers: tuple[str, ...]) -> Finding: """Reply to a blocking finding, or resume an identical resolution.""" threads = _review_threads(repo, number, include_resolved=True) for node in sorted(threads, key=lambda node: bool(node.get("isResolved"))): - finding = _parse_thread(node, None) + finding = _parse_thread(node, None, publishers) if finding is None: continue - marker = MARKER_RE.search(node["comments"]["nodes"][0]["body"]) thread_id = node["id"] - if (marker.group("id") or thread_id) != finding_id: + if _thread_marker(node, publishers).group("id") != finding_id: continue confirmed = _has_thread_reply(node, reply) if node.get("isResolved"): @@ -1093,15 +1102,17 @@ def refresh_eligibility(repo: str, number: int, base: str) -> None: def open_blocking_findings( - repo: str, number: int, current_head: str | None = None + repo: str, number: int, current_head: str | None, publishers: tuple[str, ...], ) -> list[Finding]: - """Findings from unresolved review threads whose first comment carries a blocking marker. + """Findings from unresolved review threads whose first comment opens with a blocking marker. - Only explicit critical and important markers block. When `current_head` is supplied, an - outdated thread is ignored unless its marker names that head. + Only critical and important v=1 markers on the first line of a comment written by a + review publisher block. When `current_head` is supplied, an outdated thread is ignored + unless its marker names that head. """ return [ - f for node in _unresolved_threads(repo, number) if (f := _parse_thread(node, current_head)) + f for node in _unresolved_threads(repo, number) + if (f := _parse_thread(node, current_head, publishers)) ] @@ -1289,6 +1300,7 @@ def readiness( review_grace: bool = False, workflow_wait: bool = False, stale_verdict_grace: bool = False, + publishers: tuple[str, ...], ) -> Readiness: """Decide whether `pr` may be marked ready / merged. Never raises on policy failures.""" reasons: list[str] = [] @@ -1304,7 +1316,8 @@ def readiness( reasons.append(MISSING_REVIEW_REASON) elif pr.head_sha != reviewed_head: reasons.append(f"head {pr.head_sha[:12]} differs from reviewed {reviewed_head[:12]}") - for f in open_blocking_findings(repo, pr.number, None if ancestor_review else pr.head_sha): + for f in open_blocking_findings(repo, pr.number, None if ancestor_review else pr.head_sha, + publishers): where = f"{f.path}:{f.line}" if f.path else "(no location)" reasons.append(f"open {f.severity} finding at {where}: {f.title}") checks, stale, stale_verdicts, capped = (_check_signals( diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 720e78b8..7a994ac3 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -260,12 +260,23 @@ def merges_since(wt: Path, sha: str) -> list[str]: def cleanup(wt: Path) -> None: - """Remove the worktree and its branch. Refuses when the worktree is dirty.""" + """Remove the worktree and branch if there are no local user files.""" wt = Path(wt).absolute() if not wt.exists(): raise WorktreeError(f"no such worktree: {wt}") if is_dirty(wt): raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") + ignored = _git( + wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True + ) + for path in ignored.split("\0")[:-1]: + if ( + (path in {".loopzero/task.md", ".loopzero/checks.json"} + or re.fullmatch(r"\.loopzero/review-[0-9a-f]{12}-(primary|delta)\.json", path)) + and not (wt / path).is_symlink() + ): + continue + raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}") name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve() _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout try: diff --git a/tests/test_cli.py b/tests/test_cli.py index ca25c35f..53b0e0ba 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2186,7 +2186,7 @@ def test_ready_after_reviewed_head( prefix = cli._repost_prefix(result) if reposted else marker(reviewed, kind) review["body"] = github.review_payload(REPO, 7, reviewed, result, prefix)["body"] thread = {"isResolved": resolved, "isOutdated": True, "path": "feature.py", "line": 1, - "comments": {"nodes": [{"body": f""}]}} + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": f""}]}} reviews = [rev("f" * 40, "primary"), review] if kind == "delta" else [review] arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=reviews, readiness={"threads": (thread,)}, isDraft=False) @@ -2220,7 +2220,7 @@ def test_exact_head_delta_ignores_outdated_blocker(wt, gh, capsys, head): previous = git(wt, "rev-parse", "HEAD^").strip() history = [rev("f" * 40, "primary"), rev(head, "delta")] thread = {"isResolved": False, "isOutdated": True, "path": "feature.py", "line": 1, - "comments": {"nodes": [{"body": f""}]}} + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": f""}]}} arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=history, readiness={"threads": (thread,)}, isDraft=False) code, _, _ = run(capsys, "ready") @@ -2996,8 +2996,8 @@ def test_ready_draft_with_open_blocking_finding_does_not_mark_ready( ) -> None: finding = { "isResolved": False, "path": "feature.py", "line": 1, - "comments": {"nodes": [{"body": - f"\n" + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": + f"\n" "**important: Fix this**"}]}, } arm_approved_pr_with_check_result(gh, head, wt, "skipped", readiness={"threads": (finding,)}) @@ -3201,7 +3201,7 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non gh.respond(reviews_key(), [rev(head, "primary")]) arm_readiness(gh, head, wt, conclusion="failure", threads=( {"isResolved": False, "isOutdated": False, "path": "feature.py", "line": 1, - "comments": {"nodes": [{"body": f"" + "comments": {"nodes": [{"author": {"login": LOGIN}, "body": f"" "\n**critical: Bad**"}]}},)) code, out, err = run(capsys, "merge") assert code == 1 and without_accepted_receipt(out) == "" @@ -4002,7 +4002,7 @@ def _finding_thread(marker_id: str, head: str) -> dict: body = (f"\n" "**important: Off by one**\n\nThe loop skips the last row.") return {"id": "THREAD_1", "isResolved": False, "isOutdated": False, "path": "src/a.py", - "line": 3, "comments": {"nodes": [{"body": body}]}} + "line": 3, "comments": {"nodes": [{"author": {"login": LOGIN}, "body": body}]}} @pytest.fixture @@ -4028,7 +4028,8 @@ def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: Fak code, out, err = run(capsys, "resolve", "0b9b59e7", "Fixed in abc1234: loop bound corrected.") assert out.splitlines()[0] == "resolved 0b9b59e7: Off by one" - calls = [c["argv"] for c in gh.calls if c["argv"][:2] == ["api", "graphql"]][2:] + calls = [c["argv"] for c in gh.calls + if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]][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" @@ -4053,6 +4054,8 @@ def test_resolve_resumes_after_github_accepts_mutation(gh, finding_pr, capsys, m def github_call(*args, **kwargs): query = args[3] + if "viewer {" in query: + return {"data": {"viewer": {"login": LOGIN}}} if "reviewThreads(" in query: node["isResolved"] = bool(accepted["resolution"]) node["comments"]["pageInfo"] = { @@ -4107,6 +4110,38 @@ def resolve_or_dispatch(*args, **kwargs): assert run(capsys, "resolve") == (0, "", "") +def test_resolve_takes_review_publishers_from_the_base(wt: Path, gh: FakeGh, capsys, head) -> None: + (wt / "workflow.toml").write_text(WORKFLOW + '\nreview_publishers = ["outsider"]\n') + planted, genuine = _finding_thread("0b9b59e7", head), _finding_thread("1c2d3e4f", head) + planted["comments"]["nodes"][0]["author"] = {"__typename": "User", "login": "outsider"} + gh.respond_pr_list([pr_json(headRefOid=head)]) + gh.respond("api graphql", threads_json(planted, genuine)) + assert run(capsys, "resolve") == (0, "1c2d3e4f important src/a.py:3 Off by one\n", "") + + +@pytest.mark.parametrize("argv", [("resolve",), ("resolve", "0b9b59e7", "Fixed.")]) +def test_resolve_refuses_a_pr_targeting_another_base(wt: Path, gh: FakeGh, capsys, head, argv) -> None: + gh.respond_pr_list([pr_json(headRefOid=head, baseRefName="release")]) + code, out, err = run(capsys, *argv) + assert (code, out) == (1, "") and "PR #7 targets release, configured base is main" in err + assert not any("reviewThreads" in " ".join(c["argv"]) for c in gh.calls) + + +def test_resolve_and_ready_ignore_findings_from_non_publishers(wt: Path, gh: FakeGh, capsys, head) -> None: + planted = _finding_thread("0b9b59e7", head) + planted["comments"]["nodes"][0]["author"] = {"__typename": "User", "login": "outsider"} + gh.respond_pr_list([pr_json(headRefOid=head)]) + gh.respond("api graphql", threads_json(planted)) + assert run(capsys, "resolve") == (0, "", "") + + arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=[rev(head, "primary")], + readiness={"threads": (planted,)}, isDraft=False) + code, out, _ = run(capsys, "ready") + gh.respond_pr_view(pr_json(headRefOid=head)) + hosted = cli.eligibility.evaluate(REPO, 7, head, "main", (LOGIN,)) + assert (code, hosted.ready) == (0, True), out + + @pytest.mark.parametrize("response", [ {"data": {"resolveReviewThread": {"thread": {"isResolved": False}}}}, {"data": {"resolveReviewThread": {"thread": {}}}}, @@ -4166,7 +4201,8 @@ def test_resolve_retries_only_thread_resolution(finding_pr, gh: FakeGh, capsys, assert code == 1 assert "reply posted to finding 0b9b59e7" in err assert "Retry loopzero resolve with the same reply" in err - queries = [c["argv"][3] for c in gh.calls if c["argv"][:2] == ["api", "graphql"]] + queries = [c["argv"][3] for c in gh.calls + if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]] assert len(queries) == 2 + len(outcomes) + recovers assert "addPullRequestReviewThreadReply" in queries[1] assert all("resolveReviewThread" in query for query in queries[2:2 + len(outcomes)]) @@ -4719,7 +4755,7 @@ def interrupt(staged, dest): def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head): - (wt / ".loopzero" / "review-existing.json").write_text("{broken") + cli._review_file(wt, head, "primary").write_text("{broken") arm_pr(gh, head, isDraft=False, state="MERGED") gh.append(f"api repos/{REPO}/pulls/7", merge_json(state="MERGED", head=head, sha="c" * 40)) ref = f"api repos/{REPO}/git/ref/heads/lz/t1" diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index 7a06d0e9..9f31898a 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -59,7 +59,7 @@ def captured_argv(tmp_path_factory: pytest.TempPathFactory) -> list[dict]: result = ReviewResult("codex", HEAD, "primary", "request_changes", (Finding("important", "src/a.py", 10, "Problem", "Details"),), "raw") github.post_review(REPO, 7, HEAD, result) - github.open_blocking_findings(REPO, 7, HEAD) + github.open_blocking_findings(REPO, 7, HEAD, ("bot-user",)) github._check_signals(REPO, HEAD) github.mark_ready(REPO, 7) github.merge(REPO, 7, "squash", HEAD) diff --git a/tests/test_github.py b/tests/test_github.py index fe1254fb..3066bfb7 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -206,7 +206,10 @@ def thread(body: str, resolved: bool = False, path: str = "src/a.py", line: int def marker(sev: str, head: str = HEAD) -> str: - return f"" + return f"" + + +PUBLISHERS = ("bot-user",) FILES_KEY = f"api repos/{REPO}/pulls/7/files" @@ -670,35 +673,54 @@ def test_open_blocking_findings_filters_and_parses(gh: FakeGh) -> None: versioned = github.finding_marker( "critical", HEAD, Finding("critical", "src/a.py", 3, "Null deref", "x may be None") ) - gh.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}}) + app = thread(f"{marker('important')}\n**important: From the App**", path="src/c.py") + app["comments"]["nodes"][0]["author"] = {"__typename": "Bot", "login": "loopzero-app"} gh.respond("api graphql", threads_json( thread(f"{versioned}\n**critical: Null deref**\n\nx may be None"), thread(f"{marker('important')}\nplain title", resolved=True), thread(f"{marker('suggestion')}\n**suggestion: Rename**"), - thread("human intro\n" + marker("critical") + "\n**critical: Human marker**"), - thread("\nheadless", path="h.py", line=9), thread(f"{marker('important')}\n**important: Missing check**\n\nvalidate", path="src/b.py", line=2), + app, )) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, ("BOT-user", "loopzero-app[bot]")) assert found == [ Finding("critical", "src/a.py", 3, "Null deref", "**critical: Null deref**\n\nx may be None"), - Finding("critical", "src/a.py", 3, "Human marker", "**critical: Human marker**"), - Finding("important", "h.py", 9, "headless", "headless"), Finding("important", "src/b.py", 2, "Missing check", "**important: Missing check**\n\nvalidate"), + Finding("important", "src/c.py", 3, "From the App", "**important: From the App**"), ] argv = gh.argv(0) assert argv[:2] == ["api", "graphql"] assert "-F" in argv and "owner=acme" in argv and "name=widgets" in argv and "number=7" in argv - assert any(a.startswith("query=") and "lastEditedAt" not in a and "author" not in a for a in argv) + assert any(a.startswith("query=") and "author { __typename login }" in a for a in argv) + + +@pytest.mark.parametrize("body, author", [ + # A valid marker written by someone who is not a review publisher. + (f"{marker('critical')}\n**critical: Planted**", "outsider"), + # The App user name without the Bot type is a different (user) account. + (f"{marker('critical')}\n**critical: Lookalike**", "loopzero-app"), + # A publisher comment that only quotes a marker below its first line. + (f"**suggestion: Quote**\n\n{marker('critical')}", "bot-user"), + (f" {marker('critical')}\n**critical: Indented**", "bot-user"), + # Markers without a head and id are not tied to a reviewed head. + ("\nheadless", "bot-user"), + (f"\nunversioned", "bot-user"), + # Only the exact emitted line counts: not split, trailed by prose or truncated. + (marker("critical").replace(" head=", "\nhead=") + "\n**critical: Split**", "bot-user"), + (marker("critical") + " trailing prose\n**critical: Trailed**", "bot-user"), + (marker("critical", head=HEAD[:7]) + "\n**critical: Short head**", "bot-user"), +]) +def test_open_findings_ignore_untrusted_or_quoted_markers(gh: FakeGh, body: str, author: str) -> None: + gh.respond("api graphql", threads_json({**thread(body, author=author), "id": "T_1"})) + assert github.open_blocking_findings(REPO, 7, HEAD, ("bot-user", "loopzero-app[bot]")) == [] + assert github.open_findings(REPO, 7, ("bot-user", "loopzero-app[bot]")) == [] -def test_markers_without_id_are_resolvable_by_thread_id(gh: FakeGh) -> None: - legacy = {**thread("\nheadless"), "id": "T_1"} - gh.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}}) - gh.respond("api graphql", threads_json(legacy)) - assert [(m, t) for m, t, _ in github.open_findings(REPO, 7)] == [("T_1", "T_1")] +def test_open_findings_without_publishers_block_nothing(gh: FakeGh) -> None: + gh.respond("api graphql", threads_json(thread(f"{marker('critical')}\n**critical: X**"))) + assert github.open_blocking_findings(REPO, 7, HEAD, ()) == [] @pytest.mark.parametrize("data", [ @@ -710,7 +732,7 @@ def test_markers_without_id_are_resolvable_by_thread_id(gh: FakeGh) -> None: def test_open_blocking_findings_missing_pr_is_gh_error(gh: FakeGh, data: dict) -> None: gh.respond("api graphql", data) with pytest.raises(github.GhError, match="PR #7 not found or not accessible"): - github.open_blocking_findings(REPO, 7, HEAD) + github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) def test_pr_for_branch_missing_key_is_gh_error(gh: FakeGh) -> None: @@ -799,15 +821,12 @@ def test_app_review_is_comment_with_inline_findings(gh: FakeGh, app_token_helper assert payload["event"] == "COMMENT" and payload["comments"] -def test_marker_parser_accepts_old_and_v1_forms() -> None: - old = github.MARKER_RE.search("") - assert old and old.groupdict() == { - "version": None, "severity": "critical", "head": None, "id": None, - } +def test_marker_parser_accepts_only_the_emitted_v1_line() -> None: + assert github.MARKER_RE.fullmatch("") is None finding = Finding("important", "src/b.py", 2, "Missing check", "validate") - new = github.MARKER_RE.search(github.finding_marker("important", HEAD, finding)) + new = github.MARKER_RE.fullmatch(github.finding_marker("important", HEAD, finding)) assert new and new.groupdict() == { - "version": "1", "severity": "important", "head": HEAD, + "severity": "important", "head": HEAD, "id": github.finding_id(HEAD, "src/b.py", 2, "Missing check"), } @@ -824,7 +843,7 @@ def test_open_blocking_findings_counts_only_explicit_blocking_markers(gh: FakeGh thread(f"{marker('suggestion')}\n**suggestion: nit**", edited="2026-09-18T01:00:00Z"), thread(f"{marker('critical')}\nX", edited="2026-09-18T01:00:00Z", path="e.py", line=4), )) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) assert [(f.severity, f.path, f.line, f.title) for f in found] == [ ("critical", "e.py", 4, "X"), ] @@ -837,7 +856,7 @@ def test_open_blocking_findings_does_not_guess_from_body_or_author(gh: FakeGh) - thread("mentions loopzero but a human wrote it", author="human"), thread("bot-user wrote this but it is unrelated", author="bot-user"), )) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) assert found == [] assert all(c["argv"] != ["api", "user"] for c in gh.calls) @@ -846,7 +865,7 @@ def test_open_blocking_findings_paginates(gh: FakeGh) -> None: gh.respond("api graphql", threads_json(thread(f"{marker('critical')}\nA"), has_next=True, cursor="C1"), threads_json(thread(f"{marker('important')}\nB"))) - found = github.open_blocking_findings(REPO, 7, HEAD) + found = github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS) assert [f.title for f in found] == ["A", "B"] assert "after=C1" not in gh.argv(0) and "after=C1" in gh.argv(1) @@ -947,7 +966,8 @@ def arm_workflow_check(gh: FakeGh, check: dict, statuses: list[dict] | None = No def readiness(*, reviewed=HEAD, workflow_wait=False): pr = github._pr_from_rest(rest_pr_json(pr_json())) - return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait) + return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait, + publishers=PUBLISHERS) def failed_check(conclusion="failure", **fields): @@ -1032,7 +1052,8 @@ def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks( def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) -> None: arm_readiness(gh, runs={"checks": failure}) r = github.readiness( - REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace + REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace, + publishers=PUBLISHERS, ) assert r.reasons == ( f"required check 'checks' is {failure}", @@ -1165,13 +1186,14 @@ def test_readiness_rerun_attempt_requires_start_after_old_failure( def test_readiness_metadata_blocker(gh: FakeGh, metadata: dict, reason: str) -> None: arm_readiness(gh) pr = github._pr_from_rest(rest_pr_json(pr_json(**metadata))) - r = github.readiness(REPO, pr, "main", ("checks",), HEAD) + r = github.readiness(REPO, pr, "main", ("checks",), HEAD, publishers=PUBLISHERS) assert r.reasons == (reason,) def test_readiness_without_required_ci_skips_check_lookup(gh: FakeGh) -> None: gh.respond("api graphql", threads_json()) - assert github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD).ready + assert github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD, + publishers=PUBLISHERS).ready assert [c["argv"][:2] for c in gh.calls] == [["api", "graphql"]] @@ -1487,7 +1509,7 @@ def test_readiness_at_check_suite_limit(gh: FakeGh, unrelated, legacy_success, c gh.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs", *({"check_runs": runs[i:i + 100]} for i in range(0, len(runs) + 1, 100))) result = github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), - "main", ("required-ci",), HEAD) + "main", ("required-ci",), HEAD, publishers=PUBLISHERS) reasons = { "suite limit": f"cannot determine required check 'required-ci' on {HEAD[:12]}: GitHub's 1,000-suite limit", diff --git a/tests/test_hosted.py b/tests/test_hosted.py index f9295795..abe46760 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -89,7 +89,8 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st if blocker == "conflict": publisher.respond(f"api repos/{REPO}/pulls/7", fixtures.rest_pr_json(pr_json(mergeable="CONFLICTING"))) if blocker == "important": - publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding"))) + publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding", + author="trusted-publisher"))) assert hosted.main() == (1 if status == "failure" else 0) statuses = [json.loads(c["--input"]) for c in publisher.calls if "--input" in c] assert ([s["state"] for s in statuses] == ["pending", status] diff --git a/tests/test_worktree.py b/tests/test_worktree.py index d4c30478..8b6c5fc2 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -133,13 +133,11 @@ def interrupt_after_add(cwd, *args, **kwargs): def test_start_excludes_worktrees_and_task_dir(repo: Path) -> None: exclude = repo / ".git" / "info" / "exclude" - exclude.parent.mkdir(parents=True, exist_ok=True) exclude.write_text("*.log") # no trailing newline on purpose old_inode = exclude.stat().st_ino wt = worktree.start(repo, "t1", "main") assert exclude.stat().st_ino != old_inode - lines = exclude.read_text().splitlines() - assert lines == ["*.log", ".worktrees/", ".loopzero/"] + assert exclude.read_text().splitlines() == ["*.log", ".worktrees/", ".loopzero/"] assert not worktree.is_dirty(wt), "fresh worktree with task.md is clean" assert git(repo, "status", "--porcelain") == "" installed = exclude.stat() @@ -269,12 +267,14 @@ def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None: assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list") -def test_cleanup_refuses_dirty(repo: Path) -> None: +@pytest.mark.parametrize("file", ["scratch.txt", "local.env", ".loopzero/user-notes.md"]) +def test_cleanup_preserves_user_files(repo: Path, file: str) -> None: + (repo / ".git/info/exclude").write_text("local.env\n") wt = worktree.start(repo, "dirty", "main") - (wt / "scratch.txt").write_text("x") - with pytest.raises(worktree.WorktreeError, match="dirty"): + (wt / file).write_text("x") + with pytest.raises(worktree.WorktreeError, match="worktree is dirty" if file == "scratch.txt" else "ignored file"): worktree.cleanup(wt) - assert wt.exists() and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty") + assert (wt / file).read_text() == "x" and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty") def test_cleanup_missing_worktree(repo: Path) -> None: