~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(ci): harden auto-merge branch updates (#6171)
LearningCircuit760a6f2148ad
diff --git a/.github/workflows/update-oldest-auto-merge-pr.yml b/.github/workflows/update-oldest-auto-merge-pr.ymlindex 39a9955021..685d73fba0 100644--- a/.github/workflows/update-oldest-auto-merge-pr.yml+++ b/.github/workflows/update-oldest-auto-merge-pr.yml@@ -2,8 +2,8 @@ name: Update oldest auto-merge PRon:schedule:- # Avoid the top of the hour, when scheduled Actions traffic is highest.- - cron: '17 * * * *'+ # Run twice hourly while avoiding the busiest :00 and :30 boundaries.+ - cron: '17,47 * * * *'workflow_dispatch:concurrency:@@ -45,8 +45,9 @@ jobs:- name: Update the selected PR branchif: ${{ steps.select.outputs.number != '' }}env:- # Keep the PAT scoped to this trusted step. Unlike GITHUB_TOKEN,- # it allows the resulting synchronize event to start normal PR CI.+ # Fork updates require a classic PAT with public_repo + workflow+ # scopes. Keep it confined to this trusted step; unlike GITHUB_TOKEN,+ # it also lets the synchronize event start normal PR CI.GH_TOKEN: ${{ secrets.PAT_TOKEN }}PR_NUMBER: ${{ steps.select.outputs.number }}EXPECTED_HEAD_SHA: ${{ steps.select.outputs.head_sha }}diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex a84bc87a3e..f5cb5f23fb 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -108,7 +108,7 @@| `sbom.yml` | last 30 days | manual, schedule(0 10 * * 3), release | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/sbom.yml?query=event%3Aschedule) || `update-dependencies.yml` | last 30 days | workflow_call, manual, schedule(0 8 * * 3) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-dependencies.yml?query=event%3Aschedule) || `update-npm-dependencies.yml` | last 30 days | workflow_call, manual, schedule(0 8 * * 4) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-npm-dependencies.yml?query=event%3Aschedule) |-| `update-oldest-auto-merge-pr.yml` | never | schedule(17 * * * *), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-oldest-auto-merge-pr.yml?query=event%3Aschedule) |+| `update-oldest-auto-merge-pr.yml` | never | schedule(17,47 * * * *), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-oldest-auto-merge-pr.yml?query=event%3Aschedule) |## PR / push checksdiff --git a/scripts/ci/update_oldest_auto_merge_pr.py b/scripts/ci/update_oldest_auto_merge_pr.pyindex a53825c80d..cfae7ae958 100644--- a/scripts/ci/update_oldest_auto_merge_pr.py+++ b/scripts/ci/update_oldest_auto_merge_pr.py@@ -22,7 +22,8 @@ from collections.abc import Sequencefrom pathlib import Pathfrom typing import Any-PR_FIELDS = (+PR_LIST_FIELDS = (+ "id","number","url","createdAt",@@ -38,6 +39,40 @@ PR_FIELDS = ("autoMergeRequest",)+PR_FIELDS = (+ *PR_LIST_FIELDS,+ "statusCheckRollup",+)++FAILED_CHECK_RESULTS = frozenset(+ {+ "ACTION_REQUIRED",+ "ERROR",+ "FAILURE",+ "STARTUP_FAILURE",+ "TIMED_OUT",+ }+)++UPDATE_BRANCH_MUTATION = """\+mutation UpdatePullRequestBranch(+ $pullRequestId: ID!+ $expectedHeadOid: GitObjectID!+) {+ updatePullRequestBranch(+ input: {+ pullRequestId: $pullRequestId+ expectedHeadOid: $expectedHeadOid+ updateMethod: MERGE+ }+ ) {+ pullRequest {+ number+ }+ }+}+"""+class UpdaterError(RuntimeError):"""A safe, user-facing workflow failure."""@@ -75,14 +110,31 @@ def run_gh_json(args: Sequence[str]) -> Any:raise UpdaterError("gh returned invalid JSON") from exc-def is_eligible(+def failed_check_names(pull_request: dict[str, Any]) -> list[str]:+ """Return the names of current checks with a red result."""+ rollup = pull_request.get("statusCheckRollup")+ if not isinstance(rollup, list):+ return []++ failures = {+ str(check.get("name") or check.get("context") or "unnamed check")+ for check in rollup+ if isinstance(check, dict)+ and (check.get("conclusion") or check.get("state"))+ in FAILED_CHECK_RESULTS+ }+ return sorted(failures)+++def matches_update_state(pull_request: dict[str, Any],*,base: str,expected_head_sha: str | None = None,) -> bool:- """Return whether a PR is safe and useful to update right now."""+ """Return whether a PR has the GitHub state required for an update."""number = pull_request.get("number")+ pull_request_id = pull_request.get("id")created_at = pull_request.get("createdAt")head_sha = pull_request.get("headRefOid")is_cross_repository = pull_request.get("isCrossRepository")@@ -90,16 +142,14 @@ def is_eligible(has_valid_identity = (type(number) is intand number > 0+ and isinstance(pull_request_id, str)+ and bool(pull_request_id)and isinstance(created_at, str)and bool(created_at)and isinstance(head_sha, str)and bool(head_sha)and type(is_cross_repository) is bool)- can_modify_head = (- is_cross_repository is False- or pull_request.get("maintainerCanModify") is True- )head_is_current = expected_head_sha is None or head_sha == expected_head_shareturn bool(@@ -111,11 +161,47 @@ def is_eligible(and pull_request.get("autoMergeRequest") is not Noneand pull_request.get("mergeable") == "MERGEABLE"and pull_request.get("mergeStateStatus") == "BEHIND"- and can_modify_headand head_is_current)+def candidate_skip_reason(pull_request: dict[str, Any]) -> str | None:+ """Explain an operational reason not to update an otherwise-ready PR."""+ if (+ pull_request.get("isCrossRepository") is True+ and pull_request.get("maintainerCanModify") is not True+ ):+ return "fork does not allow maintainer edits"++ rollup = pull_request.get("statusCheckRollup")+ if not isinstance(rollup, list) or not all(+ isinstance(check, dict) for check in rollup+ ):+ return "check status is unavailable"++ failed_checks = failed_check_names(pull_request)+ if failed_checks:+ return f"failed checks: {', '.join(failed_checks)}"+ return None+++def is_eligible(+ pull_request: dict[str, Any],+ *,+ base: str,+ expected_head_sha: str | None = None,+) -> bool:+ """Return whether a PR is safe and useful to update right now."""+ return (+ matches_update_state(+ pull_request,+ base=base,+ expected_head_sha=expected_head_sha,+ )+ and candidate_skip_reason(pull_request) is None+ )++def eligible_pull_requests(pull_requests: Sequence[dict[str, Any]], *, base: str) -> list[dict[str, Any]]:@@ -151,7 +237,7 @@ def fetch_pull_requests(repository: str, base: str) -> list[dict[str, Any]]:"--limit","1000","--json",- ",".join(PR_FIELDS),+ ",".join(PR_LIST_FIELDS),])if not isinstance(response, list) or not all(@@ -209,38 +295,77 @@ def select_oldest(step_summary: Path | None,) -> dict[str, Any] | None:"""Discover candidates, report all of them, and output the oldest."""- candidates = eligible_pull_requests(- fetch_pull_requests(repository, base), base=base+ pull_requests = fetch_pull_requests(repository, base)+ update_state_candidates = sorted(+ (+ pull_request+ for pull_request in pull_requests+ if matches_update_state(pull_request, base=base)+ ),+ key=lambda pull_request: (+ pull_request["createdAt"],+ pull_request["number"],+ ),+ )+ candidates = []+ skipped_candidates = []+ for listed_pull_request in update_state_candidates:+ pull_request = fetch_pull_request(+ repository, listed_pull_request["number"]+ )+ if not matches_update_state(pull_request, base=base):+ continue+ reason = candidate_skip_reason(pull_request)+ if reason is None:+ candidates.append(pull_request)+ else:+ skipped_candidates.append((pull_request, reason))+ candidates.sort(+ key=lambda pull_request: (+ pull_request["createdAt"],+ pull_request["number"],+ ),+ )+ skipped_candidates.sort(+ key=lambda item: (item[0]["createdAt"], item[0]["number"]),)print(f"Found {len(candidates)} eligible pull request(s).")summary_lines = ["## Auto-merge branch updater", ""]if not candidates:summary_lines.append(- f"No approved, auto-merge-enabled PR is currently behind `{base}`."+ "No approved, auto-merge-enabled PR with an editable head "+ f"and no failed checks is currently behind `{base}`.")write_outputs(github_output, {"number": "", "head_sha": ""})- append_summary(step_summary, summary_lines)- return None-- summary_lines.extend(["Eligible PRs, oldest first:", ""])- summary_lines.extend(- f"- [#{pull_request['number']}]({pull_request['url']}) — "- f"opened `{pull_request['createdAt']}`"- for pull_request in candidates- )+ selected = None+ else:+ summary_lines.extend(["Eligible PRs, oldest first:", ""])+ summary_lines.extend(+ f"- [#{pull_request['number']}]({pull_request['url']}) — "+ f"opened `{pull_request['createdAt']}`"+ for pull_request in candidates+ )++ selected = candidates[0]+ summary_lines.extend(+ ["", f"Selected oldest candidate: #{selected['number']}."]+ )+ write_outputs(+ github_output,+ {+ "number": str(selected["number"]),+ "head_sha": selected["headRefOid"],+ },+ )++ if skipped_candidates:+ summary_lines.extend(["", "Skipped candidates:", ""])+ summary_lines.extend(+ f"- [#{pull_request['number']}]({pull_request['url']}) — {reason}"+ for pull_request, reason in skipped_candidates+ )- selected = candidates[0]- summary_lines.extend(- ["", f"Selected oldest candidate: #{selected['number']}."]- )- write_outputs(- github_output,- {- "number": str(selected["number"]),- "head_sha": selected["headRefOid"],- },- )append_summary(step_summary, summary_lines)return selected@@ -265,25 +390,50 @@ def update_pull_request(append_summary(step_summary, ["", message])return False- response = run_gh_json(- [- "api",- "--method",- "PUT",- "-H",- "Accept: application/vnd.github+json",- "-H",- "X-GitHub-Api-Version: 2022-11-28",- f"/repos/{repository}/pulls/{number}/update-branch",- "-f",- f"expected_head_sha={expected_head_sha}",- ]- )- message = (- response.get("message", "Branch update accepted.")- if isinstance(response, dict)- else "Branch update accepted."- )+ # Use the same mutation as ``gh pr update-branch``. Passing the PR node ID+ # and revalidated head SHA directly preserves the atomic stale-head guard.+ try:+ response = run_gh_json(+ [+ "api",+ "graphql",+ "-f",+ f"query={UPDATE_BRANCH_MUTATION}",+ "-F",+ f"pullRequestId={current['id']}",+ "-F",+ f"expectedHeadOid={expected_head_sha}",+ ]+ )+ except UpdaterError as exc:+ detail = str(exc)+ fork_auth_errors = (+ "permission to update head repository",+ "without `workflow` scope",+ "without `workflows` permission",+ )+ if current["isCrossRepository"] and any(+ marker in detail for marker in fork_auth_errors+ ):+ raise UpdaterError(+ "PAT_TOKEN cannot update this editable fork; use a classic "+ "PAT with public_repo and workflow scopes"+ ) from exc+ raise+ try:+ updated_number = response["data"]["updatePullRequestBranch"][+ "pullRequest"+ ]["number"]+ except (KeyError, TypeError) as exc:+ raise UpdaterError(+ "GitHub returned an unexpected branch-update response"+ ) from exc+ if updated_number != number:+ raise UpdaterError(+ "GitHub returned an unexpected pull request after branch update"+ )++ message = "Branch update accepted."print(message)append_summary(step_summary,diff --git a/tests/ci/test_update_oldest_auto_merge_pr.py b/tests/ci/test_update_oldest_auto_merge_pr.pyindex e0346e4413..08e6216fbf 100644--- a/tests/ci/test_update_oldest_auto_merge_pr.py+++ b/tests/ci/test_update_oldest_auto_merge_pr.py@@ -1,4 +1,4 @@-"""Tests for the hourly auto-merge pull-request branch updater.+"""Tests for the twice-hourly auto-merge pull-request branch updater.The production script is exercised with mocked ``gh`` responses. No test usesGitHub credentials, calls the network, updates a branch, or merges a PR.@@ -35,6 +35,7 @@ def pull_request():"""Return a minimal PR that satisfies every update requirement."""result = {+ "id": f"PR_example_{number}","number": number,"url": f"https://github.com/example/project/pull/{number}","createdAt": created_at,@@ -48,6 +49,7 @@ def pull_request("mergeStateStatus": "BEHIND","reviewDecision": "APPROVED","autoMergeRequest": {"enabledAt": "2026-01-02T04:00:00Z"},+ "statusCheckRollup": [],}result.update(overrides)return result@@ -91,6 +93,45 @@ def test_modifiable_fork_is_eligible():assert updater.is_eligible(candidate, base="main")+ "check",+ [+ {"name": "unit-tests", "conclusion": "FAILURE"},+ {"name": "lint", "conclusion": "TIMED_OUT"},+ {"name": "policy", "conclusion": "ACTION_REQUIRED"},+ {"name": "bootstrap", "conclusion": "STARTUP_FAILURE"},+ {"context": "legacy-ci", "state": "ERROR"},+ ],+ ids=["failure", "timeout", "action-required", "startup", "status-error"],+)+def test_red_check_is_skipped_even_when_optional(check):+ candidate = pull_request(statusCheckRollup=[check])++ assert not updater.is_eligible(candidate, base="main")+++ "conclusion",+ ["SUCCESS", "SKIPPED", "NEUTRAL", "CANCELLED", "STALE", None],+)+def test_non_red_check_does_not_block_update(conclusion):+ candidate = pull_request(+ statusCheckRollup=[{"name": "optional-check", "conclusion": conclusion}]+ )++ assert updater.is_eligible(candidate, base="main")+++def test_failed_candidate_becomes_eligible_after_checks_pass():+ candidate = pull_request(+ statusCheckRollup=[{"name": "tests", "conclusion": "FAILURE"}]+ )++ assert not updater.is_eligible(candidate, base="main")+ candidate["statusCheckRollup"][0]["conclusion"] = "SUCCESS"+ assert updater.is_eligible(candidate, base="main")++def test_candidates_are_sorted_oldest_first_then_by_number():candidates = [pull_request(30, "2026-03-01T00:00:00Z"),@@ -135,7 +176,10 @@ def test_selection_queries_oldest_approved_prs_and_writes_outputs(def fake_gh(args):calls.append(args)- return [newer, oldest]+ if args[:2] == ["pr", "list"]:+ return [newer, oldest]+ number = int(args[2])+ return {oldest["number"]: oldest, newer["number"]: newer}[number]monkeypatch.setattr(updater, "run_gh_json", fake_gh)@@ -154,6 +198,71 @@ def test_selection_queries_oldest_approved_prs_and_writes_outputs(assert calls[0][:2] == ["pr", "list"]assert "review:approved sort:created-asc" in calls[0]assert calls[0][calls[0].index("--limit") + 1] == "1000"+ fields = calls[0][calls[0].index("--json") + 1]+ assert "id" in fields+ assert "maintainerCanModify" in fields+ assert "statusCheckRollup" not in fields+ assert [call[:2] for call in calls[1:]] == [+ ["pr", "view"],+ ["pr", "view"],+ ]+ detail_fields = calls[1][calls[1].index("--json") + 1]+ assert "statusCheckRollup" in detail_fields+++def test_selection_skips_failed_oldest_candidate(monkeypatch, tmp_path):+ failed = pull_request(+ 12,+ "2026-01-01T00:00:00Z",+ statusCheckRollup=[{"name": "optional-lint", "conclusion": "FAILURE"}],+ )+ healthy = pull_request(13, "2026-02-01T00:00:00Z")+ output = tmp_path / "output"+ summary = tmp_path / "summary"++ def fake_gh(args):+ if args[:2] == ["pr", "list"]:+ return [failed, healthy]+ number = int(args[2])+ return {failed["number"]: failed, healthy["number"]: healthy}[number]++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ selected = updater.select_oldest(+ "example/project",+ "main",+ github_output=output,+ step_summary=summary,+ )++ assert selected == healthy+ assert output.read_text() == f"number=13\nhead_sha={HEAD_A}\n"+ assert "#12" in summary.read_text()+ assert "failed checks: optional-lint" in summary.read_text()+++def test_all_failed_candidates_are_a_successful_no_op(monkeypatch, tmp_path):+ failed = pull_request(+ statusCheckRollup=[{"name": "tests", "conclusion": "FAILURE"}]+ )+ output = tmp_path / "output"+ summary = tmp_path / "summary"++ def fake_gh(args):+ return [failed] if args[:2] == ["pr", "list"] else failed++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ selected = updater.select_oldest(+ "example/project",+ "main",+ github_output=output,+ step_summary=summary,+ )++ assert selected is None+ assert output.read_text() == "number=\nhead_sha=\n"+ assert "failed checks: tests" in summary.read_text()def test_empty_selection_is_a_successful_no_op(monkeypatch, tmp_path):@@ -181,7 +290,9 @@ def test_update_revalidates_and_uses_expected_head_sha(monkeypatch, tmp_path):calls.append(args)if args[:2] == ["pr", "view"]:return pull_request(55)- return {"message": "Updating pull request branch."}+ return {+ "data": {"updatePullRequestBranch": {"pullRequest": {"number": 55}}}+ }monkeypatch.setattr(updater, "run_gh_json", fake_gh)@@ -197,11 +308,53 @@ def test_update_revalidates_and_uses_expected_head_sha(monkeypatch, tmp_path):assert len(calls) == 2assert calls[0][:3] == ["pr", "view", "55"]update_call = calls[1]- assert update_call[:3] == ["api", "--method", "PUT"]- assert "/repos/example/project/pulls/55/update-branch" in update_call- assert f"expected_head_sha={HEAD_A}" in update_call- assert "/repos/example/project/pulls/55/merge" not in update_call- assert "Updating pull request branch." in summary.read_text()+ assert update_call[:2] == ["api", "graphql"]+ query_argument = update_call[update_call.index("-f") + 1]+ assert "updatePullRequestBranch" in query_argument+ assert "mergePullRequest" not in query_argument+ assert "pullRequestId=PR_example_55" in update_call+ assert f"expectedHeadOid={HEAD_A}" in update_call+ assert "Branch update accepted." in summary.read_text()+++ "api_error",+ [+ "GraphQL: user doesn't have permission to update head repository",+ "GraphQL: refusing to update a workflow without `workflow` scope",+ "GraphQL: refusing to update a workflow without `workflows` permission",+ ],+)+def test_fork_authorization_error_explains_classic_pat_requirement(+ monkeypatch, tmp_path, api_error+):+ calls = []++ def fake_gh(args):+ calls.append(args)+ if args[:2] == ["pr", "view"]:+ return pull_request(+ 55,+ isCrossRepository=True,+ maintainerCanModify=True,+ )+ raise updater.UpdaterError(api_error)++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ with pytest.raises(+ updater.UpdaterError,+ match=r"classic PAT with public_repo and workflow scopes",+ ):+ updater.update_pull_request(+ "example/project",+ "main",+ number=55,+ expected_head_sha=HEAD_A,+ step_summary=tmp_path / "summary",+ )++ assert len(calls) == 2@pytest.mark.parametrize(@@ -212,6 +365,11 @@ def test_update_revalidates_and_uses_expected_head_sha(monkeypatch, tmp_path):{"reviewDecision": "CHANGES_REQUESTED"},{"autoMergeRequest": None},{"mergeStateStatus": "CLEAN"},+ {+ "statusCheckRollup": [+ {"name": "late-failure", "conclusion": "FAILURE"}+ ]+ },],ids=["merged-or-closed",@@ -219,6 +377,7 @@ def test_update_revalidates_and_uses_expected_head_sha(monkeypatch, tmp_path):"approval-revoked","auto-merge-disabled","already-updated",+ "check-failed",],)def test_changed_pr_is_not_updated(monkeypatch, tmp_path, change):@@ -277,12 +436,12 @@ def workflow():return yaml.safe_load(WORKFLOW.read_text())-def test_workflow_runs_hourly_and_serializes_updates(workflow):+def test_workflow_runs_twice_hourly_and_serializes_updates(workflow):# PyYAML 1.1 parses the unquoted key ``on`` as boolean True.triggers = workflow.get("on", workflow.get(True))assert triggers == {- "schedule": [{"cron": "17 * * * *"}],+ "schedule": [{"cron": "17,47 * * * *"}],"workflow_dispatch": None,}assert workflow["concurrency"] == {@@ -314,6 +473,26 @@ def test_workflow_is_a_thin_pinned_wrapper(workflow):assert "gh pr" not in run_scriptsassert "gh api" not in run_scripts+ select_step = next(+ step for step in job["steps"] if step.get("id") == "select"+ )+ update_step = next(+ step+ for step in job["steps"]+ if step.get("name") == "Update the selected PR branch"+ )+ assert " select " in select_step["run"]+ assert update_step["if"] == "${{ steps.select.outputs.number != '' }}"+ assert update_step["env"]["PR_NUMBER"] == (+ "${{ steps.select.outputs.number }}"+ )+ assert update_step["env"]["EXPECTED_HEAD_SHA"] == (+ "${{ steps.select.outputs.head_sha }}"+ )+ assert " update " in update_step["run"]+ assert '--pr-number "${PR_NUMBER}"' in update_step["run"]+ assert '--expected-head-sha "${EXPECTED_HEAD_SHA}"' in update_step["run"]+def test_workflow_keeps_pat_in_update_step_only(workflow):steps = workflow["jobs"]["update-branch"]["steps"]@@ -331,8 +510,10 @@ def test_workflow_keeps_pat_in_update_step_only(workflow):assert "PAT_TOKEN" not in str(step)-def test_production_script_has_no_merge_endpoint():+def test_production_script_only_contains_branch_update_mutation():script = SCRIPT.read_text()- assert "/update-branch" in script+ assert "updatePullRequestBranch" in script+ assert "expectedHeadOid" in script+ assert "mergePullRequest" not in scriptassert "/merge" not in script