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/src/loopzero/worktree.py b/src/loopzero/worktree.py index 6b6a53ba..008a7cde 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -136,8 +136,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( @@ -146,8 +147,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: @@ -155,7 +155,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_cli.py b/tests/test_cli.py index d86327d1..3421662b 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") diff --git a/tests/test_github.py b/tests/test_github.py index 14770538..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.time, "time", 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"] @@ -765,10 +768,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"], {}) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 78315115..1d5ee7ce 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"