diff --git a/SETUP.md b/SETUP.md index 557f4782..5b87243d 100644 --- a/SETUP.md +++ b/SETUP.md @@ -74,6 +74,14 @@ symlinked skill directory and resolve its relative links from the real files, so the contract and references stay reachable. Do not also keep copies of these skills in a repository: both would load. +Before resuming automated PR check refreshes or explicit PR resyncs after an +upgrade, advance every PR-body writer to the selected CLI revision. For +unverified receipt warnings, use a revision containing +[3ff80bd9 (#1160)](https://github.com/feder-positronics/loop-zero/commit/3ff80bd91c92f12d557cead31776df40d4328097). +Once the writers are updated, run `loopzero check` for the current head to +replace old receipts. If you roll back across that fix, pause those writes before +switching the CLI and resume them once the writers support the warning again. + If you roll back across [#732](https://github.com/feder-positronics/loop-zero/pull/732) after GitHub may have accepted a Claude review, run `loopzero review --repost` with the publishing CLI revision or a newer compatible revision. The rollback diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b1393e13..df90da9c 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -628,6 +628,11 @@ def cmd_check(args: argparse.Namespace) -> int: print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}", file=sys.stderr) return 1 + 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) + _refresh_pr_checks(wt, config) + return 1 if report.ok and not report.dirty: _print_receipt(wt, report, "produced") _refresh_pr_checks(wt, config) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index dc8baabb..dc64281d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1462,6 +1462,14 @@ def commit_status(repo: str, head: str, context: str, state: str, description: s raise +def status_matches(repo: str, head: str, context: str, state: str, description: str) -> bool: + statuses = _iter_paged(f"repos/{repo}/commits/{head}/statuses") + latest = next((row for row in statuses if row.get("context") == context), {}) + creator = latest.get("creator") + return (isinstance(creator, dict) and creator.get("login") == "github-actions[bot]" + and (latest.get("state"), latest.get("description")) == (state, description)) + + def _status_limit_reached(repo: str, head: str, context: str) -> bool: # A validation error alone does not prove exhaustion. with suppress(GhError, ProcTimeout, OSError): diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 726b64f6..3b963850 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -89,12 +89,25 @@ def policy(source_number: int, source: dict) -> None: if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" state = "pending" - publish(state, message) - print(message) - return 0 if ready or state == "pending" else 1 except Exception as exc: _mark_refresh_failed(publish, exc) raise + _publish_verdict(cfg.repo, head, state, message[:140]) + print(message) + return 0 if ready or state == "pending" else 1 + + +def _publish_verdict(repo: str, head: str, state: str, description: str) -> None: + context = eligibility.CONTEXT + try: + github.commit_status(repo, head, context, state, description) + except github.StatusLimitReached: + raise + except (github.GhError, github.ProcTimeout, OSError) as exc: + with suppress(github.GhError, github.ProcTimeout, OSError): + if github.status_matches(repo, head, context, state, description): + return + raise LoopZeroError(f"Could not confirm eligibility status publication: {exc}") from exc def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index 51f3b12a..0ae28782 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3063,6 +3063,43 @@ def change_policy(_seconds): assert run(capsys, *args, "check")[0] == 1 +def test_check_refuses_unverified_receipt_after_runner_retarget(wt, gh, capsys, head, tmp_path): + runner = tmp_path / "runner" + original = tmp_path / "runner-a" + replacement = tmp_path / "runner-b" + stage = ( + f"#!{sys.executable}\n" + "import json, sys\n" + "frame = json.load(sys.stdin)\n" + "del frame['env']\n" + "frame.update(exit_code=0, duration_s=0, not_started=False, tail='')\n" + ) + for target, extra in ( + (original, f"from pathlib import Path\np = Path({str(runner)!r})\n" + f"p.unlink()\np.symlink_to({str(replacement)!r})\n"), + (replacement, ""), + ): + target.write_text(stage + extra + "print(json.dumps(frame))\n") + target.chmod(0o755) + runner.symlink_to(original) + publish_workflow(wt, WORKFLOW.replace("[checks]", f"[checks]\nrunner = {json.dumps([str(runner)])}")) + arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) + + code, out, err = run(capsys, "check") + assert code == 1 + assert "receipt produced:" not in out and "PASS" not in out + assert "stages passed but the receipt is unverified" in err + assert "rerun loopzero check from the task worktree with a stable, readable configured runner" in err + report = cli._load_report(wt) + assert report.head == head and not report.dirty and report.ok + assert report.settings_sha256 is None + assert run(capsys, "ready")[0] == 1 + + code, out, _ = run(capsys, "check") + assert code == 0 and "receipt produced:" in out + assert run(capsys, "ready")[0] == 0 + + @pytest.mark.parametrize("base_sensitive", [False, True]) def test_wait_snapshot_handles_trusted_base_advance(wt, repo, base_sensitive): if base_sensitive: @@ -4795,19 +4832,28 @@ def test_generated_pr_body_limit(wt, gh, capsys, monkeypatch, create, extra): assert json.loads(writes[0]["--input"])["body"] == prose + suffix -def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): +@pytest.mark.parametrize("refresh", ["resync", "automatic"]) +def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys, refresh): head = head_of(wt) - live = "# PR\n\n## Validation\nManual validation evidence.\n" + config = cli._load_config(SimpleNamespace(command="check", config=None), wt, pin_checks=True) + live = ("# PR\n\n## Validation\nManual validation evidence.\n\n" + "\n" + f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0\n" + "\n") gh.respond_pr_list([pr_json(headRefOid=head, body=live)]) gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) - cli._save_report(wt, CheckReport(head, False, (CheckResult("echo ok", 0, 0.0, ""),))) + stages = tuple(CheckResult(command, 0, 0.0, "") for command in config.checks) + cli._save_report(wt, CheckReport(head, False, stages)) + git(wt, "push", "-q", "-u", "origin", "lz/t1") - assert run(capsys, "pr")[0] == 0 + if refresh == "resync": + assert run(capsys, "pr")[0] == 0 + else: + cli._refresh_pr_checks(wt, config) draft = json.loads(gh.calls[-1]["--input"])["body"] assert "unverified" in draft and "run `loopzero check`" in draft assert "Manual validation evidence." in draft - git(wt, "push", "-q", "-u", "origin", "lz/t1") gh.respond_pr_list([pr_json(headRefOid=head, body=draft)]) assert run(capsys, "check")[0] == 0 draft = json.loads(gh.calls[-1]["--input"])["body"] diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e15e7912..60092cc1 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -104,6 +104,45 @@ def test_merged_source_refresh_publishes_nothing(publisher): assert hosted.main() == 0 and not [c for c in publisher.calls if "--input" in c] and publisher.argv(0)[-1] == "--include" +@pytest.mark.parametrize("state,readback", [ + ("success", "match"), ("failure", "match"), ("success", "absent"), + ("success", "publisher"), ("success", "description"), ("success", "state"), + ("success", "unreadable"), +]) +def test_final_status_lost_reply(publisher, monkeypatch, state, readback): + ready = state == "success" + monkeypatch.setattr(hosted.eligibility, "evaluate", + lambda *_: github.Readiness(ready, () if ready else ("Blocking finding",))) + post = github.commit_status + endpoint = f"api repos/{REPO}/commits/{HEAD}/statuses" + monkeypatch.setattr(github, "_retry_sleep", lambda _: None) + + def lose_reply(repo, head, context, value, description): + post(repo, head, context, value, description) + if description.startswith(("Refreshing", "Eligibility refresh failed")): + return + accepted = {"context": context, "state": value, "description": description, + "creator": {"login": "github-actions[bot]"}} + assert value == state + observed = { + "absent": [], + "publisher": [accepted | {"creator": {"login": "other"}}, accepted], + "description": [accepted | {"description": "other"}, accepted], + "state": [accepted | {"state": "pending"}, accepted], + "unreadable": {"exit": 1, "stderr": "unavailable"}, + }.get(readback, [accepted]) + publisher.respond(endpoint, observed) + raise github.ProcTimeout("lost status reply", "") + + monkeypatch.setattr(github, "commit_status", lose_reply) + if readback == "match": + assert hosted.main() == (0 if ready else 1) + else: + with pytest.raises(hosted.LoopZeroError, match="confirm eligibility status publication"): + hosted.main() + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] + + @pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): monkeypatch.setattr(github, "_retry_sleep", lambda _: None) @@ -124,7 +163,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er if error == "publication": assert "invalid description (HTTP 422)" in str(raised.value) statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending", "failure"] + assert statuses == ([] if error == "config" else ["pending", "pending"] if error == "publication" else ["pending", "failure"])