Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,11 +1044,21 @@ def open_findings(repo: str, number: int,
"""


def _next_thread_cursor(page: dict, seen: set[str]) -> str:
cursor = page.get("endCursor")
if not isinstance(cursor, str) or not cursor.strip() or cursor in seen:
raise GhError(("gh", "api", "graphql"), "missing or repeated review thread cursor")
seen.add(cursor)
return cursor


def _has_thread_reply(node: dict, reply: str) -> bool:
page = node["comments"].get("pageInfo", {})
seen: set[str] = set()
while page.get("hasNextPage"):
cursor = _next_thread_cursor(page, seen)
data = _gh_json("api", "graphql", "-f", f"query={_THREAD_REPLIES_QUERY}",
"-F", f"thread={node['id']}", "-f", f"after={page['endCursor']}")
"-F", f"thread={node['id']}", "-f", f"after={cursor}")
try:
comments = data["data"]["node"]["comments"]
page = comments["pageInfo"]
Expand Down Expand Up @@ -1137,6 +1147,7 @@ def _unresolved_threads(repo: str, number: int) -> list[dict]:
def _review_threads(repo: str, number: int, *, include_resolved: bool = False) -> list[dict]:
owner, name = repo.split("/", 1)
after: str | None = None
seen: set[str] = set()
found: list[dict] = []
while True:
args = [
Expand All @@ -1153,7 +1164,7 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) -
found += [node for node in nodes if include_resolved or not node.get("isResolved")]
if not page["hasNextPage"]:
return found
after = page["endCursor"]
after = _next_thread_cursor(page, seen)
except (KeyError, TypeError) as exc:
raise _not_found(number, exc) from exc

Expand Down
26 changes: 0 additions & 26 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,6 @@ def marker(head: str, kind: str, source: str = "model") -> str:
return cli.review_marker(head, kind, source)


def test_review_marker_parser_accepts_old_and_v1_forms() -> None:
old = f"<!-- loopzero:review head={'a' * 40} kind=primary -->"
new = cli.review_marker("b" * 40, "delta")
assert cli.REVIEW_MARKER_RE.search(old).groups() == ("a" * 40, "primary")
assert cli.REVIEW_MARKER_RE.search(new).groups() == ("b" * 40, "delta")


@pytest.mark.parametrize("source", ["model", "pair"])
def test_review_marker_quoted_in_prose_neither_voids_nor_hides_a_review(gh: FakeGh, source: str) -> None:
head = "a" * 40
Expand Down Expand Up @@ -1148,17 +1141,6 @@ def test_progress_output_precedes_the_stderr_verdict_in_one_file(tmp_path: Path)
assert (tmp_path / "log").read_text().splitlines() == ["waiting", "loopzero merge: dequeued"]


def test_pr_migrates_old_checks_heading_to_validation(wt: Path) -> None:
task = wt / ".loopzero" / "task.md"
task.write_text(task.read_text().replace("## Validation", "## Checks"))

body = cli._pr_body(wt, head_of(wt), cli.config_mod.load(wt / "workflow.toml"))

assert "## Checks" not in body
assert body.count("## Validation") == 1
assert "(no `loopzero check` run recorded)" in body


@pytest.mark.parametrize("corrupt_report", [False, True], ids=["no-report", "corrupt-report"])
def test_pr_updates_existing_open_pr(wt, gh, capsys, corrupt_report):
if corrupt_report:
Expand Down Expand Up @@ -3803,14 +3785,6 @@ def test_gh_errors_are_one_line_on_stderr(wt: Path, gh: FakeGh, capsys) -> None:
assert err.startswith("loopzero status: gh api") and "gh auth login" in err


def test_help_lists_all_commands(capsys) -> None:
with pytest.raises(SystemExit) as info:
cli.main(["--help"])
assert info.value.code == 0
out = capsys.readouterr().out
assert all(word in out for word in ("start", "check", "pr", "review", "ready", "merge", "status"))


@pytest.mark.parametrize("command", ["ready", "merge"])
@pytest.mark.parametrize("budget,conclusion", [
("-1", "success"), ("NaN", "pending"), ("inf", "success"), ("-inf", "success"),
Expand Down
17 changes: 17 additions & 0 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,23 @@ def test_open_blocking_findings_paginates(gh: FakeGh) -> None:
assert "after=C1" not in gh.argv(0) and "after=C1" in gh.argv(1)


@pytest.mark.parametrize("cursors", [(None,), ("C1", "C1"), ("C1", "C2", "C1")])
def test_open_blocking_findings_rejects_invalid_cursor(gh: FakeGh, cursors) -> None:
gh.respond("api graphql", *(threads_json(has_next=True, cursor=c) for c in cursors))
with pytest.raises(github.GhError, match="missing or repeated review thread cursor"):
github.open_blocking_findings(REPO, 7, HEAD, PUBLISHERS)
assert len(gh.calls) == len(cursors)


def test_thread_reply_read_rejects_repeated_cursor(gh: FakeGh) -> None:
page = {"hasNextPage": True, "endCursor": "C1"}
gh.respond("api graphql", {"data": {"node": {"comments": {"pageInfo": page, "nodes": []}}}})
node = {"id": "T1", "comments": {"pageInfo": page}}
with pytest.raises(github.GhError, match="missing or repeated review thread cursor"):
github._has_thread_reply(node, "reply")
assert len(gh.calls) == 1 and "after=C1" in gh.argv(0)


# --- checks --------------------------------------------------------------------------------


Expand Down
10 changes: 0 additions & 10 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
RunnerPromptTooLong,
RunnerUsageLimit,
author_families,
build_prompt,
codex_evidence,
merge_reviews,
render_patch,
Expand Down Expand Up @@ -267,15 +266,6 @@ def repo(tmp_path):
# ----------------------------------------------------------------- prompt


def test_prompt_frames_exact_task_and_raw_diff() -> None:
prompt = build_prompt(kind="delta", head="deadbeef", task_text=" Objective ", diff="+line\n")
header, diff = prompt.split("\n", 1)
assert json.loads(header) == {
"head": "deadbeef", "kind": "delta", "task_text": " Objective ", "diff_utf8_bytes": 6,
}
assert diff == "+line\n"


@pytest.mark.parametrize("family", ["claude", "codex"])
@pytest.mark.parametrize("kind", ["primary", "delta"])
@pytest.mark.parametrize("chunk", [None, (2, 3)])
Expand Down
13 changes: 0 additions & 13 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,8 @@ def interleave(path, *args, **kwargs):
headings = [ln for ln in text.splitlines() if ln.startswith("## ")]
assert headings == ["## Context and goal", "## Acceptance", "## Notes", "## Base",
"## Validation", "## Review"], "matches core/HANDOFF.md"
assert "- **Context:** <plain newcomer context; explain domain terms from read sources or describe what they do instead; rulings and dispatch belong in Notes>" in text
assert "- **Problem:** <one or two plain sentences before code names: what goes wrong (one problem only), who notices, and evidence/cost; refs in brackets at the end>" in text
assert "- **Goal:** <one plain sentence: what the owner or users now notice (and cost/saving if known), because this change fixes the problem>" in text
prompts = [ln.split(":**", 1)[0] for ln in text.splitlines() if ln.startswith("- **")]
assert prompts == ["- **Goal", "- **Problem", "- **Context"], "owner-facing goal leads"
assert "Refs #<issue number, or remove this line>" in text
base_section = text.split("## Base\n", 1)[1].split("\n## ", 1)[0]
assert base_section.strip().splitlines() == [f"main @ {upstream}", f"Base: {upstream}"]
assert "lz/my-task" in git(repo, "branch", "--list", "lz/my-task")
Expand Down Expand Up @@ -184,15 +180,6 @@ def test_start_rejects_bad_slug(repo: Path, slug: str) -> None:
assert not (repo / ".worktrees").exists(), "rejected before fetch or worktree add"


@pytest.mark.parametrize("slug,title", [
("add-workflow-config-note", "Add workflow config note"),
("fix_bug--123", "Fix bug 123"),
("x", "X"),
])
def test_title_from_slug(slug: str, title: str) -> None:
assert worktree.title_from_slug(slug) == title


def test_branch_name_uses_git_check_ref_format(repo: Path) -> None:
assert worktree.branch_name(repo, "ok-1.2_x") == "lz/ok-1.2_x"
with pytest.raises(worktree.WorktreeError):
Expand Down
Loading