# 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 provision lease the sandbox; install the pinned lease set (our deps by exact version+digest) with pacman -U; assert the sandbox's pacman -Q confirms the approved world landed → fail closed on mismatch 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 makepkg -c -f in the provisioned sandbox (no -s: deps are installed; no -si: the sandbox never holds the signing key) 6 collect parse .PKGINFO/.BUILDINFO, extract artifacts + build log 7 verify deps satisfiable in target repo, no downgrade 8 ingest move artifacts to content-addressed store, sign hub-side, 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 build environment specifics * The sandbox boots from a **base image** we build per profile (`extra-x86_64`), content-addressed by the world it contains, carrying `base` + `base-devel`, the arch keyring and our signing key in pacman's keyring, and a pacman.conf with `SigLevel = Required` and no `Server=` lines: dependencies enter only as digest-pinned blobs through the lease (§8a), never from a live mirror. * The provisioning step installs the **lease manifest** — every dependency we publish, pinned to the exact version and digest the index serves — with `pacman -U`, and the sandbox's own `pacman -Q` must confirm the pinned world landed. A byte that hashes differently, or a world that drifted, fails the build closed (`WorldMismatch`). The devtools chroot (`mkarchroot`, `makechrootpkg`, nspawn) is gone: the sandbox *is* the isolation boundary, and the machine boundary makes I9 stronger than a chroot did (DECISIONS.md). * 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. ### 8a. Sandbox backends (remote builder) Where build code *runs* is a deployment fact, so it is an interface (`crate::sandbox::SandboxBackend`), not a pipeline fact. The step machine leases a sandbox (`acquire`), runs argv-shaped commands on it (`run`, streaming output into the same build log the SSE tail reads), moves content-addressed blobs in and out (`put`/`get` — there is no "path on the sandbox" concept in the interface), and destroys it. Three bodies: * **loopback** — commands run as subprocesses of the hub, with the §16a shim protocol applied. This is `cargo test` and the single-machine deployment; the shim suite passing through it unchanged is what keeps the seam honest. * **remote** — an ephemeral `sandbox-agent` dials the hub (outbound rendezvous: the hub never needs a route into an untrusted box), serves `Run`/`Put`/`Get` frames over length-prefixed JSON, and dies — taking its child with it — when the connection drops or its TTL expires. A vanished sandbox fails the step, which is already the shape of an expired lease (I5): the remote path adds no new failure vocabulary. * **kata** — ad-hoc, TTL-bounded sandboxes provisioned by an orchestrator (agent-sandbox-style CR with `runtimeClass: kata` and `activeDeadlineSeconds`). `acquire` mints a rendezvous nonce, provisions, and leases only the dial-in whose hello carries the nonce back; a box that never dials in is a TTL expiry. A pool that cannot fit a lease is `PoolExhausted`: the build blocks on `sandbox-pool` using the same blocked machinery as missing deps (§10.4) — capacity is a fact to wait on, not a failure to retry. The TTL is the guarantee under every leak: hub crash, partition, a forgotten destroy. Every sandbox is garbage-collected by its deadline, and the hub itself never needs root — the privileged surface shrank to "nothing on this machine runs build code at all." Workspace sync over the wire is deliberately not implemented: `Run` carries a hub-side cwd, honest for loopback-shaped deployments and the test tier, and the code says so. --- ## 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 `
` with a CSRF token, so approve/reject work with no JS at all. Target: **< 20 KB of JS, all of it vendored, none of it written by us** (htmx only), plus ~30 lines of glue for the log tail. --- ## 13. GUI Five primary surfaces: **Inbox / Reviews** (the heart of the product) Pending reviews, sorted by risk desc then age. Row shows `pkgbase · v1 → v2 · recipe/VCS · 3 signals · 4h`. Detail view: tabbed diff panels (recipe / sources / deps / install hooks / upstream-commits-when-implemented), side-by-side and unified, with risk signals called out inline ("⚠ new source host: `evil.example`", "⚠ pkgrel reset 7→1"). Approve / Reject / Approve-with-note. Keyboard-driven (j/k, a, r). Two things are always visible and unmissable: * the base: *"comparing against **v1.2.3** — accepted 2025-03-02"* (proves I2 to the user), * the pin: *"AUR commit `4f9c02e` — this exact tree is what will be built"*, linked to AUR cgit so it can be independently verified. If a newer detection landed after the page rendered, approve comes back as a 409 and the page re-renders with the new diff and an explicit explanation (§7.1a). **Builds** Live table of running builds with step + elapsed + queue position; per-build page with step timeline and streaming log; failures pinned at top; cancel/retry. Queue header shows depth, configured parallelism, and a rough ETA for the backlog. **Attention** (see §10.3) Three kinds of row, all "a human may want to look at this", none "the system will act": outdated dependencies (package, its version, which dep moved from what to what, how long ago), downgrades (AUR now lower than what we serve), and blocked builds (approved but waiting on a dependency that is not in the index yet, with a link to the review that would unblock it). Each row links out; the only action is a manual rebuild. **Index** What consumers actually get: pkgbase, version, published at, `aur_commit`, built-against world, staleness flags, artifact size. Per-package drill-down: full timeline (detected → reviewed → approved → built → published), dependencies in and out, "rebuild now", "withdraw". **Subscriptions** Add/remove/pause, last-checked + last-error per pkgbase, "check now", per-source poll interval override. **Ops** Audit log, **notices** (unacknowledged integrity alerts, pin drift with no publishable change, unpinable `pkgver`, queue depth/ETA — badge on the dashboard), watcher health (last successful poll per source, Stage-B budget usage), worker thread status, disk/chroot pool status, publish history, SQLite checkpoint/WAL size. --- ## 14. Security posture The threat model is unusual: **the input is arbitrary code chosen by third parties, and a human is the intended firewall.** * **Single-user ≠ unauthenticated.** An approval is a decision to run third-party code on every consumer machine, so the UI must not be open. Default: bind to localhost or a tailnet interface only. If it must be internet-reachable, put it behind a reverse proxy with client certs or basic auth over TLS, plus a session cookie and CSRF tokens on every POST. No password database, no reset flow, no user table - one credential, deliberately. * **Untrusted build code, same host, enforced by OS users.** Since this is one process on one machine, the boundary is file permissions + `sudo`: the build worker spawns `makechrootpkg` as user `aurbuild`, which cannot read the SQLite file, the mirrors directory, the signing keyring, or the config. Ideally the signing key lives on a separate host and the publisher only ever asks it to sign a digest; if that's overkill, at minimum keep the key in a separate user's keyring with a `sudo` rule permitting exactly the `repo-add`/`gpg` invocation and nothing else. * **Chroot trust pinning**: only our key + the arch keyring; `SigLevel = Required` for packages inside the build chroot, so a poisoned mirror cannot inject a build dep. * **Source integrity**: we resolve and record a digest for every source ourselves (§5.3), so a `SKIP` declaration does not mean "unknown" — it means "unverified by the recipe, but hashed and diffed by us". PGP verification is required where the PKGBUILD declares keys; `--skippgpcheck` and removed `validpgpkeys` are high-risk signals. Every source URL + digest is on the candidate, so the reviewer sees exactly what will run. * **Network during `build()` is granted, with no controls, in v1** (decided). This is the weakest point in the design and we are accepting it knowingly: a `PKGBUILD` can fetch code the reviewer never saw, and neither `sha256sums` nor PGP covers it. Per-package network denial was considered and dropped — it would break a large share of AUR packages, and the machinery to discover which ones tolerate it is not worth building up front. Recorded as future work (§20) alongside egress accounting, which would at least make the exposure visible after the fact. * **Tamper-evident review**: diffs are rendered from the pinned local mirror, never live-fetched at review time, and `diff_digest` + `identity_hash` are stored with the approval and re-checked at approve time (§7.1a). This is what makes "we built what you saw" provable rather than aspirational. --- ## 15. Observability Metrics: poll lag per source, detections/h, candidates pending + age histogram (the "review debt" number), approvals/rejections/h, build queue depth + step latency histogram, build success rate by pkgbase, publish latency, index size, count of stale releases by reason, blocked_missing_dep count, Stage-B budget usage, SQLite WAL size + checkpoint lag. Alerts: watcher silent > N min, publish failure, chroot pool exhausted, disk low, review debt older than X days, a pkgbase stuck in `blocked`, a build blocked on a missing dependency for longer than a budget, queue age past a configured budget. Backups: the SQLite DB via `VACUUM INTO` (the approval history is the crown jewel), the **AUR git mirrors** (now load-bearing for rebuildability, §5.1a), and the artifact store. --- ## 16. Edge cases to design for explicitly * **Split pkgbases** — one approval, N packages; partial build failure means nothing publishes. * **`pkgbase` rename / package moves between pkgbases** — re-pin subscription, don't orphan index entries. * **AUR deletion or orphaning** — subscription state `orphaned`, keep serving last accepted, warn loudly. * **Downgrades** (maintainer reverts) — allowed but flagged; pacman needs `--allow-downgrades`, so decide policy. * **Epoch bumps** — flagged; often means a version-format change, not a real update. * **`provides`/`conflicts` collisions** with the official repos or with another subscribed pkgbase. * **Cyclic build deps** through `makedepends` (very common: python packages). * **A dep that isn't built yet** — plan step must detect "required package not in our index and not in official repos" and block with a clear message rather than fail obscurely. * **VCS `pkgver()` that ignores the pins** (e.g. uses `date`, or reads a non-default branch) — the version can move without the code moving, or vice versa. Detect: pins unchanged but `pkgver` changed, or pins moved but `pkgver` frozen. Mark the pkgbase as "unpinable", emit a `notice`, and fall back to recipe-hash + poll-time identity. * **Recurring build failures** — don't retry forever; exponential backoff + park. * **Two users, different approval states** — out of scope by decision; single user, one repo. * **Clock skew / ordering** — use DB time (`strftime` at write) for all ordering and audit stamps. * **Concurrent approvals on the same pkgbase** — `current_accepted_release_id` update is a guarded compare-and-swap inside the writer actor. * **Mirror divergence** — if the local mirror's history is ever force-pushed or rewritten (AUR shouldn't, but), `aur_commit` may vanish. Detect at fetch time and hard-fail the pkgbase rather than silently re-pinning. --- ## 16a. Testability (first-class, not an afterthought) A system whose side effects are chroot builds and repo mutations is impossible to develop against if every test needs a real Arch host. Development would slow to a crawl. So the test harness is part of the design, built alongside P0. **Two layers.** **1. Fake-package corpus.** A checked-in `testcorpus/` of synthetic PKGBUILDs, each exercising one behaviour the system must handle: | Fixture | Exercises | |---|---| | `plain-make` | trivial build, happy path | | `with-patch` | shipped patch file in the recipe → `recipe_hash` coverage | | `install-hooks` | `.install` script → hook diff panel | | `skip-checksum` | `sha256sums=('SKIP')` on a static file → digest resolution + risk signal | | `git-sourced` | `git+file://` upstream with a real local git repo → Stage A/B, `pkgver()` | | `git-submodules` | submodule gitlink handling | | `split-pkgbase` | one PKGBUILD, three packages → one approval, N index rows | | `epoch-bump` / `downgrade` / `pkgrel-reset` | version-delta flagging | | `build-fails` | deterministic failure, no auto-retry | | `check-fails` | `check()` failure → the `--nocheck` decision path | | `missing-dep` | depends on a pkgbase not in the index → `blocked_missing_dep` | | `dep-cycle` | `makedepends` cycle | | `digest-drift` | same version, swapped tarball → `integrity_alert`, not a candidate | | `pin-drift` | upstream moved, `pkgver` unchanged → `notice`, not a candidate | | `unresolvable` | source 404 → `blocked` + backoff | Each fixture is a directory with a PKGBUILD, an optional local git repo, and a `manifest` describing the expected outcome, so the corpus doubles as executable documentation of the edge cases in §16. **2. Toolchain shims.** The pipeline shells out to `mkarchroot`, `makechrootpkg`, `repo-add`, `gpg`, `pacman` and `git`. In test mode the harness prepends a directory of **fake executables to `PATH`**. Each fake records its invocation, respects a scripted outcome from the fixture manifest, and emits plausible `.PKGINFO`/`.BUILDINFO`/`.sig` output. That means: * the full step machine, checkpointing, lease/reaper recovery, publishing and index regeneration all run for real, in milliseconds, on any machine — no Arch host, no root, no network; * crash-recovery tests become trivial: kill the process mid-step, restart, assert it resumes at the right step (I5); * staleness tracking is testable because the fakes can emit arbitrary dependency sets; * `dry_run` in `settings` gives the same shimming for manual exploration. **The §2 invariants become executable tests**, not prose. I1 (no artifact without an approval) is a query run after every test. I2 (diff base is last accepted) is asserted by the multi-detection fixtures. I4 (atomic publish) is a kill-mid-publish test. If an invariant cannot be written as a test, that is a signal the invariant is wrong or the design is. **3. Real integration, gated.** A `#[ignore]`-style tier that does actual `mkarchroot` + `makechrootpkg` builds against one or two real AUR packages, run manually or on a schedule on a real host. Fast tests give confidence about our logic; this tier gives confidence that the assumptions about devtools are still true. --- ## 17. Suggested phasing **P0 — walking skeleton + test harness** Rust binary, SQLite schema + writer actor, the toolchain shims and the first corpus fixtures (§16a), AUR git mirror watcher with `aur_commit` pinning, source digest resolution for `SKIP` sources, candidate creation with `base = last accepted`, `first_introduction` handling, manual approval via a CLI subcommand, single-machine build with `makechrootpkg` (`max_concurrent_builds = 1`), `repo-add` publish with package + db signing, static file serving. Prove I1/I2/I4/I5 end to end on one normal package. **P1 — VCS / pkgver detection** (core requirement, not a nice-to-have) Stage A upstream probes over all VCS sources, persistent VCS clone cache, Stage B `pkgver()` resolution with commit capture, `upstream_pins` in the identity, upstream commit-range diffs, `notice` for non-publishable drift. Prove it on one real `-git` package. **P2 — review surface** `tiny_http` + templates, the Inbox and diff panels, risk scoring (advisory), the optimistic-concurrency approve flow with 409-on-stale, the Attention dashboard. This is where the value lands. **P3 — durability** Dispatcher + worker pool + reaper, chroot pool, step checkpointing, cancellation, deterministic build ids, SSE log tail, crash-resume tests against the shims. **P4 — staleness** `.PKGINFO`/`.BUILDINFO` parsing, world snapshots, the staleness query, downgrades and blocked-build views, retention & GC (N versions with logs and sources), metrics/alerting. **P5 — polish** `network` controls if ever wanted, backup automation, hardening transforms (§20). --- ## 18. Decisions taken | # | Decision | |---|---| | 1 | **Stack**: Rust, no `async`/`await`, no tokio. Threads + channels. | | 2 | **DB**: SQLite (WAL, single writer actor). | | 3 | **UI**: server-rendered, minimal functional JS (htmx + SSE), no SPA, no bundler. | | 4 | **Tenancy**: single user. One repo, one credential, no user table, no RBAC. | | 5 | **Stale approvals**: refused with HTTP 409 and a re-render. Never retarget silently. | | 6 | **AUR pin**: record `aur_commit` as first-class metadata; show it in the diff; build by checking that SHA out of the local mirror and re-hashing. | | 7 | **Network in `build()`**: granted, no controls in v1 (§14). Accepted risk. | | 8 | **Superseded reviews**: collapse in place; `superseded` only when a human already saw the old diff. | | 9 | **No automatic rebuild engine.** Record the world each package was built against and surface staleness in a dashboard; leave automation to later (§10, §20). | | 10 | **`upstream_pins[]` is part of the candidate key** — one HEAD (commit SHA) per VCS source. No separate tree hash; the commit already pins the tree and any submodule gitlinks. | | 11 | **Source digests are recorded for every source**, regardless of what the PKGBUILD declares, and are part of the candidate key. | | 12 | **Non-publishable changes** (version string unchanged) produce a `notice`, never a review, and are never silently dropped. | | 13 | **VCS detection is P1**, not a later enhancement — `-git` pkgver changes are a core requirement. | | 14 | **Recipe-mutating hardening transforms are deferred** (§20). We record pins and digests; we do not rewrite the PKGBUILD. | | 15 | **First acceptance is a distinct review kind** (`first_introduction`): full recipe shown, no diff, subtly accented — not obnoxious. | | 16 | **Missing dependencies: block and wait.** Builds enter `blocked_missing_dep`, the Attention dashboard monitors them, and the review page warns about missing deps before approval. | | 17 | **Architecture: x86_64 only.** | | 18 | **Default parallelism: 1.** Configurable. | | 19 | **No auto-approval in v1.** Risk scoring is advisory only. | | 20 | **Downgrades are a dashboard warning**, alongside outdated dependencies. Not blocked. | | 21 | **Retention: N versions per pkgbase for rollback**, with the build log and source cache retained alongside the package as a unit. | | 22 | **Sign packages as well as the database; key on the same host.** Consumers can use `SigLevel = Required`. | | 23 | **Withdrawal warns, it does not block.** Breakage of dependents is the user's call. | | 24 | **Full integration testability via a fake-package corpus and toolchain PATH shims** (§16a). Built in P0, not retrofitted. | | 25 | **Conservative default poll interval: once a day**, configurable per source. | --- ## 19. Still open Most of the earlier open questions were resolved above. What is genuinely left: 1. **`N` for retention** — how many versions per pkgbase? Depends on the disk budget for the target host, which is still unchosen. 2. **Target host specs** — cores, RAM, disk. Only affects defaults now that parallelism is 1, but the retention number and the Stage-B budget both want real numbers. 3. **How `first_introduction` interacts with a pkgbase that has history elsewhere** — e.g. the user unsubscribed and resubscribed. Do we treat the old releases as the base again, or start fresh? Cheap to decide now, annoying to retrofit. 4. **Split pkgbases and partial subscription** — the unit is the pkgbase, so subscribing to `foo` also publishes `foo-lua`. Probably fine, but worth confirming rather than discovering. 5. **`unpinable pkgver` fallback identity** — §16 says "fall back to recipe-hash + poll-time", which is vague and non-deterministic. Needs a concrete rule. 6. **Askama vs minijinja** — compile-time checked templates are nicer, but slow rebuild times. Decide in P2. 7. **Backup frequency and retention** — the mirrors and the DB are load-bearing; the schedule and retention are unspecified. 8. **Repo hostname / path and the consumer `pacman.conf` snippet** — trivial, but it is the entire user-facing contract and worth pinning down before P0. --- ## 20. Future extensions (explicitly not in v1) Kept here so they are not lost, and so nobody has to re-derive the reasoning later. **Automatic rebuilds on dependency change.** The obvious follow-up to the staleness dashboard. Blocked on the versioning problem described in §10: a rebuild produces a same-version package that `pacman` will not offer, so any automation has to decide how consumers observe it — most likely a server-side `pkgrel` bump with collision handling. Build the dashboard first, watch which packages actually go stale, and let real usage pick the policy. **Auto-approval policies.** Narrow rules evaluated against risk scoring — `metadata-only` (recipe diff touches only `pkgrel`/`pkgdesc`/comments), `vcs-bump` (recipe unchanged, only the upstream commit moved, low risk), `pin-range` (accept only commits matching a refspec or semver range). Would need risk scoring to become load-bearing, plus a revocable auto-approved review state. **Recipe-mutating hardening transforms (§5.3a).** Rewrite `sha256sums=('SKIP')` to the digest we recorded, and/or pin VCS sources to `#commit=`. Both make the built artifact match the reviewed one. Both must be displayed as an explicit "server applied:" transform, and the `#commit=` one interacts badly with `pkgver()` functions that expect a branch. **Honouring `upstream_pins` at build time.** We record the commit; making the build actually check it out (rather than following the branch tip) needs either the transform above or seeding a prepared clone into `$startdir` with the fetch suppressed. **Network controls.** Per-package `network = deny` for the packages that tolerate it, and egress accounting so "this build touched N new hosts" can be surfaced. Both are pure hardening on top of the v1 posture of granting network unconditionally. **Cost-weighted build admission.** Admit work against a capacity budget rather than a slot count, using a per-pkgbase `build_cost` (EMA of measured durations, initialised pessimistically for never-seen pkgbases). Makes a queue of 40 two-minute packages behave differently from 40 half-hour ones, and enables honest ETA display. **Official-repo-triggered staleness.** Currently the world snapshot is filtered to our own packages (§10.1), so an Arch `python` update does not mark our `python-*` packages stale. If that bites, the cheap fix is an allowlist of ABI-critical official packages rather than general `world` tracking. **Soname/ABI-aware staleness**, if plain version-inequality turns out to be too noisy. **Notifications** (email / matrix / webhook) for pending reviews, build failures, notices, and newly stale packages.