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
14 changes: 11 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,8 @@ def _append_review(body: str, result: ReviewResult) -> str:
match = pattern.search(body)
if not match:
return f"{body.rstrip()}\n\n## Review\n{line}\n"
if line in match.group(2).splitlines():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Idempotence check also changes non-recovery reposts; consider a direct unit test

The new early return in _append_review applies to every caller, not just confirmed recovery. Today _finish_review is the only caller, so an explicit --repost that posts a new review with the same kind, family, head and verdict no longer adds a second identical Review line. That looks intended, but the only test for it goes through the full recovery flow (test_repost_after_lost_summary_reply_does_not_patch_again). A short table test of _append_review would pin this contract down cheaply. It should cover: a placeholder-only section, a section that already has the line, a different line next to the same head, and a section followed by another ## heading.

return body
existing = match.group(2).rstrip()
if existing.startswith("(filled by `loopzero review`)"):
existing = ""
Expand Down Expand Up @@ -796,7 +798,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
confirmed, reviews = _recover_review(wt, config, pr, result,
publication["publisher"], token)
if confirmed:
return _review_verdict(result)
return _finish_review(wt, config, pr, result)
else:
reviews = _pr_reviews(config.repo, pr.number)
# Exact read-back above may confirm an older published note; a new post needs the current form.
Expand Down Expand Up @@ -842,7 +844,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
path = _review_file(wt, head, kind)
try:
if _recover_review(wt, config, pr, result, publisher, token)[0]:
return _review_verdict(result)
return _finish_review(wt, config, pr, result)
except (github.GhError, CliError, _proc.ProcTimeout) as recovery:
raise CliError(f"{exc} | publication read-back blocked: {recovery}; "
f"review saved at {path}; retry `loopzero review --repost` "
Expand All @@ -851,10 +853,16 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
f"{exc} | publication unconfirmed; review saved at {path}; "
"inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry"
) from exc
return _finish_review(wt, config, pr, result)


def _finish_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult) -> int:
try:
with _lock_task_state(wt):
live = github.pr_view(config.repo, pr.number)
github.update_body(config.repo, pr.number, _append_review(live.body, result))
body = _append_review(live.body, result)
if body != live.body:
github.update_body(config.repo, pr.number, body)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc:
print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr)
return _review_verdict(result)
Expand Down
51 changes: 38 additions & 13 deletions tests/test_review_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


def lost_reply(wt, gh, fake_bin, monkeypatch, *, kind, verdict, interrupted=False,
mutate=None, timeout=False):
mutate=None, timeout=False, summary_timeout=False):
history = []
if kind == "delta":
history = [rev(head_of(wt), "primary")]
Expand All @@ -50,11 +50,17 @@ def transport(endpoint, payload, **kwargs):
gh.respond(reviews_key(), rows)
gh.respond(f"api repos/{REPO}/pulls/7/reviews/17/comments?per_page=100&page=1",
comments)
if summary_timeout:
return response
if interrupted:
raise KeyboardInterrupt
if timeout:
raise _proc.ProcTimeout("gh POST timed out")
raise github.GhError(("gh", "api", endpoint), "client timed out after acceptance")
if summary_timeout and kwargs.get("method") == "PATCH":
gh.respond(f"api {endpoint}", support.rest_pr_json(
support.pr_json(headRefOid=head, body=payload["body"])))
raise _proc.ProcTimeout("lost summary PATCH reply")
return response

monkeypatch.setattr(github, "_api", transport)
Expand All @@ -70,9 +76,9 @@ def interrupted_receipt(wt, gh, fake_bin, monkeypatch, capsys):
return head, path, json.loads(path.read_text()), original


def assert_single_publication(gh, fake_bin):
def assert_single_publication(gh, fake_bin, *, summary=True):
assert (fake_bin / "claude.runs").read_text().splitlines() == ["run"]
assert len([c for c in gh.calls if "--input" in c]) == 1
assert len([c for c in gh.calls if "--input" in c]) == 1 + int(summary)


@pytest.mark.parametrize("kind", ["primary", "delta"])
Expand All @@ -81,8 +87,8 @@ def assert_single_publication(gh, fake_bin):
def test_accepted_publication_recovers_saved_verdict(
wt, gh, fake_bin, monkeypatch, capsys, kind, verdict, interrupted,
):
lost_reply(wt, gh, fake_bin, monkeypatch, kind=kind, verdict=verdict,
interrupted=interrupted is True, timeout=interrupted == "timeout")
head = lost_reply(wt, gh, fake_bin, monkeypatch, kind=kind, verdict=verdict,
interrupted=interrupted is True, timeout=interrupted == "timeout")
if interrupted is True:
assert run(capsys, "review")[0] == 130
(fake_bin / "claude.stdin").unlink()
Expand All @@ -94,13 +100,32 @@ def test_accepted_publication_recovers_saved_verdict(
assert out.splitlines()[-1].startswith(f"{kind} review by claude")
assert interrupted is True or out.startswith("reviewer paths pinned to origin/main@")
assert (fake_bin / "claude.runs").read_text().splitlines() == ["run"]
writes = [c for c in gh.calls if "--input" in c]
assert len(writes) == 1, "confirmed recovery must not write again, including the PR body"
assert_review_and_summary(gh, head, kind, verdict)
if verdict == 5:
files = ["api", f"repos/{REPO}/pulls/7/files"]
assert sum(call["argv"][:2] == files for call in gh.calls) == 2


def assert_review_and_summary(gh, head, kind, verdict):
review, summary = [c for c in gh.calls if "--input" in c]
assert review["argv"][1].endswith("/reviews")
assert "PATCH" in summary["argv"]
expected = "approve" if verdict == 0 else "request_changes"
body = json.loads(summary["--input"])["body"]
assert body == f"# T1\n\n## Review\n- {kind}, claude, {head[:12]}, {expected}\n\n## Notes\n"


def test_repost_after_lost_summary_reply_does_not_patch_again(wt, gh, fake_bin, monkeypatch, capsys):
head = lost_reply(wt, gh, fake_bin, monkeypatch, kind="primary", verdict=0,
summary_timeout=True)
code, _, err = run(capsys, "review")
assert code == 0 and "lost summary PATCH reply" in err
code, _, err = run(capsys, "review", "--repost")
assert (code, err) == (0, "")
assert (fake_bin / "claude.runs").read_text().splitlines() == ["run"]
assert_review_and_summary(gh, head, "primary", 0)


@pytest.mark.parametrize("change", ["body", "comment", "location", "publisher", "pending",
"dismissed", "newer", "duplicates", "bad_page", "auth", "quota",
"head", "comment_page", "kind", "wrong_head"])
Expand Down Expand Up @@ -151,7 +176,7 @@ def mutate(rows, comments):
assert not out if interrupted else (
out.startswith("reviewer paths pinned to origin/main@") and len(out.splitlines()) == 1
)
assert len([c for c in gh.calls if "--input" in c]) == 1
assert len([c for c in gh.calls if "--input" in c]) == (2 if change == "duplicates" else 1)


@pytest.mark.parametrize("change", ["login", "raw", "repo", "publisher", "number"])
Expand All @@ -171,7 +196,7 @@ def test_interrupted_publication_uses_valid_saved_runner_and_request_identity(
path.write_text(json.dumps(saved))
code, _out, err = run(capsys, "review", "--repost")
assert code == (5 if change == "login" else 1), err
assert len([c for c in gh.calls if "--input" in c]) == 1
assert len([c for c in gh.calls if "--input" in c]) == (2 if change == "login" else 1)


@pytest.mark.parametrize("change", ["revoked", "deadline", "read_timeout"])
Expand Down Expand Up @@ -214,7 +239,7 @@ def rejected(endpoint, payload, **kwargs):
code, out, err = run(capsys, "review", "--repost")
assert code == 5 and out.startswith("primary review by claude"), err
assert not (fake_bin / "claude.stdin").exists()
assert len([c for c in gh.calls if "--input" in c]) == 1
assert len([c for c in gh.calls if "--input" in c]) == 2
assert support.marker(head, "primary", "repost") in support.posted_review(gh)["body"]


Expand Down Expand Up @@ -277,7 +302,7 @@ def test_historical_publication_recovery_is_exact_and_legacy_only(
"state": "COMMENTED", "user": {"login": LOGIN}}])
code, _out, err = run(capsys, "review", "--repost")
assert code == (0 if metadata == "legacy" else 1), err
assert_single_publication(gh, fake_bin)
assert_single_publication(gh, fake_bin, summary=metadata == "legacy")
if metadata == "legacy":
mixed = body.partition("\n\n<details>")[0] + (
"\n\nNative Claude output is retained in the restricted local review receipt."
Expand Down Expand Up @@ -342,7 +367,7 @@ def mutate(rows, comments): # an older version published the raw runner line
assert code == 0, err
else:
assert code == 1 and "not in the published form" in err
assert len([c for c in gh.calls if "--input" in c]) == 1
assert len([c for c in gh.calls if "--input" in c]) == (2 if published else 1)


@pytest.mark.parametrize("publication", ["pre-configured", "transcript", "summary"])
Expand Down Expand Up @@ -422,4 +447,4 @@ def unexpected_launch(*args, **kwargs):
assert code == int(altered), err
if altered:
assert "conflicting or ambiguous review publication" in err
assert all("--input" not in call for call in gh.calls)
assert sum("--input" in call for call in gh.calls) == int(not altered)
Loading