~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
ci: update oldest eligible auto-merge PR hourly (#6150)
LearningCircuit2915dc05a3f9
diff --git a/.github/workflows/update-oldest-auto-merge-pr.yml b/.github/workflows/update-oldest-auto-merge-pr.ymlnew file mode 100644index 0000000000..39a9955021--- /dev/null+++ b/.github/workflows/update-oldest-auto-merge-pr.yml@@ -0,0 +1,58 @@+name: Update oldest auto-merge PR++on:+ schedule:+ # Avoid the top of the hour, when scheduled Actions traffic is highest.+ - cron: '17 * * * *'+ workflow_dispatch:++concurrency:+ group: update-oldest-auto-merge-pr+ cancel-in-progress: false++permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions++jobs:+ update-branch:+ name: Update oldest eligible PR+ runs-on: ubuntu-latest+ timeout-minutes: 10+ permissions:+ contents: read+ pull-requests: read++ steps:+ - name: Harden the runner (Audit all outbound calls)+ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0+ with:+ egress-policy: audit++ - name: Checkout trusted automation code+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ ref: main++ - name: Find the oldest eligible PR+ id: select+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ python3 scripts/ci/update_oldest_auto_merge_pr.py select \+ --repo "${GITHUB_REPOSITORY}" \+ --base main++ - name: Update the selected PR branch+ if: ${{ 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.+ GH_TOKEN: ${{ secrets.PAT_TOKEN }}+ PR_NUMBER: ${{ steps.select.outputs.number }}+ EXPECTED_HEAD_SHA: ${{ steps.select.outputs.head_sha }}+ run: |+ python3 scripts/ci/update_oldest_auto_merge_pr.py update \+ --repo "${GITHUB_REPOSITORY}" \+ --base main \+ --pr-number "${PR_NUMBER}" \+ --expected-head-sha "${EXPECTED_HEAD_SHA}"diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 3765075cfb..a84bc87a3e 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -29,7 +29,7 @@<!-- BEGIN GENERATED -->-**66 workflows:** 1 disabled · 1 manual-only · 64 active+**67 workflows:** 1 disabled · 3 stale · 1 manual-only · 62 active## ⚠ Disabled workflows@@ -39,7 +39,11 @@## ⚠ Stale (scheduled but no recent successful run)-_None._+| Workflow | Cron | Last successful run |+|---|---|---|+| `osv-scanner.yml` | `39 12 * * 1` | never |+| `puppeteer-e2e-tests.yml` | `0 2 * * 0` | never |+| `update-precommit-hooks.yml` | `0 8 * * 5` | never |## ℹ Manual-only by design@@ -75,21 +79,20 @@ _None._| Workflow | Last activity | Trigger | Live badge ||---|---|---|---|-| `check-env-vars.yml` | 3-6 months ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/check-env-vars.yml) |+| `check-env-vars.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/check-env-vars.yml) || `ci-gate.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/ci-gate.yml) || `compose-integration-test.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/compose-integration-test.yml) || `docker-publish.yml` | last 30 days | workflow_call | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/docker-publish.yml) |-| `docker-tests.yml` | 3-6 months ago | PR, push:main, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/docker-tests.yml) |-| `file-whitelist-check.yml` | 3-6 months ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/file-whitelist-check.yml) |-| `mypy-type-check.yml` | 3-6 months ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mypy-type-check.yml) |+| `docker-tests.yml` | last 30 days | PR, push:main, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/docker-tests.yml) |+| `file-whitelist-check.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/file-whitelist-check.yml) |+| `mypy-type-check.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mypy-type-check.yml) || `playwright-notes-tests.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/playwright-notes-tests.yml) || `playwright-webkit-tests.yml` | last 30 days | workflow_call, manual, schedule(0 2 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/playwright-webkit-tests.yml) |-| `pre-commit.yml` | 3-6 months ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pre-commit.yml) |+| `pre-commit.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pre-commit.yml) || `prerelease-docker.yml` | last 30 days | workflow_call | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/prerelease-docker.yml) |-| `puppeteer-e2e-tests.yml` | last 30 days | PR, workflow_call, manual, schedule(0 2 * * 0) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/puppeteer-e2e-tests.yml) || `responsive-ui-tests-enhanced.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/responsive-ui-tests-enhanced.yml) |-| `security-file-write-check.yml` | 3-6 months ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-file-write-check.yml) |-| `validate-image-pinning.yml` | 3-6 months ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/validate-image-pinning.yml) |+| `security-file-write-check.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-file-write-check.yml) |+| `validate-image-pinning.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/validate-image-pinning.yml) || `vulture-dead-code.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/vulture-dead-code.yml) |## Scheduled (own cron)@@ -101,12 +104,11 @@ _None._| `gitleaks.yml` | last 30 days | PR, manual, schedule(0 3 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/gitleaks.yml?query=event%3Aschedule) || `ossf-scorecard.yml` | last 30 days | branch_protection_rule, schedule(0 8 * * 1), manual, push:main | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/ossf-scorecard.yml?query=event%3Aschedule) || `osv-scanner-scheduled.yml` | last 30 days | push:main, schedule(41 21 * * 1), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/osv-scanner-scheduled.yml?query=event%3Aschedule) |-| `osv-scanner.yml` | last 30 days | PR, merge_group, schedule(39 12 * * 1), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/osv-scanner.yml?query=event%3Aschedule) || `release-gate.yml` | last 30 days | workflow_call, manual, schedule(0 2 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release-gate.yml?query=event%3Aschedule) || `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-precommit-hooks.yml` | last 30 days | manual, schedule(0 8 * * 5) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-precommit-hooks.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) |## PR / push checks@@ -119,7 +121,7 @@ _None._| `danger-zone-alert.yml` | last 30 days | PR | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/danger-zone-alert.yml) || `dependency-review.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/dependency-review.yml) || `e2e-research-test.yml` | last 30 days | PR | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/e2e-research-test.yml) |-| `fastapi-migration-quality.yml` | never | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/fastapi-migration-quality.yml) |+| `fastapi-migration-quality.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/fastapi-migration-quality.yml) || `labels-sync.yml` | last 30 days | push:main, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/labels-sync.yml) || `mcp-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mcp-tests.yml) || `pr-triage.yml` | last 30 days | PR, pull_request_review | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pr-triage.yml) |diff --git a/scripts/ci/update_oldest_auto_merge_pr.py b/scripts/ci/update_oldest_auto_merge_pr.pynew file mode 100644index 0000000000..a53825c80d--- /dev/null+++ b/scripts/ci/update_oldest_auto_merge_pr.py@@ -0,0 +1,389 @@+#!/usr/bin/env python3+"""Select and update the oldest eligible auto-merge pull request.++The GitHub Actions workflow invokes this module in two separate steps:++* ``select`` uses the short-lived ``GITHUB_TOKEN`` to list and rank PRs.+* ``update`` uses ``PAT_TOKEN`` (exposed as ``GH_TOKEN`` only to that step)+ to revalidate one PR and request an update of its branch.++Keeping the state transition logic here makes it deterministic and unit+testable without exposing a token or changing a real pull request.+"""++from __future__ import annotations++import argparse+import json+import os+import subprocess+import sys+from collections.abc import Sequence+from pathlib import Path+from typing import Any++PR_FIELDS = (+ "number",+ "url",+ "createdAt",+ "state",+ "baseRefName",+ "headRefOid",+ "isCrossRepository",+ "isDraft",+ "maintainerCanModify",+ "mergeable",+ "mergeStateStatus",+ "reviewDecision",+ "autoMergeRequest",+)+++class UpdaterError(RuntimeError):+ """A safe, user-facing workflow failure."""+++def run_gh_json(args: Sequence[str]) -> Any:+ """Run a ``gh`` command and decode its JSON response."""+ command = ["gh", *args]+ try:+ result = subprocess.run(+ command,+ capture_output=True,+ check=False,+ text=True,+ timeout=120,+ )+ except FileNotFoundError as exc:+ raise UpdaterError("gh is not installed on this runner") from exc+ except subprocess.TimeoutExpired as exc:+ raise UpdaterError(+ f"gh command timed out: {' '.join(command)}"+ ) from exc++ if result.returncode != 0:+ detail = (+ result.stderr.strip() or result.stdout.strip() or "unknown error"+ )+ raise UpdaterError(+ f"gh command failed with exit {result.returncode}: {detail}"+ )++ try:+ return json.loads(result.stdout)+ except json.JSONDecodeError as exc:+ raise UpdaterError("gh returned invalid JSON") from exc+++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."""+ number = pull_request.get("number")+ created_at = pull_request.get("createdAt")+ head_sha = pull_request.get("headRefOid")+ is_cross_repository = pull_request.get("isCrossRepository")++ has_valid_identity = (+ type(number) is int+ and number > 0+ 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_sha++ return bool(+ has_valid_identity+ and pull_request.get("state") == "OPEN"+ and pull_request.get("baseRefName") == base+ and pull_request.get("isDraft") is False+ and pull_request.get("reviewDecision") == "APPROVED"+ and pull_request.get("autoMergeRequest") is not None+ and pull_request.get("mergeable") == "MERGEABLE"+ and pull_request.get("mergeStateStatus") == "BEHIND"+ and can_modify_head+ and head_is_current+ )+++def eligible_pull_requests(+ pull_requests: Sequence[dict[str, Any]], *, base: str+) -> list[dict[str, Any]]:+ """Return eligible PRs sorted oldest-first, then by PR number."""+ eligible = [+ pull_request+ for pull_request in pull_requests+ if is_eligible(pull_request, base=base)+ ]+ return sorted(+ eligible,+ key=lambda pull_request: (+ pull_request["createdAt"],+ pull_request["number"],+ ),+ )+++def fetch_pull_requests(repository: str, base: str) -> list[dict[str, Any]]:+ """Fetch open, approved PRs, asking GitHub for the oldest page first."""+ response = run_gh_json(+ [+ "pr",+ "list",+ "--repo",+ repository,+ "--state",+ "open",+ "--base",+ base,+ "--search",+ "review:approved sort:created-asc",+ "--limit",+ "1000",+ "--json",+ ",".join(PR_FIELDS),+ ]+ )+ if not isinstance(response, list) or not all(+ isinstance(item, dict) for item in response+ ):+ raise UpdaterError("gh pr list returned an unexpected response")+ return response+++def fetch_pull_request(repository: str, number: int) -> dict[str, Any]:+ """Fetch the current state of one PR for last-moment revalidation."""+ response = run_gh_json(+ [+ "pr",+ "view",+ str(number),+ "--repo",+ repository,+ "--json",+ ",".join(PR_FIELDS),+ ]+ )+ if not isinstance(response, dict):+ raise UpdaterError("gh pr view returned an unexpected response")+ return response+++def append_summary(path: Path | None, lines: Sequence[str]) -> None:+ """Append lines to the GitHub step summary when one is available."""+ if path is None:+ return+ with path.open("a", encoding="utf-8") as summary:+ summary.write("\n".join(lines))+ summary.write("\n")+++def write_outputs(path: Path | None, values: dict[str, str]) -> None:+ """Write single-line values using the GitHub Actions output protocol."""+ if path is None:+ return+ with path.open("a", encoding="utf-8") as output:+ for name, value in values.items():+ if "\n" in name or "\n" in value:+ raise UpdaterError(+ "workflow output names and values must be single-line"+ )+ output.write(f"{name}={value}\n")+++def select_oldest(+ repository: str,+ base: str,+ *,+ github_output: Path | None,+ 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+ )+ 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}`."+ )+ 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 = 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+++def update_pull_request(+ repository: str,+ base: str,+ *,+ number: int,+ expected_head_sha: str,+ step_summary: Path | None,+) -> bool:+ """Revalidate and request a branch update; return whether one was sent."""+ current = fetch_pull_request(repository, number)+ if not is_eligible(+ current,+ base=base,+ expected_head_sha=expected_head_sha,+ ):+ message = f"PR #{number} changed after selection and was not updated."+ print(message)+ 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."+ )+ print(message)+ append_summary(+ step_summary,+ ["", f"Update requested for PR #{number}: {message}"],+ )+ return True+++def build_parser() -> argparse.ArgumentParser:+ """Build the command-line parser."""+ parser = argparse.ArgumentParser(description=__doc__)+ subparsers = parser.add_subparsers(dest="command", required=True)++ def add_common_arguments(command: argparse.ArgumentParser) -> None:+ command.add_argument(+ "--repo",+ default=os.environ.get("GITHUB_REPOSITORY"),+ help="GitHub repository in OWNER/REPO form",+ )+ command.add_argument("--base", default="main")+ command.add_argument(+ "--step-summary",+ type=Path,+ default=(+ Path(os.environ["GITHUB_STEP_SUMMARY"])+ if os.environ.get("GITHUB_STEP_SUMMARY")+ else None+ ),+ )++ select_parser = subparsers.add_parser("select")+ add_common_arguments(select_parser)+ select_parser.add_argument(+ "--github-output",+ type=Path,+ default=(+ Path(os.environ["GITHUB_OUTPUT"])+ if os.environ.get("GITHUB_OUTPUT")+ else None+ ),+ )++ update_parser = subparsers.add_parser("update")+ add_common_arguments(update_parser)+ update_parser.add_argument("--pr-number", type=int, required=True)+ update_parser.add_argument("--expected-head-sha", required=True)+ return parser+++def validate_repository(repository: str | None) -> str:+ """Validate the OWNER/REPO value before placing it in an API path."""+ if repository is None:+ raise UpdaterError(+ "repository is required; pass --repo or set GITHUB_REPOSITORY"+ )+ owner, separator, name = repository.partition("/")+ if separator != "/" or not owner or not name or "/" in name:+ raise UpdaterError("repository must use OWNER/REPO form")+ return repository+++def require_token(command: str) -> None:+ """Fail clearly before invoking ``gh`` when its token is unavailable."""+ if os.environ.get("GH_TOKEN"):+ return+ token_name = "PAT_TOKEN" if command == "update" else "GITHUB_TOKEN"+ raise UpdaterError(+ f"GH_TOKEN is empty; the workflow must provide {token_name}"+ )+++def main(argv: Sequence[str] | None = None) -> int:+ """CLI entry point."""+ parser = build_parser()+ args = parser.parse_args(argv)++ try:+ repository = validate_repository(args.repo)+ require_token(args.command)++ if args.command == "select":+ select_oldest(+ repository,+ args.base,+ github_output=args.github_output,+ step_summary=args.step_summary,+ )+ else:+ update_pull_request(+ repository,+ args.base,+ number=args.pr_number,+ expected_head_sha=args.expected_head_sha,+ step_summary=args.step_summary,+ )+ except UpdaterError as exc:+ print(f"::error::{exc}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/ci/test_update_oldest_auto_merge_pr.py b/tests/ci/test_update_oldest_auto_merge_pr.pynew file mode 100644index 0000000000..e0346e4413--- /dev/null+++ b/tests/ci/test_update_oldest_auto_merge_pr.py@@ -0,0 +1,338 @@+"""Tests for the hourly auto-merge pull-request branch updater.++The production script is exercised with mocked ``gh`` responses. No test uses+GitHub credentials, calls the network, updates a branch, or merges a PR.+"""++from __future__ import annotations++import importlib.util+from pathlib import Path++import pytest+import yaml++REPO_ROOT = Path(__file__).resolve().parents[2]+SCRIPT = REPO_ROOT / "scripts" / "ci" / "update_oldest_auto_merge_pr.py"+WORKFLOW = (+ REPO_ROOT / ".github" / "workflows" / "update-oldest-auto-merge-pr.yml"+)+HEAD_A = "a" * 40+HEAD_B = "b" * 40++_SPEC = importlib.util.spec_from_file_location(+ "update_oldest_auto_merge_pr", SCRIPT+)+assert _SPEC is not None and _SPEC.loader is not None+updater = importlib.util.module_from_spec(_SPEC)+_SPEC.loader.exec_module(updater)+++def pull_request(+ number: int = 100,+ created_at: str = "2026-01-02T03:04:05Z",+ **overrides,+):+ """Return a minimal PR that satisfies every update requirement."""+ result = {+ "number": number,+ "url": f"https://github.com/example/project/pull/{number}",+ "createdAt": created_at,+ "state": "OPEN",+ "baseRefName": "main",+ "headRefOid": HEAD_A,+ "isCrossRepository": False,+ "isDraft": False,+ "maintainerCanModify": False,+ "mergeable": "MERGEABLE",+ "mergeStateStatus": "BEHIND",+ "reviewDecision": "APPROVED",+ "autoMergeRequest": {"enabledAt": "2026-01-02T04:00:00Z"},+ }+ result.update(overrides)+ return result+++ "change",+ [+ {"state": "CLOSED"},+ {"baseRefName": "release"},+ {"isDraft": True},+ {"reviewDecision": "REVIEW_REQUIRED"},+ {"autoMergeRequest": None},+ {"mergeable": "CONFLICTING"},+ {"mergeStateStatus": "CLEAN"},+ {"mergeStateStatus": "UNKNOWN"},+ {"isCrossRepository": True, "maintainerCanModify": False},+ ],+ ids=[+ "closed",+ "wrong-base",+ "draft",+ "not-approved",+ "auto-merge-disabled",+ "conflict",+ "already-current",+ "mergeability-unknown",+ "unmodifiable-fork",+ ],+)+def test_ineligible_pull_requests_are_rejected(change):+ assert not updater.is_eligible(pull_request(**change), base="main")+++def test_modifiable_fork_is_eligible():+ candidate = pull_request(+ isCrossRepository=True,+ maintainerCanModify=True,+ )++ 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"),+ pull_request(20, "2026-01-01T00:00:00Z"),+ pull_request(10, "2026-01-01T00:00:00Z"),+ ]++ selected = updater.eligible_pull_requests(candidates, base="main")++ assert [item["number"] for item in selected] == [10, 20, 30]+++def test_pr_can_become_eligible_again_each_time_main_advances():+ candidate = pull_request(42, mergeStateStatus="CLEAN")++ # It was just updated and is current with main, so there is no work.+ assert updater.eligible_pull_requests([candidate], base="main") == []++ # Another PR merges without waiting for this PR's CI, advancing main.+ candidate["mergeStateStatus"] = "BEHIND"+ assert updater.eligible_pull_requests([candidate], base="main") == [+ candidate+ ]++ # Updating makes it current; a later main change makes it eligible again.+ candidate["mergeStateStatus"] = "CLEAN"+ assert updater.eligible_pull_requests([candidate], base="main") == []+ candidate["mergeStateStatus"] = "BEHIND"+ assert updater.eligible_pull_requests([candidate], base="main") == [+ candidate+ ]+++def test_selection_queries_oldest_approved_prs_and_writes_outputs(+ monkeypatch, tmp_path+):+ calls = []+ oldest = pull_request(12, "2026-01-01T00:00:00Z")+ newer = pull_request(13, "2026-02-01T00:00:00Z")+ output = tmp_path / "output"+ summary = tmp_path / "summary"++ def fake_gh(args):+ calls.append(args)+ return [newer, oldest]++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ selected = updater.select_oldest(+ "example/project",+ "main",+ github_output=output,+ step_summary=summary,+ )++ assert selected == oldest+ assert output.read_text() == f"number=12\nhead_sha={HEAD_A}\n"+ summary_text = summary.read_text()+ assert summary_text.index("#12") < summary_text.index("#13")+ assert "Selected oldest candidate: #12." in summary_text+ assert calls[0][:2] == ["pr", "list"]+ assert "review:approved sort:created-asc" in calls[0]+ assert calls[0][calls[0].index("--limit") + 1] == "1000"+++def test_empty_selection_is_a_successful_no_op(monkeypatch, tmp_path):+ output = tmp_path / "output"+ summary = tmp_path / "summary"+ monkeypatch.setattr(updater, "run_gh_json", lambda _args: [])++ 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 "No approved, auto-merge-enabled PR" in summary.read_text()+++def test_update_revalidates_and_uses_expected_head_sha(monkeypatch, tmp_path):+ calls = []+ summary = tmp_path / "summary"++ def fake_gh(args):+ calls.append(args)+ if args[:2] == ["pr", "view"]:+ return pull_request(55)+ return {"message": "Updating pull request branch."}++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ updated = updater.update_pull_request(+ "example/project",+ "main",+ number=55,+ expected_head_sha=HEAD_A,+ step_summary=summary,+ )++ assert updated is True+ assert len(calls) == 2+ assert 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()+++ "change",+ [+ {"state": "CLOSED"},+ {"headRefOid": HEAD_B},+ {"reviewDecision": "CHANGES_REQUESTED"},+ {"autoMergeRequest": None},+ {"mergeStateStatus": "CLEAN"},+ ],+ ids=[+ "merged-or-closed",+ "head-changed",+ "approval-revoked",+ "auto-merge-disabled",+ "already-updated",+ ],+)+def test_changed_pr_is_not_updated(monkeypatch, tmp_path, change):+ calls = []+ current = pull_request(55, **change)++ def fake_gh(args):+ calls.append(args)+ return current++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ updated = updater.update_pull_request(+ "example/project",+ "main",+ number=55,+ expected_head_sha=HEAD_A,+ step_summary=tmp_path / "summary",+ )++ assert updated is False+ assert len(calls) == 1+ assert calls[0][:2] == ["pr", "view"]+++def test_cli_fails_before_api_access_when_token_is_missing(monkeypatch, capsys):+ monkeypatch.delenv("GH_TOKEN", raising=False)+ api_called = False++ def fake_gh(_args):+ nonlocal api_called+ api_called = True+ return []++ monkeypatch.setattr(updater, "run_gh_json", fake_gh)++ exit_code = updater.main(+ [+ "update",+ "--repo",+ "example/project",+ "--pr-number",+ "55",+ "--expected-head-sha",+ HEAD_A,+ ]+ )++ assert exit_code == 1+ assert api_called is False+ assert "provide PAT_TOKEN" in capsys.readouterr().err++[email protected](scope="module")+def workflow():+ return yaml.safe_load(WORKFLOW.read_text())+++def test_workflow_runs_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 * * * *"}],+ "workflow_dispatch": None,+ }+ assert workflow["concurrency"] == {+ "group": "update-oldest-auto-merge-pr",+ "cancel-in-progress": False,+ }+++def test_workflow_is_a_thin_pinned_wrapper(workflow):+ assert workflow["permissions"] == {}+ job = workflow["jobs"]["update-branch"]+ assert job["permissions"] == {+ "contents": "read",+ "pull-requests": "read",+ }++ checkout = next(+ step+ for step in job["steps"]+ if str(step.get("uses", "")).startswith("actions/checkout@")+ )+ checkout_ref = checkout["uses"].split("@", 1)[1]+ assert len(checkout_ref) == 40+ assert all(character in "0123456789abcdef" for character in checkout_ref)+ assert checkout["with"] == {"persist-credentials": False, "ref": "main"}++ run_scripts = "\n".join(step.get("run", "") for step in job["steps"])+ assert run_scripts.count("scripts/ci/update_oldest_auto_merge_pr.py") == 2+ assert "gh pr" not in run_scripts+ assert "gh api" not in run_scripts+++def test_workflow_keeps_pat_in_update_step_only(workflow):+ steps = workflow["jobs"]["update-branch"]["steps"]+ select_step = next(step for step in steps if step.get("id") == "select")+ update_step = next(+ step+ for step in steps+ if step.get("name") == "Update the selected PR branch"+ )++ assert select_step["env"] == {"GH_TOKEN": "${{ github.token }}"}+ assert update_step["env"]["GH_TOKEN"] == "${{ secrets.PAT_TOKEN }}"+ for step in steps:+ if step is not update_step:+ assert "PAT_TOKEN" not in str(step)+++def test_production_script_has_no_merge_endpoint():+ script = SCRIPT.read_text()++ assert "/update-branch" in script+ assert "/merge" not in script