# GitHub App server

> Run patchula serve as a GitHub App: webhooks, scheduled sweeps, acting on checkboxes in seconds, the repository API and remote commands.

`patchula serve` runs the same engine as `patchula run` as a long-lived GitHub App: it queues webhooks, sweeps on a schedule, mints its own tokens and keeps caches warm, so a ticked checkbox is acted on within seconds.

> **No web UI**
>
> The routes are `POST /webhook`, `GET /healthz`, `GET /readyz`, the small `/api/v1` API behind [`--remote`](#run-from-your-machine) and the read-only [repository API](#repository-api). It listens on `127.0.0.1:8080` by default, so put an HTTPS reverse proxy in front for GitHub’s deliveries.

## Create the GitHub App

The App needs:

- repository permissions: contents write, pull requests write, issues write (dashboard and labels), workflows write (workflow updates), and checks and commit statuses read (merge fallback);
- events: push, issues, pull request, installation, installation repositories, check suite, check run and repository (which keeps the [repository API](#repository-api) current);
- a webhook secret;
- **Enable Device Flow** ticked, so people can [run from their machines](#run-from-your-machine).

A repository or organisation webhook can point at the server instead of the App’s own webhook URL, using the same secret.

## Settings

Operator settings are a Pkl file that amends the bundled `PatchulaSettings.pkl`, the same file the CLI reads. They are separate from repository configs, which amend `PatchulaConfig.pkl`. Only the server reads the `server` section.

`/etc/patchula/settings.pkl`

```pkl
amends "PatchulaSettings.pkl"

concurrency = 8
server {
  allowedInstallations { 123456 }
  allowedRepositories { "acme/my-app" }
  sweepCron = "0 0 * * * *"   // hourly; six fields, seconds first
  reportDirectory = "/var/lib/patchula/reports"
}
```

```sh
patchula config settings-schema           # print the schema
patchula config check-settings /etc/patchula/settings.pkl
```

Empty allowlists allow everything the App can see. The file is re-read about once a second. An invalid edit keeps the last good settings, logs a sanitised error and makes `/readyz` fail until it is fixed; a running batch keeps the snapshot it started with. A change to the `http` section takes effect at each installation’s next batch. Every setting is in the [settings reference](https://count-patchula.sweepy.dev/reference/settings/).

Each batch’s report is logged as one JSON event, or with `reportDirectory` written to a file there. The directory keeps the newest `reportsKept` reports (200 by default) and deletes older ones after each new report, so a busy or failing server does not fill its volume. A temporary file a crashed write left behind is deleted once it is a day old. Only files named as the server names reports are touched.

## Credentials and startup

```sh
export PATCHULA_APP_ID=12345
export PATCHULA_APP_PRIVATE_KEY_FILE=/etc/patchula/app.pem
export PATCHULA_WEBHOOK_SECRET_FILE=/etc/patchula/webhook-secret
export PATCHULA_SETTINGS=/etc/patchula/settings.pkl
export PATCHULA_SERVER_CACHE=/var/lib/patchula
patchula serve
```

`PATCHULA_APP_PRIVATE_KEY` and `PATCHULA_WEBHOOK_SECRET` can hold the values directly instead, but not both a file and a value for the same secret. Secrets never appear in settings or command-line arguments, and no key, JWT, token, signature or request body is ever logged. Installation tokens live in memory, are renewed two minutes before they expire, and never touch SQLite. Keep the host clock synchronised; JWTs are issued 60 seconds in the past.

`/healthz` is liveness. `/readyz` needs valid settings, a working cache and a successful token probe for every allowed installation, and returns 503 while draining. Logs are JSON on stderr; `PATCHULA_LOG=debug` adds request-level detail.

## What starts a batch

- a push to a repository’s default branch;
- a ticked box on the Count’s dashboard, or the re-check, add-to-batch or remove-from-batch box on one of his PRs;
- one of his PRs being closed;
- the App being installed, or a repository being added;
- checks completing on one of his PRs;
- the sweep schedule. Starting the server does not sweep; queued work survives restarts.

Each trigger can be turned off under `triggers`. Events from the App itself, disallowed repositories and unrelated events are acknowledged and ignored.

## Webhook handling

Signatures (`X-Hub-Signature-256`) are verified over the raw bytes before any JSON is parsed. A bad signature gets 401, a body over 2 MiB 413, a signed but malformed delivery 400, and a durably queued one 202. If SQLite is busy or the server is draining, the answer is 503 so GitHub redelivers. Delivery IDs are deduplicated for seven days. Every rejection carries a JSON `error_kind`, such as `bad-signature` or `draining`.

Repository and organisation webhooks can omit the installation; the server looks it up with the App JWT and caches the answer for five minutes.

## The queue

Batches of up to `workers` installations (4 by default) run at once, each installation one batch at a time, with up to `concurrency` repositories scanned in parallel in each. Each installation has its own GitHub rate limits, so they do not wait on each other; each batch runs its own lockfile tools, though, so lower `workers` on a small host. Within an installation and across them, a person’s work runs first — a push, a dashboard or pull request checkbox, or a closed pull request — then completed checks, then the sweep and discovery; a repository queued by more than one of these keeps the most urgent class, whatever runs first. A batch’s claims finish before its public record writes, so recording never holds queue rows. The first event opens a coalescing window (`coalescingMs`), and events that arrive during a batch fold into one follow-up batch. Each repository finishes on its own: when one fails, only that one is retried, after a backoff that starts at a minute and doubles with each consecutive failure up to an hour, plus a small spread per repository so that repositories that failed together do not retry in step. A success resets it. A new event for the repository, such as a push that fixes it, runs it after the usual coalescing window instead of waiting out the backoff. A run that dies with the server or takes it down, such as by an OOM kill or a panic, counts as a failure; one cut short by a shutdown does not. If the repository changes while a batch is running — its default branch moves, a pull request the run is reconciling changes, or the write inventory disagrees with what the run read — the run stops rather than write against the stale view, reports the repository `stale` with the race as its reason, and the server requeues it for a minute later. A stale repository is not a failure and does not back off; a repository that both raced and errored is a failure, as before. A repository requeued three times in a row fails the next one instead, backing off like any other failure; a success or a failure resets the count.

Queue rows survive restarts. SIGTERM stops new work, drains the running batches within `--shutdown-timeout-secs` (60 by default), and requeues the rest. A lock beside the cache allows one server per cache; give CLI jobs a separate cache.

## Quiet sweeps

A repository that has not moved since its last complete run does not cost GitHub requests during a sweep. Each complete run stores the head commit, a hash of the repository’s report — timings, stats and evaluation timestamps excluded — and `next_due`, the earliest instant at which time alone can change the answer: a held-back release becoming eligible, an update or maintenance window opening, a waiting lockfile refresh, an hourly PR quota freeing. On a batch the sweep alone started, the server replays the cached extraction and catalog reads for every claimed repository, and one whose report hashes the same, is not due and ran within the last six hours is skipped with no GitHub request of its own beyond the hinted tag and digest refreshes every sweep makes — the installation’s listing still costs what discovery always costs. Missing state, a missing cached extraction, a passed due or a changed answer all run the repository in full, as does any batch carrying more than the sweep — a delivered event, a person’s trigger, a check callback or a discovery row — and a push the webhook missed is caught at the six-hour bound: the check always fails open toward running.

## Run from your machine

`--remote` hands a `lookup`, `run --dry-run`, `run` or `tui` to the server instead of running it locally:

```sh
export PATCHULA_SERVER=https://patchula.acme.dev
patchula run --dry-run --remote acme/my-app
```

The run uses the server’s App credentials, warm caches and lockfile tools, so the machine needs no GitHub token and no mise. The server is `PATCHULA_SERVER`, or, in a checkout with no repository named, the one [found for the checkout](#found-from-a-checkout); with neither, `--remote` fails. The URL must use HTTPS, except for a server on `localhost` or a loopback address.

With no repository named, `--remote` runs the checkout’s GitHub repository, so the server reads what is pushed, not the working tree. A real `run` there has the same [clean-checkout rule](https://count-patchula.sweepy.dev/guide/how-it-works/#working-tree-or-github) as one on this machine.

On first use the CLI asks you to sign in: it prints a code to enter at `github.com/login/device`, and you authorise the server’s App. The token is stored in `~/.config/patchula/servers.json` (or under `XDG_CONFIG_HOME`) and refreshed as it expires. `patchula auth login` and `patchula auth logout` sign in and out explicitly, with `--server <URL>` or `PATCHULA_SERVER`; GitHub’s Settings → Applications revokes the App’s access. The server refuses any other token, including personal access tokens and other Apps’ tokens.

Each repository in the request must:

- have the App installed, in the same installation as the others, and be allowed by the server’s settings;
- let you push. Read access is not enough, because on a public repository everyone has it.

A server runs one request per user at a time, and a real run uses its installation’s engine, so it never races that installation’s webhook batch. The repository’s own `patchula.pkl` applies; `--config`, `--config-dir`, `--default-config`, `--all-repos`, `--allow-lockfile-pending`, `--recheck`, `--cache`, `--concurrency` and `--settings` only work locally — `--remote` refuses them — and the server’s own settings file decides the rest. A run in progress at shutdown finishes within the shutdown deadline.

### Found from a checkout

The server hides its URL in an HTML comment in each PR and dashboard it writes. `patchula lookup`, `run` or `tui` in a checkout, with no repository named and neither `--remote` nor `--here`, looks for that comment in the 500 most recently updated open issues and PRs. The comment counts only if a GitHub App wrote it, the server names that App’s bot at `/api/v1/auth`, and GitHub’s own description of that App (`GET /apps/{slug}`) has the client ID the server hands out for sign-in. A comment pasted by a person is ignored, and a server advertised in another App’s comment can only ever sign you in to that other App, never to the Count’s; when GitHub cannot be asked, nothing is found. The client ID is remembered with your answer, and a server that later names a different App is refused before sign-in. If it finds a server, it asks once whether to run there, and remembers your answer for that repository in `~/.config/patchula/repositories.json` until you sign out of that server with `patchula auth logout`:

- yes: plain commands in that checkout run on the server;
- no: they read the working tree;
- `--here` runs one command locally anyway, and `--remote` uses the remembered server even after a no;
- without a terminal nothing is looked up or asked;
- local-only flags always run locally.

The advertised URL is `publicUrl`, or the App’s webhook URL with `/webhook` removed. A webhook relay such as smee.io gives no server URL, so set `publicUrl` there. Set `advertise = false` to keep the URL out of what the Count writes. Turning it on or off edits the open PRs once. A server whose App has no client ID advertises nothing, because the CLI could not sign in.

## Repository API

A read-only JSON API shows what the Count last saw of each public repository he runs, for a dashboard to display. It needs no sign-in and answers any origin (`Access-Control-Allow-Origin: *`), so a page on another site can call it from the browser. Set `publicApi = false` to turn it off.

`GET /api/v1/repositories` lists the repositories in name order:

```json
{
  "repositories": [
    {
      "repository": "acme/my-app",
      "ranAt": "2026-10-23T09:00:00+00:00",
      "queued": null,
      "status": "complete",
      "reason": null,
      "defaultBranch": "main",
      "dependencies": 42,
      "updates": 3,
      "pullRequests": 2,
      "dashboard": 7
    }
  ]
}
```

`updates` counts dependencies with at least one update, `pullRequests` counts the Count’s open PRs, and `dashboard` is the dependency dashboard’s issue number. `status` is the last run’s repository status — `complete`, `skipped`, `stale` or `error`, as in the [report](https://count-patchula.sweepy.dev/reference/report/) — and `reason` says why a non-complete one ended that way. A repository that has not run yet has only `repository`, `ranAt: null` and `queued`. `queued` is `null`, or `{"at", "running"}` when work for the repository is waiting or in a batch.

`GET /api/v1/repositories/{owner}/{repo}` returns everything from the last run:

| Field | Meaning |
| - | - |
| `repository`, `ranAt`, `queued`, `status`, `reason`, `defaultBranch`, `dashboard` | as in the list |
| `commit` | the default branch commit the run read |
| `warnings` | the run’s warnings |
| `lookupFailures` | dependencies whose lookup failed, as in the [report](https://count-patchula.sweepy.dev/reference/report/#lookup-failures) |
| `packageFiles` | each package file’s dependencies and their updates, as in the [report](https://count-patchula.sweepy.dev/reference/report/) |
| `branches` | each update branch the run planned: `branch`, `status`, `reason`, `message`, `baseCommit`, `commit`, `lockfilePending`, and the `files` it changes, without diffs |
| `pullRequests` | the Count’s open PRs, read from GitHub after the run; `null` if GitHub would not list them |
| `merged` | up to 20 PRs the Count merged himself: `number`, `title`, `url`, and `mergedAt` when GitHub recorded it |

Each open PR has `number`, `url`, `branch`, `title`, `body`, `draft`, `labels`, `headSha`, `base`, `createdAt`, `updatedAt`, `mergeable`, `mergeableState`, `autoMerge`, and `action`: what the run did to it (`{"status", "reason"}`), or `null` if the run left it alone. GitHub works out `mergeable` and `mergeableState` in the background, so either can be `null`.

A dashboard that merges sends GitHub’s `PUT /repos/{owner}/{repo}/pulls/{number}/merge` with its own token, passing `headSha` as `sha` so that GitHub refuses if the PR changed since the run.

A public repository shows everything, including what lookups with [private registry](https://count-patchula.sweepy.dev/guide/sources/#private-registries) credentials found, as its dependency dashboard does. A repository that is private when it runs is stored without that: such a dependency keeps what the repository declares, but loses its `updates`, and its metadata’s held-back releases, lookup evidence, tag digests and image checks, and does not count in `updates`. So if the repository later becomes public, the API does not show what its private-registry lookups found until it runs again as a public repository.

Discovery and installation events decide which repositories are listed:

- a sweep replaces each installation’s list;
- repositories added to or removed from an installation, and renamed ones, come and go straight away;
- an uninstalled installation’s repositories go within a minute;
- a run of a repository the server has not listed yet adds it once GitHub confirms it is in the installation;
- settings that no longer allow a repository hide it at once;
- every webhook about a repository updates its visibility, and a run can hide it but never show it, since a webhook may have changed it during the run.

A private repository is never shown, and neither is one whose visibility the server could not read.

The server records a repository after each run that writes: queued batches and `--remote` runs, but not lookups or dry runs. A run never replaces one that started later. An unknown or hidden repository is a 404 with `errorKind` `unknown-repository`, and with the API off every request is a 404 with `errorKind` `disabled`.

## Container image

Each release publishes an image for linux/amd64 and linux/arm64 to the GitHub Container Registry:

```text
ghcr.io/sweepies/count-patchula:X.Y.Z
```

The tags are each release’s version without the `v`, and `latest`, which a prerelease does not move. There are no minor, major or edge tags, so pin the version and upgrade on purpose.

The image is built with [apko](https://github.com/chainguard-dev/apko) from [Wolfi](https://wolfi.dev) packages. It holds `patchula`, `git`, `curl` and [packslip](https://packslip.dev), on Wolfi’s glibc, and starts `patchula serve` as user and group 10001. Lockfile tools are not in the image: mise installs each one into the volume the first time a repository needs it (see [what the runner needs](https://count-patchula.sweepy.dev/installation/#what-the-runner-needs)). The image has no ICU, so it sets `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`, which the runner passes on to dotnet. The image sets no `HEALTHCHECK` or `EXPOSE`; configure the [health check](#health-check) and publish 8080 yourself.

Each build takes Wolfi’s current packages, so a release picks up Wolfi’s fixes, and rebuilding an old commit later gives a different image. The image a tag publishes is exactly the one the release smoke-tested, and its [provenance attestation](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations) records the commit and workflow run that built it. The release workflow attests that provenance, and each platform’s SPDX SBOM from apko, in GitHub and in the registry. Check the provenance with:

```sh
gh attestation verify oci://ghcr.io/sweepies/count-patchula:X.Y.Z --repo sweepies/count-patchula
```

A platform’s SBOM is attested to that platform’s image, so name it by digest and add `--predicate-type https://spdx.dev/Document/v2.3`.

`/var/lib/patchula` is a volume. It holds the server cache and queue, the partial clones, mise and the tool store, so a new container picks up where the last one stopped. A new named volume takes the directory’s owner; a bind mount must be writable by user 10001.

| Variable | Image default |
| - | - |
| `PATCHULA_LISTEN` | `0.0.0.0:8080` |
| `PATCHULA_SETTINGS` | `/etc/patchula/settings.pkl`, which only amends `PatchulaSettings.pkl` |
| `PATCHULA_SERVER_CACHE` | `/var/lib/patchula` |
| `PATCHULA_TOOLS_DIR` | `/var/lib/patchula/tools` |
| `RUSTUP_HOME` | `/var/lib/patchula/rustup` |
| `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT` | `1` |

The credentials have no default. Mount your [settings](#settings) file over `/etc/patchula/settings.pkl`, or point `PATCHULA_SETTINGS` at another path.

```sh
docker run --detach --name patchula \
  --publish 127.0.0.1:8080:8080 \
  --stop-timeout 75 \
  --health-cmd 'curl --fail --silent --output /dev/null http://127.0.0.1:8080/healthz' \
  --health-start-period 30s \
  --volume patchula:/var/lib/patchula \
  --volume /etc/patchula/settings.pkl:/etc/patchula/settings.pkl:ro \
  --volume /etc/patchula/app.pem:/run/secrets/app.pem:ro \
  --volume /etc/patchula/webhook-secret:/run/secrets/webhook-secret:ro \
  --env PATCHULA_APP_ID=12345 \
  --env PATCHULA_APP_PRIVATE_KEY_FILE=/run/secrets/app.pem \
  --env PATCHULA_WEBHOOK_SECRET_FILE=/run/secrets/webhook-secret \
  ghcr.io/sweepies/count-patchula:X.Y.Z
```

The mounted secret files must be readable by user 10001. To pass the values instead, use `--env PATCHULA_APP_PRIVATE_KEY` and `--env PATCHULA_WEBHOOK_SECRET` with no value, which read them from your shell. `--stop-timeout 75` keeps the stop signal’s grace period longer than the 60-second drain, because Docker’s default of 10 seconds would kill a running batch.

The lockfile runner works in the container’s temporary directory, so a read-only root filesystem needs a writable `/tmp`.

### Health check

`GET /healthz` answers 200 while the server runs. The image has `curl` for runtimes that run a command, such as Docker (above) and Compose:

```yaml
services:
  patchula:
    image: ghcr.io/sweepies/count-patchula:X.Y.Z
    ports:
      - "127.0.0.1:8080:8080"
    healthcheck:
      test: ["CMD", "curl", "--fail", "--silent", "--output", "/dev/null", "http://127.0.0.1:8080/healthz"]
      interval: 30s
      timeout: 5s
      start_period: 30s
      retries: 3
```

Kubernetes probes the port itself:

```yaml
ports:
  - containerPort: 8080
livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
  periodSeconds: 30
  timeoutSeconds: 5
  failureThreshold: 3
startupProbe:
  httpGet:
    path: /healthz
    port: 8080
  failureThreshold: 30
  periodSeconds: 2
```

### mise on first start

When there is no `mise` on `PATH`, as in the image, `patchula serve` makes sure the tool store has the mise version the Count pins before it signs in to GitHub. If it is missing, it runs packslip:

```sh
packslip install github.com/jdx/mise --version <pinned> --pin ps1_nlhmwtfeufglxv5myvwvronk7a
```

packslip checks the release’s signature against mise’s GitHub repository and that signer fingerprint, then unpacks it into `$PATCHULA_TOOLS_DIR/patchula-mise/<version>/`, as user 10001. That takes about 15 seconds, once per volume; later starts find it there and log the same `lockfile tools run with this mise` line. When an upgrade pins a newer mise, the next start installs it and removes the old one.

If the install fails, for example without network access, the server logs `cannot install mise` with packslip’s reason and keeps running: webhooks, lookups and branches without lockfiles work, and mise tools and lockfiles fail until a start succeeds. packslip asks GitHub’s API for the release; set `GITHUB_TOKEN` (any token, no scopes needed) if the host shares an address that runs out of GitHub’s anonymous API limit.

### Offline hosts

A host that cannot reach GitHub needs a volume that already holds mise. Fill one on a connected machine, with the same image version, and copy it over:

```sh
docker run --rm --volume patchula:/var/lib/patchula \
  --entrypoint patchula ghcr.io/sweepies/count-patchula:X.Y.Z tools install
```

`patchula tools install` installs mise the same way, then prewarms every pinned lockfile tool into the store, so the offline host needs no downloads for the default tool versions either.

## Hosting on Railway

[Railway](https://railway.com) bills by the minute for the CPU and memory a service uses, which suits a server that idles between batches.

1. Create a service from the Docker image `ghcr.io/sweepies/count-patchula:X.Y.Z` (see [the container image](#container-image)). It starts `patchula serve` and already listens on `0.0.0.0:8080`.
2. Give the service a public domain on port 8080. Railway terminates HTTPS, so the App’s webhook URL is `https://<domain>/webhook`.
3. Attach a volume mounted at `/var/lib/patchula`, so the cache, queue and tool store survive deploys. Railway mounts volumes owned by root, which user 10001 cannot write, so set `RAILWAY_RUN_UID=0` in the service’s variables, as [Railway’s volume reference](https://docs.railway.com/volumes/reference) describes.
4. Put `PATCHULA_APP_ID`, `PATCHULA_APP_PRIVATE_KEY` and `PATCHULA_WEBHOOK_SECRET` in the service’s variables.

> **Leave Serverless off**
>
> Leave Railway’s Serverless setting (formerly App Sleeping) off, under the service’s Settings, Deploy. The server checks its App with GitHub every 30 seconds, so it would never sleep, and one that did would miss its sweeps.

## systemd

Install mise or packslip for the service user, on the `PATH` in `/etc/patchula/environment`; the server needs it like any [runner](https://count-patchula.sweepy.dev/installation/#what-the-runner-needs).

```ini
[Unit]
Description=Count Patchula GitHub webhook server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=patchula
Group=patchula
StateDirectory=patchula
WorkingDirectory=/var/lib/patchula
EnvironmentFile=/etc/patchula/environment
LoadCredential=app.pem:/etc/patchula/app.pem
LoadCredential=webhook-secret:/etc/patchula/webhook-secret
ExecStart=/usr/local/bin/patchula serve --settings /etc/patchula/settings.pkl --cache /var/lib/patchula --private-key-file %d/app.pem --webhook-secret-file %d/webhook-secret --shutdown-timeout-secs 60
Restart=on-failure
RestartSec=10
TimeoutStopSec=75
KillSignal=SIGTERM
UMask=0077
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
```

`/etc/patchula/environment` needs `PATCHULA_APP_ID` and that `PATH`. Keep the stop timeout longer than the drain deadline.
