diff --git a/SETUP.md b/SETUP.md index 4747e04d..0484df66 100644 --- a/SETUP.md +++ b/SETUP.md @@ -365,6 +365,9 @@ writes the receipt. For remote stages, configure an operator-trusted Without a stage adapter, run the whole check locally. Use a local slot if the host requires one. On miki, if you used the isolated install, run these from the task worktree with the `install_dir` from that recipe. +Make a scratch clone standalone before queueing, for example with +`git clone --no-local`. If a Git object alternate is outside the check sandbox, +`loopzero check` refuses it after the slot wait and before any stage runs. ```sh export PATH="$install_dir/venv/bin:$PATH" diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index fe3d0697..758e24b5 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1579,7 +1579,7 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None for _ in _poll_until(started, timeout): if sha := _landed(config, pr, closed): return sha - if not github.merge_pending(config.repo, pr.number): + if not github.merge_pending(config.repo, pr.number, pr.head_sha): if sha := _landed(config, pr, closed): return sha if not closed: diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 65fe1b67..314f77bb 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1403,7 +1403,7 @@ def mark_ready(repo: str, number: int) -> None: _QUEUE_QUERY = ( "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name)" - "{pullRequest(number:$number){isInMergeQueue autoMergeRequest{enabledAt}}}}" + "{pullRequest(number:$number){headRefOid isInMergeQueue autoMergeRequest{enabledAt}}}}" ) @@ -1434,7 +1434,7 @@ def merged_sha( raise error(argv, "PR closed without a verified merge or invalid merge evidence") -def merge_pending(repo: str, number: int) -> bool: +def merge_pending(repo: str, number: int, head_sha: str) -> bool: """True when GitHub holds the PR for merging: queued, or accepted as an auto-merge request that it moves into the queue shortly after (observed ~1 minute, #180).""" args = _pull_query(repo, number, _QUEUE_QUERY) @@ -1448,6 +1448,8 @@ def merge_pending(repo: str, number: int) -> bool: raise MergeFailed(("gh", "api", "graphql"), f"GitHub queue lookup for PR #{number}: queue status could not be verified. " f"Check the PR's queue or merge state before retrying.\n{str(exc)[-300:]}") from exc + if pr.get("headRefOid") != head_sha: + raise MergeFailed(("gh", *args), "PR head changed or unavailable during queue verification") return queued or bool(auto) @@ -1464,16 +1466,19 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: argv = ( "pr", "merge", str(number), "--repo", repo, *method, "--match-head-commit", head_sha, ) + if strategy == "queue" and merge_pending(repo, number, head_sha): + return None + write_error = None try: _gh(*argv, timeout=300) - except GhError as exc: - raise MergeFailed(exc.command, exc.tail) from exc + except (GhError, ProcTimeout, OSError) as exc: + write_error = exc sha = merged_sha(repo, number, expected_head=head_sha) if sha: return sha queue_error = None try: - if merge_pending(repo, number): + if merge_pending(repo, number, head_sha): return None except MergeFailed as exc: queue_error = exc @@ -1483,7 +1488,8 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: return sha if queue_error: raise queue_error - raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued") + detail = f": {write_error}" if write_error else "" + raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued{detail}") def _remote_branch_head(endpoint: str) -> str | None: diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index a0bf539e..ac45d157 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -171,6 +171,16 @@ def _tail(text: str) -> str: return text[-TAIL_CHARS:] +def _auth_failure(family: str, diagnostic: str) -> RunnerAuthFailed: + names = CLAUDE_AUTH_ENV if family == "claude" else CODEX_AUTH_ENV + env = _proc.build_env(names) + values = {variant for value in env.values() if value for variant in (value, json.dumps(value)[1:-1])} + patterns = [*map(re.escape, sorted(values, key=len, reverse=True)), r"\bsk-[A-Za-z0-9_-]{8,}", + r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"] + diagnostic = re.sub("|".join(patterns), "[REDACTED]", diagnostic) + return RunnerAuthFailed(f"{family}: CLI is not authenticated\n{_tail(diagnostic)}") + + def _looks_like_auth_failure(text: str) -> bool: return _AUTH_FAILURE.search(text) is not None @@ -270,7 +280,7 @@ def _run( with contextlib.suppress(json.JSONDecodeError, ValueError): envelope = _extract_json_object(done.stdout) if _claude_envelope_auth_failure(envelope) or _looks_like_auth_failure(combined): - raise RunnerAuthFailed(f"{family}: CLI is not authenticated\n{_tail(combined)}") + raise _auth_failure(family, combined) if _subscription_exhausted(combined, envelope): raise RunnerUsageLimit(f"{family}: usage limit reached", _tail(combined)) if _looks_too_long(combined): @@ -1050,13 +1060,13 @@ def _review_claude( if not isinstance(envelope, dict): raise RunnerMalformedOutput("claude: result envelope is not an object", _tail(raw)) if _claude_envelope_auth_failure(envelope): - raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(raw)}") + raise _auth_failure("claude", raw) if envelope.get("is_error") and _subscription_exhausted(raw, envelope): raise RunnerUsageLimit("claude: usage limit reached", _tail(raw)) if envelope.get("is_error") or envelope.get("subtype", "success") != "success": text = str(envelope.get("result", "")) if _looks_like_auth_failure(text): - raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(text)}") + raise _auth_failure("claude", text) if _looks_too_long(text) or _looks_too_long(raw): raise RunnerPromptTooLong("claude: prompt is too long", _tail(raw)) raise RunnerBadOutput(f"claude: {envelope.get('subtype', 'error')}", _tail(raw)) diff --git a/tests/test_cli.py b/tests/test_cli.py index 1a2658f3..466e6377 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2247,6 +2247,21 @@ def test_review_observes_new_codex_version_in_saved_receipt( assert result.provenance["cli_version"] == version +def test_review_redacts_native_authentication_diagnostics(wt, gh, fake_tool, capsys, monkeypatch, head): + arm_empty_primary_review_history(gh, head) + for family, env in (("claude", "ANTHROPIC_API_KEY"), ("codex", "OPENAI_API_KEY")): + monkeypatch.setenv(env, f"opaque-fake-{family}-credential") + fake_tool(family, "if [ \"$1\" = --version ]; then echo 'codex-cli 0.161.0'; exit 0; fi\n" + f'printf "Not logged in with %s (server echoed sk-FakeToken0123)\\n" "${env}" >&2\nexit 1\n') + code, _, err = run(capsys, "review") + assert code == 4 + assert err.count("Not logged in with [REDACTED] (server echoed [REDACTED])") == 2 + assert "opaque-fake-" not in err and "sk-FakeToken0123" not in err + for family, remedy in (("claude", "claude auth login"), ("codex", "codex login")): + assert f"{family}: CLI is not authenticated" in err + assert f"Fix: run `{remedy}`." in err + + @pytest.mark.parametrize("save", [True, False]) def test_review_malformed_fragments_stay_out_of_terminal(wt, gh, fake_bin, monkeypatch, capsys, save): prepare_review(wt, gh, fake_bin) @@ -3280,15 +3295,30 @@ def test_open_finding_blocks_delivery(wt, gh, capsys, head, command, conclusion, assert all(c["argv"][:2] != ["pr", command] for c in gh.calls) +def lose_native_merge_reply(monkeypatch): + original = github._gh + + def transport(*args, **kwargs): + result = original(*args, **kwargs) + if args[:2] == ("pr", "merge"): + raise github.ProcTimeout("lost native merge reply", "") + return result + + monkeypatch.setattr(github, "_gh", transport) + + +@pytest.mark.parametrize("lost_reply", [False, True]) @pytest.mark.parametrize("branch,changed", [ *((branch, False) for branch in TASK_BRANCHES), ("lz/t1", True), ]) def test_merge_prints_sha_and_cleans_up( - wt: Path, repo: Path, gh: FakeGh, capsys, changed, head, branch + wt: Path, repo: Path, gh: FakeGh, capsys, changed, head, branch, monkeypatch, lost_reply ) -> None: git(wt, "branch", "-m", branch) arm_squash_merge(gh, head, wt, merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='c' * 40), branch=branch) gh.respond("api -X", "") + if lost_reply: + lose_native_merge_reply(monkeypatch) code, out, err = run(capsys, "merge") out = without_accepted_receipt(out) if changed: @@ -3856,13 +3886,16 @@ def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up( assert not err and f"PR #7 was already merged as {'e' * 12}" in out and out.endswith("e" * 40 + "\n") -def native_queue(queued): - return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued}}}} +def native_queue(queued, head): + return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued, "headRefOid": head}}}} -def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None: - arm_squash_merge(gh, head, wt, merge_json(state='OPEN', head=head_of(wt), sha=None)) - gh.respond("api graphql", threads_json(), native_queue(True)) +@pytest.mark.parametrize("lost_reply", [False, True]) +def test_merge_queued_prints_and_keeps_worktree(wt, gh, capsys, head, monkeypatch, lost_reply): + arm_squash_merge(gh, head, wt, merge_json(state='OPEN', head=head, sha=None)) + gh.respond("api graphql", threads_json(), native_queue(True, head)) + if lost_reply: + lose_native_merge_reply(monkeypatch) expect_cli(capsys, 0, "merge", stderr="", stdout_contains=("queued for merge into main",), stdout_endswith="next: loopzero merge --wait follows the queue, verifies and cleans up\n") assert wt.exists() @@ -3992,7 +4025,7 @@ def test_merge_wait_preserves_reviewed_head_and_cleans_only_landed_work( merge_json(state="MERGED", head=head, sha="e" * 40) if landed else open_pr] gh.append(f"api repos/{REPO}/pulls/7", *snapshots) ejected = outcome in {"ejected", "landed-on-ejection"} - gh.respond("api graphql", threads_json(), native_queue(True), native_queue(not ejected)) + gh.respond("api graphql", threads_json(), native_queue(True, head), native_queue(not ejected, head)) gh.respond("api -X", "") poll_clock(monkeypatch, jitter=1.0) wait = 0 if ejected else 60 diff --git a/tests/test_github.py b/tests/test_github.py index 3f6aede4..a8cb8798 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -1114,6 +1114,8 @@ def test_merge_success_verifies_rest_landing(gh: FakeGh) -> None: def test_merge_command_failure(gh: FakeGh) -> None: gh.fail("pr merge", "head commit mismatch") + gh.respond(f"api repos/{REPO}/pulls/7", merge_json()) + gh.respond("api graphql", _queue_json(False)) with pytest.raises(github.MergeFailed) as info: github.merge(REPO, 7, "rebase", HEAD) assert "--rebase" in info.value.command and "mismatch" in info.value.tail @@ -1147,7 +1149,7 @@ def test_delete_remote_branch_scopes_operator_tokens(gh: FakeGh, fake_tool, monk def _queue_json(queued: bool) -> dict: - return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued}}}} + return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued, "headRefOid": HEAD}}}} def arm_merge(gh: FakeGh, queue: dict, *details: dict) -> None: @@ -1178,10 +1180,15 @@ def test_merge_reports_queue_admission_or_landing(gh, strategy, queue_state): if landed: snapshots.append(merge_json(state="MERGED", sha="d" * 40)) arm_merge(gh, accepted, *snapshots) + if strategy == "queue": + gh.respond("api graphql", _queue_json(False), accepted) assert github.merge(REPO, 7, strategy, HEAD) == ("d" * 40 if landed else None) - if not landed: - assert ("--squash" in gh.argv(0)) == (strategy == "squash") - assert "--queue" not in gh.argv(0) + if strategy == "queue": + assert github.merge(REPO, 7, strategy, HEAD) is None + writes = [c["argv"] for c in gh.calls if c["argv"][:2] == ["pr", "merge"]] + assert len(writes) == 1 + assert ("--squash" in writes[0]) == (strategy == "squash") + assert "--queue" not in writes[0] def test_merged_sha_only_for_merged_state(gh: FakeGh) -> None: diff --git a/tests/test_runners.py b/tests/test_runners.py index 828cca8e..c7f610a2 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -625,7 +625,7 @@ def test_claude_bad_severity(fake_bin: Path, tmp_path: Path) -> None: CLAUDE_EXPIRED_OAUTH = { "is_error": True, "api_error_status": 401, "terminal_reason": "api_error", - "result": "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue.", + "result": "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue. Token sk-ant-FAKE0123.", } @@ -653,6 +653,8 @@ def test_claude_classifies_error_envelopes(fake_bin, tmp_path, exit_code, output _review("claude", tmp_path) if error is RunnerBadOutput: assert not isinstance(raised.value, RunnerUsageLimit) + if output is CLAUDE_EXPIRED_OAUTH: + assert "Token [REDACTED]." in str(raised.value) @pytest.mark.parametrize("family,message", [