From fbcce3a2ec6bcae5517e4e557044c76cf68eb8c0 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:06:50 +0100 Subject: [PATCH 1/6] Verify linked PR commit completeness at the activity limit Co-Authored-By: Codex --- scripts/retro_metrics.py | 15 +++++++++-- tests/test_retro_metrics.py | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/scripts/retro_metrics.py b/scripts/retro_metrics.py index 4945b5ac..a8cee3ed 100755 --- a/scripts/retro_metrics.py +++ b/scripts/retro_metrics.py @@ -294,6 +294,16 @@ def count(value): } +def _complete_pr_commits(inputs, path, commits): + if commits is None: + return False + if len(commits) < 250: + return True + detail = inputs.get(path, lambda: run_json(["gh", "api", "--method", "GET", path]), dict) + count = (detail or {}).get("commits") + return type(count) is int and count == len(commits) + + def issue_progress(inputs, repo, issue, end): timeline = pages(inputs, f"repos/{repo}/issues/{issue['number']}/timeline") if timeline is None: @@ -313,9 +323,10 @@ def issue_progress(inputs, repo, issue, end): if not match or timestamp(event["created_at"]) >= end: continue dates += [timestamp(source["created_at"]), timestamp(event["created_at"])] - commits = pages(inputs, f"repos/{match[1]}/pulls/{match[2]}/commits") + pull = f"repos/{match[1]}/pulls/{match[2]}" + commits = pages(inputs, f"{pull}/commits") comments = pages(inputs, f"repos/{match[1]}/issues/{match[2]}/comments") - if commits is None or len(commits) >= 250 or comments is None: + if comments is None or not _complete_pr_commits(inputs, pull, commits): raise ValueError("linked PR activity unavailable or truncated") dates += [timestamp(item["commit"]["committer"]["date"]) for item in commits] dates += [timestamp(item["created_at"]) for item in comments] diff --git a/tests/test_retro_metrics.py b/tests/test_retro_metrics.py index 9f1309a5..f66cb609 100644 --- a/tests/test_retro_metrics.py +++ b/tests/test_retro_metrics.py @@ -1,5 +1,6 @@ import json import subprocess +from types import SimpleNamespace import pytest @@ -196,3 +197,53 @@ def test_invalid_band_is_usage_error(capsys): retro_metrics.main(["--repo", REPO, "--until", END, "--band", "merges", "3", "2"]) assert exc.value.code == 2 assert "ordered limits" in capsys.readouterr().err + + +@pytest.mark.parametrize(("rows", "total", "stalled"), [ + (101, None, True), + (250, 250, True), + (250, 251, False), + (250, None, False), +]) +def test_stalled_issue_checks_linked_pr_commit_count_at_limit( + tmp_path, monkeypatch, rows, total, stalled, +): + old = "2026-05-26T00:00:00Z" + pull = f"repos/{REPO}/pulls/3" + calls = [] + + def collect(argv): + endpoint = argv[-1] + calls.append(endpoint) + if endpoint == pull: + return {} if total is None else {"commits": total} + if endpoint.startswith(f"{pull}/commits?"): + page = int(endpoint.rsplit("=", 1)[1]) + size = min(100, rows - (page - 1) * 100) + return [{"commit": {"committer": {"date": old}}}] * size + if endpoint == f"repos/{REPO}/issues/3/comments?per_page=100&page=1": + return [] + assert endpoint == f"repos/{REPO}/issues/4/timeline?per_page=100&page=1" + return [{ + "event": "cross-referenced", "created_at": old, + "source": {"issue": {"created_at": old, "pull_request": { + "url": f"https://api.github.com/{pull}", + }}}, + }] + + monkeypatch.setattr(retro_metrics, "run_json", collect) + args = SimpleNamespace(repo=REPO, stall_hours=12) + priority_issues = [issue(4, old)] + end = retro_metrics.timestamp(END) + live = retro_metrics.Inputs(tmp_path, record=True) + alerts = retro_metrics.stalled_p0s(live, args, priority_issues, end) + assert [alert["kind"] for alert in alerts] == (["stalled_p0"] if stalled else []) + assert any(a["source"] == "p0/#4/activity" for a in live.alerts) == (not stalled) + assert calls.count(pull) == (1 if rows == 250 else 0) + + live.save() + before = calls.copy() + replay = retro_metrics.Inputs(tmp_path, record=False) + assert retro_metrics.stalled_p0s(replay, args, priority_issues, end) == alerts + assert replay.alerts == live.alerts + assert calls == before From 5a35ab212b1c105e6f5d2525f49cae6edb321d27 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:08:59 +0100 Subject: [PATCH 2/6] Use suspend-aware elapsed time for GitHub App token reuse Architecture-Review: unchanged; GitHub identities and credential sources stay the same while cache expiry uses elapsed boot time. Co-Authored-By: Codex --- src/loopzero/github.py | 19 +++++++++++++++---- tests/test_gh_contract.py | 18 ++++++++++++++++++ tests/test_github.py | 10 +++++----- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 4415b796..c572b88d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -255,10 +255,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: @@ -267,14 +275,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_gh_contract.py b/tests/test_gh_contract.py index f9d8b19b..45a8daa2 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -179,3 +179,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 5189977b..e82e5733 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -690,7 +690,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", {}) @@ -721,10 +721,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"], {}) From e0558633dcae7ac61da5323913a01dcf1d32cc47 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:23:24 +0100 Subject: [PATCH 3/6] Drive review token remint tests with elapsed boot time Co-Authored-By: Codex --- tests/test_cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 356ca373..75c78ff7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1678,9 +1678,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") From 95f8767d991510c6ffaa981c54f29488211669f5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:47:10 +0100 Subject: [PATCH 4/6] Reuse the retro fixture for the commit limit regression Co-Authored-By: Codex --- tests/test_retro_metrics.py | 76 +++++++++++++------------------------ 1 file changed, 26 insertions(+), 50 deletions(-) diff --git a/tests/test_retro_metrics.py b/tests/test_retro_metrics.py index f66cb609..ef53fd05 100644 --- a/tests/test_retro_metrics.py +++ b/tests/test_retro_metrics.py @@ -1,6 +1,5 @@ import json import subprocess -from types import SimpleNamespace import pytest @@ -16,7 +15,8 @@ def issue(number, created, closed=None, reason=None): @pytest.fixture -def sources(tmp_path, monkeypatch): +def sources(tmp_path, monkeypatch, request): + commit_rows, commit_total = getattr(request, "param", (1, 1)) merged = issue(1, "2026-05-26T06:00:00Z", SINCE) at_end = issue(2, SINCE, END) p0 = issue(4, "2026-05-23T12:00:00Z") @@ -42,7 +42,8 @@ def sources(tmp_path, monkeypatch): {"event": "commented", "created_at": END}, ], "issues/5/timeline": [pull_ref], - "pulls/3/commits": [{"commit": {"committer": {"date": "2026-05-28T21:00:00Z"}}}], + "pulls/3": {"commits": commit_total}, + "pulls/3/commits": [{"commit": {"committer": {"date": "2026-05-28T21:00:00Z"}}}] * commit_rows, "issues/3/comments": [], } calls = [] @@ -69,6 +70,9 @@ def collect(argv, *, input, **kwargs): raise subprocess.CalledProcessError(1, argv) path = label data = rows[path] + if path == "pulls/3/commits": + offset = (int(query.rsplit("=", 1)[1]) - 1) * 100 + data = data[offset:offset + 100] return subprocess.CompletedProcess(argv, 0, json.dumps(data), "") monkeypatch.setattr(retro_metrics.subprocess, "run", collect) @@ -199,51 +203,23 @@ def test_invalid_band_is_usage_error(capsys): assert "ordered limits" in capsys.readouterr().err -@pytest.mark.parametrize(("rows", "total", "stalled"), [ - (101, None, True), - (250, 250, True), - (250, 251, False), - (250, None, False), -]) -def test_stalled_issue_checks_linked_pr_commit_count_at_limit( - tmp_path, monkeypatch, rows, total, stalled, -): - old = "2026-05-26T00:00:00Z" - pull = f"repos/{REPO}/pulls/3" - calls = [] +@pytest.mark.parametrize(("sources", "detail_reads", "stalled"), [ + ((101, None), 0, True), + ((250, 250), 1, True), + ((250, 251), 1, False), + ((250, None), 1, False), +], indirect=["sources"]) +def test_stalled_issue_checks_linked_pr_commit_count_at_limit(sources, detail_reads, stalled, capsys): + calls, args = sources + options = ["--alerts", "--stall-hours", "1"] + assert retro_metrics.main([*args, *options, "--record"]) == 0 + live = capsys.readouterr() + alerts = json.loads(live.out)["alerts"] + assert any(a["kind"] == "stalled_p0" and a["issue"] == 5 for a in alerts) == stalled + assert any(a.get("source") == "p0/#5/activity" for a in alerts) == (not stalled) + assert sum(call[-1] == f"repos/{REPO}/pulls/3" for call in calls) == detail_reads - def collect(argv): - endpoint = argv[-1] - calls.append(endpoint) - if endpoint == pull: - return {} if total is None else {"commits": total} - if endpoint.startswith(f"{pull}/commits?"): - page = int(endpoint.rsplit("=", 1)[1]) - size = min(100, rows - (page - 1) * 100) - return [{"commit": {"committer": {"date": old}}}] * size - if endpoint == f"repos/{REPO}/issues/3/comments?per_page=100&page=1": - return [] - assert endpoint == f"repos/{REPO}/issues/4/timeline?per_page=100&page=1" - return [{ - "event": "cross-referenced", "created_at": old, - "source": {"issue": {"created_at": old, "pull_request": { - "url": f"https://api.github.com/{pull}", - }}}, - }] - - monkeypatch.setattr(retro_metrics, "run_json", collect) - args = SimpleNamespace(repo=REPO, stall_hours=12) - priority_issues = [issue(4, old)] - end = retro_metrics.timestamp(END) - live = retro_metrics.Inputs(tmp_path, record=True) - alerts = retro_metrics.stalled_p0s(live, args, priority_issues, end) - assert [alert["kind"] for alert in alerts] == (["stalled_p0"] if stalled else []) - assert any(a["source"] == "p0/#4/activity" for a in live.alerts) == (not stalled) - assert calls.count(pull) == (1 if rows == 250 else 0) - - live.save() - before = calls.copy() - replay = retro_metrics.Inputs(tmp_path, record=False) - assert retro_metrics.stalled_p0s(replay, args, priority_issues, end) == alerts - assert replay.alerts == live.alerts - assert calls == before + count = len(calls) + assert retro_metrics.main([*args, *options]) == 0 + assert capsys.readouterr() == live + assert len(calls) == count From 279dbbd8f69e1f1130c15e683af984375271fa4f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:06:41 +0100 Subject: [PATCH 5/6] Cover wall-clock rollback in the existing token cache test Co-Authored-By: Codex --- tests/test_gh_contract.py | 18 ------------------ tests/test_github.py | 9 ++++++--- 2 files changed, 6 insertions(+), 21 deletions(-) diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index 1c38bf8f..fdcc7a71 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -178,21 +178,3 @@ 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 e96278ba..cbdc0588 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -733,8 +733,10 @@ def test_app_identity_selection_and_cache(gh: FakeGh, tmp_path: Path, monkeypatc helper.write_text(f"#!/bin/sh\necho called >> {counter}\necho synthetic-app-token\n") helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) - clock = [0.0] - monkeypatch.setattr(github, "_app_token_clock", lambda: clock[0]) + wall_time = 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 _: boot_time) monkeypatch.setattr(github.time, "monotonic", lambda: 100.0) # stopped during host suspend monkeypatch.setenv("GH_TOKEN", "operator-token") gh.respond("api repos/acme/widgets", {}) @@ -754,7 +756,8 @@ def test_app_identity_selection_and_cache(gh: FakeGh, tmp_path: Path, monkeypatc "operator-token", "operator-token", "operator-token", ] assert counter.read_text().splitlines() == ["called"] - clock[0] = 3601.0 + boot_time += 3_620 + wall_time += 2_620 # The wall clock stepped back by a thousand seconds. github.api_get("repos/acme/widgets") assert counter.read_text().splitlines() == ["called", "called"] From e01d259a60fa953815e510be7c14fbcd38a95ff6 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:17:48 +0100 Subject: [PATCH 6/6] Resolve the fetched task base by ref Architecture-Review: unchanged; start still creates its worktree at the fetched configured base. Co-Authored-By: Codex --- src/loopzero/worktree.py | 8 ++++---- tests/test_worktree.py | 14 +++++++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 8dce414f..93966fe4 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -130,8 +130,9 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: raise WorktreeError(refusal) if not existing and _branch_exists(repo_root, branch): raise WorktreeError(f"branch already exists: {branch}") + base_ref = f"refs/remotes/origin/{base_branch}" try: - _git(repo_root, "fetch", "--quiet", "origin", f"refs/heads/{base_branch}") + _git(repo_root, "fetch", "--quiet", "origin", f"+refs/heads/{base_branch}:{base_ref}") except GitError: if "origin" not in _git(repo_root, "remote").splitlines(): raise WorktreeError( @@ -140,8 +141,7 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: "with `git remote rename origin`." ) from None raise - base_ref = f"origin/{base_branch}" - base = _git(repo_root, "rev-parse", "--verify", "FETCH_HEAD^{commit}") + base = _git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}") if existing: existing_head = _resumable_head(repo_root, wt, branch) if existing_head is None: @@ -149,7 +149,7 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: if existing_head != base: raise WorktreeError( f"cannot resume start at {wt}: existing HEAD {existing_head} does not match " - f"{base_ref} at {base}; run loopzero start with a new slug" + f"origin/{base_branch} at {base}; run loopzero start with a new slug" ) _ensure_excludes(repo_root) if not existing: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 90460bac..14aa39e2 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -51,9 +51,9 @@ def test_branch_refuses_detached_head(repo: Path) -> None: @pytest.mark.parametrize("branch", [None, "feature/ci+release"]) -def test_start_creates_branch_worktree_and_task_file(repo: Path, branch: str | None) -> None: - if branch: - git(repo, "push", "-q", "origin", f"HEAD:refs/heads/{branch}") +def test_start_creates_branch_worktree_and_task_file(repo: Path, branch: str | None, monkeypatch) -> None: + side = branch or "side" + git(repo, "push", "-q", "origin", f"HEAD:refs/heads/{side}") upstream = commit_on_origin(repo, "feature.txt") if branch: checkout = repo.parent / "single-branch" @@ -61,6 +61,14 @@ def test_start_creates_branch_worktree_and_task_file(repo: Path, branch: str | N git(repo, "clone", "-q", "--single-branch", "--branch", branch, origin, str(checkout)) assert not git(checkout, "for-each-ref", "refs/heads/main", "refs/remotes/origin/main").strip() repo = checkout + invoke = worktree._git + def interleave(path, *args, **kwargs): + result = invoke(path, *args, **kwargs) + if args[0] == "fetch": + git(path, "fetch", "-q", "origin", f"refs/heads/{side}") + return result + + monkeypatch.setattr(worktree, "_git", interleave) wt = worktree.start(repo, "my-task", "main") assert wt == repo / ".worktrees" / "my-task" assert (wt / "feature.txt").exists(), "fetched origin/main before branching"