Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/githubbot_core/multibot.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 37 additions & 1 deletion src/githubbot_core/multibot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand All @@ -85,13 +111,23 @@ 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",
Expand Down
6 changes: 6 additions & 0 deletions src/githubbot_core/prompts/MULTI-BOT.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Branch>`)
oder `actions.rerun` eines abgeschlossenen früheren Laufs desselben Heads. Verboten bleiben leere Commits,
Expand Down
56 changes: 56 additions & 0 deletions src/githubbot_core/typed_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions tests/test_multibot_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
):
Expand Down
99 changes: 98 additions & 1 deletion tests/test_typed_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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})
Expand Down
Loading