summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--ARCH_REVIEW.md438
-rw-r--r--Cargo.toml2
-rw-r--r--DESIGN.md1279
-rw-r--r--README.md21
-rw-r--r--docs/DECISIONS.md511
-rw-r--r--docs/INVARIANTS.md73
-rw-r--r--src/db/migrations.rs2
7 files changed, 9 insertions, 2317 deletions
diff --git a/ARCH_REVIEW.md b/ARCH_REVIEW.md
deleted file mode 100644
index 438e45f..0000000
--- a/ARCH_REVIEW.md
+++ /dev/null
@@ -1,438 +0,0 @@
-# Architecture Review — `aur-build`
-
-**Scope.** A review of the code as it stands, judged on its own merits: module
-boundaries, encapsulation, coupling, API surfaces, state modeling, naming, and
-clarity. No conformance check against `DESIGN.md` / `INVARIANTS.md` was
-attempted; where those documents are cited it is only because the code cites
-them back at the reader.
-
-**Method.** Full read of `src/` (~12.0k lines, 40 modules), plus the module
-dependency graph, public-surface census, and inline-SQL census. Every finding
-cites `file:line`. Severity definitions at the top of §6.
-
----
-
-## 1. Executive summary
-
-This is an unusually thoughtful codebase. The core safety story — *nothing is
-published that a human did not approve, and what is published is byte-identical
-to what was reviewed* — is expressed in mechanisms (identity hashes, diff
-digests echoed by the approve request, compare-and-swap on the accepted-release
-pointer, checkpointed build steps, lease-based crash recovery) rather than in
-prose, and the module doc comments explain *why* far more often than they
-explain *what*. The single-writer database actor, the deterministic build id,
-and the read-derived staleness/metrics design are all genuinely good
-architectural decisions, and they are implemented consistently.
-
-The review found **one critical defect**, which is also the sharpest encapsulation
-failure in the codebase: the web session is a static cookie value (`auth=1`),
-so the login gate is trivially bypassed by any client that sets the cookie
-itself (§6, C-1). Everything else is structural:
-
-- **Encapsulation is by convention, not by the compiler.** There are zero
- `pub(crate)`/`pub(super)` items in the crate; 513 items are fully `pub`. The
- DB writer actor hands raw `&mut Connection` closures to any module that asks,
- and 12 modules outside `db/` contain hand-rolled SQL (22 statements in
- `ops.rs` alone). The schema is the system's most protected asset and nothing
- stands guard over it.
-- **The persistence layer depends on a domain layer** (`db/queries.rs` returns
- `watch::upstream::StageB`), and `watch` ↔ `review` are mutually dependent —
- the dependency graph has cycles at the module-group level.
-- **State machines are stringly typed.** Candidate, build, step, release, and
- subscription states are `&str` constants; transitions are validated
- per-call-site at runtime, and `builds::set_state` will happily write any
- string. The compile-time guarantees the writer-actor comment promises
- ("*who can write* is a compile-time fact") stop at the connection and never
- reach the data.
-- **Test scaffolding is load-bearing in production surfaces.** The production
- publish path calls into the test-shim module to read `.PKGINFO`; fault-
- injection and clock-pinning hooks live in the production `Config` and the
- hot path; the clock helper's `secs_ahead`/`secs_ago` silently ignore the
- pinned clock that `now()` honors.
-- **Error-type discipline slips exactly where the stakes are highest**: the
- approve path maps *all* internal failures (including SQLite errors) into
- `Stale::NotPending`, and `bulk()` stuffs unrelated refusals into the same
- variant.
-
-None of these are hard to fix, and most have obvious fixes that the existing
-style invites. §7 is a prioritized punch list.
-
----
-
-## 2. Architecture at a glance
-
-One binary (`src/main.rs`), one library crate (`src/lib.rs`), no async runtime.
-Threads: a DB writer actor, a watcher tick, an HTTP accept loop (thread per
-connection), a dispatcher + worker pool, and a reaper folded into the
-dispatcher loop.
-
-```
- main.rs (CLI) http/ (UI)
- | |
- v v
- review/ (approve, candidates, diff, risk)
- | |
- watch/ (scheduler, detect, upstream, |
- digests, staleness, mirror) <------+----> risk.rs -> watch::digests
- | |
- v v
- pipeline/ (steps, dispatch, publish) ---> shims/ (prod path!)
- |
- v
- db/ (writer actor, readers, queries, builds, model)
- config.rs error.rs time.rs hash.rs git.rs fetch.rs
- pkgver/ pkginfo.rs recipe.rs ops.rs
-```
-
-**Inline-SQL census** (statements outside `src/db/`): `ops.rs` 22,
-`review/approve.rs` 17, `review/candidates.rs` 15, `pipeline/publish.rs` 11,
-`watch/staleness.rs` 4, `watch/digests.rs` 3, one or two each in
-`watch/detect.rs`, `review/diff.rs`, `pipeline/{steps,mod,dispatch}.rs`,
-`http/routes.rs`.
-
-**Visibility census:** 513 `pub` items, **0** `pub(crate)` / `pub(super)`.
-`db/mod.rs:17-18` glob-re-exports `model::*` and `queries::*`, so the entire
-row/query surface is flattened into `db::` and reachable from everywhere.
-
----
-
-## 3. Encapsulation assessment
-
-**The good.** The writer actor (`db/mod.rs:89-190`) is a clean idea well
-executed: one thread owns the write connection, mutations arrive as closures,
-`tx()` wraps everything in `BEGIN IMMEDIATE`, readers are thread-local
-read-only connections, and the `Readers::with` re-entrancy hazard is called out
-and reasoned about in a comment (`db/mod.rs:220-223`). The compare-and-swap on
-`current_accepted_release_id` *inside* the publish transaction
-(`pipeline/publish.rs:213, 258`) is exactly the right way to make I4
-crash-safe. `review::candidates::upsert_candidate` (`review/candidates.rs:45`)
-is the model the rest of the codebase should follow: one transaction, a rich
-return enum (`Upsert`), no leaked SQL semantics to callers.
-
-**The bad.** The actor's *distribution* is unguarded. `Writer::call` /
-`Writer::tx` / `Writer::send` (`db/mod.rs:144,159,177`) are `pub` and hand any
-caller a `&mut Connection`. There are ~50 write sites outside `db/`, and 12
-modules contain raw SQL. This is not merely stylistic:
-
-- `review/approve.rs` hand-writes its `INSERT INTO audit` rows
- (`approve.rs:134, 187, 256`) instead of calling `db::audit`
- (`db/queries.rs:53`), so the audit trail's shape is defined in four places
- with three subtly different detail payloads.
-- `pipeline/publish.rs:42-52, 369-373` queries `artifact.path` directly in two
- duplicated blocks; `pipeline/mod.rs:316-323` re-implements
- `builds::set_release` inline.
-- `watch/detect.rs:86-104` (`schedule_next`) re-queries `poll_interval_secs`
- with raw SQL even though `db::get_subscription` already returns that column —
- and the scheduler already has it in hand (`watch/scheduler.rs:47-51`).
-
-When the schema changes, the blast radius is "any module," which means the
-`db/` module is not a boundary, it is a directory.
-
-**Layer inversions and cycles.**
-
-- `db/queries.rs:641, 670, 699` — the persistence layer constructs and returns
- `crate::watch::upstream::StageB`. The cache row type belongs in `db/model.rs`
- (or its own module) with a conversion at the `watch` boundary.
-- `watch` ↔ `review` is a cycle: `watch/detect.rs` calls
- `review::candidates::{accepted_for, upsert_candidate, set_risk}` and
- `review::risk::assess` (`detect.rs:14, 113, 258-266`), while
- `review/risk.rs:74` calls `watch::digests::skip_on_non_vcs` and
- `review/risk.rs` imports from `watch`. The cycle is survivable today only
- because nobody mutates across it, which is exactly the kind of fact
- encapsulation should make mechanical.
-- `pipeline/publish.rs:353` — production publish calls `crate::shims::read_pkginfo`
- to parse a package name out of a tarball. The shims module is the fake
- toolchain (§16a); the real parser already exists in `pkginfo.rs:61-71`. Worse,
- `shims/mod.rs:568-576` contains a *second* `.PKGINFO` parser
- (`shims::parse_pkginfo`) that duplicates `pkginfo::parse_pkginfo`
- (`pkginfo.rs:73`). Two parsers that can drift is a supply-chain-shaped
- foot-gun in a system whose whole job is provenance.
-
-**Test hooks in production surfaces.** `Config` carries `publish_fault`,
-`shim_fail`, `shim_kill_parent`, `shim_plant_link` (`config.rs:62-83`); the
-publish hot path branches on `publish_fault` twice (`publish.rs:115, 146`);
-`time::pin` (`time.rs:32`) thread-locally fakes the clock. The *existence* of
-these hooks is defensible — the test suite drives the real binary and real
-crashes, which is admirable — but they are unmarked, un-gated, and part of the
-public `Config` API a production operator reads and edits. A `cfg(test)`/feature
-gate, or a separate `TestHooks` struct that production `Config` cannot
-deserialize, would keep the power and drop the exposure.
-
----
-
-## 4. Clarity-of-design assessment
-
-**Naming and docs are a strength.** Module headers read like design notes
-("Clone, don't scrape", "A stored staleness flag goes wrong the moment anything
-else is published"), and functions that fail closed say what they refuse and
-why. `pipeline/dispatch.rs:1-17` is the best module comment in the repo: it
-states the loop shape, the recovery story, and *why there is no startup
-recovery routine*.
-
-**Where clarity breaks down:**
-
-1. **Stringly-typed state.** `db/model.rs:70-135` defines six state modules of
- `&str` constants. `builds::set_state(db, id, state: &str, ...)`
- (`db/builds.rs:195`) accepts any string; legality of a transition is checked
- (when it is checked) at individual call sites, e.g. `approve.rs` checks
- `state != candidate_state::PENDING` itself. The build state machine —
- queued → leased → running → {succeeded, failed, cancelled,
- blocked_missing_dep} — is the most consequential state machine in the system
- and exists only as a comment plus scattered `WHERE state IN (...)` clauses.
- Rust enums (with `str` mapping at the SQL boundary) would move a whole class
- of "impossible state" bugs to compile time.
-2. **Error types that lie.** `approve()` returns `Result<Result<Approval, Stale>>`
- and then collapses every inner error into `Stale::NotPending { state:
- e.to_string() }` (`approve.rs:153`), so a SQLite failure is reported to the
- reviewer as "review is no longer pending (state: sqlite: …)". `bulk()`
- reuses `Stale::NotPending` for "high-risk: needs individual confirmation"
- (`approve.rs:216`) and "unknown decision" (`approve.rs:224`), and fabricates
- an `Approval { id: 0, … }` sentinel for rejects (`approve.rs:222`). When one
- enum is bent to carry four unrelated meanings, callers cannot branch on
- anything.
-3. **A no-op that reads like a safety mechanism.** `mark_approved_but_unbuilt`
- (`pipeline/mod.rs:272-274`) has a five-line doc comment and an empty body —
- the real mechanism is the derived query `db::queries::approved_but_unbuilt`.
- A reader tracing the failure path is invited to believe state is written
- here. Delete the function, keep the comment on the query.
-4. **Two locks, one promise.** `publish.rs` holds `REPO_LOCK` (line 25) *and*
- `PUBLISH_LOCK` (line 64), each documented as *the* "one publish per repo"
- guarantee, both acquired in `publish()` (lines 67, 99); `withdraw_package`
- takes only `REPO_LOCK` (line 397). Either the second lock is redundant (then
- delete it) or the guarantee is incomplete (then fix it); today a reader
- cannot tell which, which is worse than either.
-5. **Dead parameters and `let _ =` debris.** `let _ = db;`
- (`watch/upstream.rs:262`, `review/risk.rs:113`), `let _ = pb;`
- (`watch/detect.rs:103`, `review/risk.rs:243`), `let _ = ord;`
- (`review/diff.rs:254`), `compare_digests(_old, _new, …)`
- (`risk.rs:178`), `finish(_state, _req, …, _sid, _new)`
- (`http/mod.rs:263`). Each one is a parameter the design once wanted or no
- longer wants; leaving them signals a contract that doesn't exist.
-6. **Duplicated logic that can drift.** `hosts()` is byte-identical in
- `review/diff.rs:226` and `review/risk.rs:220`. The "did the executable part
- of the PKGBUILD change" heuristic exists twice with *different semantics*:
- `diff.rs:196-214` keeps only lines that start a function, while
- `risk.rs:197-215` keeps everything from the first match to EOF. The same
- change could be flagged by one panel and not the other. The 21-column
- candidate `SELECT` is copy-pasted four times (`review/candidates.rs:149,
- 181, 201, 243`) even though `db/queries.rs` establishes the `*_COLS`
- constant pattern two files over.
-7. **Silent error swallowing in durability-critical spots.** `fsync_file` /
- `fsync_dir` (`publish.rs:316-329`) ignore every error — in a module whose
- entire claim is "fsync, then rename". `db::setting_i64`
- (`queries.rs:29-35`) turns any DB error into a default. `hash::canonical_json`
- (`hash.rs:76-78`) — which is not actually canonical, despite the name and
- the comment conceding it isn't — returns `"{}"` on serialization failure,
- meaning two unserializable identities would hash identically into the
- approval echo. `auth::random_hex` (`http/auth.rs:22-33`) ignores a failed
- `/dev/urandom` read and proceeds with a zero buffer.
-
----
-
-## 5. Per-area notes
-
-### 5.1 `db/` — foundation
-The actor design is sound (§3). The row-mapping discipline (`*_COLS` constants,
-`row_to_*` fns) is good, but `builds_for_pkgbase` (`queries.rs:617`) and
-`all_settings` (`queries.rs:13`) use `filter_map(|r| r.ok())`, silently
-dropping unreadable rows while most queries propagate — pick one policy.
-`builds.rs` is a field-by-field setter buffet (`set_release`, `set_world`,
-`set_candidate`, `set_pkgbase`, `set_profile`, `set_kind`, `set_blocked_on`,
-lines 398-450): anemic rows plus transitions smeared into callers.
-`current_state` returns `""` for a missing build (`builds.rs:455-458`) —
-"no such build" and "build in state (empty)" are different facts.
-`requeue_blocked` (`builds.rs:230-260`) runs one `SELECT count(*)` per waiting
-name per blocked build inside a write transaction (N+1); fine at this scale,
-worth a comment. `approved_but_unbuilt` (`queries.rs:970+`) re-implements
-`pkgver::full_version`'s epoch logic in SQL `CASE` — the version format now
-lives in two languages.
-
-### 5.2 `watch/` — detection
-`detect.rs::analyse` is the longest function in the crate (~150 lines, `detect.rs:107`) and
-carries the most subtle logic in the system (two-stage VCS funnel, identity
-construction, notice-vs-candidate routing). It is readable, but it would
-benefit from extracting the stage-A/stage-B resolution into a named function
-with the `Option<StageA>`/`Option<StageB>` dance inside it rather than four
-parallel `Option`s in scope. `Outcome` (`detect.rs:20-38`) mirrors
-`review::candidates::Upsert` field-for-field with an `outcome_of` converter
-(`detect.rs:292`) — one enum would do. `mirror.rs` is the cleanest module
-in the repo: `Sync` and `Tree` are exactly the right abstractions, and the
-divergence fail-closed (`mirror.rs:91-98`) is well placed.
-`staleness::dependents_of` (`staleness.rs:134-167`) is N+1 (one recipe query
-per index package) and matches on `p.name == name` for the self-exclusion but
-pushes `p.name` — it excludes *the package itself* by name equality on the
-wrong field (`staleness.rs:137-139` compares `p.name == name`, then queries
-`pk.name = ?1` with `p.name`; correct but only by accident of the filter).
-`digests.rs` overloads `skip_declared: true` for all VCS entries
-(`digests.rs:66, 122`) — "declared SKIP" and "digest is a pin, not a checksum"
-are different statements crammed into one boolean.
-
-### 5.3 `review/` — approval
-The heart of the system and mostly its best-written part.
-`upsert_candidate`'s collapse/supersede/reject-memory rules are expressed as
-one transaction with an exhaustive result enum — textbook. `diff.rs`'s
-panel-set design and `render_and_store` (`diff.rs:342`) make the
-displayed-bytes-hash invariant concrete. The problems are the error-type
-abuses in `approve.rs` (§4.2), the hand-rolled audit inserts (§3),
-`withdraw` not checking the release's current state (`approve.rs:245-264` —
-withdrawing an already-withdrawn release silently "succeeds"), and the
-duplications noted in §4.6.
-
-### 5.4 `pipeline/` + `shims/` — build & publish
-The ten-step machine with checkpoint/resume (`pipeline/mod.rs:196-260`) is
-clear and honest; `StepResult::{Done,Skipped,Blocked}` maps cleanly onto the
-step-state column. `steps.rs::collect`'s I9 symlink/containment defense
-(`steps.rs:265-290`) is the kind of paranoid check a reviewer wants to see,
-with the threat model spelled out. Issues: the two-lock confusion (§4.4),
-`extend_lease(..., 90)` hardcoding what `cfg.lease_secs` should own
-(`pipeline/mod.rs:215`), staged artifacts left in the served tree when
-`commit_release` rejects with a conflict (`publish.rs:84-96` — harmless to
-consumers, garbage forever otherwise), `SourceIdentity`'s two-phase
-initialization (`from_candidate` leaves fields empty for `Ctx::new` to fill,
-`pipeline/mod.rs:36-52, 130-140`), and the shims dependency (§3). The
-`shims/` module itself is well-built for its purpose; the problem is only that
-production code can see it at all.
-
-### 5.5 `http/` + CLI + `ops.rs`
-The read/write split (handlers read via thread-local readers, mutations go
-through the writer) is real and consistently applied. The flat route table
-(`http/mod.rs:200-247`) is fine at this size. But `routes.rs` is 1,040 lines
-mixing page rendering, mutations, CSV-ish helpers, and metrics; the auth gate
-is broken (C-1); `Req::form_get` re-parses the whole body per call
-(`http/mod.rs:46-48`); and `metrics` is unauthenticated by design
-(`http/mod.rs:207-212`) — documented and loopback-default, acceptable, but it
-should say so in the response's own docs page (`http/mod.rs:226-230`). The CLI (`main.rs`) genuinely
-drives the same `review::approve` / `pipeline::run` entry points as the UI,
-which is the claim this architecture should make and most such projects fail
-to make. `ops.rs` is cohesive; metrics-on-read (like staleness) is the right
-call and is done twice consistently.
-
-### 5.6 Leaf utilities
-`pkgver/`, `pkginfo.rs`, `recipe.rs`, `git.rs`, `fetch.rs`, `hash.rs`,
-`time.rs` are well-scoped leaf modules with no upward dependencies — except
-that `hash.rs`'s `canonical_json` misnames what it does (§6, M-2) and
-`time.rs`'s pinning is half-honored (§6, m-1).
-
----
-
-## 6. Findings (severity-ranked)
-
-Severity: **Critical** = exploitable/incorrect behavior in the default
-configuration. **Major** = structural defect that will cause bugs or block
-change. **Minor** = real defect or drift risk with limited blast radius.
-**Nit** = style/clutter.
-
-### Critical
-
-| # | Finding | Evidence |
-|---|---------|----------|
-| C-1 | **Login gate is bypassed by forging a static cookie.** `gate()` treats `Cookie: auth=1` as proof of authentication, and login merely sets that literal value. Any client can read every page (reviews, audit, settings, build logs) by sending `auth=1` without ever supplying the password. The random `sid` session machinery exists (`http/mod.rs:236-239`, `auth.rs:42-59`) but is never bound to the authenticated flag; CSRF then *re-issues* a valid session to the attacker, so even POSTs are reachable once any page is read. | `src/http/routes.rs:20` (`req.cookie("auth").as_deref() == Some("1")`), `src/http/routes.rs:50` (`Set-Cookie: auth=1`), `src/http/mod.rs:236-239` |
-
-*Fix direction:* make the session id the credential — set `sid` at login, mark
-that sid authenticated inside `auth.rs`'s session set, and gate on
-`is_valid_session(sid) && session.is_authenticated`. Delete the `auth` cookie.
-
-### Major
-
-| # | Finding | Evidence |
-|---|---------|----------|
-| M-1 | Writer actor hands raw `&mut Connection` to every module; 12 modules outside `db/` contain hand-rolled SQL (~50 write sites). The schema has no owner. | `src/db/mod.rs:144,159,177`; `src/ops.rs` (22 stmts), `src/review/approve.rs:134,187,256`, `src/pipeline/publish.rs:42-52,369-373`, `src/pipeline/mod.rs:316-323`, `src/watch/detect.rs:86-104` |
-| M-2 | `canonical_json` is not canonical (comment admits it) and returns `"{}"` on serialization failure — every failed identity hashes to the same digest, silently. This is the function behind `Identity::hash`, the value approvals must echo. | `src/hash.rs:76-78`, `src/db/model.rs:64-66` |
-| M-3 | `approve()` converts *all* internal errors (incl. SQLite) into `Stale::NotPending`; `bulk()` reuses the same variant for high-risk refusal and unknown decision, and fabricates `Approval { id: 0 }` for rejects. Callers cannot distinguish "stale review" from "database broken". | `src/review/approve.rs:153, 216, 222-224` |
-| M-4 | Production publish path depends on the test-shim module and its duplicate `.PKGINFO` parser (second parser can drift from `pkginfo.rs`). | `src/pipeline/publish.rs:353`, `src/shims/mod.rs:568-576`, `src/pkginfo.rs:61-71` |
-| M-5 | Two static locks (`REPO_LOCK`, `PUBLISH_LOCK`) each documented as *the* publish serialization guarantee; `withdraw_package` takes only one of the two. | `src/pipeline/publish.rs:25,64,67,99,397` |
-| M-6 | Layer inversion: `db/queries.rs` returns `watch::upstream::StageB`, making persistence depend on a domain module. | `src/db/queries.rs:641,670,699` |
-| M-7 | Module-group cycle: `watch` → `review` (candidates, risk) and `review` → `watch` (digests). | `src/watch/detect.rs:14,113,258-266`; `src/review/risk.rs:74` |
-| M-8 | State machines are `&str` constants with no transition validation; `builds::set_state` writes any string. The build state machine exists only as scattered `WHERE state IN (...)` clauses. | `src/db/model.rs:70-135`, `src/db/builds.rs:195-207` |
-| M-9 | Test hooks are part of the production API surface: fault injection branches in the publish hot path, shim env vars in `Config`, thread-local clock pinning — none gated or marked. | `src/config.rs:62-83`, `src/pipeline/publish.rs:115,146`, `src/time.rs:26-38` |
-
-### Minor
-
-| # | Finding | Evidence |
-|---|---------|----------|
-| m-1 | `secs_ago`/`secs_ahead` ignore the pinned clock that `now()` honors — a pinned-clock test computes real-clock lease expiries. | `src/time.rs:62-70` vs `src/time.rs:14-19` |
-| m-2 | `hosts()` duplicated verbatim; "PKGBUILD body changed" heuristic duplicated with *different* semantics between the diff panel and risk scoring. | `src/review/diff.rs:226` / `src/review/risk.rs:220`; `src/review/diff.rs:196-214` / `src/review/risk.rs:197-215` |
-| m-3 | 21-column candidate `SELECT` copy-pasted 4× despite the `*_COLS` convention used everywhere else in `db/`. | `src/review/candidates.rs:149,181,201,243` |
-| m-4 | Audit rows hand-inserted in three places with three different detail shapes, bypassing `db::audit`. | `src/review/approve.rs:134,187,256` vs `src/db/queries.rs:53` |
-| m-5 | `mark_approved_but_unbuilt` is a documented no-op; the real mechanism is a derived query. Misleading during failure-path tracing. | `src/pipeline/mod.rs:236-241,272-274` |
-| m-6 | `extend_lease` hardcodes 90s instead of `cfg.lease_secs`. | `src/pipeline/mod.rs:215` |
-| m-7 | `fsync_file`/`fsync_dir` swallow all errors in the module whose guarantee is "fsync then rename". | `src/pipeline/publish.rs:316-329` |
-| m-8 | Dead parameters / `let _ =` debris across six modules. | `src/watch/upstream.rs:262`, `src/review/risk.rs:113,178,243`, `src/watch/detect.rs:103`, `src/review/diff.rs:254`, `src/http/mod.rs:263` |
-| m-9 | `setting_i64` maps DB errors to defaults; `filter_map(\|r\| r.ok())` silently drops unreadable rows in some queries but not others. | `src/db/queries.rs:29-35,13-20,617-635` |
-| m-10 | `withdraw` does not check the release's current state; re-withdrawing silently succeeds. | `src/review/approve.rs:245-264` |
-| m-11 | `schedule_next` re-queries with raw SQL a value the caller already had (`sub.poll_interval_secs`). | `src/watch/detect.rs:86-104`, `src/watch/scheduler.rs:47-51` |
-| m-12 | `current_state` returns `""` for a nonexistent build. | `src/db/builds.rs:455-458` |
-| m-13 | `random_hex` proceeds with a zero buffer if `/dev/urandom` read fails. | `src/http/auth.rs:22-33` |
-| m-14 | `is_transient` classifies every `Io` error (incl. ENOSPC/EACCES) as retryable. | `src/error.rs:73-77` |
-| m-15 | `Config::load/save` use `anyhow::Result` while the rest of the crate uses `error::Error`. | `src/config.rs:125,140` |
-| m-16 | Publish leaves staged artifacts in the served tree when `commit_release` rejects (conflict path). | `src/pipeline/publish.rs:84-96` |
-| m-17 | N+1 query patterns: `dependents_of`, `requeue_blocked`. | `src/watch/staleness.rs:134-167`, `src/db/builds.rs:230-260` |
-| m-18 | Version formatting duplicated between Rust (`pkgver::full_version`) and SQL `CASE` in `approved_but_unbuilt`. | `src/db/queries.rs:970+` |
-| m-19 | `digests.rs` overloads `skip_declared: true` for VCS entries (means "digest is a pin", not "declared SKIP"). | `src/watch/digests.rs:66,122` |
-
-### Nit
-
-| # | Finding | Evidence |
-|---|---------|----------|
-| n-1 | `SourceIdentity::from_candidate` returns a half-initialized value completed by `Ctx::new`. | `src/pipeline/mod.rs:36-52,130-140` |
-| n-2 | `watch::detect::Outcome` mirrors `review::candidates::Upsert` with a hand-written converter. | `src/watch/detect.rs:20-38,292` |
-| n-3 | `Req::form_get` re-parses the entire body per call. | `src/http/mod.rs:46-48` |
-| n-4 | `routes.rs` is 1,040 lines mixing pages, mutations, and formatting helpers. | `src/http/routes.rs` |
-| n-5 | `enqueue_manual_rebuild` invents its own identity string format (`aur_commit|recipe_hash|manual`) distinct from candidate identities. | `src/pipeline/mod.rs:295-298` |
-| n-6 | `recipe_at` is `pub` though only used inside `steps.rs`. | `src/pipeline/steps.rs:435` |
-
----
-
-## 7. Prioritized recommendations
-
-1. **Fix C-1 now.** Bind authentication to the random session id inside
- `auth.rs` (session set → set of authenticated sids); gate on the sid;
- delete the `auth=1` cookie. ~30 lines, entirely inside `http/auth.rs` +
- two call sites. Add a test that a hand-crafted `Cookie: auth=1` gets 302.
-2. **Make `canonical_json` honest** (M-2): rename to `digest_json`, propagate
- the serialization error instead of `"{}"`, and (cheap) serialize through a
- `BTreeMap`-normalizing value so the name could eventually be true.
-3. **Give the schema an owner** (M-1): move the ~40 stray SQL statements into
- `db/queries.rs`/`db/builds.rs` (mechanical), then mark `Writer::call/tx/send`
- `pub(crate)` so future SQL must land in `db/`. Same trick for the shims
- dependency (M-4): point `publish.rs::package_name` at `pkginfo::pkginfo_text`,
- delete `shims::read_pkginfo`/`parse_pkginfo`, and make `shims` a
- `pub(crate)`-visible test module (or move it under `tests/` support).
-4. **Repair the approve error channel** (M-3): `approve()` should return
- `Result<Approval, ApproveError>` where `ApproveError = Stale(Stale) |
- System(Error)`; give `bulk()` its own refusal reasons instead of
- `Stale::NotPending` overload; return `Option<Approval>` (or nothing) for
- rejects.
-5. **Pick one publish lock** (M-5) and say so in one comment.
-6. **Break the two dependency cycles** (M-6, M-7): move `StageB` (or a plain
- `StageBCacheRow`) into `db/model.rs`; move `skip_on_non_vcs` into `recipe.rs`
- (it is a recipe question, not a watcher question) — both are one-file moves
- that make the layering a DAG.
-7. **Enum-ify the state machines** (M-8), starting with `build_state`: parse at
- the row boundary, expose `fn can_transition(from, to) -> bool`, and replace
- `set_state(&str)` with typed transitions. This is the largest change on the
- list; do it after 1-6.
-8. **Gate the test hooks** (M-9): a `#[serde(default)] TestHooks` submodule of
- `Config` documented as test-only (or a cargo feature), and honor the pinned
- clock in `secs_ago`/`secs_ahead` (m-1).
-9. **De-duplicate**: `hosts()` → `pkgver` or a small `urlutil`; one shared
- `pkgbuild_bodies()` used by both `diff.rs` and `risk.rs` (m-2); a
- `CANDIDATE_COLS` constant (m-3); route all audit writes through `db::audit`
- (m-4).
-10. **Sweep the minors** in whatever order they cross your path: delete the
- no-op (m-5), use `cfg.lease_secs` (m-6), propagate fsync errors (m-7),
- remove dead params (m-8), decide the row-error policy (m-9).
-
----
-
-## 8. Verdict
-
-The domain design is strong — the approval-echo/hash/CAS chain is a coherent
-mechanism for the invariant it serves, and the crash-recovery story (leases +
-reaper-first dispatcher loop + step checkpoints) is better than most systems
-three times this size. What the codebase lacks is *enforcement*: the boundaries
-everyone clearly has in mind (schema lives in `db/`, shims are test-only, states
-have legal transitions, sessions are secrets) are conventions that any future
-commit can violate without a compiler complaint. The fix list is mostly small,
-mechanical, and in the code's own style. Fix C-1 today; the rest will make the
-next hundred commits safer.
diff --git a/Cargo.toml b/Cargo.toml
index 91843cd..3290225 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,7 +21,7 @@ name = "sandbox-agent"
path = "src/bin/sandbox-agent.rs"
# ---------------------------------------------------------------------------
-# Toolchain shims (DESIGN.md §16a). These are real binaries with the exact names
+# Toolchain shims. These are real binaries with the exact names
# the pipeline shells out to; the test harness prepends their directory to PATH
# so the whole step machine runs without root, network or an Arch chroot.
#
diff --git a/DESIGN.md b/DESIGN.md
deleted file mode 100644
index 6d64ff8..0000000
--- a/DESIGN.md
+++ /dev/null
@@ -1,1279 +0,0 @@
-# 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 `<meta refresh>` 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/<pkgbase>/ ← git clone https://aur.archlinux.org/<pkgbase>.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 <accepted.aur_commit>..<candidate.aur_commit>
-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/<pkgbase> worktree add --detach <builddir> <aur_commit>
- (or: git archive <aur_commit> | tar -x -C <builddir>)
-verify: recompute recipe_hash over <builddir>; 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=<pkgbase>&id=<sha>`, 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=<sha>`.
-
-**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 <accepted_aur_commit>..<candidate_aur_commit>` |
-| 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 <builddir> <aur_commit> (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 <admissible>;
- 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/<build_id>/` 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 <keyid> -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<T>`. 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 `<form method=post>` 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=<sha>`. 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.
diff --git a/README.md b/README.md
index 4d75386..b020ebe 100644
--- a/README.md
+++ b/README.md
@@ -4,14 +4,9 @@ A build server for AUR packages: it watches recipes, shows a human what changed,
and publishes a signed pacman repository containing **only what a human
approved**. One process, no async runtime, no external services.
-The design is in [`DESIGN.md`](DESIGN.md). The invariants it must never violate
-are in [`docs/INVARIANTS.md`](docs/INVARIANTS.md), each mapped to a named test.
-Judgement calls where the design left an opening are in
-[`docs/DECISIONS.md`](docs/DECISIONS.md).
-
## The rule everything else follows
-Nothing reaches a consumer without an `approval` row behind it (I1). Every other
+Nothing reaches a consumer without an `approval` row behind it. Every other
behaviour is downstream of that: the review page freezes the exact bytes a human
looked at and hashes them, the approve request must echo both hashes, the build
re-checks the recipe pin and the resolved version before it runs, and publish
@@ -98,13 +93,12 @@ src/
testcorpus/ the fixture packages the tests build for real
templates/ askama templates, server-rendered
static/ app.css and one vendored htmx
-docs/ DECISIONS.md, INVARIANTS.md
```
## Testing without root, network, or a real chroot
`cargo test` runs the whole thing on an ordinary user account. Two mechanisms
-make that possible (§16a):
+make that possible:
* **PATH shims.** `src/bin/` contains `makepkg`, `pacman`, `repo-add` and
`gpg` — the tools the pipeline actually shells out to now that builds run
@@ -132,7 +126,7 @@ process mid-step, and a separate test spawns the compiled binary and kills *it*,
then asserts a fresh process resumes from the step checkpoints with no duplicate
work and the old index still byte-identical.
-The sandbox seam (§8a of the design) is tested the same way — the interface is
+The sandbox seam is tested the same way — the interface is
executed, not mocked: `tests/remote_agent.rs` drives a **full build over the
real agent protocol** (frames, rendezvous, log streaming, blob round-trip,
bad-token refusal) against the shims on a loopback socket, and
@@ -154,8 +148,7 @@ than failing:
and compares the hand-written comparator against it over ~1100 pairs.
* The live kata tier needs `/dev/kvm` and a cluster (`AUR_KATA_API`); the kata
rendezvous and TTL logic itself runs everywhere via a real `sandbox-agent`
- process with no VM. The old real-chroot tier retired with devtools; what it
- caught is recorded in `docs/DECISIONS.md` rather than silently absent.
+ process with no VM. The old real-chroot tier retired with devtools.
## Operations
@@ -194,12 +187,12 @@ at all; a test greps the rendered page for `<script` to keep it that way.
Approve is a POST carrying `identity_hash` and `diff_digest`. If either no
longer matches what the candidate became while the reviewer was reading, the
server answers **409** and re-renders the current state, so a reviewer can never
-approve bytes they did not see (§7.1a). Every POST requires a CSRF token bound
+approve bytes they did not see. Every POST requires a CSRF token bound
to the session; the whole site is gated behind a password by default.
## Constraints this codebase keeps
-From §14, and they are not suggestions:
+These are not suggestions:
* No `async`/`await`, no tokio. Threads and crossbeam channels; blocking HTTP
with `tiny_http`, outbound HTTP with `ureq`.
@@ -212,4 +205,4 @@ From §14, and they are not suggestions:
* Fail closed. A pin that does not match, a recipe hash that drifted, a package
with no signature, a symlink in the srcdir: the build stops and says why. A
change that is real but not publishable becomes a `notice` — never a candidate,
- never silently dropped (I11).
+ never silently dropped.
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
deleted file mode 100644
index 32daa8c..0000000
--- a/docs/DECISIONS.md
+++ /dev/null
@@ -1,511 +0,0 @@
-# Decisions
-
-Choices made where DESIGN.md left an opening (§19), or where following the letter
-of the design would have been worse than following its intent. Each entry states
-the pressure, the choice, and what it costs.
-
----
-
-## Vendored JavaScript: htmx 1.9.12, served precompressed
-
-The design budgets "vendored htmx (~14 KB)". Real htmx is not that size: 1.9.12
-is 48 KB minified, and no released build of htmx is under 20 KB. The budget was
-an estimate, not a constraint with a reason attached to it, and the reason it
-was written — do not let a build step and a JavaScript dependency creep in — is
-fully satisfied by vendoring one unmodified upstream file.
-
-**Choice.** Vendor `htmx.min.js` unmodified, plus a precompressed `.gz` beside
-it, and serve the gzip to clients that accept it. The budget is enforced on
-**served bytes**, which is what a browser actually downloads: 15.6 KB, asserted
-by a test that reads the wire with a bare socket rather than an HTTP client that
-would transparently decompress and hide the number.
-
-**Cost.** Two copies of one file in the repo, and a budget that has to be stated
-as "on the wire" rather than "on disk". A reviewer who wants to audit the JS can
-read the upstream file; the test asserts the served copy decompresses to it.
-
-## No JavaScript on the review surface, and no SSE extension
-
-htmx ships an SSE extension, and the obvious move was to wire the build log
-stream into the page with it. Not done, for two reasons:
-
-- It swaps with `innerHTML`, and a build log is untrusted text produced by a
- PKGBUILD someone else wrote. Wiring it up would be an XSS hole opened
- specifically to make a log scroll by itself.
-- It would add 3 KB gzipped to a budget the base library already nearly spends.
-
-**Choice.** The review flow ships no JavaScript at all — asserted by a test that
-greps the rendered review page for `<script`. The log tail is a real endpoint
-(`/builds/:id/log.stream`, server-sent events, tested end to end) and the page
-links to it; the builds table refreshes by htmx polling, which degrades to "press
-reload".
-
-## `identity_hash` is a digest, not the canonical JSON
-
-`Identity::hash()` originally returned the canonical JSON of the identity tuple.
-That is an identity token, but it is not a hash, it is large, and it contains
-quotes — so it could not survive an HTML attribute round-trip, which is exactly
-what the approve form needs (§7.1a requires the form to carry it back).
-
-**Choice.** `hash()` returns `sha256:<hex of the canonical JSON>`. The JSON stays
-internal; the token is what a form can carry and what a comparison can be made
-on.
-
-## The reaper reaps `running`, not only `leased`
-
-§8.2 writes the reaper as
-`UPDATE build SET state='queued' WHERE state='leased' AND lease_expires_at < now()`.
-A worker sets `state='running'` the moment it starts a step, so a process that
-dies mid-step leaves a `running` row — and following the design literally would
-strand every real crash forever. Found by the SIGKILL test in `tests/crash.rs`.
-
-**Choice.** The reaper matches `state IN ('leased','running')`.
-
-## Paused subscriptions are not observed at all
-
-The design has `paused` as a subscription state but does not say what the watcher
-does with it. Polling a package nobody will act on wastes requests and keeps
-opening reviews nobody will read.
-
-**Choice.** `check_pkgbase` returns `Outcome::Paused` before it touches the
-network. Pausing is a statement that we are not looking.
-
-## Staleness is computed on read, never stored
-
-§10.2 asks for this and the code follows it exactly: there is no `stale` column.
-A stored flag goes wrong the moment anything else is published, and something else
-is always being published. Deriving it from the recorded world snapshots against
-the live index means it cannot lie, at the cost of a query per page view.
-
-## Downgrades are an announcement, not a build request
-
-When AUR offers a lower version than we serve, nothing should be rebuilt and
-nothing should be withdrawn automatically — a human has to decide whether the
-mirror or the upstream is wrong. The row appears on Attention with both versions
-and no action button.
-
-## The test hooks are a gated submodule, not fields on `Config`
-
-`publish_fault`, `shim_fail`, `shim_kill_parent` and their siblings exist only so
-the harness can reproduce failures it cannot otherwise cause: a crash between the
-rename and the signature, a tool that exits non-zero, and a process killed
-mid-step with a signal it cannot catch. The alternative — an in-process
-simulation of a crash — can be caught and cleaned up by accident, which is
-precisely what I5 must not allow.
-
-They are no longer seven `Option` fields on the production `Config`, and the
-branches that consult them are no longer compiled into the binary at all. Under
-the default features there is a `TestHooks` type with no fields, the shims and
-their binaries do not exist, and `Config::child_env` exports nothing; the fault
-branches in `publish` are `#[cfg]`-ed away rather than guarded by a runtime
-`if`. A production binary that carries its own fault injection is a binary in
-which someone will eventually ask whether a fault can be triggered from the
-network, and the honest answer will be "not today".
-
-**Cost.** The test harness depends on the crate with `features = ["test-support"]`,
-so `cargo test` and `cargo build` compile slightly different libraries — which is
-the point, and is why `production_surface.rs` asserts the default build is clean.
-
-## CAS baseline comes from the candidate, not from the live pointer
-
-At publish time the compare-and-swap compares against the `base_release_id`
-recorded on the candidate, not against `pkgbase.current_accepted_release_id` as
-it reads it then. If they differ, someone accepted a newer version while this
-build was running, and publishing over it would silently drop a human decision.
-
-## One publisher lock per process, not a queue
-
-§8.2 says the publish step goes through the publisher's single-thread channel.
-With `max_concurrent_builds > 1` two workers could otherwise interleave the index
-rewrite. A `static Mutex` around `publish()` gives the same guarantee with less
-machinery; the critical section is the db file rewrite, never a build. The lock
-poison is cleared deliberately: atomic publish means a panic cannot have left a
-half-written db, so wedging the queue would be worse than continuing.
-
-There is now exactly one such lock, `REPO_LOCK`, taken at the top of `publish()`
-for the whole sequence — file rewrite, signature, index update — and by
-`withdraw_package`, which rewrites the same files. There used to be a second one
-(`PUBLISH_LOCK`) covering a shorter span inside the first, which gave the
-appearance of a second serialization point and would have been the natural place
-for the next writer to acquire the wrong one. A test fails if a second lock
-guarding the served index appears.
-
-## The session id is the credential, not a cookie the client controls
-
-Login used to set `auth=1`, so the secret was the *name* of a cookie and anyone
-who could type `Cookie: auth=1` was the reviewer. Sessions are now a map the
-server owns — a random sid minted at login, marked authenticated only in the
-server's table — and the cookie carries the sid and nothing else. Logging in
-rotates the sid, so a session id that a previous identity might have leaked is
-useless after a re-login; logging out deletes the entry, so the id stops working
-rather than being re-interpreted.
-
-**Cost.** Sessions are per-process and lost on restart, so a server restart signs
-everyone out. For a single-operator tool that is a feature: the same restart that
-reloads the binary also revokes every session it was running under.
-
-## `db/` is a boundary, and the writer does not hand out connections
-
-Every SQL statement in the crate lives in `db/`. `Writer::call`, `tx` and `send`
-are `pub(crate)`, and the raw door the test harness needs exists only under
-`test-support`. A module that needs the database asks `db/` for a typed query;
-if the query does not exist, writing it is the change to make.
-
-**Cost.** `db/` is large, and a one-off ad-hoc query now costs a function instead
-of a line. That is the trade: the schema's shape is knowable from one directory,
-and a grep for a table name finds every reader of it.
-
-## A stale review and a broken database are different answers
-
-`approve()` used to return an `Approval` with `id: 0` when the transaction
-failed, which the UI then rendered as "someone else got there first" — telling a
-reviewer their click lost a race it did not lose, and hiding an I/O error behind
-a message that invites them to retry. It returns `Result<Approval, ApproveError>`
-now, with `Stale` (the review moved: 409, re-render the current diff) kept apart
-from `System` (the database failed: 500, name the cause). `bulk()` answers the
-same way, per row.
-
-## The shims are test-only, and the real `.PKGINFO` parser is the only one
-
-The publish path used to read a package's name out of the archive with a
-simplified parser that the shim harness also had a copy of, which meant
-production was tested against a model of the format rather than the format. There
-is one parser (`pkginfo::parse_pkginfo`), the shims are behind `test-support`,
-and the shim binaries are not built by default.
-
-## States are enums, and writing one is a compare-and-swap
-
-`build.state`, `candidate.state`, `step.state`, `release.state` and
-`subscription.state` were free text, and `current_state` returned `""` for a
-build that did not exist. They are five enums now, parsed at the row boundary — a
-state the code does not define is an error, not a default — and every transition
-is a conditional update (`WHERE state IN (…)`), so a worker whose lease expired
-finds its write refused instead of quietly overwriting the state of the build
-somebody else now owns. A zombie finishing a live build is the failure mode this
-prevents, and it is silent in the old shape.
-
-**Cost.** The transition table is real code that has to be kept honest with the
-schema, and `failed → running` is legal (I5 says a failed build resumes on its
-own row), which is not obvious and is commented where it is defined.
-
-## A row that cannot be read fails the query
-
-`filter_map(|r| r.ok())` was used in some queries and not others, so a row that
-failed to deserialize was sometimes skipped and sometimes an error — and the
-skips were invisible. The policy is now uniform: if a row cannot be read, the
-query fails. A silently missing package is worse than a failed page, because the
-missing package looks like an absent one. `setting_i64` is the one documented
-exception, because a *setting* falling back to its default is the designed
-behaviour, not a lost row.
-
-## Only momentary I/O is transient
-
-`is_transient` classified every `Io` error as retryable, so ENOSPC and EACCES
-were retried with the same backoff as a connection reset — a full disk produced a
-build that retried until it gave up, blaming a network that was fine. Retryable
-now means the kinds that can genuinely pass on the next attempt: would-block,
-timed out, interrupted, broken pipe, connection reset/refused/aborted.
-
-## The pipeline refuses symlinks in the srcdir, even though a chroot should make that moot
-
-`collect` scans the build's srcdir for `*.pkg.tar.zst`, and `ingest` copies
-whatever those paths resolve to into the content-addressed store — from where
-the bytes are served from our repo and signed with our key. The paths are ours
-(the scan generates them) but their *targets* are not: a PKGBUILD that drops a
-symlink named `evil.pkg.tar.zst` pointing at the signing keyring, the database,
-or anyone's home directory would have its target copied in and published.
-
-**Choice.** `collect` rejects any entry that is a symlink, and any entry whose
-canonicalized target escapes the build's own staging directory. The build fails
-closed with the path in the message. `tests/invariants.rs::i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir`
-acts the attack out through a shim hook rather than arguing it is unlikely.
-
-**Cost.** A legitimate build that stages a package outside its srcdir and
-symlinks it in now fails. That is a build we want to fail: it is telling us the
-recipe does something we cannot see the whole of.
-
-**Why this is not a substitute for the chroot.** I9's real enforcement is
-isolation, and that tier is gated. This is the narrower claim that the control
-plane does not *depend* on isolation for its own secrets — the layers should not
-be load-bearing on each other.
-
-## Metrics are served without a session
-
-Everything else in the UI is behind a password. `/metrics` is not, because a
-Prometheus scraper has no session to present, and the alternative — teaching the
-scraper to log in and hold a cookie — puts a credential in a monitoring config
-to protect numbers.
-
-**Choice.** `/metrics` returns counts only: queue depth, review debt and its age
-histogram, build success rate, WAL size, index size, stale counts by reason,
-staging usage. No package names, no versions, no audit detail, no paths. The
-bind address is loopback by default, which is where that is safe; anyone exposing
-it further is exposing their own choice of numbers, not their recipe history.
-
-**Cost.** A visitor on the host can see how busy the server is. If that ever
-matters, the fix is a scrape token, not a session.
-
-## Retention records a purge instead of deleting the row
-
-The schema exists so that "which bytes produced this installed package" stays
-answerable years later (§11a). Disk cannot be kept forever, so something has to
-give, and the honest option is to let the *bytes* go while the *record* stays.
-
-**Choice.** Eviction deletes the package, signature, build log and cached
-sources of releases beyond the keep window — as a unit, because a package whose
-log is gone but whose bytes remain is full price for no explanation — and sets
-`purged_at` on the release and its artifact rows. The digest and size survive, so
-the database says "these bytes existed, hashed to this, and were dropped at T"
-rather than continuing to claim a file that is no longer there. Shared
-content-addressed files are reference-checked against every *retained* release
-first: two releases built from the same source share one cached archive, and
-aging one out must not corrupt the other.
-
-**Cost.** A `purged_at` column on two tables, and a UI that has to say "bytes no
-longer held" rather than offering a download that 404s.
-
-## The real-chroot tier: what was actually run, and where it stopped
-
-§16a gates the tier that needs root, network and devtools. It was not skipped
-for lack of trying; it was run on a host with all three, and here is how far it
-got.
-
-**What passed with the real tools.** Real `gpg` (a generated 2048-bit RSA key)
-detached-signed the artifact the pipeline produced, and `gpg --verify` reported a
-good signature. Real `repo-add -s -k` built a pacman database over that artifact
-and signed it, and that signature verified too. So the claim "both the packages
-and the `.db` are signed" is checked against real crypto, not the shim's fake
-key.
-
-**What the attempt caught.** `mkarchroot` has no `-N` flag. The pipeline was
-calling `mkarchroot -N <seed>`, which the shim accepted (it ignores unknown
-flags) and the real tool rejected with a usage error — so the first real chroot
-build would have died on its very first step, in a code path no shim test could
-ever have caught. The seed's package list is now configuration
-(`mkarchroot_args`, default `base`) and the call follows the real usage,
-`mkarchroot <working-dir> <packages...>`.
-
-**Where it still stops.** `mkarchroot <dir> base` against a live mirror
-downloaded and installed the base set into the chroot (437 MB, 14 packages,
-install scripts ran), then failed in devtools' init stage with
-`Failed to parse --bind(-ro)= argument : Invalid argument` from
-`systemd-nspawn` 262, and with `etc/pacman.conf` unreadable inside the root.
-That is a devtools/nspawn interaction inside an unprivileged container, not
-something this codebase controls.
-
-**What therefore remains unverified by execution:** `makechrootpkg`'s
-copy-on-write snapshot semantics, `systemd-nspawn` isolation behaviour, and GPG
-passphrase handling through a real agent. The shim tier drives the *unmodified*
-pipeline against fake tools that produce real archives, and the crash tests kill
-real processes with real signals, so the step machine, the checkpoints and the
-publish path are all exercised for real — it is the chroot boundary itself that
-is modelled rather than crossed.
-
-**How to run it properly.** A privileged Arch host (or a container with the
-nspawn capabilities devtools expects), devtools installed, a real signing key,
-`signing_key_id` set, `path_prepend` left unset so the real tools are found, then
-subscribe to a real pkgbase and drive it through `aur-build serve`.
-
-## Signing moved from the build step to hub-side ingest
-
-The build step used to pass `-si<key>` through to `makepkg`, which meant
-whatever machine ran the build had to hold the signing key. That was survivable
-when the build was a chroot on the hub; it disqualifies every form of remote or
-disposable build sandbox, because a machine executing untrusted PKGBUILD code
-must never be a machine that can mint our signatures.
-
-**Choice.** The build produces unsigned bytes. `ingest` signs the exact bytes
-that entered the store, with the same key and the same code path that signs the
-database (`publish::sign_to`), and a gpg failure fails the build closed.
-`verify` no longer checks for a build-made signature — the meaningful guarantee
-moved to "ingest produced one or the build failed." The shim `makechrootpkg`
-now emits `.sig` only when `-si` is passed, like the real tool, so the suite
-cannot accidentally test a signing path the pipeline no longer has. A test
-asserts both halves: zero `-si` on any build invocation, and the signature
-ingest recorded was made over the stored artifact's bytes.
-
-**Cost.** The artifact is unsigned between build and ingest — a window that
-matters not at all here (staging is hub-local and ingest re-hashes) but must
-never be widened by moving ingest off-hub. And a rebuild of a stored artifact
-re-signs it with the *current* key, which is correct but worth knowing.
-
-## The devtools chroot is gone: the sandbox is the isolation boundary
-
-§8.3 bought isolation with `mkarchroot` + `makechrootpkg`, which costs a sudo
-requirement on the build host — and DECISIONS' own real-chroot entry records
-that stack failing inside containers anyway (`systemd-nspawn` bind-arg errors).
-Once the build runs in a disposable sandbox — a Kata VM, a throwaway container,
-the loopback harness — the chroot is scaffolding inside a boundary that already
-does the job, and I9 gets *stronger*: the untrusted build never touches the
-kernel that runs the hub.
-
-**Choice.** No `mkarchroot`, no `makechrootpkg`, no nspawn, anywhere in the
-pipeline. The build step is plain `makepkg -c -f`: no `-s` (dependencies
-arrive installed; resolving them at build time is what the pinning model
-forbids) and no `-si` (see the signing entry). The step id stays `chroot` in
-the checkpoint table — the DB does not care what the string means, and
-renaming would strand every existing checkpoint row. The devtools shims stay
-in the test tier as stand-ins for the real tools so the shim protocol itself
-remains exercised, but nothing in `src/pipeline` names them.
-
-**Cost.** The "must build in a clean chroot" folklore has a real tail: some
-PKGBUILDs assume `makechrootpkg` conventions (`$PKGDEST`, non-root builder).
-A per-build disposable VM bootstrapped from a pinned base is at least as clean
-— this is how OBS builds distro packages — but expect the tail to show up in
-the gated real-build tier, and budget for `-e` shims there.
-
-## Dependencies arrive pinned by digest via `pacman -U`, not resolved
-
-A sandbox that runs `pacman -Sy` at build time re-resolves against live mirrors
-*after* `plan()` approved a world — a path from "mirror moved since review" to
-"we built it anyway," which is exactly what the fail-closed posture forbids.
-
-**Choice.** The provisioning step (step id `chroot`) builds a **lease
-manifest**: every dependency this build needs that we publish, pinned to the
-exact version and digest of the artifact the index serves
-(`db::index_artifact`). The hub re-hashes every blob before staging it into
-the sandbox, installs with `pacman -U` — no repo DBs, no `Server=`, no mirror
-at build time — and the sandbox's own `pacman -Q` must confirm the pinned
-world landed, or the build fails closed with a dedicated `WorldMismatch`
-error class. Official packages are the base image's business: they arrive
-with the sandbox, and hub-side caching of official artifacts (which also
-solves mirror-rot and mirror etiquette) is recorded as future work, not
-pretended to.
-
-**Cost.** The lease covers only what we publish; pinning the official set
-end-to-end needs the hub's official-repo cache, which is not built. And
-`pacman -U` does no dependency resolution — an incomplete closure fails with a
-world mismatch rather than being helpfully fetched, which is correct here but
-depends on `plan()` computing the closure honestly. The shim `pacman` models
-all of this for real: `-U` refuses bytes that do not hash to the digest their
-name claims, and `-Q` reports exactly what landed.
-
-## repo-add names the database; the render happens in scratch space
-
-Publishing needs the index rendered *before* the DB transaction commits and
-renamed into place *after* it, so a crash between the two leaves the old index
-serving (I4). The obvious way to get that was to render to `<db>.tar.gz.tmp`
-beside the live file and rename over it. That is also a filename real `repo-add`
-refuses: its database argument has to be a name pacman would itself accept, and
-a trailing `.tmp` is a usage error to it. Every publish test passed and the first
-real package anyone tried to publish died at the last step, with the database
-already committed and the served index untouched.
-
-**Choice.** `render_db` renders into a scratch directory *under* the served
-directory — `.render-<pid>-<n>-<tag>/` — under the exact name a consumer will
-download. Same filesystem, so the caller's `rename` is still the atomic swap I4
-requires, and the live database is never the file repo-add is writing into. The
-scratch directory is removed on every path this code controls, and
-`reconcile` sweeps leftovers at startup for the paths it does not. `run_repo_add`
-also dropped `-s`: repo-add would sign the database into scratch space that is
-about to be deleted, and `publish::sign` signs the renamed file — one key, one
-code path, signature always over the bytes that shipped.
-
-**Cost.** Three call sites (`publish`, `reconcile`, `withdraw_package`) now share
-the render helper instead of each doing its own tmp-and-rename, and a publish that
-dies between render and rename leaves a directory for the next startup to sweep
-rather than a single stray `.tmp` for a human to notice.
-
-## A shim is as strict as the tool it replaces, or it is not a test of it
-
-The `repo-add` shim wrote the database wherever it was told to. The real tool
-validates the filename first. That asymmetry is the whole reason the previous
-entry was possible: 200+ tests drove a real subprocess through a real publish and
-reported success, because the fake accepted what the real thing rejects.
-
-**Choice.** The shim enforces the accepted set — `.db.tar` with or without a
-compression suffix, nothing else, `.files.*` included in the refusals because
-those belong to `repo-files` — with the real tool's wording and exit status. The
-set was measured against `repo-add (pacman) 7.1.0`, not read out of its docs, and
-`shims::repo_add_db_names_match_the_real_repo_add` re-derives it against the
-installed tool whenever there is one, in the shape of the `vercmp` oracle test.
-The same rule already holds elsewhere — the `pacman` shim refuses bytes that do
-not hash to the digest their name claims — this is that rule, applied where it was
-missing.
-
-**Cost.** The shim now rejects things the pipeline might one day want to do, and
-the rejection has to be updated if pacman's rule changes. That is the correct
-failure: a shim drifting from its tool should break a test loudly, not let a
-production path go untested.
-## The root is the directory `config.json` lives in
-
-`--root` selects a directory and `init` writes `config.json` inside it, so the
-root is already named by the location of the config. The `root` field in the file
-was treated as a second source of truth: a relative one was re-joined onto the
-config's own directory, and `init` saved whatever it had been handed. So
-`--root runtime` wrote `"root": "runtime"`, and every command after `init`
-resolved that to `runtime/runtime/` — a second tree, with its own empty database,
-while `init` had created and migrated the first one. Compounding it, the CLI fell
-back to a default config whenever loading failed, so a typo'd `--root` produced a
-fresh empty server that answered every command as if it were the real one.
-
-**Choice.** `Config::load` sets the root to the directory it found the config in,
-absolutized; the field in the file is a record for whoever is reading the tree,
-and `save` writes it absolute so it stays readable. A missing config is an error
-for every command except `init`, which is the only one that runs before one
-exists.
-
-**Cost.** A hand-edited absolute `root` in a config file no longer relocates a
-tree — you move the directory and point `--root` at it, which is how the CLI
-already worked. And an existing tree that was already split by the doubling keeps
-its two databases until someone notices and moves the rows; the fix stops the
-bleeding rather than reconstructing what went into the wrong tree.
-
-## The sandbox backend is a tagged enum, and an unwired kind is an error
-
-`sandbox_backend` was a string, and `backend_for` matched it with `_ => loopback`.
-The design documents a Kata backend, so `sandbox_backend = "kata"` was a
-configuration an operator could write in good faith — and it meant "run the
-untrusted PKGBUILD as the hub's own user", silently. There was no validation of
-any kind in the crate: an empty `agent_token`, a missing listen address, a
-half-filled cluster coordinate set, all parsed and failed later as something
-else.
-
-**Choice.** One `sandbox` object, three kinds — `loopback`, `remote`,
-`agent-sandbox` — internally tagged, `deny_unknown_fields`, required fields
-required by the type rather than by a validation pass someone must remember.
-An unknown kind is a parse error naming the value and the valid set; a misspelled
-field is named rather than read as absent. `Config::validate` catches what a type
-cannot see (a field present but empty) and runs both at startup and wherever a
-backend is constructed, so nothing that builds one can skip it. Retired flat keys
-are refused when they carry intent — a config saying `"remote"` errors and names
-the replacement — while the `"loopback"` plus empty strings that `init` used to
-write is noise, not intent, and keeps loading. `agent-sandbox` parses, validates,
-and builds a real `KataBackend` over `K8sSandboxProvisioner`; the
-containerd/`nerdctl` payload builder is deleted rather than left as a route the
-configuration refuses.
-
-Two consequences of "actually reachable from config" needed fixing on the way.
-The agent listener was bound per build, because `Ctx::new` constructed a backend
-per build, so a second concurrent build on a fixed `listen` died of `EADDRINUSE`
-— the listener is now shared per `(address, token)` for the life of the process,
-with the token in the key so two tokens cannot quietly share one. And a Kata
-backend cannot share only a listener: it routes dial-ins by nonce into a map of
-its own, so two on one address would each see half of them; the whole backend is
-shared per configuration instead, keyed by a digest so the token and bearer are
-not copied into a second place.
-
-**Cost.** Existing configs that named a non-loopback backend must be rewritten —
-deliberately, because silently reinterpreting them is the bug. And a kind that is
-valid but not yet implemented is now a hard error at the first build instead of a
-silent downgrade, which is correct but will bite someone mid-rollout.
-
-## A remote sandbox must be told the workspace is shared
-
-The workspace is not shipped to a remote sandbox: `Run` frames carry a hub-side
-cwd and `build` runs `makepkg` in `ctx.srcdir`. On a hub that shares that path
-with the sandbox — the test tier, and any same-host deployment — this works. On
-one that does not, it fails obscurely inside `makepkg`. Worse, a misconfiguration
-could make a "remote" build succeed on the hub, which is the exact substitution
-the whole enum exists to prevent, one layer down.
-
-**Choice.** Both remote kinds require `"shared_workspace": true`, and the refusal
-explains the gap rather than just naming the field. The field defaults to false
-rather than being required by the type precisely so the error can say why.
-`loopback` needs no assertion because it shares the filesystem by construction.
-
-**Cost.** This is a guard, not a fix. The real fix is the workspace manifest and
-tar sync the design sketches, which touches the wire protocol, `collect`, and the
-I9 containment checks; until then a genuinely networked remote deployment is not
-possible, and the config now says so at startup instead of letting `makepkg`
-discover it.
diff --git a/docs/INVARIANTS.md b/docs/INVARIANTS.md
deleted file mode 100644
index 80a98aa..0000000
--- a/docs/INVARIANTS.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# §2 invariants, and the test that holds each one
-
-Every invariant in DESIGN.md §2 maps to at least one named test. The primary
-name is listed first; corroborating tests are listed after it. Run any of them
-with `cargo test --test <file> <name>`.
-
-| # | Invariant | Test |
-|---|---|---|
-| **I1** | Every artifact in a served index traces to an `approval` row. | `invariants::i1_every_index_entry_traces_back_to_an_approval` · `pipeline::i1_no_index_entry_without_an_approval` · `pipeline::publish_refuses_without_an_approval_behind_it` · `db::i1_query_flags_index_entries_without_approval` |
-| **I2** | A review's base is the pkgbase's `current_accepted_release`, not the last detected candidate. | `invariants::i2_base_is_the_last_accepted_version_after_many_detections` · `detect::i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive` |
-| **I3** | Candidate identity is content-addressed over everything that becomes a byte. | `invariants::i3_materialization_fails_closed_on_the_recipe_pin` · `detect::epoch_and_pkgrel_are_part_of_the_identity` · `detect::recipe_hash_covers_shipped_patches` · `detect::detection_is_idempotent_and_records_no_duplicate_candidate` · `db::candidate_identity_is_unique_per_pkgbase` |
-| **I4** | Publishing is the only externally visible step, and it is atomic and serialized. | `invariants::i4_kill_mid_publish_leaves_the_old_index_byte_identical` · `pipeline::i4_kill_mid_publish_leaves_the_old_index_intact` · `pipeline::a_stale_accepted_pointer_refuses_to_publish` |
-| **I5** | Every step is idempotent and checkpointed; a worker can die at any instant. | `invariants::i5_resume_after_a_crash_repeats_no_completed_step` · `pipeline::i5_a_restarted_build_resumes_at_the_next_incomplete_step` · `crash::a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work` · `dispatch::a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work` |
-| **I6** | A manual rebuild reuses the approved source identity, with no new approval. | `invariants::i6_manual_rebuild_publishes_the_same_version_without_a_new_approval` · `pipeline::i6_manual_rebuild_reuses_the_approved_identity` · `surfaces::a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval` |
-| **I7** | At most one open review per pkgbase; a newer detection collapses into it. | `invariants::i7_the_schema_refuses_a_second_open_review` · `db::i7_second_open_review_is_rejected_by_the_database` · `approve::collapse_in_place_bumps_revision_without_a_new_row` |
-| **I8** | The index is exactly the set of `current_accepted_release` pointers. | `invariants::i8_index_equals_the_accepted_pointers` · `pipeline::i8_served_index_holds_exactly_the_accepted_pointers` |
-| **I9** | Build hosts are untrusted: a malicious PKGBUILD must not reach the DB, the signing key, or another build. | `invariants::i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir` |
-| **I10** | Every state transition is recorded, append-only, with actor and timestamp. | `invariants::i10_audit_is_append_only_and_records_the_decisions` · `db::audit_log_is_append_only` · `surfaces::the_builds_page_names_the_version_and_the_audit_page_records_the_decision` |
-| **I11** | A non-publishable change never silently disappears; it becomes a `notice`. | `notices::i11_nothing_publishable_is_ever_silently_dropped` · `detect::recipe_drift_under_a_static_version_is_a_notice_not_a_candidate` · `vcs::a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate` · `notices::digest_drift_is_a_high_severity_integrity_alert_and_no_candidate` |
-| **I12** | Every release records the set of our own packages it was built against. | `invariants::i12_every_build_records_a_world_snapshot` · `pipeline::i12_world_snapshot_is_recorded_at_ingest` · `world::the_world_snapshot_is_intersected_with_our_index_at_ingest_time` · `db::world_snapshot_dedupes_by_hash` |
-
-## What I9 does and does not cover
-
-The full statement of I9 is enforced by the sandbox: with a remote or kata
-backend the build code runs on a machine that holds no database, no mirrors,
-and — since signing moved to hub-side ingest — not even the signing key. The
-boundary is now a VM, which is stronger than the chroot it replaced. What is
-*not* gated, and what
-`i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir` pins,
-is the pipeline's own hygiene: `collect` scans the srcdir for `*.pkg.tar.zst`
-and `ingest` copies whatever those paths resolve to into the content-addressed
-store, from where the bytes are served from our repo and signed with our key. A
-build that could make one of those paths be a symlink to the keyring or the
-database would turn a missing sandbox into a signed artifact of our own secrets.
-The test acts that attack out — the shim plants a symlink to the database file —
-and asserts the build fails closed, the store is untouched, and nothing
-publishes. The provisioning layer adds its own I9-adjacent assertions: staged
-blobs are re-hashed by the hub before a sandbox sees them, and a sandbox whose
-`pacman -Q` misreports its world fails the build closed
-(`failure_modes::an_incomplete_closure_fails_closed_as_a_world_mismatch`).
-
-## Invariants that are properties of the schema, not of a code path
-
-Two of these are enforced by SQLite itself so that no future code path can forget
-them, and each has a test that tries to violate it through the database rather
-than through the application:
-
-* I7 — a partial unique index on `candidate (pkgbase_id) WHERE state='pending_review'`.
-* I10 — `UPDATE`/`DELETE` triggers on `audit`, and on `approval` (§7.2, the
- approval record is immutable because it is the only proof of what a human saw).
-
-## Structural invariants, and the test that holds each one
-
-The rest of this file is about the twelve numbered invariants, which are claims
-about what the system does. The ones below are claims about how the code is
-allowed to be shaped — the kind that a review finds once and that a test then
-holds forever, because a convention nobody checks erodes back into inconsistency
-within a few commits. Each is enforced by a test that reads the source tree and
-fails on the shape, not on behaviour.
-
-| Invariant | Test |
-|---|---|
-| SQL has one owner: `db/`. No other module holds a statement or touches a rusqlite connection. | `schema_ownership::no_sql_statements_outside_the_db_module` |
-| A version string is formatted in exactly one place, `pkgver::full_version` — never again as a `CASE` in SQL. | `schema_ownership::only_rust_formats_a_version` |
-| Dependency direction: `db` does not know about `review`/`watch`/`pipeline`; `review` does not call back into the watcher; `watch` does not reach into the pipeline or the UI; `recipe` is a leaf. | `layers::persistence_names_nothing_above_itself` · `layers::review_does_not_call_back_into_the_watcher` · `layers::the_watcher_does_not_reach_into_the_pipeline_or_the_ui` · `layers::the_recipe_leaf_depends_on_nothing_above_it` |
-| The five state machines are enums. A row whose state text the code does not define is an error, not an empty string, and a transition the table does not define is refused rather than applied. | `state_machine::the_machine_refuses_a_transition_it_does_not_define` · `state_machine::a_state_the_code_does_not_know_is_an_error_not_an_empty_string` · `state_machine::every_state_round_trips_through_its_column_text` · `state_machine::an_unnamed_state_in_any_row_is_an_error` |
-| A worker that lost its lease cannot write over the worker that owns the build. | `state_machine::a_zombie_worker_cannot_finish_a_build_it_no_longer_owns` |
-| The production binary contains no test scaffolding: no shim harness, no shim binaries, no ungated fault-injection branch, and a default config with no hooks attached. | `production_surface::no_production_module_references_the_shim_harness` · `production_surface::the_shim_binaries_are_test_only` · `production_surface::the_publish_hot_path_has_no_ungated_test_branch` · `production_surface::a_default_config_has_no_hooks_attached` |
-| The served index has exactly one serialization lock, so no second lock can be added that does not know about the first. | `production_surface::the_served_index_has_exactly_one_serialization_lock` |
-| The rules a reviewer reads are the same rules the machine scored: no private copies of the host rule, the body-changed rule, or a hand-built audit row. | `production_surface::the_review_modules_do_not_keep_private_copies_of_the_rules` · `production_surface::audit_rows_are_built_by_the_constructors_not_by_hand` |
-| `canonical_json` is canonical in fact — key order is a property of the bytes, not of the struct declaration — and a value that cannot be serialized is an error, never an empty object that hashes like a real identity. | `hash::the_rendering_is_canonical_in_fact_not_in_name` · `hash::a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object` |
-| The session id is the credential: a cookie a client typed by hand proves nothing, and logging out invalidates the id rather than flipping a bit inside a cookie the client controls. | `http::a_forged_auth_cookie_is_not_a_session` · `http::login_rotates_the_session_and_logout_ends_it` |
-| A pinned clock pins everything derived from it, including lease expiry — a test that freezes time must not compute a real-clock deadline. | `time::a_pinned_clock_moves_relative_arithmetic_with_it` · `time::a_lease_taken_under_a_pinned_clock_expires_against_that_clock` |
diff --git a/src/db/migrations.rs b/src/db/migrations.rs
index 18e9a4b..4c4774e 100644
--- a/src/db/migrations.rs
+++ b/src/db/migrations.rs
@@ -5,7 +5,7 @@ pub struct Migration {
}
const M_0001_CORE: &str = r#"
--- The single repo we publish. Exactly one row (DESIGN.md §9, decision 4).
+-- The single repo we publish. Exactly one row.
CREATE TABLE repo (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,