From bc72b83f20024891ad0a8aa6c4474545f748e38d Mon Sep 17 00:00:00 2001 From: SDNick484 Date: Tue, 10 Nov 2026 10:26:29 -0800 Subject: [PATCH] sync_all_siblings: optional --auto-merge for update --pr With --auto-merge, each new sync PR gets `gh pr merge --auto --squash`, so it merges itself once the sibling's CI passes. Off by default; only with --pr. It never fails a sibling (the PR is open either way) and says in the status table why it didn't turn auto-merge on: - the repo has "Allow auto-merge" off (allow_auto_merge from the REST API); - the default branch requires no status checks, from classic protection or rulesets: GitHub's auto-merge would then merge at once, before CI ran; - the required checks can't be read (a 404 from branch protection just means "not protected"); - `gh pr merge` refused, with its message. When it is on, the row names the checks it waits for. Today all nine siblings have auto-merge off and require no checks (checked against the API), so the flag would skip every one of them; README says what it takes. Refs #16 Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++ scripts/sync_all_siblings.py | 66 +++++++++++++++++++++++++++++++- tests/test_sync_all_siblings.py | 67 +++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ce99cc3..996aa11 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,12 @@ python scripts/sync_all_siblings.py update --pr --setup-venvs `sync-shared-` branch, push it, and open a PR with `gh`. The PR lists the files, links the shared diff and reports the local checks. Older sync PRs still open are flagged as superseded, not closed. +6. With `--auto-merge` (off by default): `gh pr merge --auto --squash` on the new PR, so it + merges itself once CI passes. Skipped, with the reason in the table, where the repo has + "Allow auto-merge" off, or where the default branch requires no status checks (branch + protection or a ruleset): there GitHub's auto-merge merges at once, before CI has run. As of + 2026-11 every sibling is in both cases, so it takes a ruleset requiring the CI jobs, plus the + repo setting, before it does anything. `--commit` stops after a local commit on the default branch; `--push` pushes that commit straight to it instead of opening a PR. `--no-test` skips the local checks (CI still runs diff --git a/scripts/sync_all_siblings.py b/scripts/sync_all_siblings.py index 89d7965..109593e 100644 --- a/scripts/sync_all_siblings.py +++ b/scripts/sync_all_siblings.py @@ -484,6 +484,7 @@ def release_sibling( setup_venvs: bool, keep_failed: bool, shared_main: str | None, + auto_merge: bool = False, ) -> StatusRow: """Refresh, sync, check, commit and (per `mode`) push or open a PR for one sibling.""" info = read_sibling_info(sibling) @@ -574,7 +575,10 @@ def row(status: str, ok: bool, commit: str | None = None) -> StatusRow: ) if proc.returncode != 0: return row(f"PR failed ({(proc.stderr or proc.stdout).strip()}); branch {branch} pushed", False, new) - status = f"PR {proc.stdout.strip()}" + url = proc.stdout.strip() + status = f"PR {url}" + if auto_merge: + status += "; " + enable_auto_merge(sibling, url, default) # Older sync PRs still open are now stale: flag them rather than close them unasked. others = _gh( ["pr", "list", "--state", "open", "--json", "headRefName,url", "-q"] @@ -594,6 +598,54 @@ def row(status: str, ok: bool, commit: str | None = None) -> StatusRow: _git(sibling, "switch", "--quiet", default) # ready for the next run +def required_checks(sibling: Path, branch: str) -> list[str]: + """The status checks `branch` requires, from classic branch protection and from rulesets. + + Raises SiblingError when GitHub can't say (a 404 from branch protection only means "not + protected"). gh fills in {owner}/{repo} from the sibling's origin remote. + """ + checks: list[str] = [] + protection = _gh( + ["api", f"repos/{{owner}}/{{repo}}/branches/{branch}/protection/required_status_checks"] + + ["--jq", ".contexts[]"], + cwd=sibling, + ) + if protection.returncode == 0: + checks += protection.stdout.splitlines() + elif "HTTP 404" not in protection.stderr: + raise SiblingError(f"branch protection: {(protection.stderr or protection.stdout).strip()}") + rules = _gh( + ["api", f"repos/{{owner}}/{{repo}}/rules/branches/{branch}", "--jq"] + + ['.[] | select(.type == "required_status_checks") | .parameters.required_status_checks[].context'], + cwd=sibling, + ) + if rules.returncode != 0: + raise SiblingError(f"rulesets: {(rules.stderr or rules.stdout).strip()}") + checks += rules.stdout.splitlines() + return list(dict.fromkeys(c.strip() for c in checks if c.strip())) + + +def enable_auto_merge(sibling: Path, pr_url: str, base: str) -> str: + """Turn on squash auto-merge for a sync PR, or say why not: a clause for the status row. + + Never a failure: the PR is open either way, and a person can merge it. Without required + checks GitHub's auto-merge merges at once, before CI has run, so that case is skipped. + """ + allowed = _gh(["api", "repos/{owner}/{repo}", "--jq", ".allow_auto_merge"], cwd=sibling) + if allowed.returncode == 0 and allowed.stdout.strip() == "false": + return "auto-merge skipped: turned off for the repo (Settings > General > Allow auto-merge)" + try: + checks = required_checks(sibling, base) + except SiblingError as exc: + return f"auto-merge skipped: couldn't read {base}'s required checks ({exc})" + if not checks: + return f"auto-merge skipped: {base} requires no status checks, so it would merge before CI ran" + proc = _gh(["pr", "merge", pr_url, "--auto", "--squash"], cwd=sibling) + if proc.returncode != 0: + return f"auto-merge failed ({(proc.stderr or proc.stdout).strip()})" + return f"auto-merge on (squash, once {', '.join(checks)} pass)" + + def run_update( parent_dir: Path, *, @@ -604,6 +656,7 @@ def run_update( setup_venvs: bool = False, keep_failed: bool = False, only: str | None = None, + auto_merge: bool = False, ) -> int: siblings = select_siblings(discover_siblings(parent_dir), only) if not siblings: @@ -626,6 +679,7 @@ def run_update( setup_venvs=setup_venvs, keep_failed=keep_failed, shared_main=shared_main, + auto_merge=auto_merge, ) for sibling in siblings ] @@ -810,6 +864,13 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: default=False, help="with --pr/--commit/--push: leave a sync whose checks failed in the tree (default: undo it)", ) + update_parser.add_argument( + "--auto-merge", + action="store_true", + default=False, + help="with --pr: turn on squash auto-merge for each new PR; skipped (and said why) where the repo " + "has auto-merge off or its default branch requires no checks, which would merge before CI ran", + ) args = parser.parse_args(list(argv) if argv is not None else None) if args.command is None: @@ -821,6 +882,8 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: update_parser.error("--dry-run doesn't go with --pr/--commit/--push; use it alone to preview") if args.mode is None and (args.no_test or args.keep_failed): update_parser.error("--no-test and --keep-failed only go with --pr/--commit/--push") + if args.auto_merge and args.mode != "pr": + update_parser.error("--auto-merge only goes with --pr") if args.mode is not None and args.test and args.no_test: update_parser.error("--test and --no-test contradict each other") return args @@ -843,6 +906,7 @@ def main(argv: Sequence[str] | None = None) -> int: setup_venvs=bool(args.setup_venvs), keep_failed=bool(args.keep_failed), only=only, + auto_merge=bool(args.auto_merge), ) return run_status(parent_dir, latest=bool(args.latest), only=only) diff --git a/tests/test_sync_all_siblings.py b/tests/test_sync_all_siblings.py index 2057e98..3940988 100644 --- a/tests/test_sync_all_siblings.py +++ b/tests/test_sync_all_siblings.py @@ -329,6 +329,13 @@ def __init__(self) -> None: self.created: list[list[str]] = [] self.repos: list[str] = [] self.logged_in = True + # For --auto-merge, per sibling: the repo setting, the checks branch protection and rulesets + # require (None: the API call fails), and what `gh pr merge` says (None: it works). + self.auto_merge_allowed: dict[str, bool] = {} + self.protected_checks: dict[str, list[str] | None] = {} + self.ruleset_checks: dict[str, list[str]] = {} + self.merge_error: dict[str, str] = {} + self.merged: list[list[str]] = [] def __call__(self, args: Sequence[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: a = list(args) @@ -347,6 +354,24 @@ def __call__(self, args: Sequence[str], *, cwd: Path | None = None) -> subproces u for (n, b), u in self.open.items() if n == cwd.name and b.startswith("sync-shared-") and b != current ] return subprocess.CompletedProcess(a, 0, stdout="".join(u + "\n" for u in urls), stderr="") + if a[:2] == ["api", "repos/{owner}/{repo}"]: + return subprocess.CompletedProcess( + a, 0, stdout=f"{str(self.auto_merge_allowed.get(cwd.name, True)).lower()}\n", stderr="" + ) + if a[0] == "api" and a[1].endswith("/protection/required_status_checks"): + if cwd.name not in self.protected_checks: + return subprocess.CompletedProcess(a, 1, stdout="", stderr="gh: Branch not protected (HTTP 404)") + checks = self.protected_checks[cwd.name] + if checks is None: + return subprocess.CompletedProcess(a, 1, stdout="", stderr="gh: Resource not accessible (HTTP 403)") + return subprocess.CompletedProcess(a, 0, stdout="".join(c + "\n" for c in checks), stderr="") + if a[0] == "api" and "/rules/branches/" in a[1]: + checks = self.ruleset_checks.get(cwd.name, []) + return subprocess.CompletedProcess(a, 0, stdout="".join(c + "\n" for c in checks), stderr="") + if a[:2] == ["pr", "merge"]: + self.merged.append(a) + error = self.merge_error.get(cwd.name) + return subprocess.CompletedProcess(a, 1 if error else 0, stdout="", stderr=error or "") if a[:2] == ["pr", "create"]: self.created.append(a) url = f"https://github.example/{cwd.name}/pull/{len(self.created)}" @@ -554,3 +579,45 @@ def test_select_siblings_accepts_short_and_full_names(tmp_path: Path): "mcp-server-gamma", ] assert mod.select_siblings(paths, None) == paths + + +def test_update_pr_auto_merge_only_where_checks_gate_it(tmp_path: Path, portfolio, capsys): + mod, _, gh = portfolio + names = ["alpha", "beta", "gamma", "delta", "eps", "zeta"] + for name in names: + make_git_sibling(tmp_path, f"mcp-server-{name}", f"{name}_mcp") + gh.protected_checks["mcp-server-alpha"] = ["test (3.11)", "alpine"] # classic protection: merges + gh.ruleset_checks["mcp-server-beta"] = ["shared-drift"] # a ruleset: merges too + gh.auto_merge_allowed["mcp-server-gamma"] = False # repo setting off + # delta: neither protection nor rulesets, so auto-merge would merge before CI + gh.protected_checks["mcp-server-eps"] = None # can't read protection + gh.protected_checks["mcp-server-zeta"] = ["test"] + gh.merge_error["mcp-server-zeta"] = "Pull request is in clean status" + + assert mod.main(["update", "--parent-dir", str(tmp_path / "src"), "--pr", "--auto-merge"]) == 0 # never fails + table = capsys.readouterr().out + table = table[table.index("SIBLING") :] + rows = {line.split()[0]: line for line in table.splitlines()[2:]} + + assert "auto-merge on (squash, once test (3.11), alpine pass)" in rows["mcp-server-alpha"] + assert "auto-merge on (squash, once shared-drift pass)" in rows["mcp-server-beta"] + assert "auto-merge skipped: turned off for the repo" in rows["mcp-server-gamma"] + assert "auto-merge skipped: main requires no status checks" in rows["mcp-server-delta"] + assert "auto-merge skipped: couldn't read main's required checks (branch protection: " in rows["mcp-server-eps"] + assert "auto-merge failed (Pull request is in clean status)" in rows["mcp-server-zeta"] + assert all(row.split()[3] == "PR" for row in rows.values()) # every PR opened regardless + merged = sorted(m[2].rsplit("/", 3)[1] for m in gh.merged) + assert merged == ["mcp-server-alpha", "mcp-server-beta", "mcp-server-zeta"] + assert all(m[3:] == ["--auto", "--squash"] for m in gh.merged) + + +def test_auto_merge_is_off_by_default_and_only_with_pr(tmp_path: Path, portfolio, capsys): + mod, _, gh = portfolio + make_git_sibling(tmp_path, "mcp-server-alpha", "alpha_mcp") + gh.protected_checks["mcp-server-alpha"] = ["test"] + assert mod.main(["update", "--parent-dir", str(tmp_path / "src"), "--pr"]) == 0 + assert gh.merged == [] and "auto-merge" not in capsys.readouterr().out + for mode in ([], ["--commit"], ["--push"]): + with pytest.raises(SystemExit): + mod.main(["update", "--parent-dir", str(tmp_path / "src"), *mode, "--auto-merge"]) + assert "--auto-merge only goes with --pr" in capsys.readouterr().err