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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ Format: [Keep a Changelog](https://keepachangelog.com/de/1.1.0/), [Semantic Vers

### Hinzugefügt / Added

- STOPP-Gate für `pr.merge` und `pr.review` mit `APPROVE`: Ein STOPP-, „NICHT MERGEN“-,
„do not merge“- oder `REQUEST_CHANGES`-Signal in PR-Kommentaren, Inline-Review-Kommentaren
oder Reviews hält Approve und Merge an, unabhängig vom Konto. Aufheben kann es nur eine spätere
eigene Zeile `STOPP aufgehoben` (o. ä.) desselben Kontos oder eines Kontos aus
`policy.stop_release_accounts`, oder ein späteres Approve desselben Kontos auf einem per
Compare nachweislich neueren Head; das Merge-Konto hebt nie durch Approve auf. Unlesbare
Daten gelten als HOLD; scharfes Auto-Merge wird im HOLD gemeldet. / Stop-signal gate on
approve and merge, account-independent, strict line-anchored release, fail closed.
- Opt-in-Aktion `pr.close` für nachweislich integrierte Heads: explizite Repository-Liste,
eigenes Policy-Opt-in, exakte Head-/Default-SHAs, Kontoprüfung und unabhängiges Rücklesen.
Keine Branch-Löschung, keine pauschalen Schließungen. / Typed opt-in closure of heads
Expand Down
5 changes: 5 additions & 0 deletions src/githubbot_core/multibot.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ def permission_contract(config, layers):
"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": [],
"stop_release_accounts": [], # accounts (besides the stopping one) whose release comment lifts any stop
"trigger_missing_ci": False,
"publish_reviews": False,
"close_integrated_prs": False,
Expand Down Expand Up @@ -121,6 +122,10 @@ def policy_settings(raw):
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)
if policy["stop_release_accounts"]:
policy["stop_release_accounts"] = _string_list(policy["stop_release_accounts"], "stop_release_accounts")
elif policy["stop_release_accounts"] != []:
raise ValueError("multi_bot.policy.stop_release_accounts must be a list of non-empty strings")
from .write_scope import repository

exclude_repos = _string_list(policy["draft_auto_ready_exclude_repos"], "draft_auto_ready_exclude_repos")
Expand Down
14 changes: 14 additions & 0 deletions src/githubbot_core/prompts/MULTI-BOT.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,17 @@ Merge ausschließlich über die Core-Aktion `pr.merge` (`githubbot-core --config
--expect-plan <plan_sha256>`). Sie liest den PR frisch, verlangt exakten Head, Default-Base,
keinen Draft und `mergeable_state = clean`, prüft das Merge-Konto, merged sha-gebunden ohne
Admin-Bypass und liest das Ergebnis zurück. Kein `gh pr merge`, kein `--admin`/`--auto`.
`pr.merge` und `pr.review` mit `APPROVE` lesen zusätzlich alle PR-Kommentare,
Inline-Review-Kommentare und Reviews. Ein STOPP, „NICHT MERGEN“, „do not merge“, `REQUEST_CHANGES`
oder ein Review mit Änderungswunsch ist HOLD, egal unter welchem Konto er steht. Aufheben kann
ihn nur dasselbe Konto oder ein Konto aus `stop_release_accounts`, und zwar mit einer eigenen
Zeile, die nur die Formel enthält: `STOPP aufgehoben`, `STOP lifted`, `Merge freigegeben` oder
`cleared to merge`. Fragen, Verneinungen und Zusätze in dieser Zeile zählen nicht. Daneben hebt
ein späteres Approve desselben Kontos auf, wenn es auf einem nachweislich neueren Head steht als
dem im STOPP genannten. Nennt der STOPP keinen Head, gilt nur die Formel. Das Merge-Konto hebt
nie durch Approve auf. Ist Auto-Merge auf einem gehaltenen PR scharf, nennt der HOLD das. Dann
schaltest du Auto-Merge ab oder meldest es.
Vor einem Merge-Auftrag liest du diese Texte selbst, statt dich auf eine Zusammenfassung zu stützen.
Wo Branch-Schutz zusätzliche Approvals verlangt, diesen normal erfüllen.

Merges sind standardmäßig deaktiviert. Nur die ausdrücklich autorisierte Instanzkonfiguration
Expand Down Expand Up @@ -202,6 +213,9 @@ und ersetzen weder Merge-Opt-in noch Identitätsprüfung.
`[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.
- `stop_release_accounts` (Liste von Kontonamen, Standard `[]`): Ein Konto aus dieser Liste kann mit
einem späteren ausdrücklichen Aufhebungskommentar jeden STOPP aufheben, z. B. das Konto der
Eigentümerin oder des Eigentümers. Ohne Eintrag hebt nur das stoppende Konto selbst auf.
- `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
173 changes: 173 additions & 0 deletions src/githubbot_core/stop_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""Stop-signal gate shared by every approve and merge path.

A reviewing instance may stop a pull request in plain text ("STOPP", "NICHT MERGEN",
"do not merge", ...) in a PR comment, an inline review comment or a review body, or with
a CHANGES_REQUESTED review. Whatever account posted it, the stop holds ``pr.review``
APPROVE and ``pr.merge`` until a *later* event lifts it:

* a release line by the same account or by one of ``multi_bot.policy.stop_release_accounts``.
The line must consist of the formula alone (``STOPP aufgehoben``, ``STOP lifted``,
``Merge freigegeben``, ``cleared to merge``; markdown emphasis and a final ``.``/``!``
are tolerated). Questions, negations or extra words on that line never count, nor do
blockquote lines (``> ...``, as a quote-reply produces) or lines inside code fences; or
* a later APPROVED review by the same account on a head that is provably newer than
every head the stop named (GitHub compare status ``ahead``). A stop that names no
head can only be lifted by the release line. The configured merge account never
lifts a stop by approving: it is the account that writes.

Dismissed reviews are ignored (dismissal is GitHub's own explicit lift). Unreadable
comments, reviews or timestamps fail closed. If auto-merge is already armed on a held
pull request, the hold reason says so, because GitHub would merge without this gate.
Anchors: lock-master#8 (2026-09-22) and promptboard#8 (2026-11-22), both merged
minutes after a STOPP comment.
"""

from __future__ import annotations

import re
from typing import Callable, Iterable, Optional

_NEGATED = re.compile(r"\b(?:kein(?:e[nr]?)?|no|ohne|without)\s+(?:stopp?|hold)\b", re.IGNORECASE)
_STOP = re.compile(r"\bstopp\b|nicht\s+mergen|do[\s-]+not[\s-]+merge|don'?t\s+merge|\bREQUEST_CHANGES\b", re.IGNORECASE)
_STOP_UPPER = re.compile(r"\bSTOP\b") # English only in capitals, so prose like "stop the job" passes
_RELEASE_LINE = re.compile(
r"(?:stopp?\s+(?:ist\s+)?(?:aufgehoben|zurückgenommen)|stop\s+(?:lifted|released|withdrawn)"
r"|merge\s+freigegeben|cleared\s+to\s+merge)[.!]?",
re.IGNORECASE,
)
_SHORT_SHA = re.compile(r"\b[0-9a-f]{7,40}\b")


def _release_lines(text: str) -> list[tuple[str, bool]]:
"""(line, counts as release). Quoted lines and lines in code fences never release:
a quote-reply repeats someone else's words, a fence shows text instead of saying it."""
result, fence = [], None
for raw in text.splitlines():
stripped = raw.strip()
marker = re.match(r"(`{3,}|~{3,})", stripped)
if fence:
if marker and marker[1][0] == fence[0] and len(marker[1]) >= len(fence):
fence = None
result.append((raw, False))
continue
if marker:
fence = marker[1]
result.append((raw, False))
continue
line = re.sub(r"\s+", " ", stripped.strip("*_#").strip())
# ">" and backticks are deliberately not stripped: a quote line never fullmatches.
result.append((raw, bool(_RELEASE_LINE.fullmatch(line))))
return result


def _is_release(text: str) -> bool:
return any(release for _, release in _release_lines(text))


def _is_stop(text: str) -> bool:
rest = "\n".join(line for line, release in _release_lines(text) if not release)
rest = _NEGATED.sub(" ", rest)
return bool(_STOP.search(rest) or _STOP_UPPER.search(rest))


def _login(item) -> Optional[str]:
user = item.get("user") if isinstance(item, dict) else None
login = user.get("login") if isinstance(user, dict) else None
return login.casefold() if isinstance(login, str) and login.strip() else None


def evaluate(
comments: list,
reviews: list,
release_accounts: Iterable[str] = (),
*,
merge_account: str = "",
is_newer: Callable[[str, str], bool] = lambda old, new: False,
) -> Optional[str]:
"""Return why approve/merge must hold, or ``None``. No I/O except ``is_newer``.

``comments`` holds issue comments and inline review comments (the latter carry
``original_commit_id``). ``is_newer(old, new)`` must be True only when ``new`` is a
proven descendant of ``old``; the default proves nothing.
"""
owners = {account.casefold() for account in release_accounts}
writer = merge_account.casefold().strip()
events = []
if any(not isinstance(item, dict) for item in [*comments, *reviews]):
return "pull request comment or review unreadable; refusing approve/merge"
for item in comments:
login, at, body = _login(item), (item or {}).get("created_at"), (item or {}).get("body")
if not login or not isinstance(at, str) or not isinstance(body, str):
return "pull request comment unreadable; refusing approve/merge"
commit = item.get("original_commit_id") or item.get("commit_id")
events.append((at, "comment", login, body, commit if isinstance(commit, str) else None))
for item in reviews:
login, state = _login(item), (item or {}).get("state")
if state in ("PENDING", "DISMISSED"):
continue
at, body, commit = item.get("submitted_at"), item.get("body") or "", item.get("commit_id")
if not login or not isinstance(at, str) or not isinstance(body, str) or not isinstance(commit, str):
return "pull request review unreadable; refusing approve/merge"
events.append((at, state, login, body, commit))
events.sort(key=lambda event: event[0])

stops: dict[str, tuple] = {} # login -> (at, named heads)
for at, kind, login, body, commit in events:
stop_text = _is_stop(body)
if kind == "APPROVED" and not stop_text:
named = stops.get(login, (None, set()))[1]
if login != writer and named and all(is_newer(head, commit) for head in named):
del stops[login]
continue
if kind == "CHANGES_REQUESTED" or stop_text:
named = set(_SHORT_SHA.findall(body))
if commit:
named.add(commit)
stops[login] = (at, named)
elif _is_release(body):
if login in owners:
stops.clear()
stops.pop(login, None)
if not stops:
return None
login, (at, _) = min(stops.items(), key=lambda item: item[1][0])
return f"stop signal by {login!r} at {at} is not lifted; approve/merge HOLD"


def hold_reason(transport, repo: str, number: int, config: dict, pull: Optional[dict] = None) -> Optional[str]:
"""Read all comments and reviews fresh and evaluate them; read failures are a HOLD."""
from .multibot import policy_settings

settings = config.get("multi_bot") or {}
try:
release_accounts = policy_settings(settings.get("policy"))["stop_release_accounts"]
except ValueError as exc:
return f"multi_bot.policy invalid: {exc}"
lists = {}
for name, endpoint in (
("comments", f"repos/{repo}/issues/{int(number)}/comments?per_page=100"),
("inline review comments", f"repos/{repo}/pulls/{int(number)}/comments?per_page=100"),
("reviews", f"repos/{repo}/pulls/{int(number)}/reviews?per_page=100"),
):
data, error = transport.get_paginated(endpoint)
if error or not isinstance(data, list):
return f"pull request {name} unreadable ({error or 'no list'}); approve/merge HOLD"
lists[name] = data

def is_newer(old: str, new: str) -> bool:
if not _SHORT_SHA.fullmatch(old) or not _SHORT_SHA.fullmatch(new):
return False
data, error = transport.get(f"repos/{repo}/compare/{old}...{new}")
return not error and isinstance(data, dict) and data.get("status") == "ahead"

reason = evaluate(
lists["comments"] + lists["inline review comments"],
lists["reviews"],
release_accounts,
merge_account=str(settings.get("merge_account") or ""),
is_newer=is_newer,
)
if reason and isinstance(pull, dict) and pull.get("auto_merge") is not None:
enabler = ((pull.get("auto_merge") or {}).get("enabled_by") or {}).get("login") or "unknown"
reason += f"; auto-merge is armed (enabled by {enabler!r}) and GitHub may merge without this gate: disable it"
return reason
10 changes: 9 additions & 1 deletion src/githubbot_core/typed_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from typing import Any, Optional
from urllib.parse import quote, urlsplit

from . import stop_gate
from .credentials import CredentialUnavailable, EnvTokenProvider, resolve_token

SHA = re.compile(r"[0-9a-f]{40}")
Expand Down Expand Up @@ -203,6 +204,9 @@ def exec_merge(transport, params: dict, config: dict):
if pull.get("mergeable_state") != "clean":
return None, f"mergeable_state is {pull.get('mergeable_state')!r}, not 'clean'"
repo, number = params["repo"], int(params["number"])
stop = stop_gate.hold_reason(transport, repo, number, config, pull)
if stop:
return None, stop
body = {"sha": params["sha"], "merge_method": params.get("method", "merge")}
_, error = transport.request("PUT", f"repos/{repo}/pulls/{number}/merge", body)
if error:
Expand Down Expand Up @@ -334,7 +338,7 @@ def current_pull():
return {}, "cannot approve or request changes on the account's own pull request"
return pull, None

_, error = current_pull()
pull, error = current_pull()
if error:
return None, error
reviews, error = transport.get_paginated(f"{endpoint}/reviews?per_page=100")
Expand All @@ -352,6 +356,10 @@ def current_pull():
return None, "existing review record unreadable; nothing written"
if review["user"]["login"].casefold() == account.casefold() and review["commit_id"] == sha:
return None, f"review already exists for this account/head (id={review.get('id')}); nothing written"
if params["event"] == "APPROVE":
stop = stop_gate.hold_reason(transport, repo, number, config, pull)
if stop:
return None, stop
# Pagination may take time; bind the write to a fresh head again afterwards.
_, error = current_pull()
if error:
Expand Down
17 changes: 15 additions & 2 deletions tests/test_pr_review_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __init__(self):
self.pull = {"number": 7, "state": "open", "head": {"sha": SHA}, "draft": False, "user": {"login": "author"}}
self.pull_answers = []
self.reviews = []
self.comments = []
self.list_error = None
self.write_error = None
self.id = 81
Expand All @@ -76,6 +77,8 @@ def get(self, endpoint):
raise AssertionError(f"unexpected GET {endpoint}")

def get_paginated(self, endpoint):
if endpoint in (f"repos/{REPO}/issues/7/comments?per_page=100", f"{ENDPOINT}/comments?per_page=100"):
return copy.deepcopy(self.comments), None
assert endpoint == f"{ENDPOINT}/reviews?per_page=100"
return copy.deepcopy(self.reviews), self.list_error

Expand Down Expand Up @@ -200,8 +203,18 @@ def test_existing_or_unreadable_reviews_prevent_a_second_write(existing):
def test_reviews_on_old_heads_or_from_other_actors_do_not_block():
transport = Transport()
transport.reviews = [
{"user": {"login": "example-bot"}, "commit_id": OTHER},
{"user": {"login": "other-reviewer"}, "commit_id": SHA},
{
"user": {"login": "example-bot"},
"commit_id": OTHER,
"state": "COMMENTED",
"submitted_at": "2026-01-01T00:00:00Z",
},
{
"user": {"login": "other-reviewer"},
"commit_id": SHA,
"state": "APPROVED",
"submitted_at": "2026-01-01T00:01:00Z",
},
]
assert apply(transport)["status"] == "applied"

Expand Down
Loading
Loading