# AUR Build Server — Design Sketch (v0)
Status: **for discussion**. Nothing implemented. Open questions are collected in §18.
---
## 1. Problem statement
A service that lets users subscribe to AUR packages, watches them for changes, requires a
**human approval** for every change, and only then builds the package in a clean chroot and
publishes it into a signed pacman repo that end consumers use.
Two independent change sources must be caught:
1. **Recipe change** — the AUR maintainer edited `PKGBUILD` / `.SRCINFO` / shipped patches.
2. **Upstream change** — the recipe is untouched, but the *computed* `pkgver` moved
(the `-git`/`-svn`/VCS case: `pkgver()` clones upstream and derives a version).
Plus a third, related concern:
3. **Dependency drift** — when a dependency we publish moves, the packages built against the
older version must be *visible* as stale. v1 records and surfaces this; it does not
rebuild automatically (§10).
### The two hard rules the user called out
* **Nothing is accepted before it is approved.** The index is only ever a function of
approved releases. Unapproved versions are invisible to consumers.
* **Diffs are always against the last *accepted* version, never the last *seen* version.**
If v1 is accepted and v2, v3, v4 arrive while nobody is looking, the human must be shown
`v1 → v4`, not `v3 → v4`.
---
## 2. Invariants (the contract we test against)
These are the properties the design must guarantee. Everything else is an implementation
detail that can change.
| # | Invariant |
|---|---|
| I1 | Every artifact in a served repo index traces to an `approval` row. No approval ⇒ no index entry. |
| I2 | A review's `base` is the pkgbase's `current_accepted_release`, not the previously detected candidate. |
| I3 | A candidate identity is content-addressed over *everything that becomes a byte in the artifact*: AUR commit, resolved version, upstream VCS pins, and resolved source digests. Two byte-identical inputs never produce two candidates. |
| I4 | Publishing is the only externally visible step, and it is atomic + serialized per repo. A crash mid-publish leaves the old index intact. |
| I5 | Every build step is idempotent and checkpointed; a worker can die at any instant and the pipeline resumes at the next incomplete step with no duplicate side effects. |
| I6 | A manual rebuild reuses the *approved source identity*; it never needs a new approval and never changes the source version. |
| I12 | Every release records the exact set of our own packages it was built against, so "is this stale?" is always answerable from stored facts rather than re-derived guesswork. |
| I7 | A pkgbase has at most one open review at a time. A newer detection **collapses into** the open review (same base) rather than queueing beside it. |
| I8 | The set of packages in the index is exactly the set of `current_accepted_release` pointers for all active subscriptions (modulo explicit removals). No drift, no orphans. |
| I9 | Build hosts are treated as untrusted: a malicious `PKGBUILD` must not reach the control-plane DB, the signing key, or another build. |
| I10 | Every state transition is recorded in an append-only audit log with actor (human / policy / system) and timestamp. |
| I11 | A change that is **not publishable** (version string unchanged) never silently disappears: it lands in `notice` and is surfaced in the UI. |
---
## 3. Core concepts
```
Subscription a user wants pkgbase X tracked in repo R
Pkgbase the unit of AUR recipes (one PKGBUILD, may emit N packages)
Snapshot an immutable pin of the AUR git repo for a pkgbase (commit SHA + tree hash)
Candidate a detected, reviewable change: (pkgbase, snapshot, resolved version)
Review the human-facing diff + decision for a Candidate
Approval the immutable decision record: "candidate C, transition base→candidate, by U, at T"
Release an approved candidate that has been built & published (the accepted state)
Build an attempt to turn a Release-intent into artifacts; has BuildAttempts
WorldSnapshot the fingerprint of the accepted dep set a build ran against
Repo a signed pacman repo; holds Release pointers (one per pkgbase)
```
Key modelling decision: **`pkgbase` is the unit of subscription, detection, diffing and
approval; `package` is the unit of the index and dependency resolution.** A split
`PKGBUILD` producing `foo` and `foo-lua` is one approval and two index entries.
### Version identity
A candidate's identity is a tuple, not a string:
```
aur_commit, epoch, pkgver, pkgrel, upstream_pins[], source_digests[]
```
Every element is part of the key. That is deliberate, and the last one has a consequence
worth stating out loud: **if a source tarball's bytes change while `pkgver` stays the same,
that is a new candidate requiring a new approval.** Silent artifact swap is the classic AUR
compromise, and folding the digest into the identity is what turns it from an invisible
event into a reviewable one.
* `recipe_hash` = hash over the *entire* AUR snapshot tree: `PKGBUILD`, `.SRCINFO`,
`*.install`, and any shipped patches/assets. Patches shipped in the AUR repo are part of
the recipe and are a classic silent-change vector. Implied by `aur_commit`.
### Three things to pin, not one
For a `-git` package there are **two distinct repositories**, and conflating them is the
single easiest way to build something nobody reviewed:
```
PKGBUILD lives in: https://aur.archlinux.org/yay-git.git <- the RECIPE
source=(git+https://github.com/dweiss/yay.git) <- the CODE
```
| Pin | What it pins | How obtained | Answers |
|---|---|---|---|
| `aur_commit` | the recipe text | our local AUR git mirror | "which PKGBUILD did the human read?" |
| `upstream_pins[]` | the code that gets compiled | `git ls-remote` / forge API per VCS `source=()` entry | "which source revision did the human read?" |
| `source_digests[]` | the actual bytes consumed | hash each resolved source (§5.3) | "is what we built what we reviewed?" |
`upstream_pins[]` is a **set of HEADs, one per VCS source** — a pkgbase can have several
(`git+…app.git` plus `git+…vendor.git`), and each moves independently. Each entry is:
```json
{"index": 0, "url": "git+https://github.com/dweiss/yay.git",
"ref": "HEAD", "branch": "main", "commit": "9f2c1ab…"}
```
The commit SHA alone is sufficient. A git commit transitively commits to its tree, and a
gitlink entry in that tree transitively commits to any submodule's commit — so one SHA per
VCS source already pins the whole source tree, submodules included. No separate tree hash
needed.
The one real caveat: **the pin is only honoured if the build actually checks out that
commit.** A `pkgver()` or `prepare()` that clones with `--remote`, or a plain branch source
with no `#commit=` fragment, will follow the tip instead of the recorded gitlink. So for now
`upstream_pins` gives us identity, diffing, and traceability; making the build honour it is
a deferred extension (§20). The interim guard is that `-git` `pkgver()` strings almost
always encode the commit (`r1234.9f2c1ab`), so we **assert post-build that the produced
`pkgver` equals the approved `pkgver`** and fail closed on mismatch.
Displayed version is the usual `epoch:pkgver-pkgrel`; internal identity is the tuple. A
`pkgrel` reset (`pkgrel=7 → 1`) is a *major* signal and must be surfaced loudly.
---
## 4. Architecture
**One process, many threads, no async.** The whole application — HTTP server, watchers,
scheduler, build workers, publisher — is a single native binary. Concurrency is
`std::thread` + `crossbeam` channels. Blocking is not a compromise here, it is the right
shape: build workers spend their lives blocked on a `makechrootpkg` child process.
```
┌────────────────────────────────────────────┐
│ aur-build (one binary) │
│ │
browser ──HTTP──► │ http threads (thread-per-connection) │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ writer │ single SQLite writer │
│ │ actor │ (channel in, tx out) │
│ └──────┬───────┘ │
│ │ WAL │
│ ┌──────┴────────────────────────┐ │
│ │ SQLite (WAL) │ │
│ └──────┬───────────┬────────────┘ │
│ │ ▲ │
│ watcher threads │ build workers │
│ aur-mirror │ (N threads, each │
│ vcs-probe │ shells out to │
│ dep-watcher │ makechrootpkg) │
│ dispatcher │ │
│ publisher (1 thr) │ │
└──────────────────────┼────────────────────┘
▼
artifact store + repo dir ──► nginx/caddy
local AUR git mirrors
```
Process separation still matters for the security boundary, but it is achieved with **OS
users and sudo rules**, not separate services: the build steps that execute untrusted
`PKGBUILD`s run as a distinct, unprivileged user with no access to the signing key or the
DB file's directory. See §14.
### Stack
| Concern | Choice | Why |
|---|---|---|
| Language | Rust, edition 2021, **no `async`/`await`, no tokio** | user requirement; also removes the whole class of "blocking call starves the runtime" bugs |
| HTTP | `tiny_http` (thread-per-connection, blocking) | no runtime dependency; SSE is just a thread that blocks and writes |
| Templating | `askama` (compile-time checked) or `minijinja` | SSR, no build step |
| Interactivity | htmx (one vendored `.js`, no build step) + a few SSE endpoints | "minimal functional javascript"; falls back to `` if we prefer zero JS |
| DB | `rusqlite` (bundled libsqlite), **WAL mode** | user requirement; see §11a for the concurrency model |
| Migrations | `refinery` or a hand-rolled `user_version` stepper | |
| Outbound HTTP | `ureq` (blocking) | `reqwest` pulls in tokio even in blocking mode — avoid |
| Git | shell out to `git` | we need `git` on the host anyway; avoids libgit2 build pain |
| Subprocesses | `std::process::Command` + `wait` with a watchdog thread | |
| Scheduling | one tick thread + `sweep` over `next_check_at` columns | no cron dependency needed |
| Diffing | `similar` | unified diffs in Rust |
| Version/dep logic | hand-written `vercmp` + dep-string parser (~100 lines, well specified) | avoids binding libalpm |
| External tools | `mkarchroot`, `makechrootpkg`, `repo-add`, `gpg`, `pacman`, `git` | |
Deliberately **not** used: tokio, axum, actix, reqwest, sqlx (async), libgit2, any JS
bundler/framework.
---
## 5. Detection (watchers)
### 5.1 AUR recipe watcher
**Clone, don't scrape.** For each subscribed pkgbase keep a git mirror:
```
mirrors// ← git clone https://aur.archlinux.org/.git
```
Plain clone, **no `--filter=blob:none`**. A partial clone can lazily drop blobs, and we need
to be able to materialize any historical commit forever (see §5.1a). These repos contain a
PKGBUILD and maybe a few patches — they are kilobytes.
Poll cheaply with `git ls-remote` (one request per pkgbase), `git fetch` only when the SHA
moved. This gives us:
* exact change detection (SHA moved ⇒ recipe changed, no false positives from metadata),
* free, authoritative diffs (`git log -p base..head`) including patch files,
* the maintainer's own commit messages, which are excellent review context,
* **the commit SHA itself, which becomes the build pin** (§5.1a),
* detection of orphaning/deletion (repo 404s or goes read-only).
Cross-check with the AUR RPC (`type=info&id[]=…`) for `LastModified`, `Maintainer`,
`Version`, and to notice `pkgbase` renames. RPC `Version` catches the case where the
maintainer bumped a *static* `pkgver` — cheap, no clone needed, so it can gate the clone.
Also handle: package deleted from AUR, package transferred to a new maintainer,
`pkgbase` renamed (old name becomes a redirect), and a pkgbase we track being folded into
another pkgbase's split build.
### 5.1a The AUR commit pin (`aur_commit`) — first-class metadata
Every candidate records the exact AUR commit its recipe came from, and that SHA is used
throughout the lifecycle:
```
detect: git fetch → HEAD = 4f9c02e… → candidate.aur_commit = 4f9c02e…
diff: git diff ..
review: UI shows the SHA, links to AUR cgit, shows recipe_hash of that tree
build: NEVER re-fetch from the network. Materialize from the local mirror at the pin:
git --git-dir=mirrors/ worktree add --detach
(or: git archive | tar -x -C )
verify: recompute recipe_hash over ; assert == candidate.recipe_hash → fail closed
audit: release stores aur_commit + recipe_hash, so any installed package can be traced
back to the exact bytes a human approved, forever
```
Consequences worth being deliberate about:
* **The mirror is now load-bearing, not a cache.** Losing it means losing the ability to
rebuild or even reproduce any historical release. It goes in backups (§15), and mirror GC
must never prune a commit reachable from an accepted release. Since AUR branches are
append-only, "never prune" is the safe default; these repos stay small.
* **The pin is shown in the UI** next to the diff, with a link to
`https://aur.archlinux.org/cgit/aur.git/commit/?h=&id=`, so the reviewer can
independently verify what the server showed them against AUR itself.
* **It pins the recipe, not the code.** For a `-git` package the compiled source is pinned
separately, by `upstream_pins` (§3). Both pins are required for "we built what you saw";
neither alone is enough.
* **Non-reproducible by design.** `aur_commit` gives *traceability*, not bit-reproducible
builds. Reproducibility would additionally need upstream pins + a pinned build world.
Worth stating plainly so nobody mistakes one for the other.
### 5.2 VCS / computed-pkgver watcher (the expensive one)
RPC `Version` is the literal `pkgver=` field. For `-git` packages that field is frozen and
the real version comes from `pkgver()` at build time. Two-stage funnel:
**Stage A — cheap upstream probe (no build).** Parse `source=()` for VCS entries
(`git+`, `svn+`, `hg+`, `bzr+`). For `git+https://…/repo.git` ask the host for the current
ref tip: GitHub/GitLab/GitHub-Enterprise APIs, `git ls-remote` as the universal fallback,
per-ref pinning respected (`…#tag=v2.1` / `#commit=abc`). Do this for **every** VCS source
in the pkgbase, not just the first. If the resulting set of HEADs is identical to the set
recorded on the accepted release, **stop** — nothing can have changed. This makes the common
case (zero upstream movement) nearly free.
**Stage B — authoritative pkgver resolution + pin capture.** Only when Stage A saw movement,
run the real thing in a throwaway chroot:
```
makepkg --vercheck # or: makepkg -g / --printsrcinfo, then eval pkgver()
```
i.e. clone with the PKGBUILD's own depth/submodule/ref rules, run `pkgver()`, read back
the computed `pkgver-pkgrel`. This is the only correct answer, because `pkgver()` can do
arbitrary things (`git describe`, date-stamping, counting commits since a tag).
Stage B also **captures the pins**, since the clone is already there: for each VCS source,
the resolved commit and the branch/ref it came from. Cheap to do here; doing it later would
mean another clone.
**Crucial: a candidate exists only if something *publishable* changed.** If upstream moved
but the resolved `epoch:pkgver-pkgrel` is unchanged, there is nothing to publish — consumers
cannot observe a same-version package, `pacman` would not offer an upgrade, and inventing a
`pkgrel` bump is not our call to make. So:
| Situation | Action |
|---|---|
| pins moved, `pkgver` changed | normal candidate, requires approval |
| pins moved, `pkgver` unchanged | **no candidate.** Record an informational `pin_drift` event, show it on the package page ("upstream moved 14 commits; pkgver unchanged, nothing publishable"), and surface it as a hint that `pkgver()` may be degenerate (date-based, or watching a non-default branch) |
| `aur_commit` moved, version unchanged | **no candidate**, same reason — but flag it: the maintainer probably forgot to bump `pkgrel`, and the user should know the recipe drifted under a static version |
This does not weaken the approval rule. Nothing was built and nothing was published, so no
unapproved artifact can reach a consumer (I1). The index keeps serving the artifact built
from the old pins, and the accepted release keeps recording the pins it was actually built
from — which remain true.
Cost control: Stage B is gated by Stage A, so it only runs for pkgbases whose upstream tip
actually moved — with a once-a-day poll (§19) that is a small, self-limiting set per day. The
one thing worth being deliberate about is **clone reuse**: keep a persistent cache of upstream
VCS clones (same idea as the AUR mirrors) and `git fetch` into it rather than re-cloning per
run, because some upstream repos are multi-gigabyte and re-cloning one daily would be silly.
Also: per-pkgbase cooldown, a global concurrency cap on Stage B, and a cache keyed on
`(pkgbase, recipe_hash, upstream_tip)`.
### 5.3 Source digests, and the `SKIP` problem
`sha256sums=('SKIP')` is the hole in the whole integrity story. It is idiomatic and
unavoidable for VCS sources — the content changes constantly, that is the point — but it
also shows up on static tarballs, downloaded `.desktop` files, prebuilt binaries, and
"just grab whatever is on the CDN" packages. In every one of those cases the PKGBUILD
promises nothing about what will actually be downloaded.
**We resolve and record the digest of every source ourselves, at detection time**, and store
it on the candidate regardless of what the PKGBUILD declares.
| Source kind | What we record | Cost |
|---|---|---|
| Static file with a declared checksum | the declared checksum (makepkg will verify it at build anyway) | free — no download |
| Static file with `SKIP` | **download and stream-hash `sha256`** | paid once, cached and reused by the build |
| VCS (`git+`/`svn+`/`hg+`) | the resolved commit SHA (same value as `upstream_pins`), captured during Stage B where we clone anyway | near free |
| Local file shipped in the AUR repo | hash of the file at `aur_commit` | free |
Design points:
* **Only `SKIP` sources cost bandwidth.** Declared-checksum sources are trusted-as-declared
for identity purposes, because makepkg enforces them at build. This keeps the expensive
path narrow and targeted at exactly the unverified cases.
* **Stream-hash, don't buffer.** Hash while downloading into the source cache; the build
reuses the cached file, so the bytes are paid for once, not twice.
* **Digest drift is a headline event, but not a candidate.** If a source digest changes while
`pkgver`, `pkgrel` and `aur_commit` are all unchanged, there is nothing publishable (same
version string ⇒ `pacman` sees no upgrade), so per §5.2 this does not create a review.
It creates something stronger: a **high-severity `integrity_alert`** on the package page
and the dashboard — *"the artifact in your index was built from bytes upstream no longer
serves; the version string is unchanged"* — which is the signature of a swapped artifact or
a compromised CDN. An approval prompt would be useless here (approving it would not let us
publish anything); an unmissable alert is the right response. If the version *also*
changed, the digests are part of the candidate identity (§3) and it becomes a normal,
high-risk review. This is arguably the single most valuable detection in the system.
* **Digests are part of the candidate identity** (§3), so drift accompanying a version change
cannot be silently absorbed.
* **`SKIP` on a non-VCS source is itself a risk signal**, independent of whether anything
drifted — it means the recipe permanently refuses to verify its input.
### 5.3a Not in scope: turning `SKIP` into a real checksum
Since we know the digest at review time, we *could* rewrite `sha256sums=('SKIP')` to the
actual digest before building, so makepkg verifies the bytes we reviewed and the build fails
if the CDN serves something else in the meantime. Same class of thing as pinning VCS sources
to `#commit=`.
**Both are deferred** — see §20 Future extensions. For now we record digests and pins for
identity, diffing and forensics; we do not mutate the recipe. Recording is enough to make
drift visible, which is the main win, and it costs us no correctness guarantees we would
otherwise be silently skipping.
### 5.4 Dependency bookkeeping
No watcher. Dependency facts are captured at build time from `.PKGINFO`/`.BUILDINFO` and
consumed by staleness tracking (§10), which is a read-time query rather than a trigger.
---
## 6. Diff & risk analysis
A review is not one diff, it's a panel. Every panel compares **what the accepted release
recorded** against **what the candidate records now** — i.e. `accepted.aur_commit →
candidate.aur_commit`, `accepted.upstream_pins → candidate.upstream_pins`,
`accepted.source_digests → candidate.source_digests`. Never "last seen".
| Panel | Content |
|---|---|
| Recipe diff | unified diff of `PKGBUILD`, `.SRCINFO`, `*.install`, and every shipped patch file, from `git diff ..` |
| Version delta | `epoch:pkgver-pkgrel` old → new; flags `pkgrel` reset, `epoch` bump, downgrade |
| **Source digest delta** | per-source old → new digest, plus any newly-declared `SKIP` or `sha256sums` entry changed *to* `SKIP`. Note: drift with **no** version change is an `integrity_alert` on the package page, not a review (§5.3) |
| Upstream delta | for each VCS source: `git log --oneline old_commit..new_commit`, commit count, changed-file stat, links to the upstream compare URL, submodule pointer moves |
| Source delta | added/removed `source=()` entries, host changes (e.g. `github.com` → unknown mirror), new/removed `sha256sums`, `pgp`/`validpgpkeys` changes |
| Dependency delta | `depends`, `makedepends`, `checkdepends`, `optdepends`, `provides`, `conflicts` — resolved against our index so we can say "will pull in new package X" |
| Build-env delta | `options=()`, `arch=()`, `makepkg`/devtools flags, `pkgbase` renames, split-package set membership changes |
| Install-script delta | `.install` `pre_install`/`post_install`/`pre_upgrade` hooks — arbitrary code that runs on consumer machines |
### Risk scoring
The reviewer's attention is the scarcest resource, so every candidate gets a computed risk
level that drives ordering and colour in the inbox.
Elevating signals (non-exhaustive):
**source digest changed with no version change** (highest - but see §5.3: this is an
`integrity_alert`, not a review) · `SKIP` declared on a non-VCS
source · `sha256sums` entry changed *to* `SKIP` · new `source` host ·
`--skippgpcheck` / removed `validpgpkeys` · new
`makedepends` (especially compilers, `cargo`, `npm`) · new `.install` script or changed
hooks · `pkgrel` reset · `epoch` bump · `options=(!debug)`/`(!buildflags)`/`(!strip)` ·
`!security` flags · `checkdepends` removal (tests silently skipped) · recipe diff touching
`build()`/`package()` bodies vs. only comments/metadata · upstream commit range containing
build-system changes (`Cargo.toml`, `package.json`, `setup.py`, `Makefile`) · first
candidate from a newly-orphaned pkgbase (new maintainer = new trust).
Digest drift is an **alert, not an approval** (see above).
Risk level is **advisory only** in v1 — it orders and colours the inbox. There is no
auto-approval, so nothing is gated on it (§7.3).
---
## 7. Approval semantics
### 7.1 Candidate / review state machine
One review object per pkgbase at a time. New detections **collapse into** the open review
rather than creating new rows:
```
detected ──► diffing ──► pending_review ──┬──► approved ──► (build) ──► release
▲ │ ├──► rejected (terminal for this identity)
│ └────────┴──► withdrawn (terminal, pkgbase unsubscribed)
│
newer detection while pending_review and unviewed
└─► UPDATE IN PLACE: new aur_commit/pkgver/diff, revision += 1
base is unchanged, no new row, no superseded state
newer detection while pending_review and already viewed/acted-on
└─► freeze old row as `superseded` (audit trail), open a new review
```
* `base` is fixed at creation to the pkgbase's `current_accepted_release` and **never
changes**, no matter how many times the candidate collapses in place. That is what
guarantees the diff is always against the last accepted version. (I2)
* `superseded` therefore only exists for the case where a human actually saw the old diff —
otherwise it is pure noise and we don't create it. The `revision` counter plus the audit
log still records that detections happened in between.
* `rejected` is remembered per identity hash so the watcher doesn't nag about the same
version forever. A rejection can be manually re-opened. Rejection does not block newer
candidates.
### 7.1a Stale approvals are rejected outright
If a human approves a candidate whose identity no longer matches what was rendered, the
approval is **refused**. No silent retargeting, no "approve latest" magic.
The approve POST carries an optimistic-concurrency token:
```
POST /reviews/:id/approve { candidate_id, identity_hash, diff_digest }
server, in one write transaction:
1. candidate must still be state = pending_review
2. candidate.identity_hash must equal the submitted identity_hash
3. candidate.diff_digest must equal the submitted diff_digest
4. candidate.base_release_id must equal pkgbase.current_accepted_release_id
any mismatch → HTTP 409 with a re-render of the *current* diff and the message
"v3 was detected while you were looking; this is v3, not v2"
```
Rule of the system: **we build exactly what was displayed, or nothing.** The `diff_digest`
check is what makes that provable rather than aspirational — it closes the window where the
watcher updated the row between page render and click.
The UI still offers an explicit "show me the newest" path, but that is a fresh action on a
fresh diff, never a side effect of approving an old one.
### 7.1b First acceptance is a different kind of review
A brand-new subscription has no `current_accepted_release`, so there is nothing to diff
against and invariant I2 has no referent. These get a distinct review kind,
`first_introduction`:
* No diff pane. Instead: the full `PKGBUILD` and `.SRCINFO` rendered readably, the complete
source list with resolved digests, the resolved dependency set, and the `aur_commit`.
* The identity of the maintainer and how long the package has existed in AUR are shown —
with no history of our own, those are the only trust signals available.
* Visually distinguished, **quietly**. A thin red accent on the card and a one-line note
("first build of this package here") is enough. This is a more careful review, not a
warning that the user is doing something wrong.
* Approving it creates the first `release` and establishes the base every future diff will be
measured against, so it is the single most consequential approval for a pkgbase.
### 7.2 Approval record
Immutable, append-only:
```
approval(id, candidate_id, base_release_id, decided_at,
decision, risk_level, diff_digest, identity_hash, note)
```
`diff_digest` is a hash of the exact rendered diff the human was shown. Storing it means
we can later prove "the human approved *this* diff", which matters because this system's
whole purpose is being a human firewall against arbitrary code.
### 7.3 No auto-approval in v1
**Every review is approved by a human.** Auto-approve policies are deferred (§20). This
simplifies things considerably: risk scoring is *advisory* — it orders the inbox, colours
rows, and surfaces signals, but it never gates anything. There is no policy engine, no
`policy_id`, and no class of bug where a heuristic let something through.
### 7.4 Bulk operations
Multi-select approve/reject in the inbox, with a guard: bulk approve always shows a
per-item risk summary first and refuses to include anything flagged high-risk unless each is
individually confirmed. Bulk approve is per-candidate, never "approve everything forever".
---
## 8. Build pipeline
### 8.1 Steps
```
0 materialize git worktree add --detach (local mirror only, no net)
recompute recipe_hash; assert == candidate.recipe_hash → fail closed
1 plan resolve deps against current accepted index; compute WorldSnapshot
2 chroot acquire/refresh chroot overlay; install makedepends + depends from our repo
3 sources seed from source_cache, fetch what is missing, then verify against
candidate.source_digests (not only the PKGBUILD's declared sums) + PGP
4 pkgver (VCS only) resolve pkgver(); assert == approved pkgver/pkgrel
5 build makechrootpkg -c -r -- -si -f
6 collect parse .PKGINFO/.BUILDINFO, extract artifacts + build log
7 verify signature valid, deps satisfiable in target repo, no downgrade
8 ingest move artifacts to content-addressed store, record rows
9 publish repo-add + repo-remove, sign, atomic swap
8 ingest move artifacts to content-addressed store, record rows
9 publish repo-add + repo-remove, sign, atomic swap
```
Each step writes `build_step(build_id, step, status, attempt, started_at, finished_at,
output_digest, error)`. A worker claims a build, runs the next incomplete step, records it,
and requeues. Steps 0–8 are idempotent and parallel-safe across builds. **Step 9 is
serialized by a single-writer lock per repo** and is the only externally visible mutation.
Step 0 is the `aur_commit` pin doing its job: the bytes we build are checked out of the
local mirror at the reviewed SHA and re-hashed. There is no path from "AUR moved since the
review" to "we built it anyway" — the build simply never asks the network for a recipe.
Step 3 verifies against **our** recorded digest, not the PKGBUILD's. For a source declared
`SKIP` this is the only verification that exists, and it closes the window between "we
hashed it at review time" and "makepkg downloaded something else just now".
Step 4 is the belt-and-braces assertion that the thing we build is the thing that was
approved: if upstream moved between approval and build, the build fails with "approved
`r1234.9f2c1ab`, upstream now `r1248.a11beef`" instead of silently shipping the new one.
### 8.2 Restartability
SQLite has no `SKIP LOCKED`, and we don't need it: there is exactly **one writer**, so claim
contention doesn't exist. The queue is a dispatcher actor.
```
dispatcher thread:
loop:
tx: BEGIN IMMEDIATE
SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at
LIMIT ;
UPDATE build SET state='leased', lease_owner=?, lease_expires_at=now()+90s,
attempt=attempt+1 WHERE id IN (...);
COMMIT
for each id: build_tx.send(id) // crossbeam unbounded channel
worker thread (N of them):
for build_id in build_rx:
loop over incomplete steps:
run step (blocking, child process) → record → extend lease
publish step goes through the publisher's single-thread channel instead
reaper (in the dispatcher loop):
UPDATE build SET state='queued' WHERE state='leased' AND lease_expires_at < now()
mark its in-flight step 'interrupted'
```
* **Crash-safe by construction.** On restart, the dispatcher's first act is the reaper pass:
every `leased` row with an expired lease goes back to `queued`, and the step-level
checkpoint decides where it resumes. Nothing lives only in a worker's memory.
* **Idempotent steps.** `build_id` is deterministic:
`hash(pkgbase, candidate_identity_hash, world_snapshot_hash, build_profile)`.
Re-submitting the same intent is an `INSERT OR IGNORE` no-op — which is what makes
manual rebuilds safe to enqueue carelessly.
* **Staging is disposable.** Artifacts land in `staging//` and are only moved into
the content-addressed store at `ingest`. A GC pass sweeps abandoned staging dirs.
* **Cancellation.** A newer approved release for the same pkgbase marks in-flight builds
`cancel_requested`; workers check at step boundaries and kill the chroot process group.
* **Backpressure.** `admissible` is `min(max_concurrent_builds - in_flight, disk headroom,
chroot pool free)`. Default `max_concurrent_builds = 1`, which also means the chroot pool
only needs one warm root by default. A build that cannot fit on disk is not admitted.
* **Single-process assumption.** If we ever split workers onto other hosts, the claim
`UPDATE … WHERE state='queued'` in a `BEGIN IMMEDIATE` transaction is still atomic across
processes, so the design survives that split unchanged.
### 8.3 Clean chroot specifics
* devtools: `mkarchroot` per profile (`extra-x86_64`), one warm root per profile,
per-build CoW snapshot (`makechrootpkg -c`), never mutate the seed.
* The chroot's pacman is configured to trust **only** our repo key + the arch keyring;
`SigLevel = Required DatabaseOptional` inside the chroot so a poisoned mirror can't inject
a build dep.
* Network: **available during `build()`**, no controls in v1 (decided). Many AUR packages
fetch at build time (cargo, npm, go, `pip install` during `build()`), so blocking egress
would break a large share of the set. Consequence stated plainly: a `PKGBUILD` can fetch
code the reviewer never saw, and neither `sha256sums` nor PGP covers it. We accept this for
v1; egress accounting and per-package denial are future work (§20). The one cheap thing we
do now is flag `cargo`/`npm`/`go`/`pip` in `makedepends` as a risk signal, so the reviewer
at least knows the build will pull unreviewed dependencies.
* Resource limits: cgroup v2 per build (cpu, mem, io, pid, disk quota), wall-clock timeout,
disk-space guard before starting.
* Build user is unprivileged and unique per build; it has **no read access to the SQLite
file, the mirrors directory, or the signing key** — enforced with OS file permissions and
`sudo` rules, since this is one process (§14).
* `--holdsrc` + source cache to avoid re-downloading tarballs. VCS sources are re-fetched
from the branch tip for now — honouring `upstream_pins` at build time is deferred (§20).
### 8.4 Failure handling
* Retry policy per step: transient (network, mirror 5xx) retries with backoff; deterministic
build failures do **not** auto-retry — they surface as a build failure on the release with
the log, and the release stays `approved_but_unbuilt`.
**Important:** a failed build must not silently leave the old version looking healthy.
The UI shows "v2 approved, build failed, index still serving v1".
* Upstream 404 / moved URL: candidate marked `blocked`, watcher backs off, user notified.
* Flaky test suites: `checkdepends` failures produce a distinct "build ok, check() failed"
state with a "retry with --nocheck" action that is itself an explicit, audited decision.
---
## 9. Publishing & serving the index
**One repo.** Single-user system, so there is exactly one repo entity. The `repo` table
stays (it holds the signing key id, path, and the release pointers) but there is no
multi-tenancy, no per-user approval state, and no fan-out publish.
* Layout: `/srv/repo/aur-build/os/x86_64/` with `*.pkg.tar.zst`, `*.pkg.tar.zst.sig`,
`aur-build.db.{tar,zst,sig}`.
* Signing: `repo-add -s -p -R` (replace old entry). **Both the packages and the
database are signed**, so consumers can use `SigLevel = Required` and get real verification
end to end rather than trusting a plaintext package with a signed index.
* Atomic publish: write new db to `.tmp`, `fsync`, `rename` over the real one, then the sig.
Serve read-only via nginx/caddy with `etag`/`last-modified` handled correctly (pacman
caches dbs aggressively; make sure `Cache-Control` doesn't strand clients on a stale db).
* `repo-remove` path for unsubscribes and for "revoke this version" incidents — plus a
documented rollback: republishing an older accepted release is allowed and audited.
* Publish is a single-writer transaction per repo; concurrent approvals queue. Keep the
critical section tiny (db file rewrite only), not the build.
---
## 10. Staleness: tracking what a package was built against
**There is no automatic rebuild engine.** An earlier draft had one; it was removed, for a
concrete reason: a dependency-triggered rebuild produces the *same*
`epoch:pkgver-pkgrel` as the package already in the index, and `pacman -Syu` will not
reinstall a same-version package. Making rebuilds observable would have required bumping
`pkgrel` server-side, which makes our published versions diverge from AUR's and collides when
upstream later publishes that same `pkgrel`. Rather than invent a versioning scheme, v1
**records the facts and shows them**, and leaves automation for later (§20).
### 10.1 What is recorded
Every release stores the exact set of *our* packages it was built against, taken from
`.BUILDINFO` — the full installed package set at build time, with versions.
```
world_snapshot = sorted (pkgbase, epoch:pkgver-pkgrel) of .BUILDINFO members
INTERSECT our index <-- important, see below
```
**Filter to our own repo.** `.BUILDINFO` also lists the entire build chroot — `glibc`,
`pacman`, `binutils`, everything. Left unfiltered, every package would be permanently stale
because Arch never stops updating. Restricting the snapshot to packages we ourselves publish
makes staleness mean something specific and actionable: *our* dependency moved. Official-repo
drift is explicitly out of scope (§20).
Both `.PKGINFO` and `.BUILDINFO` are plain text inside the `.pkg.tar.zst`, so parsing is
`tar` + a line-oriented reader. No libalpm needed.
### 10.2 The staleness rule
> A release is **stale** if any pkgbase in its `world_snapshot` now has a different accepted
> version in our index, or is no longer present.
That is the whole rule. Purely derived, recomputed on read (or cached in a materialised
table if the query gets slow), no triggers, no queues, no cascade, no debounce, no cycle
detection. All of that machinery disappeared with the rebuild engine.
Two distinct states, shown separately because they mean different things:
| State | Meaning |
|---|---|
| `stale_outdated` | a dependency we publish has a newer accepted version |
| `stale_missing` | a dependency we used to publish is gone (withdrawn or unsubscribed) — harder to fix |
### 10.3 The Attention dashboard
This is where staleness lands (§13). One screen, three kinds of row, all of them "things a
human may want to look at" rather than "things the system will do about":
* **Outdated dependencies** — package, its accepted version, which dep moved from what to
what, how long ago.
* **Downgrades** — a subscribed pkgbase where AUR's version is now *lower* than what we
serve (maintainer reverted). Flagged, not blocked; consumers need `--allow-downgrades`.
* **Blocked builds** — an approved release that cannot build because a dependency is not in
the index yet (§10.4).
Each row gets an action: open the package, rebuild manually, ignore. The "rebuild manually"
path is how a user acts on staleness today — they bump nothing, they just ask for a rebuild
of the same version and accept that consumers must reinstall it. That is a deliberate
limitation, documented rather than papered over.
### 10.4 Missing dependencies: block and wait
A build's plan step resolves every `depends`/`makedepends` and classifies each as: in our
index / in the official repos / **unresolvable**. Unresolvable means the dependency is a
pkgbase we subscribe to but have not approved a version of yet — the classic bootstrap case
where `A` depends on `B` and `B` is still sitting in the review inbox.
* The build enters `blocked_missing_dep` and waits. It is **not** a failure and is not
retried on a timer; it is re-checked whenever a publish lands.
* It appears on the Attention dashboard with the blocking pkgbase named and a link to the
review that would unblock it.
* **The review page shows it too.** Approving `A` while `B` is missing would produce a build
that cannot run, so the review for `A` carries an inline warning listing the missing
dependencies. Approving is still allowed — the user may intend to handle `B` separately —
but they are told before they click, not after.
### 10.5 Dependents (read-only)
`dep_edge` survives as a *derived, read-only* view built from `.PKGINFO` `depend` +
`makedepends` resolved against our index. It exists for one genuinely useful piece of review
context: **"approving this will mark 12 packages stale."** That is a read-time query over the
world snapshots, not a trigger source — nothing consumes it automatically.
## 11. Data model (sketch)
Single user, so no `user` table and no per-row ownership. Authentication is one shared
credential at the HTTP edge (§14); the DB records *that* a human decision happened, not
which of several humans.
```sql
repo(id, name, signing_key_id, path, arch, state) -- exactly one row; arch = 'x86_64'
subscription(id, repo_id, pkgbase, aur_url, maintainer,
state, -- active | paused | orphaned | removed
next_check_at, last_checked_at, last_error)
pkgbase(id, name UNIQUE, aur_url, mirror_path, aur_head, -- live mirror tip
current_accepted_release_id, state)
snapshot(id, pkgbase_id,
aur_commit TEXT NOT NULL, -- THE PIN: exact AUR commit these bytes came from
recipe_hash TEXT NOT NULL, -- hash of PKGBUILD+.SRCINFO+*.install+patches
srcinfo_json, files_json, fetched_at,
UNIQUE (pkgbase_id, aur_commit))
candidate(id, pkgbase_id,
base_release_id, -- last ACCEPTED; NULL for first_introduction
kind, -- new_version | first_introduction
snapshot_id NOT NULL, -- carries aur_commit + recipe_hash
epoch, pkgver, pkgrel,
upstream_pins_json, -- [{index,url,ref,branch,commit}]
source_digests_json, -- [{index,url,kind,digest,size,skip_declared}]
identity_hash TEXT NOT NULL, -- hash(aur_commit,epoch,pkgver,pkgrel,pins,digests)
revision INT DEFAULT 0, -- bumped when a newer detection collapses in place
viewed_at, -- null until a human opened it
risk_level, risk_signals_json,
missing_deps_json, -- unresolved deps at review time; shown on the review (§10.4)
state, -- pending_review|approved|rejected|superseded|blocked
detected_at, resolved_at,
UNIQUE (pkgbase_id, state) WHERE state='pending_review', -- I7: one open review
UNIQUE (pkgbase_id, identity_hash))
approval(id, candidate_id NOT NULL UNIQUE, base_release_id, decided_at,
decision, risk_level, diff_digest, identity_hash, note)
release(id, pkgbase_id, candidate_id, approval_id,
aur_commit, recipe_hash, -- copied from the snapshot: permanent provenance
upstream_pins_json, source_digests_json, -- copied too: what was actually built
epoch, pkgver, pkgrel,
world_snapshot_id, -- what it was built against -> staleness (§10)
state, -- published | withdrawn | failed_unbuilt
published_at)
package(id, repo_id, release_id, name, arch, version, artifact_id) -- split pkgbases: N rows
artifact(id, digest, size, path, signature_path, build_log_path, source_archive_path)
build(id TEXT PRIMARY KEY, -- deterministic intent hash, see §8.2
pkgbase_id, candidate_id, release_id,
kind, -- new_version | manual_rebuild
world_snapshot_id, build_profile,
state, -- queued|leased|running|blocked_missing_dep|
-- succeeded|failed|cancelled
blocked_on_json, -- which pkgbases are holding it (§10.4)
current_step, lease_owner, lease_expires_at, attempt, priority, cancel_requested)
build_step(build_id, step, status, attempt, output_digest, error,
started_at, finished_at, PRIMARY KEY (build_id, step))
-- the dependency set a build ran against, filtered to our own repo (§10.1)
world_snapshot(id, hash UNIQUE, members_json, created_at)
-- derived, read-only: "approving this marks N packages stale". No trigger consumes it.
dep_edge(from_pkgbase, to_pkgbase, kind, updated_at,
CHECK (kind IN ('depend','makedepends')),
PRIMARY KEY (from_pkgbase, to_pkgbase, kind))
-- non-candidate events: things worth telling a human about that are not publishable
-- (digest drift with no version change, pin drift with no version change,
-- recipe drift with no version change, unpinable pkgver)
notice(id, pkgbase_id, kind, severity, detail_json, created_at, acknowledged_at)
-- the Attention dashboard (§10.3) is computed from release + world_snapshot + notice;
-- it is a query, not a table.
source_cache(url, digest, size, fetched_at, path) -- dedupe + reuse for the build
vcs_cache(url, head, path, fetched_at) -- persistent upstream clones (§5.2)
audit(id, at, actor_kind, action, entity, entity_id, detail_json) -- append-only
settings(key PRIMARY KEY, value)
-- max_concurrent_builds = 1 (default; see §8.2)
-- build_timeout = 90m
-- poll_interval = 24h (conservative default, per-source overridable)
-- stage_b_cooldown = 24h
-- retention_versions = 3 (N releases kept per pkgbase for rollback)
-- dry_run = 0 (test harness, §16a)
```
Notes:
* `release` is created only at successful publish. `current_accepted_release_id` is the
single pointer everything reads, and updating it is a compare-and-swap.
* `aur_commit`, `recipe_hash`, `upstream_pins` and `source_digests` are **copied onto the
release**, not just referenced, so provenance survives even if the snapshot/candidate
tables are ever compacted. This is what makes "which bytes produced this installed
package" answerable years later.
* The partial unique index enforcing one `pending_review` per pkgbase makes invariant I7 a
database guarantee rather than a convention. (SQLite supports partial unique indexes.)
* `notice` is the escape valve for "something changed but nothing is publishable" (§5.2).
Without it those events are invisible, and a silently-drifting tarball is exactly the kind
of thing that must not be invisible.
* `world_snapshot.members_json` is **filtered to our own packages** at ingest time (§10.1),
not at query time — storing the whole chroot would make everything permanently stale and
bloat the row for no reason.
* The Attention dashboard is a query over `release` + `world_snapshot` + `notice` +
`build.state = 'blocked_missing_dep'`. Deliberately not a table: nothing to keep in sync.
* `audit` is append-only; enforce with a trigger that rejects `UPDATE`/`DELETE`.
---
## 11a. SQLite concurrency model
SQLite is the right choice here, but only with a discipline, because the app is
multi-threaded and SQLite has one writer at a time.
* **WAL mode**: `PRAGMA journal_mode=WAL`, `busy_timeout=5000`. `synchronous=FULL` for
approval/audit writes (durability of the approval trail is worth the fsync); `NORMAL`
is acceptable elsewhere.
* **One writer actor.** A dedicated thread owns the write connection. Everything that
mutates goes to it over a crossbeam channel as a small `Tx` enum, and it replies with
`Result`. This makes "who can write" a compile-time fact and removes `SQLITE_BUSY`
from the design entirely.
* **Many reader connections**, one per thread (`thread_local!`), read-only, used by HTTP
handlers and watchers. WAL lets readers proceed concurrently with the writer.
* **No transaction spans a build step.** Steps record their result in one short
transaction; the long-running child process happens outside any transaction. Long-lived
write transactions are the classic way to make SQLite hurt.
* **DB size is a non-issue**: thousands of pkgbases, tens of thousands of audit rows. The
heavy bytes (packages, logs, mirrors) live on the filesystem, referenced by path.
* **Backups**: `VACUUM INTO` or the online backup API for a consistent snapshot — never
`cp` a live WAL database — plus the mirrors dir and the artifact store.
---
## 12. Interface: server-rendered HTML first
The UI is **server-rendered HTML from Askama templates**. No SPA, no JS bundler, no client
router. Handlers read via thread-local read connections and render a full page.
```
GET / dashboard: pending count, attention count, running builds, recent publishes
GET /reviews?state=pending&sort=risk
GET /reviews/:id full diff panels + risk (marks viewed_at)
POST /reviews/:id/approve {candidate_id, identity_hash, diff_digest} -> 409 if stale
POST /reviews/:id/reject {note}
POST /reviews/bulk {ids[], decision, tokens[]}
GET /subscriptions list + add/remove/pause
GET /attention staleness, downgrades, blocked builds (§10.3)
GET /packages current index contents
GET /packages/:name timeline, deps in/out, staleness, aur_commit history, builds
POST /packages/:name/rebuild manual rebuild of the current accepted version
POST /packages/:name/withdraw
GET /builds running + queued
GET /builds/:id step timeline + log
GET /builds/:id/log.txt full log
GET /builds/:id/log.stream SSE - a thread that blocks and tails the file
GET /audit
GET /settings
GET /metrics prometheus text format
```
**Dynamic behaviour, minimal JS.** Two mechanisms, both degradable:
1. **htmx** (one vendored ~14 KB file, no build step) for the handful of fragments that
update: the builds table (`hx-get` + `hx-trigger="every 3s"`), the pending-review badge,
approve/reject posting and swapping in the next row, log tail append. Every fragment
endpoint has a plain-HTML equivalent, so the app still works with JS disabled - just
with manual reloads.
2. **SSE** for live build logs, since polling a whole log is wasteful. With thread-per-
connection HTTP, an SSE handler is just a thread that seeks to EOF and blocks on the log
file. No async needed.
Form posts are plain `