# The merge gate

> How the merge gate's required check blocks a merge while a major or blocker finding is open, and how to set it up, use it and roll it out.

Web page: https://visto-ai.com/docs/merge-gate/

The merge gate is a GitHub check that Visto AI writes on a pull request's head commit. Once you make it a required check, a pull request cannot be merged while one of the app's major or blocker findings is still open: neither judged fixed or answered by the review of the current commit, nor answered by a person in a resolved thread. Minor findings and notes never block.

The gate also changes when reviews run. A gated pull request is not reviewed on every push: the author comments `/done` when the work is ready, and that review decides the check. The gate is off unless you switch it on for a repository.

## Turn it on

The gate is configured per deployment, under `repositories.defaults.gate` for every repository or `repositories.overrides.<owner/name>.gate` for one (each key written there replaces the default's). Start in `shadow` mode:

```yaml
repositories:
  overrides:
    acme/shop:
      gate:
        enabled: true
        branches: [main]
        mode: shadow
```

| Key | Default | What it does |
|---|---|---|
| `enabled` | `false` | Switches the gate on. When off, nothing else in the block has an effect. |
| `branches` | none | The base branches that are gated, compared exactly, letter case included. Required when the gate is enabled: a config that enables it with no branch is refused at start. |
| `checkName` | `AI Review` | The check's name, 1 to 100 printable ASCII characters. |
| `mode` | `enforce` | `enforce`, `shadow` or `bypass` (see [Roll it out](#roll-it-out-shadow-and-bypass)). |
| `clearByReply` | `true` | Whether a person's reply in a resolved thread clears a finding (see [What blocks a merge](#what-blocks-a-merge)). |
| `skipTeam` | nobody | `<org>/<team-slug>`: the one team whose members may skip the gate for a commit. The organisation must own the repository. |
| `requiredChecks` | none | Names of other checks or commit statuses that `/done` looks at before it says a head is already green (at most 20). |

[config.example.yml](https://raw.githubusercontent.com/visto-ai/visto-ai/0faf484aa43f4fcdc1f30c1d5c056ea26c1c0d32/config.example.yml) shows every key. You can also change these in the UI's Settings, under Repositories (see [Configuration](https://visto-ai.com/docs/configuration/)). A save with the gate on and no branch is refused at `Gated branches`. Nothing in a reviewed repository, `.visto-ai.yml` included, can set the gate.

A `*` in `branches` is read as a branch literally named `*`, so it gates nothing. This differs from the review filter `baseBranches`, where `*` means every branch. `baseBranches` has no say in which pull requests are gated.

### Make the check required in GitHub

Visto AI writes the check, but only GitHub can make a merge wait for it. **Until you add this rule, the check is shown and holds no merge.** On each gated branch:

- **With a ruleset:** add the rule "Require status checks to pass", add the check by its name (`AI Review` unless you changed `checkName`), and set its source to this app.
- **With branch protection:** turn on "Require status checks to pass before merging", pick the check, and set its source to this app.

Setting the source to the app matters: a check that any source may report can be passed by anyone who can write a commit status. [Automatic approval](https://visto-ai.com/docs/automatic-approval/) relies on this too.

### Give the app its permissions

An app made with `npm run app:create` already has everything the gate needs (see [Create the GitHub App](https://visto-ai.com/docs/create-the-github-app/)). For an existing app, add these in its settings:

| Permission or event | When it is needed |
|---|---|
| `Checks`: read and write | Always |
| Event `Check run` | Always, to hear a re-run of the check (GitHub sends a re-run of the whole suite, event `check_suite`, to an app with Checks write without a subscription) |
| `Commit statuses`: read | When `requiredChecks` names any check |
| Organisation `Members`: read | When `skipTeam` is set |

Each installation must then accept the new permissions. **Restart the service afterwards:** it reads the app's permissions once, at start. For anything still missing it logs `feature_off` with the feature `gate` at each start, raises an alert of that name naming the missing item (`checks:write`, `event:check_run`, `statuses:read` or `members:read`), and keeps running.

The service reads what the app asks for, not what each installation has accepted. A write that an installation refuses because it has not accepted a permission fails as described in [When GitHub fails](#when-github-fails).

## How it works

A pull request is gated when its repository has the gate enabled and its base branch is in `branches`. In `enforce` mode:

1. When the pull request is opened, reopened, marked ready for review, pushed to or retargeted, it gets the check `Waiting for /done` and no review. Drafts, pull requests by ignored authors and pull requests against a branch outside `baseBranches` get the check too, and need `/done` like any other.
2. When the author is ready, someone with access comments `/done` (or `/review`, or re-runs the check in GitHub). The check turns to `Reviewing` and a review runs.
3. The review is posted and decides the check: green if nothing blocks, `action_required` with a list of the blocking threads otherwise.
4. The author fixes or answers each blocking finding. A reply and a resolve in the thread clears that finding within seconds, with no new review (unless `clearByReply` is off), and the check turns green once nothing else blocks. A push gives the new commit its own check, which waits for `/done` again.

The check is written on the head commit, so every new commit starts over. Its link goes to the pull request's page.

A later review of a gated pull request reads every file again (`full`) unless `newHead` is written for the repository (see [Reviews after the first](https://visto-ai.com/docs/leave-dry-run/#reviews-after-the-first)).

Pull requests of the same repository against branches not in `branches` are reviewed on every push, as without a gate.

## Commands

All commands are read from the first non-empty line of a comment, in any letter case. Only an owner, a member or a collaborator of the repository may use them. On a private repository (not an internal one), where only people with access can read, GitHub's NONE or CONTRIBUTOR for a person is read as collaborator: GitHub sends those for an organization member who keeps the membership private. `/done` and `/ai-review-skip` are commands only in a repository whose gate is enabled; elsewhere they are ordinary comments.

### `/done`

`/done`, alone or followed by a space and more text, says the pull request is ready.

- The comment gets an eyes reaction.
- If the check would already be green for this head (passed, skipped or bypassed), nothing runs. When `requiredChecks` are named and every one of them is green on the head, the reply also says so in one sentence. A check counts as green only with `success`, as a commit status or as the newest check run of that name; `neutral` and `skipped` do not.
- Otherwise a review is queued. If a review of the pull request is already running or waiting its turn, `/done` joins it rather than starting a second one.
- A refused `/done` gets a confused reaction and one sentence with the code `not_allowed` or `closed`.

On a pull request of a gate-enabled repository whose base branch is not gated, `/done` works as `/review`.

### `/review`

`/review` asks for a review whatever the check says. On a gated pull request it runs the review even when the check is already green, which `/done` does not. On the head and base of the last review it is a re-check. See [The /review command](https://visto-ai.com/docs/leave-dry-run/#the-review-command) for its answers and codes.

### Re-running the check

Re-running the check in GitHub asks for a review of the head, even when the check is already green. On a pull request's Checks tab GitHub may offer only **Re-run all checks** for the app's check, which re-runs the app's whole check suite on the commit; that suite holds only the gate's check, so it counts as a re-run of the check. GitHub decides who is offered the button; the service does not check, so a re-run requested through the API by a bot is honoured too. A re-run is never answered with a comment. It does nothing on a closed pull request, one that is no longer gated, a commit that is no longer the head, or in `bypass` mode. A re-run of the check names its pull request in the check's `external_id`, or else the first one GitHub lists for the commit, so it works on a fork's pull request. A re-run of the suite carries no `external_id` and GitHub lists no fork's pull request for it, so on a fork's pull request it is ignored: comment `/done` there instead. A re-run of another app's check or suite, or of a check of another name, is ignored.

### `/ai-review-skip <reason>`

A member of the skip team can let one commit through without its blocking findings cleared:

```
/ai-review-skip urgent fix, checked by hand
```

The reason is the rest of that line and is required. Set the team with `skipTeam: <org>/<team-slug>`; with no team set, nobody can skip.

- The skip holds for one commit: the head the service knew when the comment arrived. A new commit ends it, and its check waits for `/done` again. If a commit was pushed after the comment, the skip is refused as `stale_head` and must be typed again.
- A later review does not undo a skip: a `/review` or a re-run on a skipped head still runs and posts, and the check stays skipped.
- The check reads `Skipped by @<login>` and shows the reason as one line in a code span, at most 300 characters, with control characters and text-direction characters removed and each backtick written as an apostrophe.
- The login, the reason and the comment are stored in the `gate_overrides` table.
- The team's name is never written on GitHub: the texts say "the team that may skip".
- The commenter must be an active member of the team; a pending invitation does not count. A misspelt team name is not caught at start: everyone then reads as "not a member".
- A skip does not pass a check held by a standing approval (see [Edge cases](#edge-cases)).

An accepted skip gets an eyes reaction. A refused one gets a confused reaction and a sentence with its code:

| Code | Meaning |
|---|---|
| `not_allowed` | The commenter is not an owner, member or collaborator. |
| `closed` | The pull request is closed. |
| `not_gated` | The pull request's base branch is not gated. |
| `stale_head` | A commit was pushed since the comment. |
| `missing_reason` | No reason after the command. |
| `no_skip_team` | No `skipTeam` is set. |
| `not_team_member` | The commenter is not an active member of the skip team. |
| `membership_unverified` | The team membership could not be read. Nothing is skipped; try again in a minute. |

A command that fails after all its tries gets a sentence saying it could not be handled. A command replaced by a later one while it waits is not answered.

## The check

| Title | Status or conclusion | When |
|---|---|---|
| `Waiting for /done` | queued | No review of this head exists yet, and none is under way. |
| `Reviewing` | in progress | A review that will run is running or waiting its turn. |
| `Review waiting: reviews are paused (spend_limit)` or `(model_error)` | queued | A review is waiting and reviews are paused. For `model_error` the text says only that reviews are paused on the reviewer's side. |
| `No blocking findings`, `1 finding, none blocking`, `N findings, none blocking` | `success` | The head has its review and nothing blocks. |
| `1 blocking finding is open`, `N blocking findings are open`, `Blocking findings open: N (M listed in the review only)` | `action_required` | Something blocks (see below). |
| `Review failed (<code>): comment /done to retry` | `failure` | The newest review of this head failed or was not posted. |
| `Could not evaluate (<code>): comment /done to retry` | `failure` | The review was posted but its threads could not be read. |
| `Skipped by @<login>` | `success` | The skip team skipped this commit. |
| `Gate bypassed` | `success` | The repository is in `bypass` mode. |
| `Withdrawing an earlier approval` | in progress | An approval by this app of another head or base branch still stands and is being dismissed. |
| `Earlier approval not withdrawn (<code>)` | `failure` | An approval by this app could not be dismissed (see [Automatic approval](https://visto-ai.com/docs/automatic-approval/)). |

When the review left files unread, `; N files not reviewed` follows a passing or blocking title.

A blocking check's summary lists at most 50 threads, each with its file, line and a link, and says how many more there are. The finding's text is not shown. A path is shown in printable ASCII, with any other character and the backtick shown as `?`.

GitHub does not reopen a completed check run. When a decided check has to wait or review again (a `/review` or `/done` on a head whose check is decided, or leaving `bypass`), the service writes a new run of the same name on the commit. GitHub lists, and the pull request counts, only the newest run of that name. Other changes are made in place.

## What blocks a merge

After a review, the check passes in three cases only: the head has its review and nothing blocks; a skip is stored for this head; or the mode is `bypass`. The head's review is the newest posted review whose head and merge base are the live ones; a re-check counts. A read that fails never counts as "nothing blocks".

### Which threads block

A thread blocks when it is one of the app's own, its first comment is stored as a major or blocker finding, and it is not cleared. Minor findings, notes, and findings that no thread holds never block.

The app's own thread with no stored finding also blocks, as a finding of unknown severity. This covers a minor or a note whose record was lost and a thread left by another deployment of the same app. No review can judge such a thread: it clears by a person's reply and a resolve, or, with `clearByReply` off, by a skip.

### How a thread clears

1. **By a review.** The review of the current head judged it `fixed` or `answered`, and nobody but the app has written in the thread since.
2. **By the app's resolve.** The app resolved it, and the newest verdict any posted review gave it is `fixed` or `answered`.
3. **By a reply** (only with `clearByReply: true`). The thread is resolved and a person (not the app, not a bot) has replied in it.

**A thread resolved with a click and no reply does not clear.** The check's summary names it, and the next review judges it again.

A reply is not read and its author's access is not checked: "will fix" counts, and so does a reply written before the last push. On a public repository, the author of a fork's pull request can therefore turn the check green alone, by replying and resolving, though the merge itself still needs write access. A person's comment in a thread after a review judged it undoes that review's verdict for the gate.

To object to a thread the app resolved, unresolve it: a reply alone is not read once the app has resolved the thread. The thread then blocks until a review judges it again.

### With `clearByReply: false`

Only a review clears a thread, or the app's own resolve after one does. A resolved thread with a person's reply is judged again at the next review. Three kinds of thread that no review can judge then clear only by a skip: one whose file left the pull request's diff, one whose file was not sent to the model, and the app's own thread with no stored finding. The summary marks each on its line.

### What is counted and does not block

- A major or blocker finding the review could not place on the diff.
- A major raised in an incremental review on code unchanged since the last review.
- Files not reviewed. A team that wants a person to look at them should also require an approving review in GitHub: Visto AI never approves a pull request with a file not reviewed (see [Automatic approval](https://visto-ai.com/docs/automatic-approval/)).

The review lists these and the check's summary counts them.

### When GitHub refused the inline comments

If GitHub refused a review's inline comments, its findings are in the review's text and in no thread, so no reply can clear them. The commit stays blocked while that review holds a major or blocker finding placed on the diff, until a new commit is reviewed or the skip team skips it. A `/done` on the same head, which posts a re-check with no new findings, does not turn it green. If that review's stored result cannot be read, it blocks too. With `newHead: incremental`, the review of the next commit reads only what changed, so it may not raise those findings again.

### When the check is evaluated again

The check is evaluated again without a new review:

- about three seconds after a resolve, an unresolve or a reply in a review thread, by anyone, the app included (each new event restarts the wait);
- when a review job ends;
- when reviews are paused, resume or change their reason, for each pull request with a review waiting;
- at each start of the service, for every stored open gated pull request.

An edited or deleted comment is not taken in, so a deleted reply changes the check only at its next evaluation. Each evaluation reads the pull request and the check from GitHub (and the threads, when the head has its review), and writes only when the check would change. Verifications are read from the database: a database that lost a run loses its verifications, and those threads block until the next review.

## Roll it out: `shadow` and `bypass`

| Mode | Reviews | Check |
|---|---|---|
| `enforce` | Only when asked: `/done`, `/review` or a re-run. | Decided by the rule above. |
| `shadow` | On every push, as without a gate. | Written and decided by the rule, so you can watch it before relying on it. |
| `bypass` | Only when asked. | Always `Gate bypassed`, green. |

**Start in `shadow`.** Reviews run as before and the check is written, so you can compare what it says with how your team works before you make it required. In `shadow`, a push that brings nothing new to review leaves `Waiting for /done`, as `enforce` would before a `/done`.

**Use `bypass` to stand the gate down** without removing the required check, for example during an incident. Every check is written green at its next evaluation, and a gated pull request is still reviewed only when asked. The service logs `gate_bypass` and raises an alert of that name at each start while any repository is in `bypass`. Leaving `bypass` takes full effect at the next start, when every stored open gated pull request is evaluated again and the green checks are decided anew.

## Alerts and log events

| Name | When |
|---|---|
| `feature_off` (feature `gate`) | At start, for each permission or event the gate lacks. |
| `gate_bypass` | At start, while any repository is in `bypass`. |
| `gate_check_failed` | A gate job gave up, or the runner gave it up as too old or out of tries. Raised once per code per run of the service. |

Alerts always go to the log, and to `alerts.webhook` when you set it.

## When GitHub fails

A failed evaluation is written at once as `failure` (`Review failed` or `Could not evaluate`) with a short code, and tried again twice, after 10 and 60 seconds. While it retries, the check says so. A job that gives up raises `gate_check_failed` and asks for nothing more; the next event or start tries again. A pull request whose check can never be written (the app was removed from the repository) is tried three times at each start, with one alert per code.

**A read or write that fails leaves whatever check GitHub already shows, and that can be a green one that no longer holds,** for example after a thread is unresolved while the check cannot be written. Failing closed bounds what the service writes, not what GitHub keeps. During an outage of GitHub's checks API, or after a job has given up, a merge can pass on a stale check. The alert is the sign to look.

Every call to GitHub has a 60-second time limit; one that runs out is read as `github_network`. This applies to reviews too.

## Edge cases

### Two pull requests on the same commit

GitHub attaches a check run to a commit, not to a pull request. When one commit is the head of two pull requests of one repository (for example opened against two branches), they share one check. Each pull request is evaluated on its own, and the one evaluated last decides what the commit's check says. One of them can therefore show a green check on the strength of the other's review or skip. If only one of them is gated, the other shows the gated one's check. Avoid opening the same head against two gated branches.

### Standing approvals

With [automatic approval](https://visto-ai.com/docs/automatic-approval/) on, an approval by this app of another head or base branch holds the check at `Withdrawing an earlier approval` while it is dismissed, whatever a review or a skip says. If it cannot be dismissed, the check reads `Earlier approval not withdrawn (<code>)` until it is gone.

### Joining a running review

A `/done` or a re-run joins a review of the pull request only when that review will run: one asked for by a re-run or by someone who may command, or an automatic one on a pull request reviewed on push (`shadow`, or a branch outside the gate). A stranger's `/review`, which is about to be refused, and a push's job on a pull request reviewed only when asked, which is about to be dropped as `gated`, are not joined: the `/done` queues its own review.

A review asked for by `/done` or a re-run starts over once when the head moved while it ran, or when it ended without a posted review while the pull request's stored head moved after it started. The review that starts over says nothing; the new one's end answers. A `/done` does not join a running review that has already started over, since it would not start over again and the command would be lost: it queues its own review, which costs one more.

### Pull requests that stop being gated

A pull request whose gate is switched off, or whose base moves out of `branches`, keeps the check it had, and nothing writes it again. `Waiting for /done` can therefore stand on a pull request nobody has to answer.

### Pull requests opened before the app was installed

A pull request the service holds no stored row for, such as one opened before the app was installed, is evaluated at start only once the gate has written its check, in a repository whose gate is enabled, using the installation of its newest job. One whose newest evaluation found it closed or gone is left alone (a reopening stores a row). Jobs are deleted after 14 days, after which such a pull request has no installation to be evaluated with and waits for its next event or command. Until its check is written, GitHub shows its own wait for the required check.

### Changes saved in the UI

A gate setting saved in Settings applies at each pull request's next event. Whether the gate is in use at all is decided at start (out of dry run, with some repository's gate enabled). So a gate switched on in the UI holds each pull request from its next event, but the start's sweep of checks, the evaluation of waiting reviews when a pause begins or ends, the `bypass` alert and the permission check all wait for the next start.

### Dry run

In dry run no gate job is stored and no check is read or written. A gated pull request still gets no review on a push, `/done` works as a `/review` recorded like any other dry-run review, and a skip and a re-run do nothing.

## Costs and limits

- **`check_run` deliveries.** An app subscribed to `check_run` may be sent the `created` and `completed` events of every check run in its repositories, gate or no gate. The only one the service acts on is a re-run of its own check; each of the others is stored as an ignored delivery in the `deliveries` table, which is never pruned. After a downtime the service reads at most 10 pages of GitHub's delivery log to recover missed events (see [Leave dry run](https://visto-ai.com/docs/leave-dry-run/#what-happens-at-the-switch)), so heavy check traffic can push real missed events out of reach. On a repository with a lot of CI, watch how many of these deliveries arrive on a quieter repository first.
- **Each start** evaluates every stored open gated pull request, whatever its last state: one evaluation each, with reads of GitHub and a write only when the check changes. A pull request the database still holds as open though it was closed costs one read. With hundreds of open gated pull requests, a command typed right after a start waits behind this sweep.
- **Pauses.** While reviews are paused, each pull request with a review waiting is evaluated each time the pause begins, ends or changes its reason.
- **Timing.** The check follows an event by the time a gate job takes to start, plus about three seconds for a thread event or a reply. The app's own replies cause one evaluation that changes nothing.
- **Lanes.** Gate jobs run in their own places (see [Running the service](https://visto-ai.com/docs/running-the-service/)), so a check is written while a review runs.
- **Migration.** The gate adds the migration `0008_gate`. A release older than it finds a migration it does not know and refuses to start on that database.

## Related

- [Automatic approval](https://visto-ai.com/docs/automatic-approval/)
- [Leave dry run](https://visto-ai.com/docs/leave-dry-run/)
- [Configuration](https://visto-ai.com/docs/configuration/)
- [Create the GitHub App](https://visto-ai.com/docs/create-the-github-app/)
