From af471fe58c93fcf843679c200c509ff265494658 Mon Sep 17 00:00:00 2001 From: lukisch <55554266+lukisch@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:11:52 +0100 Subject: [PATCH 1/2] fix(policy): block draft auto-ready on hold labels, title signals, and excluded repos --- src/githubbot_core/multibot.example.json | 17 ++++ src/githubbot_core/multibot.py | 43 +++++++++- src/githubbot_core/prompts/MULTI-BOT.de.md | 6 ++ src/githubbot_core/typed_actions.py | 56 ++++++++++++ tests/test_multibot_resources.py | 4 + tests/test_typed_actions.py | 99 +++++++++++++++++++++- 6 files changed, 223 insertions(+), 2 deletions(-) diff --git a/src/githubbot_core/multibot.example.json b/src/githubbot_core/multibot.example.json index 29673c0..a52145a 100644 --- a/src/githubbot_core/multibot.example.json +++ b/src/githubbot_core/multibot.example.json @@ -14,6 +14,23 @@ "unknown_author": "hold", "draft_auto_ready_hours": null, "draft_ready_when_mature": false, + "draft_auto_ready_hold_labels": [ + "do-not-merge", + "hold", + "wip", + "blocked", + "on-hold", + "needs-approval" + ], + "draft_auto_ready_hold_title_signals": [ + "nicht mergen", + "do not merge", + "don't merge", + "[hold]", + "[wip]", + "wip:" + ], + "draft_auto_ready_exclude_repos": [], "trigger_missing_ci": false, "publish_reviews": false, "open_fix_prs": false diff --git a/src/githubbot_core/multibot.py b/src/githubbot_core/multibot.py index da20e41..64436b5 100644 --- a/src/githubbot_core/multibot.py +++ b/src/githubbot_core/multibot.py @@ -59,12 +59,32 @@ def permission_contract(config, layers): return {"permissions": permissions, "config_layers": [str(Path(path).expanduser().resolve()) for path in layers]} +DEFAULT_DRAFT_HOLD_LABELS = ( + "do-not-merge", + "hold", + "wip", + "blocked", + "on-hold", + "needs-approval", +) +DEFAULT_DRAFT_HOLD_TITLE_SIGNALS = ( + "nicht mergen", + "do not merge", + "don't merge", + "[hold]", + "[wip]", + "wip:", +) + # Public defaults stay conservative; an instance opts in per key via multi_bot.policy. POLICY_DEFAULTS = { "review_independence": "model_class", # provider | model_class | instance "unknown_author": "hold", # hold | allow "draft_auto_ready_hours": None, # hours an unchanged head must age before a draft may be readied "draft_ready_when_mature": False, + "draft_auto_ready_hold_labels": list(DEFAULT_DRAFT_HOLD_LABELS), + "draft_auto_ready_hold_title_signals": list(DEFAULT_DRAFT_HOLD_TITLE_SIGNALS), + "draft_auto_ready_exclude_repos": [], "trigger_missing_ci": False, "publish_reviews": False, "close_integrated_prs": False, @@ -76,6 +96,12 @@ def permission_contract(config, layers): } +def _string_list(value, key: str) -> list[str]: + if not isinstance(value, list) or any(not isinstance(item, str) or not item.strip() for item in value): + raise ValueError(f"multi_bot.policy.{key} must be a list of non-empty strings") + return [item.strip() for item in value] + + def policy_settings(raw): """Validate multi_bot.policy; unknown keys or wrong types fail closed instead of being ignored.""" if raw is None: @@ -85,13 +111,28 @@ def policy_settings(raw): unknown = sorted(set(raw) - set(POLICY_DEFAULTS)) if unknown: raise ValueError(f"unknown multi_bot.policy keys: {unknown}") - policy = {**POLICY_DEFAULTS, **raw} + policy = { + key: list(default) if isinstance(default, list) else default + for key, default in POLICY_DEFAULTS.items() + } + policy.update(raw) for key, allowed in _POLICY_CHOICES.items(): if policy[key] not in allowed: raise ValueError(f"multi_bot.policy.{key} must be one of {list(allowed)}") hours = policy["draft_auto_ready_hours"] if hours is not None and (type(hours) not in (int, float) or hours <= 0): raise ValueError("multi_bot.policy.draft_auto_ready_hours must be null or a positive number") + for key in ("draft_auto_ready_hold_labels", "draft_auto_ready_hold_title_signals"): + policy[key] = _string_list(policy[key], key) + from .write_scope import repository + + exclude_repos = _string_list(policy["draft_auto_ready_exclude_repos"], "draft_auto_ready_exclude_repos") + try: + policy["draft_auto_ready_exclude_repos"] = [repository(repo) for repo in exclude_repos] + except ValueError as exc: + raise ValueError( + "multi_bot.policy.draft_auto_ready_exclude_repos entries must be owner/repository" + ) from exc for key in ( "draft_ready_when_mature", "trigger_missing_ci", diff --git a/src/githubbot_core/prompts/MULTI-BOT.de.md b/src/githubbot_core/prompts/MULTI-BOT.de.md index 63cabe9..56b92b4 100644 --- a/src/githubbot_core/prompts/MULTI-BOT.de.md +++ b/src/githubbot_core/prompts/MULTI-BOT.de.md @@ -196,6 +196,12 @@ und ersetzen weder Merge-Opt-in noch Identitätsprüfung. nennt Problem und Tests, keine Konflikte. Danach gilt der normale Ablauf am dann frisch gelesenen Head (unabhängige Prüfung, alle Merge-Gates). Gestapelte Drafts (Base ist nicht der Default-Branch) und Drafts mit aktivem Hold oder Lock bleiben unberührt. + `draft_auto_ready_hold_labels` (String-Liste, konservativer Standard u. a. `do-not-merge`, + `hold`, `wip`, `blocked`, `on-hold`, `needs-approval`) und `draft_auto_ready_hold_title_signals` + (String-Liste, konservativer Standard u. a. `nicht mergen`, `do not merge`, `don't merge`, + `[hold]`, `[wip]`, `wip:`) blockieren `pr.ready` zusätzlich technisch (case-insensitive). + `draft_auto_ready_exclude_repos` (Liste von `owner/repo`, Standard `[]`) nimmt explizit + freigabepflichtige Repositories vollständig von `pr.ready` aus. - `trigger_missing_ci` (bool): Hat der exakte Head keine Check-Läufe, darf der Bot sie anstoßen: Core-Aktion `actions.dispatch` (Workflow mit `workflow_dispatch`, `--ref `) oder `actions.rerun` eines abgeschlossenen früheren Laufs desselben Heads. Verboten bleiben leere Commits, diff --git a/src/githubbot_core/typed_actions.py b/src/githubbot_core/typed_actions.py index 15bfb18..49bd3ce 100644 --- a/src/githubbot_core/typed_actions.py +++ b/src/githubbot_core/typed_actions.py @@ -124,6 +124,10 @@ def param_denial(kind: str, params: dict, config: dict) -> Optional[str]: account = (config.get("multi_bot") or {}).get("merge_account") if not isinstance(account, str) or not account.strip(): return "git.push_branch requires the configured multi_bot.merge_account" + if kind == "pr.ready": + excluded = draft_auto_ready_repo_excluded(params["repo"], config) + if excluded: + return excluded if kind == "pr.merge" and params.get("method", "merge") not in MERGE_METHODS: return f"method must be one of {list(MERGE_METHODS)}" if kind == "actions.dispatch": @@ -233,10 +237,62 @@ def exec_merge(transport, params: dict, config: dict): ) +def _normalize_hold_label(label: str) -> str: + return re.sub(r"[\s_]+", "-", label.strip().casefold()) + + +def draft_auto_ready_repo_excluded(repo: str, config: dict) -> Optional[str]: + """Check whether ``repo`` is excluded from automated draft-ready transitions.""" + try: + policy = _policy(config) + except ValueError as exc: + return f"multi_bot.policy invalid: {exc}" + excluded = {item.casefold() for item in policy.get("draft_auto_ready_exclude_repos", ())} + if repo.casefold() in excluded: + return f"pr.ready is excluded for repository {repo!r} by multi_bot.policy.draft_auto_ready_exclude_repos" + return None + + +def draft_auto_ready_hold_reason(repo: str, pull: dict, config: dict) -> Optional[str]: + """Return a hold reason if a draft PR must not be auto-readied, or ``None``.""" + excluded = draft_auto_ready_repo_excluded(repo, config) + if excluded: + return excluded + policy = _policy(config) + raw_labels = pull.get("labels") + if raw_labels is not None: + if not isinstance(raw_labels, list): + return "pull request labels unreadable; refusing to ready draft" + hold_labels = {_normalize_hold_label(item) for item in policy.get("draft_auto_ready_hold_labels", ())} + for item in raw_labels: + if isinstance(item, dict): + name = item.get("name") + elif isinstance(item, str): + name = item + else: + return "pull request label entry unreadable; refusing to ready draft" + if not isinstance(name, str) or not name.strip(): + return "pull request label entry unreadable; refusing to ready draft" + if _normalize_hold_label(name) in hold_labels: + return f"draft pull request carries hold label {name.strip()!r}" + title = pull.get("title") + if title is not None: + if not isinstance(title, str): + return "pull request title unreadable; refusing to ready draft" + title_cf = title.casefold() + for signal in policy.get("draft_auto_ready_hold_title_signals", ()): + if signal.casefold() in title_cf: + return f"draft pull request title matches hold signal {signal!r}" + return None + + def exec_ready(transport, params: dict, config: dict): pull, error = _reviewed_pull(transport, params, draft=True) if error: return None, error + hold_reason = draft_auto_ready_hold_reason(params["repo"], pull, config) + if hold_reason: + return None, hold_reason data, error = transport.request("POST", "graphql", {"query": READY_MUTATION, "variables": {"id": pull["node_id"]}}) if error or (data or {}).get("errors"): return None, error or "GraphQL error" diff --git a/tests/test_multibot_resources.py b/tests/test_multibot_resources.py index e858374..b688138 100644 --- a/tests/test_multibot_resources.py +++ b/tests/test_multibot_resources.py @@ -237,6 +237,10 @@ def test_invalid_policy_switches_fail_closed_before_any_launch(tmp_path, capsys) {"unknown_key": True}, {"draft_auto_ready_hours": 0}, {"draft_auto_ready_hours": "24"}, + {"draft_auto_ready_hold_labels": "hold"}, + {"draft_auto_ready_hold_labels": [""]}, + {"draft_auto_ready_hold_title_signals": "nicht mergen"}, + {"draft_auto_ready_exclude_repos": ["invalid-repo"]}, {"publish_reviews": "yes"}, {"unknown_author": None}, ): diff --git a/tests/test_typed_actions.py b/tests/test_typed_actions.py index 49d8dfe..4f5874d 100644 --- a/tests/test_typed_actions.py +++ b/tests/test_typed_actions.py @@ -234,7 +234,10 @@ def test_merge_api_2026_does_not_query_when_rest_has_not_confirmed_the_merge(): def test_ready_uses_graphql_for_the_exact_draft_head(): gets = base_gets() - gets[f"repos/{REPO}/pulls/7"] = [pull(draft=True), pull(draft=False)] + gets[f"repos/{REPO}/pulls/7"] = [ + pull(draft=True, title="feat: mature draft ready for review", labels=[{"name": "enhancement"}]), + pull(draft=False), + ] transport = Transport(gets, write_result={"data": {"markPullRequestReadyForReview": {}}}) action = Action("pr.ready", {"repo": REPO, "number": 7, "sha": SHA}) receipt = actions.apply([action], transport, config())["receipts"][0] @@ -247,6 +250,100 @@ def test_ready_uses_graphql_for_the_exact_draft_head(): assert transport.writes == [] +@pytest.mark.parametrize( + "title", + [ + "feat: Vorschau — nicht mergen ohne LG-Freigabe", + "Do Not Merge: preview build", + "chore: don't merge before review", + "[HOLD] wait for sign-off", + "[wip] draft implementation", + "WIP: refactor config", + ], +) +def test_ready_blocks_draft_with_hold_title_signal(title): + gets = base_gets() + gets[f"repos/{REPO}/pulls/7"] = pull(draft=True, title=title, labels=[]) + transport = Transport(gets, write_result={"data": {"markPullRequestReadyForReview": {}}}) + action = Action("pr.ready", {"repo": REPO, "number": 7, "sha": SHA}) + receipt = actions.apply([action], transport, config())["receipts"][0] + assert receipt["status"] == "failed" + assert "hold signal" in receipt["detail"] + assert transport.writes == [] + + +@pytest.mark.parametrize( + "label", + [ + "do-not-merge", + "HOLD", + "wip", + "Blocked", + "On Hold", + "needs-approval", + ], +) +def test_ready_blocks_draft_with_hold_label(label): + gets = base_gets() + gets[f"repos/{REPO}/pulls/7"] = pull(draft=True, title="feat: clean title", labels=[{"name": label}]) + transport = Transport(gets, write_result={"data": {"markPullRequestReadyForReview": {}}}) + action = Action("pr.ready", {"repo": REPO, "number": 7, "sha": SHA}) + receipt = actions.apply([action], transport, config())["receipts"][0] + assert receipt["status"] == "failed" + assert "hold label" in receipt["detail"] + assert transport.writes == [] + + +def test_ready_blocks_excluded_repository_in_preview_and_apply(): + excluded_repo = "um-bruch/umbruch-website" + cfg = merge_layers( + [ + ("default", default_config()), + ( + "instance", + { + "permissions": {"enabled": ["pr.ready"], "write_owners": ["um-bruch"]}, + "multi_bot": { + "merge_account": "example-bot", + "policy": { + "draft_auto_ready_hours": 24, + "draft_ready_when_mature": True, + "draft_auto_ready_exclude_repos": [excluded_repo], + }, + }, + }, + ), + ] + ) + action = Action("pr.ready", {"repo": excluded_repo, "number": 27, "sha": SHA}) + reason = actions.denial_reason(action, cfg) + assert reason is not None and "draft_auto_ready_exclude_repos" in reason + transport = Transport({f"repos/{excluded_repo}": {"default_branch": "main", "full_name": excluded_repo}}) + receipt = actions.apply([action], transport, cfg)["receipts"][0] + assert receipt["status"] == "denied" + assert transport.writes == [] + + +def test_ready_respects_custom_hold_lists_and_fails_closed_on_malformed_pull(): + custom_cfg = config( + draft_auto_ready_hold_labels=["awaiting-lg"], + draft_auto_ready_hold_title_signals=["WAIT:"], + ) + action = Action("pr.ready", {"repo": REPO, "number": 7, "sha": SHA}) + gets = base_gets() + gets[f"repos/{REPO}/pulls/7"] = pull(draft=True, title="wait: check", labels=[]) + assert actions.apply([action], Transport(gets), custom_cfg)["receipts"][0]["status"] == "failed" + + gets[f"repos/{REPO}/pulls/7"] = pull(draft=True, title="ok", labels=[{"name": "Awaiting-LG"}]) + assert actions.apply([action], Transport(gets), custom_cfg)["receipts"][0]["status"] == "failed" + + gets[f"repos/{REPO}/pulls/7"] = pull(draft=True, title=123, labels=[]) + assert actions.apply([action], Transport(gets), config())["receipts"][0]["status"] == "failed" + + gets[f"repos/{REPO}/pulls/7"] = pull(draft=True, title="ok", labels="not-a-list") + assert actions.apply([action], Transport(gets), config())["receipts"][0]["status"] == "failed" + + def test_rerun_refuses_fork_runs_other_heads_and_running_runs(): run = {"head_sha": SHA, "status": "completed", "head_repository": {"full_name": REPO}} action = Action("actions.rerun", {"repo": REPO, "run_id": 5, "sha": SHA}) From 7804f8fd03675018355a957e56044a8d5c412fd5 Mon Sep 17 00:00:00 2001 From: lukisch <55554266+lukisch@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:16:31 +0100 Subject: [PATCH 2/2] style: format multibot.py with ruff --- src/githubbot_core/multibot.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/githubbot_core/multibot.py b/src/githubbot_core/multibot.py index 64436b5..4f3e048 100644 --- a/src/githubbot_core/multibot.py +++ b/src/githubbot_core/multibot.py @@ -111,10 +111,7 @@ def policy_settings(raw): unknown = sorted(set(raw) - set(POLICY_DEFAULTS)) if unknown: raise ValueError(f"unknown multi_bot.policy keys: {unknown}") - policy = { - key: list(default) if isinstance(default, list) else default - for key, default in POLICY_DEFAULTS.items() - } + policy = {key: list(default) if isinstance(default, list) else default for key, default in POLICY_DEFAULTS.items()} policy.update(raw) for key, allowed in _POLICY_CHOICES.items(): if policy[key] not in allowed: @@ -130,9 +127,7 @@ def policy_settings(raw): try: policy["draft_auto_ready_exclude_repos"] = [repository(repo) for repo in exclude_repos] except ValueError as exc: - raise ValueError( - "multi_bot.policy.draft_auto_ready_exclude_repos entries must be owner/repository" - ) from exc + raise ValueError("multi_bot.policy.draft_auto_ready_exclude_repos entries must be owner/repository") from exc for key in ( "draft_ready_when_mature", "trigger_missing_ci",