diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 515d3da7..e338fcd5 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1671,10 +1671,14 @@ def cmd_status(args: argparse.Namespace) -> int: print(f"branch: {branch}") print(f"head: {head}") print(f"base: {config.base_branch}") - print(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}") + dirty = worktree.is_dirty(wt) + print(f"dirty: {'yes' if dirty else 'no'}") + checked = not dirty and _current_check_report(wt, config, head) is not None + print(f"local checks: {'passed' if checked else 'no reusable pass'}", flush=True) pr = github.pr_for_branch(config.repo, branch) if pr is None: - print("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)") + hint = "run `loopzero pr`" if checked else "commit changes and pass `loopzero check` before `loopzero pr`" + print(f"pr: none ({hint})") return 0 print(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})") reviews = _pr_reviews(config.repo, pr.number) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index e85f5300..dc8baabb 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -257,10 +257,18 @@ def _read_only(args: tuple[str, ...]) -> bool: return False +def _app_token_clock() -> float | None: + """Read elapsed time including suspend, when the OS provides it.""" + if (clock := getattr(time, "CLOCK_BOOTTIME", None)) is not None: + with suppress(OSError): + return time.clock_gettime(clock) + return None + + def _cached_app_token() -> str: - # Installation tokens expire one hour after minting by wall clock, suspend included. token, minted = _app_token_cache - return token if token and 0 <= time.time() - minted < 3000 else "" + now = _app_token_clock() if token else None + return token if now is not None and 0 <= now - minted < 3000 else "" def app_token() -> str: @@ -269,14 +277,17 @@ def app_token() -> str: return token if not APP_TOKEN_HELPER.is_file() or not os.access(APP_TOKEN_HELPER, os.X_OK): return "" - minted = time.time() # before the helper runs: a suspend mid-call still ages the token + minted = _app_token_clock() # before minting so a suspend mid-call ages the token try: result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_ENV, timeout=_read_timeout(10)) except (ToolMissing, ProcTimeout, ReadDeadline, OSError): return "" if result.exit_code or not result.stdout.strip(): return "" - _app_token_cache = (result.stdout.strip(), minted) + token = result.stdout.strip() + if minted is None: + return token # no suspend-aware clock, so use this token only for this call + _app_token_cache = (token, minted) return _cached_app_token() diff --git a/tests/test_cli.py b/tests/test_cli.py index 3cd7131b..9322de8f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1900,9 +1900,9 @@ def test_review_reminted_app_token_keeps_publisher( helper.write_text(f"#!/bin/sh\necho called >> {counter}\n{fail}echo synthetic-token-$(wc -l < {counter})\n") helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) - wall, run_review = [1_000_000.0], cli._run_review - monkeypatch.setattr(github.time, "time", lambda: wall[0]) - monkeypatch.setattr(cli, "_run_review", lambda *a, **k: (run_review(*a, **k), wall.append(wall.pop() + 3601))[0]) + boot, run_review = [1_000_000.0], cli._run_review + monkeypatch.setattr(github, "_app_token_clock", lambda: boot[0]) + monkeypatch.setattr(cli, "_run_review", lambda *a, **k: (run_review(*a, **k), boot.append(boot.pop() + 3601))[0]) (wt / "workflow.toml").write_text(WORKFLOW + '\nreview_publishers = ["app[bot]"]\n') git(wt, "commit", "-qam", "configure publisher") git(wt, "update-ref", "refs/remotes/origin/main", "HEAD") @@ -3663,12 +3663,48 @@ def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls) -> None: code, out, _ = run(capsys, "status") assert_git_cost(git_calls, 7, 1) assert code == 0 and "dirty: yes" in out + assert "local checks: passed" not in out assert f"pr: #7 {URL} (draft, OPEN)" in out assert f"review: primary on {head[:12]} (approved)" in out assert "ready: no" in out and " - required check 'checks' is pending" in out assert sum(1 for c in gh.calls if c["argv"][:2] == ["api", reviews_key()[4:]]) == 1 +@pytest.mark.parametrize("receipt", ["pass", "missing", "partial", "failed", "stale", "fingerprint"]) +def test_status_no_pr_reports_receipt_before_lookup(wt, gh, capsys, monkeypatch, head, receipt): + if receipt != "missing": + arm_readiness(gh, head, wt, local_exit=int(receipt == "failed")) + path = wt / ".loopzero" / "checks.json" + report = json.loads(path.read_text()) + if receipt == "partial": + report["results"].pop() + elif receipt == "stale": + report["head"] = "0" * 40 + elif receipt == "fingerprint": + report["settings_sha256"] = "0" * 64 + path.write_text(json.dumps(report)) + + def lookup(*_): + local = capsys.readouterr().out + assert "local checks:" in local + assert ("local checks: passed" in local) == (receipt == "pass") + + monkeypatch.setattr(github, "pr_for_branch", lookup) + code, out, _ = run(capsys, "status") + assert code == 0 + hint = "run `loopzero pr`" if receipt == "pass" else "pass `loopzero check`" + assert hint in out + + +def test_status_shows_local_pass_with_pending_ci(wt, gh, capsys, head): + arm_approved_pr_with_check_result(gh, head, wt, "pending") + + code, out, _ = run(capsys, "status") + + assert code == 0 and "local checks: passed" in out + assert "ready: no" in out and "required check 'checks' is pending" in out + + def test_status_silently_ignores_legacy_report_without_dirty( wt: Path, gh: FakeGh, capsys, head ) -> None: diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index fdcc7a71..1c38bf8f 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -178,3 +178,21 @@ def test_strict_fake_matches_input_contents(fake_bin: Path, tmp_path: Path) -> N ) github.update_body(REPO, 7, "new body") fake.assert_complete() + + +def test_app_token_expires_after_wall_clock_rollback(tmp_path, monkeypatch): + helper = tmp_path / "app-token" + counter = tmp_path / "helper-calls" + helper.write_text(f'#!/bin/sh\necho called >> "{counter}"\nwc -l < "{counter}"\n') + helper.chmod(0o755) + monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) + wall_time = 10_000.0 + boot_time = 10_000.0 + monkeypatch.setattr(github.time, "time", lambda: wall_time) + monkeypatch.setattr(github.time, "CLOCK_BOOTTIME", 7, raising=False) + monkeypatch.setattr(github.time, "clock_gettime", lambda _clock_id: boot_time) + assert github.app_token() == "1" + assert github.app_token() == "1" + wall_time += 2_620 + boot_time += 3_620 + assert github.app_token() == "2" diff --git a/tests/test_github.py b/tests/test_github.py index 14770538..e96278ba 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -734,7 +734,7 @@ def test_app_identity_selection_and_cache(gh: FakeGh, tmp_path: Path, monkeypatc helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) clock = [0.0] - monkeypatch.setattr(github.time, "time", lambda: clock[0]) + monkeypatch.setattr(github, "_app_token_clock", lambda: clock[0]) monkeypatch.setattr(github.time, "monotonic", lambda: 100.0) # stopped during host suspend monkeypatch.setenv("GH_TOKEN", "operator-token") gh.respond("api repos/acme/widgets", {}) @@ -765,10 +765,10 @@ def test_app_token_age_counts_suspend_during_mint_and_retry(gh: FakeGh, tmp_path helper.write_text(f"#!/bin/sh\necho called >> {counter}\necho synthetic-token-$(wc -l < {counter})\n") helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) - wall, real_run = [1_000_000.0], github.run - suspend = lambda: wall.append(wall.pop() + 3601) # noqa: E731 - monkeypatch.setattr(github.time, "time", lambda: wall[0]) - monkeypatch.setattr(github, "run", lambda argv, **k: (real_run(argv, **k), wall[0] == 1e6 and suspend())[0]) + boot, real_run = [1_000_000.0], github.run + suspend = lambda: boot.append(boot.pop() + 3601) # noqa: E731 + monkeypatch.setattr(github, "_app_token_clock", lambda: boot[0]) + monkeypatch.setattr(github, "run", lambda argv, **k: (real_run(argv, **k), boot[0] == 1e6 and suspend())[0]) monkeypatch.setattr(github, "_retry_sleep", lambda delay: suspend()) monkeypatch.setenv("GH_TOKEN", "operator-token") gh.expect(["api", "repos/acme/widgets", "--include"], {})