From 36aac2b46a2206bc72d0657b6ed73dda4610904a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:02:52 +0100 Subject: [PATCH 1/3] Redact credentials in reviewer authentication diagnostics Architecture-Review: unchanged; the runner keeps existing credential forwarding and authentication failure behavior and scrubs native diagnostic text. Co-Authored-By: Codex --- src/loopzero/runners.py | 16 +++++++++++++--- tests/test_cli.py | 15 +++++++++++++++ tests/test_runners.py | 6 ++++-- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 3499b866..74ecd5e8 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -176,6 +176,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 any(p.search(text) for p in _AUTH_PATTERNS) @@ -281,7 +291,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): @@ -1149,13 +1159,13 @@ def _review_claude( if not isinstance(envelope, dict): raise RunnerBadOutput("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 3cd7131b..f5659007 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2041,6 +2041,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("mixed_authors", [False, True]) def test_review_fails_with_three_line_errors_and_remedies_without_spending_budget( wt: Path, gh: FakeGh, capsys, monkeypatch, head, mixed_authors diff --git a/tests/test_runners.py b/tests/test_runners.py index 991d10ab..2c243368 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -690,7 +690,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.", } @@ -706,8 +706,10 @@ def test_claude_bad_severity(fake_bin: Path, tmp_path: Path) -> None: ]) def test_claude_auth_failure(fake_bin, tmp_path, output, exit_code, diagnostic): _fake_claude(fake_bin, output, exit_code=exit_code) - with pytest.raises(RunnerAuthFailed, match=diagnostic): + with pytest.raises(RunnerAuthFailed, match=diagnostic) as failure: _review("claude", tmp_path) + if output is CLAUDE_EXPIRED_OAUTH: + assert "Token [REDACTED]." in str(failure.value) @pytest.mark.parametrize("exit_code", [0, 1]) From d82dd4afa3df822d0ccaae9215d3ccfa59fcafb1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:55:38 +0100 Subject: [PATCH 2/3] Merge origin/main and retain hosted test imports Architecture-Review: unchanged; merge recovery keeps the reviewed head checks and the conflict resolution only changes a test reference. Co-Authored-By: Codex --- src/loopzero/cli.py | 2 +- src/loopzero/github.py | 18 ++++++++++++------ tests/test_cli.py | 26 ++++++++++++++++++++++---- tests/test_github.py | 14 ++++++++++---- 4 files changed, 45 insertions(+), 15 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2077c223..f2b5f9d7 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1411,7 +1411,7 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None sha = _landed(config, pr, closed) if sha: return sha - if not github.merge_pending(config.repo, pr.number): + if not github.merge_pending(config.repo, pr.number, pr.head_sha): sha = _landed(config, pr, closed) if sha: return sha diff --git a/src/loopzero/github.py b/src/loopzero/github.py index c9a77a48..944c67ef 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1322,7 +1322,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}}}}" ) @@ -1354,7 +1354,7 @@ def merged_sha( raise GhError(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).""" owner, name = repo.split("/", 1) @@ -1373,6 +1373,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", *argv), "PR head changed or unavailable during queue verification") return queued or bool(auto) @@ -1389,16 +1391,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 @@ -1408,7 +1413,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/tests/test_cli.py b/tests/test_cli.py index 6933ecd3..5a23ba1f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3223,6 +3223,19 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non assert wt.exists() +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", [ ("lz/t1", False), ("t3/archive-review-receipts", False), @@ -3231,13 +3244,15 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non ("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_approved_ready_pr(gh, head, wt, isDraft=False, branch=branch) gh.respond("pr merge", "") gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='c' * 40)) 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: @@ -3914,12 +3929,15 @@ def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up( assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls) -def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None: +@pytest.mark.parametrize("lost_reply", [False, True]) +def test_merge_queued_prints_and_keeps_worktree(wt, gh, capsys, head, monkeypatch, lost_reply): arm_approved_ready_pr(gh, head, wt, isDraft=False) gh.respond("pr merge", "") gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='OPEN', head=head_of(wt), sha=None)) gh.respond("api graphql", threads_json(), - {"data": {"repository": {"pullRequest": {"isInMergeQueue": True}}}}) + {"data": {"repository": {"pullRequest": {"isInMergeQueue": True, "headRefOid": head}}}}) + if lost_reply: + lose_native_merge_reply(monkeypatch) code, out, err = run(capsys, "merge") assert (code, err) == (0, "") assert "queued for merge into main" in out and out.endswith( @@ -4045,7 +4063,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) def queue(value: bool) -> dict: - return {"data": {"repository": {"pullRequest": {"isInMergeQueue": value}}}} + return {"data": {"repository": {"pullRequest": {"isInMergeQueue": value, "headRefOid": head}}}} ejected = outcome in {"ejected", "landed-on-ejection"} gh.respond("api graphql", threads_json(), queue(True), queue(not ejected)) gh.respond("api -X", "") diff --git a/tests/test_github.py b/tests/test_github.py index cbdc0588..2a8d08dd 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -1221,6 +1221,8 @@ def test_merge_success_verifies_rest_landing( 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 @@ -1239,7 +1241,7 @@ def test_delete_remote_branch_checks_encoded_ref(gh: FakeGh, remote_head: str | def _queue_json(queued: bool) -> dict: - return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued}}}} + return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued, "headRefOid": HEAD}}}} @pytest.mark.parametrize("missing", [False, True]) @@ -1262,10 +1264,14 @@ def test_merge_queued_returns_none(gh: FakeGh, strategy, auto) -> None: accepted = _queue_json(not auto) if auto: accepted["data"]["repository"]["pullRequest"]["autoMergeRequest"] = {"enabledAt": "t"} - gh.respond("api graphql", accepted) + gh.respond("api graphql", *([_queue_json(False)] if strategy == "queue" else []), accepted) assert github.merge(REPO, 7, strategy, HEAD) is None - 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_merge_landed_between_reads_is_reported_merged(gh: FakeGh) -> None: From 534fa2f0895e250e3c07fcf20f4426e7e3977350 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:12:15 +0100 Subject: [PATCH 3/3] Document standalone scratch clones for slotted checks Architecture-Review: unchanged; documents the established sandbox visibility check and leaves admission and mounts unchanged. Co-Authored-By: Codex --- SETUP.md | 3 +++ 1 file changed, 3 insertions(+) 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"