summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.pi/.goals-pool-snapshot.json2
-rw-r--r--.pi/goals/.goal-ledger-checkpoint.json2
-rw-r--r--.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md20
-rw-r--r--.pi/goals/goal_events.jsonl2
-rw-r--r--src/db/migrations.rs30
-rw-r--r--src/http/mod.rs5
-rw-r--r--src/http/routes.rs19
-rw-r--r--src/lib.rs1
-rw-r--r--src/main.rs54
-rw-r--r--src/ops.rs650
-rw-r--r--tests/common/mod.rs10
-rw-r--r--tests/db.rs2
-rw-r--r--tests/ops.rs381
13 files changed, 1164 insertions, 14 deletions
diff --git a/.pi/.goals-pool-snapshot.json b/.pi/.goals-pool-snapshot.json
index caf54d7..77c9a80 100644
--- a/.pi/.goals-pool-snapshot.json
+++ b/.pi/.goals-pool-snapshot.json
@@ -1 +1 @@
-{"version":1,"dirMtimeMs":1794995066854.156,"goals":[{"id":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","status":"active","autoContinue":true,"usage":{"tokensUsed":8192565,"activeSeconds":14533},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-18T09:44:26.851Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":746,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"dfbaf4f2-dad9-4dc6-9717-5038550aa75e","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"kickoff"},"dispatch":{"id":"27430841-6f83-4343-a9fa-dd1c866de9d3","kind":"kickoff","claimedAt":1794985072841}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"complete","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"complete","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test.","completedAt":"2026-11-17T21:31:09.120Z","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO"},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"complete","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction.","completedAt":"2026-11-17T21:20:02.693Z","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi"},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"complete","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected.","completedAt":"2026-11-17T22:10:06.063Z","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi"},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"complete","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap.","completedAt":"2026-11-17T21:58:00.936Z","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean"},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"complete","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8).","completedAt":"2026-11-18T07:01:31.398Z","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re"}],"completedAt":"2026-11-18T07:02:29.831Z","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit"},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"complete","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"complete","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry.","completedAt":"2026-11-18T07:16:40.077Z","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma"},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"complete","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD.","completedAt":"2026-11-18T07:17:57.387Z","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o"},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"complete","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped.","completedAt":"2026-11-18T07:29:10.456Z","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-"}],"completedAt":"2026-11-18T07:30:36.958Z","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri"},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"complete","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"complete","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled.","completedAt":"2026-11-18T08:06:45.433Z","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr"},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"complete","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane.","completedAt":"2026-11-18T08:07:10.624Z","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r"},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"complete","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable.","completedAt":"2026-11-18T08:07:36.401Z","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written"},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"complete","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6).","completedAt":"2026-11-18T08:23:18.650Z","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down"}],"completedAt":"2026-11-18T08:24:11.640Z","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a"},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"complete","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"complete","verificationContract":"Dispatcher claims with BEGIN IMMEDIATE + lease expiry, requeues expired leases on startup, marks in-flight steps interrupted; the deterministic build id makes re-enqueue an INSERT OR IGNORE no-op; backpressure respects max_concurrent_builds and disk headroom.","completedAt":"2026-11-18T08:36:46.877Z","evidence":"src/pipeline/dispatch.rs + tests/dispatch.rs (9 tests): claim_batch runs SELECT+UPDATE in one BEGIN IMMEDIATE tx (db.writer.tx uses TransactionBehavior::Immediate); an_expired_lease_is_requeued_and_it"},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"complete","verificationContract":"A test kills the process mid-step and asserts resume at the next incomplete step with no duplicate side effects; cancel_requested stops a worker at a step boundary; deterministic build failures do not auto-retry and the release stays approved_but_unbuilt with the UI showing 'index still serving v1'.","completedAt":"2026-11-18T08:47:32.080Z","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si"},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"complete","verificationContract":"GET /builds/:id/log.stream streams appended log bytes from a blocking thread; the builds table refreshes via htmx every 3s; vendored htmx is the only JS shipped and total vendored JS stays under 20 KB.","completedAt":"2026-11-18T09:01:22.683Z","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE"}],"completedAt":"2026-11-18T09:03:07.796Z","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai"},{"id":"task-p4","title":"P4 — staleness, retention, metrics (§10, §15)","status":"pending","subtasks":[{"id":"task-p4-world","title":".PKGINFO/.BUILDINFO parsing and world_snapshot filtered to our own repo","status":"complete","verificationContract":"Ingest parses tar+text without libalpm; world_snapshot members are intersected with our index at ingest time (not query time); split pkgbases produce N package rows from one approval.","completedAt":"2026-11-18T09:12:33.747Z","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo "},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"complete","verificationContract":"stale_outdated and stale_missing are derived purely on read; a build with an unresolvable dep enters blocked_missing_dep, appears on Attention with the blocking pkgbase named, and the review page warns about missing deps before approval; the dep_edge view answers 'approving this marks N packages stale'.","completedAt":"2026-11-18T09:27:24.780Z","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips"},{"id":"task-p4-ops","title":"Retention/GC, metrics endpoint, and backup helper","status":"pending","verificationContract":"Retention keeps N versions with logs and sources as a unit and sweeps abandoned staging dirs; GET /metrics emits prometheus text including queue depth, pending-review age histogram, build success rate and WAL size; backup uses VACUUM INTO (never cp of a live WAL db)."},{"id":"task-p4-deps","title":"vercmp + dependency-string parser and version-delta flagging (§4, §6)","status":"pending","verificationContract":"Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests."}]},{"id":"task-verify","title":"Final verification pass, real-chroot attempt, and documentation","status":"pending","verificationContract":"Full `cargo test` and `cargo clippy` run clean; every §2 invariant maps to a named passing test (list produced); README + docs/DECISIONS.md written; git history reviewed for incremental commits; the gated real-chroot integration attempt against devtools is run or explicitly recorded as skipped with the reason."}],"blockCompletion":true,"proposedAt":"2026-11-17T20:39:23.165Z"},"currentTaskId":"task-p4-deps"}]} \ No newline at end of file
+{"version":1,"dirMtimeMs":1794996104033.389,"goals":[{"id":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","status":"active","autoContinue":true,"usage":{"tokensUsed":8635397,"activeSeconds":15531},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-18T10:01:44.017Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":817,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"dfbaf4f2-dad9-4dc6-9717-5038550aa75e","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"kickoff"},"dispatch":{"id":"27430841-6f83-4343-a9fa-dd1c866de9d3","kind":"kickoff","claimedAt":1794985072841}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"complete","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"complete","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test.","completedAt":"2026-11-17T21:31:09.120Z","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO"},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"complete","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction.","completedAt":"2026-11-17T21:20:02.693Z","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi"},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"complete","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected.","completedAt":"2026-11-17T22:10:06.063Z","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi"},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"complete","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap.","completedAt":"2026-11-17T21:58:00.936Z","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean"},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"complete","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8).","completedAt":"2026-11-18T07:01:31.398Z","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re"}],"completedAt":"2026-11-18T07:02:29.831Z","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit"},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"complete","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"complete","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry.","completedAt":"2026-11-18T07:16:40.077Z","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma"},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"complete","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD.","completedAt":"2026-11-18T07:17:57.387Z","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o"},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"complete","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped.","completedAt":"2026-11-18T07:29:10.456Z","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-"}],"completedAt":"2026-11-18T07:30:36.958Z","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri"},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"complete","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"complete","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled.","completedAt":"2026-11-18T08:06:45.433Z","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr"},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"complete","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane.","completedAt":"2026-11-18T08:07:10.624Z","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r"},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"complete","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable.","completedAt":"2026-11-18T08:07:36.401Z","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written"},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"complete","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6).","completedAt":"2026-11-18T08:23:18.650Z","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down"}],"completedAt":"2026-11-18T08:24:11.640Z","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a"},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"complete","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"complete","verificationContract":"Dispatcher claims with BEGIN IMMEDIATE + lease expiry, requeues expired leases on startup, marks in-flight steps interrupted; the deterministic build id makes re-enqueue an INSERT OR IGNORE no-op; backpressure respects max_concurrent_builds and disk headroom.","completedAt":"2026-11-18T08:36:46.877Z","evidence":"src/pipeline/dispatch.rs + tests/dispatch.rs (9 tests): claim_batch runs SELECT+UPDATE in one BEGIN IMMEDIATE tx (db.writer.tx uses TransactionBehavior::Immediate); an_expired_lease_is_requeued_and_it"},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"complete","verificationContract":"A test kills the process mid-step and asserts resume at the next incomplete step with no duplicate side effects; cancel_requested stops a worker at a step boundary; deterministic build failures do not auto-retry and the release stays approved_but_unbuilt with the UI showing 'index still serving v1'.","completedAt":"2026-11-18T08:47:32.080Z","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si"},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"complete","verificationContract":"GET /builds/:id/log.stream streams appended log bytes from a blocking thread; the builds table refreshes via htmx every 3s; vendored htmx is the only JS shipped and total vendored JS stays under 20 KB.","completedAt":"2026-11-18T09:01:22.683Z","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE"}],"completedAt":"2026-11-18T09:03:07.796Z","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai"},{"id":"task-p4","title":"P4 — staleness, retention, metrics (§10, §15)","status":"pending","subtasks":[{"id":"task-p4-world","title":".PKGINFO/.BUILDINFO parsing and world_snapshot filtered to our own repo","status":"complete","verificationContract":"Ingest parses tar+text without libalpm; world_snapshot members are intersected with our index at ingest time (not query time); split pkgbases produce N package rows from one approval.","completedAt":"2026-11-18T09:12:33.747Z","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo "},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"complete","verificationContract":"stale_outdated and stale_missing are derived purely on read; a build with an unresolvable dep enters blocked_missing_dep, appears on Attention with the blocking pkgbase named, and the review page warns about missing deps before approval; the dep_edge view answers 'approving this marks N packages stale'.","completedAt":"2026-11-18T09:27:24.780Z","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips"},{"id":"task-p4-ops","title":"Retention/GC, metrics endpoint, and backup helper","status":"pending","verificationContract":"Retention keeps N versions with logs and sources as a unit and sweeps abandoned staging dirs; GET /metrics emits prometheus text including queue depth, pending-review age histogram, build success rate and WAL size; backup uses VACUUM INTO (never cp of a live WAL db)."},{"id":"task-p4-deps","title":"vercmp + dependency-string parser and version-delta flagging (§4, §6)","status":"complete","verificationContract":"Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests.","completedAt":"2026-11-18T09:44:44.096Z","evidence":"tests/versions.rs (12 tests). The table-driven suite became a differential one: vercmp_matches_the_system_oracle compares the hand-written comparator against pacman's own `vercmp` binary over a 34-fra"}]},{"id":"task-verify","title":"Final verification pass, real-chroot attempt, and documentation","status":"pending","verificationContract":"Full `cargo test` and `cargo clippy` run clean; every §2 invariant maps to a named passing test (list produced); README + docs/DECISIONS.md written; git history reviewed for incremental commits; the gated real-chroot integration attempt against devtools is run or explicitly recorded as skipped with the reason."}],"blockCompletion":true,"proposedAt":"2026-11-17T20:39:23.165Z"},"currentTaskId":"task-p4-ops"}]} \ No newline at end of file
diff --git a/.pi/goals/.goal-ledger-checkpoint.json b/.pi/goals/.goal-ledger-checkpoint.json
index c7991e4..e7d3b18 100644
--- a/.pi/goals/.goal-ledger-checkpoint.json
+++ b/.pi/goals/.goal-ledger-checkpoint.json
@@ -1 +1 @@
-{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-18T09:29:34.446Z","coveredBytes":13146,"coveredEvents":43,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z","resumedAt":"2026-11-18T06:57:52.837Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","evidence":"src/pipeline/dispatch.rs + tests/dispatch.rs (9 tests): claim_batch runs SELECT+UPDATE in one BEGIN IMMEDIATE tx (db.writer.tx uses TransactionBehavior::Immediate); an_expired_lease_is_requeued_and_it","at":"2026-11-18T08:36:46.878Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","at":"2026-11-18T08:38:10.587Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si","at":"2026-11-18T08:47:32.080Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","at":"2026-11-18T08:48:58.608Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE","at":"2026-11-18T09:01:22.685Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai","at":"2026-11-18T09:03:07.796Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","at":"2026-11-18T09:04:51.588Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo ","at":"2026-11-18T09:12:33.748Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","evidence":"src/pipeline/dispatch.rs + tests/dispatch.rs (9 tests): claim_batch runs SELECT+UPDATE in one BEGIN IMMEDIATE tx (db.writer.tx uses TransactionBehavior::Immediate); an_expired_lease_is_requeued_and_it","at":"2026-11-18T08:36:46.878Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","at":"2026-11-18T08:38:10.587Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si","at":"2026-11-18T08:47:32.080Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","at":"2026-11-18T08:48:58.608Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE","at":"2026-11-18T09:01:22.685Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai","at":"2026-11-18T09:03:07.796Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","at":"2026-11-18T09:04:51.588Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo ","at":"2026-11-18T09:12:33.748Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma","at":"2026-11-18T07:16:40.078Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down","at":"2026-11-18T08:23:18.652Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a","at":"2026-11-18T08:24:11.640Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","evidence":"src/pipeline/dispatch.rs + tests/dispatch.rs (9 tests): claim_batch runs SELECT+UPDATE in one BEGIN IMMEDIATE tx (db.writer.tx uses TransactionBehavior::Immediate); an_expired_lease_is_requeued_and_it","at":"2026-11-18T08:36:46.878Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","at":"2026-11-18T08:38:10.587Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si","at":"2026-11-18T08:47:32.080Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","at":"2026-11-18T08:48:58.608Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE","at":"2026-11-18T09:01:22.685Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai","at":"2026-11-18T09:03:07.796Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","at":"2026-11-18T09:04:51.588Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo ","at":"2026-11-18T09:12:33.748Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"}],"oracle":[],"lifecycle":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"}}]]} \ No newline at end of file
+{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-18T09:45:18.859Z","coveredBytes":13574,"coveredEvents":45,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z","resumedAt":"2026-11-18T06:57:52.837Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","at":"2026-11-18T08:38:10.587Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si","at":"2026-11-18T08:47:32.080Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","at":"2026-11-18T08:48:58.608Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE","at":"2026-11-18T09:01:22.685Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai","at":"2026-11-18T09:03:07.796Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","at":"2026-11-18T09:04:51.588Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo ","at":"2026-11-18T09:12:33.748Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","evidence":"tests/versions.rs (12 tests). The table-driven suite became a differential one: vercmp_matches_the_system_oracle compares the hand-written comparator against pacman's own `vercmp` binary over a 34-fra","at":"2026-11-18T09:44:44.096Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-ops","at":"2026-11-18T09:45:18.852Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","at":"2026-11-18T08:38:10.587Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si","at":"2026-11-18T08:47:32.080Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","at":"2026-11-18T08:48:58.608Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE","at":"2026-11-18T09:01:22.685Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai","at":"2026-11-18T09:03:07.796Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","at":"2026-11-18T09:04:51.588Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo ","at":"2026-11-18T09:12:33.748Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","evidence":"tests/versions.rs (12 tests). The table-driven suite became a differential one: vercmp_matches_the_system_oracle compares the hand-written comparator against pacman's own `vercmp` binary over a 34-fra","at":"2026-11-18T09:44:44.096Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-ops","at":"2026-11-18T09:45:18.852Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma","at":"2026-11-18T07:16:40.078Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down","at":"2026-11-18T08:23:18.652Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a","at":"2026-11-18T08:24:11.640Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","evidence":"src/pipeline/dispatch.rs + tests/dispatch.rs (9 tests): claim_batch runs SELECT+UPDATE in one BEGIN IMMEDIATE tx (db.writer.tx uses TransactionBehavior::Immediate); an_expired_lease_is_requeued_and_it","at":"2026-11-18T08:36:46.878Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","at":"2026-11-18T08:38:10.587Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-crash","evidence":"tests/crash.rs (4 tests): a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work spawns the real aur-build binary, has a shim SIGKILL it inside the build step (asserts status.si","at":"2026-11-18T08:47:32.080Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","at":"2026-11-18T08:48:58.608Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-sse","evidence":"tests/live.rs (5 tests): the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends — a producer thread appends to the log while the SSE stream is open and the reader must see those bytes BEFORE","at":"2026-11-18T09:01:22.685Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3","evidence":"All three P3 children complete: dispatcher/worker pool/reaper with BEGIN IMMEDIATE claims and disk-headroom backpressure (e27e90a), a real SIGKILL mid-step crash test plus the approved_but_unbuilt fai","at":"2026-11-18T09:03:07.796Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","at":"2026-11-18T09:04:51.588Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-world","evidence":"src/pkginfo.rs is now the production home for tar+text parsing (no libalpm); shims delegate to it and steps.rs uses it. tests/world.rs (5 tests) builds real .pkg.tar.zst archives and asserts: pkginfo ","at":"2026-11-18T09:12:33.748Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","evidence":"tests/versions.rs (12 tests). The table-driven suite became a differential one: vercmp_matches_the_system_oracle compares the hand-written comparator against pacman's own `vercmp` binary over a 34-fra","at":"2026-11-18T09:44:44.096Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-ops","at":"2026-11-18T09:45:18.852Z"}],"oracle":[],"lifecycle":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-ops","at":"2026-11-18T09:45:18.852Z"}}]]} \ No newline at end of file
diff --git a/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md b/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md
index cd83652..e920f78 100644
--- a/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md
+++ b/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md
@@ -5,14 +5,14 @@
"status": "active",
"autoContinue": true,
"usage": {
- "tokensUsed": 8192565,
- "activeSeconds": 14533
+ "tokensUsed": 8635397,
+ "activeSeconds": 15531
},
"sisyphus": false,
"createdAt": "2026-11-17T20:43:24.440Z",
- "updatedAt": "2026-11-18T09:44:26.851Z",
+ "updatedAt": "2026-11-18T10:01:44.017Z",
"activePath": ".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md",
- "revision": 746,
+ "revision": 817,
"scheduler": {
"version": 1,
"owner": "01a1eb32-2e3f-757c-a79a-21ac993facc5",
@@ -234,8 +234,10 @@
{
"id": "task-p4-deps",
"title": "vercmp + dependency-string parser and version-delta flagging (§4, §6)",
- "status": "pending",
- "verificationContract": "Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests."
+ "status": "complete",
+ "verificationContract": "Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests.",
+ "completedAt": "2026-11-18T09:44:44.096Z",
+ "evidence": "tests/versions.rs (12 tests). The table-driven suite became a differential one: vercmp_matches_the_system_oracle compares the hand-written comparator against pacman's own `vercmp` binary over a 34-fra"
}
]
},
@@ -249,7 +251,7 @@
"blockCompletion": true,
"proposedAt": "2026-11-17T20:39:23.165Z"
},
- "currentTaskId": "task-p4-deps"
+ "currentTaskId": "task-p4-ops"
}
# Goal Prompt
@@ -282,8 +284,8 @@ IF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninsta
- Status: running
- Auto-continue: on
- Sisyphus mode: no
-- Time spent: 4h02m13s
-- Tokens used: 8.2M (8,192,565) tokens
+- Time spent: 4h18m51s
+- Tokens used: 8.6M (8,635,397) tokens
## Tasks
<!-- blockCompletion: true -->
diff --git a/.pi/goals/goal_events.jsonl b/.pi/goals/goal_events.jsonl
index 42f2b5a..13cf644 100644
--- a/.pi/goals/goal_events.jsonl
+++ b/.pi/goals/goal_events.jsonl
@@ -41,3 +41,5 @@
{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","at":"2026-11-18T09:14:30.194Z"}
{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-stale","evidence":"tests/staleness.rs (6 tests): staleness_is_derived_on_read_and_nothing_stores_it (a sqlite_master/pragma_table_info scan asserts NO column anywhere stores staleness, and withdrawing a dependency flips","at":"2026-11-18T09:27:24.780Z"}
{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","at":"2026-11-18T09:29:34.423Z"}
+{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-deps","evidence":"tests/versions.rs (12 tests). The table-driven suite became a differential one: vercmp_matches_the_system_oracle compares the hand-written comparator against pacman's own `vercmp` binary over a 34-fra","at":"2026-11-18T09:44:44.096Z"}
+{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p4-ops","at":"2026-11-18T09:45:18.852Z"}
diff --git a/src/db/migrations.rs b/src/db/migrations.rs
index bb8974f..9e60132 100644
--- a/src/db/migrations.rs
+++ b/src/db/migrations.rs
@@ -319,6 +319,35 @@ CREATE TABLE stage_b_cache (
CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at);
"#;
+/// Retention (§15, open question 21). The rows are never compacted — the whole
+/// point of the schema is that "which bytes produced this installed package"
+/// stays answerable — but the bytes on disk cannot be kept forever. So eviction
+/// is recorded rather than implied: the artifact row keeps its digest, size and
+/// provenance and gains a `purged_at`, which says "these bytes existed, and were
+/// dropped from the store at T" instead of silently pretending they are still
+/// there. A `cp` of the store and a database that disagrees about what is on disk
+/// is the failure mode this avoids.
+const M_0008_RETENTION: &str = r#"
+ALTER TABLE artifact ADD COLUMN purged_at TEXT;
+
+-- Set when a release's files have been evicted; NULL means the bytes are held.
+ALTER TABLE release ADD COLUMN purged_at TEXT;
+
+-- Staging is disposable (§8.2), but "disposable" needs a definition: a dir is
+-- swept when its build is terminal or unknown and the dir is older than the
+-- grace period. Recording the sweep keeps a crashed-then-swept build auditable.
+CREATE TABLE IF NOT EXISTS gc_run (
+ id INTEGER PRIMARY KEY,
+ ran_at TEXT NOT NULL,
+ releases_kept INTEGER NOT NULL,
+ releases_evicted INTEGER NOT NULL,
+ files_removed INTEGER NOT NULL,
+ bytes_freed INTEGER NOT NULL,
+ staging_swept INTEGER NOT NULL,
+ detail_json TEXT NOT NULL DEFAULT '{}'
+);
+"#;
+
pub static MIGRATIONS: &[Migration] = &[
Migration { version: 1, name: "core", sql: M_0001_CORE },
Migration { version: 2, name: "build", sql: M_0002_BUILD },
@@ -327,6 +356,7 @@ pub static MIGRATIONS: &[Migration] = &[
Migration { version: 5, name: "artifact-build", sql: M_0005_ARTIFACT_BUILD },
Migration { version: 6, name: "approval-immutable", sql: M_0006_APPROVAL_IMMUTABLE },
Migration { version: 7, name: "stage-b-cache", sql: M_0007_STAGE_B_CACHE },
+ Migration { version: 8, name: "retention", sql: M_0008_RETENTION },
];
/// Default settings seeded into `settings` (DESIGN.md §11).
diff --git a/src/http/mod.rs b/src/http/mod.rs
index 7ca4875..16ff6b1 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -223,6 +223,11 @@ fn dispatch(state: &State, req: &Req) -> Res {
("GET", ["login"]) => return routes::login_form(state, req),
("POST", ["login"]) => return routes::login(state, req),
("GET", ["healthz"]) => return Res::text(200, "ok\n".into()),
+ // Metrics are counts only — no package names, no versions, no audit
+ // detail — and a Prometheus scraper has no session to present. Serving
+ // them unauthenticated is what makes them scrapeable at all; the bind
+ // address is loopback by default, which is where that is safe.
+ ("GET", ["metrics"]) => return routes::metrics(state),
_ => {}
}
diff --git a/src/http/routes.rs b/src/http/routes.rs
index 26aaa89..9efb90b 100644
--- a/src/http/routes.rs
+++ b/src/http/routes.rs
@@ -6,7 +6,7 @@
use crate::db::{self, builds, model::*, Db};
use crate::review::{approve as ap, candidates, diff, risk};
-use crate::{pipeline, time};
+use crate::{ops, pipeline, time};
use super::auth;
use super::render::*;
@@ -995,6 +995,23 @@ fn audit(state: &State, req: &Req) -> Res {
page_to_res(Audit { page, rows }, 200)
}
+/// `GET /metrics` in Prometheus text exposition format (§12, §15).
+///
+/// Everything here is computed from live state on every scrape. There are no
+/// counters incremented at event sites, because a counter that has to be
+/// maintained by every code path is a counter that quietly drifts the first time
+/// a path is added; a query cannot drift.
+pub fn metrics(state: &State) -> Res {
+ match ops::metrics(&state.cfg, &state.db) {
+ Ok(m) => {
+ let mut res = Res::text(200, m.to_prometheus());
+ res.content_type = "text/plain; version=0.0.4; charset=utf-8".into();
+ res
+ }
+ Err(e) => Res::text(500, format!("metrics unavailable: {e}\n")),
+ }
+}
+
fn settings(state: &State, req: &Req) -> Res {
let page = chrome(state, req, "Settings", "nav_settings");
let rows = db::all_settings(&state.db)
diff --git a/src/lib.rs b/src/lib.rs
index bee4303..445ae2f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -12,6 +12,7 @@ pub mod fetch;
pub mod git;
pub mod hash;
pub mod http;
+pub mod ops;
pub mod pipeline;
pub mod pkginfo;
pub mod pkgver;
diff --git a/src/main.rs b/src/main.rs
index 7297a96..6df2bd7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -95,6 +95,25 @@ enum Cmd {
#[arg(long, default_value_t = 30)]
limit: i64,
},
+ /// Print metrics in Prometheus text format (the same numbers /metrics serves).
+ Metrics,
+ /// Drop the files of releases beyond the retention window, and sweep
+ /// abandoned staging directories. Rows are never deleted (§15).
+ Gc {
+ /// Versions per pkgbase whose files are kept. Defaults to the
+ /// `retention_versions` setting.
+ #[arg(long)]
+ keep: Option<usize>,
+ /// Show what would be removed without removing it.
+ #[arg(long)]
+ dry_run: bool,
+ },
+ /// Write a consistent snapshot of the database with `VACUUM INTO`.
+ Backup {
+ /// Destination file. It must not already exist: a backup that silently
+ /// overwrites last week's backup is not a backup.
+ to: PathBuf,
+ },
}
fn main() -> anyhow::Result<()> {
@@ -317,6 +336,41 @@ fn main() -> anyhow::Result<()> {
}
Ok(())
}
+ Cmd::Metrics => {
+ print!("{}", aur_build::ops::metrics(&cfg, &ctx.db)?.to_prometheus());
+ Ok(())
+ }
+ Cmd::Gc { keep, dry_run } => {
+ let keep = keep.unwrap_or(aur_build::ops::DEFAULT_KEEP);
+ if dry_run {
+ let (kept, evict) = aur_build::ops::plan_retention(&ctx.db, keep)?;
+ println!("retention: keep {keep} version(s) per pkgbase");
+ println!(" {} release(s) keep their files", kept.len());
+ for e in evict {
+ let files = aur_build::ops::release_files(&cfg, &ctx.db, e.release_id)?;
+ println!(" release {} would lose {} file(s)", e.release_id, files.len());
+ for f in files {
+ println!(" {}", f.display());
+ }
+ }
+ return Ok(());
+ }
+ let r = aur_build::ops::retention(&cfg, &ctx.db, Some(keep))?;
+ println!(
+ "kept {} release(s), evicted {}, removed {} file(s), freed {} bytes, swept {} staging dir(s)",
+ r.releases_kept, r.releases_evicted, r.files_removed, r.bytes_freed, r.staging_swept
+ );
+ Ok(())
+ }
+ Cmd::Backup { to } => {
+ let path = aur_build::ops::backup(&ctx.db, &to)?;
+ println!(
+ "wrote {} bytes to {} (VACUUM INTO, single file, no WAL)",
+ std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
+ path.display()
+ );
+ Ok(())
+ }
}
}
diff --git a/src/ops.rs b/src/ops.rs
new file mode 100644
index 0000000..e211a95
--- /dev/null
+++ b/src/ops.rs
@@ -0,0 +1,650 @@
+//! Retention, metrics and backups (§15).
+//!
+//! Three separate jobs that share one premise: the database is the thing that
+//! must survive, and the bytes on disk are the thing that cannot be kept forever.
+//!
+//! *Retention* evicts files for releases beyond the last N of a pkgbase. It never
+//! deletes a row. The artifact keeps its digest, size and provenance and gains a
+//! `purged_at`, so the record says "these bytes existed and were dropped at T"
+//! rather than continuing to claim a file that is no longer there.
+//!
+//! *Metrics* are computed on read, like staleness. A counter that has to be
+//! incremented on every state change is a counter that drifts.
+//!
+//! *Backups* use `VACUUM INTO`. Copying a live WAL database with `cp` produces a
+//! main file plus a WAL that may or may not belong to it, which is to say a backup
+//! that is only sometimes restorable.
+
+use std::path::{Path, PathBuf};
+
+use crate::config::Config;
+use crate::db::{self, Db};
+use crate::error::Result;
+use crate::time;
+
+/// Default number of versions kept per pkgbase (§11 `retention_versions`).
+pub const DEFAULT_KEEP: usize = 3;
+
+#[derive(Debug, Default, Clone)]
+pub struct RetentionReport {
+ pub releases_kept: usize,
+ pub releases_evicted: usize,
+ pub files_removed: usize,
+ pub bytes_freed: u64,
+ pub staging_swept: usize,
+}
+
+/// Everything a metrics scrape reports, computed in one pass over the database.
+///
+/// Kept as a struct rather than a string builder so the HTTP handler, the CLI and
+/// the tests all read the same numbers from the same source.
+#[derive(Debug, Default, Clone)]
+pub struct Metrics {
+ pub builds: Vec<(String, i64)>,
+ pub queue_depth: i64,
+ pub oldest_queued_age_secs: i64,
+ pub pending_review: i64,
+ /// Age of pending candidates in seconds, already sorted, for bucketing.
+ pub review_ages: Vec<i64>,
+ pub succeeded: i64,
+ pub failed: i64,
+ pub blocked_missing_dep: i64,
+ pub index_packages: i64,
+ pub releases: i64,
+ pub stale_outdated: i64,
+ pub stale_missing: i64,
+ pub downgrades: i64,
+ pub subscriptions: i64,
+ pub notices_unseen: i64,
+ pub db_bytes: u64,
+ pub wal_bytes: u64,
+ pub artifact_bytes: u64,
+ pub staging_dirs: usize,
+ pub staging_bytes: u64,
+ pub last_gc_age_secs: Option<i64>,
+ pub poll_lag_age_secs: Option<i64>,
+}
+
+impl Metrics {
+ /// Share of recorded builds that published. Reported as 1.0 when nothing has
+ /// run yet: a fresh install is not a failing install, and an alert rule that
+ /// reads 0% success on an empty system pages someone for no reason.
+ pub fn build_success_rate(&self) -> f64 {
+ match self.succeeded + self.failed {
+ 0 => 1.0,
+ n => self.succeeded as f64 / n as f64,
+ }
+ }
+
+ /// Render in Prometheus text exposition format.
+ ///
+ /// Every family is declared with `# HELP` and `# TYPE` because a scrape that
+ /// fails validation silently drops the whole payload, not just the bad line.
+ pub fn to_prometheus(&self) -> String {
+ let mut o = String::new();
+
+ o.push_str("# HELP aurbuild_up Always 1: the process answered the scrape.\n# TYPE aurbuild_up gauge\naurbuild_up 1\n");
+ o.push_str(&header("aurbuild_queue_depth", "Builds waiting to run."));
+ o.push_str(&format!("aurbuild_queue_depth {}\n", self.queue_depth));
+ o.push_str(&header("aurbuild_oldest_queued_age_seconds", "How long the oldest queued build has waited."));
+ o.push_str(&format!("aurbuild_oldest_queued_age_seconds {}\n", self.oldest_queued_age_secs));
+
+ o.push_str("# HELP aurbuild_builds_total Builds by state.\n# TYPE aurbuild_builds_total gauge\n");
+ for (state, n) in &self.builds {
+ o.push_str(&format!("aurbuild_builds_total{{state=\"{state}\"}} {n}\n"));
+ }
+
+ o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt."));
+ o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review));
+
+ // The debt number nobody asks for until it is weeks old: not how many
+ // reviews are pending, but how stale the pending ones are.
+ o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n");
+ for le in [3600i64, 21600, 86400, 259200, 604800] {
+ let n = self.review_ages.iter().filter(|a| **a <= le).count();
+ o.push_str(&format!("aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}\n"));
+ }
+ o.push_str(&format!(
+ "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}\n",
+ self.review_ages.len()
+ ));
+ let sum: i64 = self.review_ages.iter().sum();
+ o.push_str(&format!("aurbuild_pending_review_age_seconds_sum {sum}\n"));
+ o.push_str(&format!("aurbuild_pending_review_age_seconds_count {}\n", self.review_ages.len()));
+
+ o.push_str(&header("aurbuild_builds_succeeded_total", "Builds that published."));
+ o.push_str(&format!("aurbuild_builds_succeeded_total {}\n", self.succeeded));
+ o.push_str(&header("aurbuild_builds_failed_total", "Builds that failed."));
+ o.push_str(&format!("aurbuild_builds_failed_total {}\n", self.failed));
+ let rate = self.build_success_rate();
+ o.push_str(&header("aurbuild_build_success_rate", "Share of recorded builds that succeeded."));
+ o.push_str(&format!("aurbuild_build_success_rate {rate:.4}\n"));
+
+ o.push_str(&header("aurbuild_blocked_missing_dep", "Builds blocked on a package we have not published."));
+ o.push_str(&format!("aurbuild_blocked_missing_dep {}\n", self.blocked_missing_dep));
+ o.push_str(&header("aurbuild_index_packages", "Packages in the served index."));
+ o.push_str(&format!("aurbuild_index_packages {}\n", self.index_packages));
+ o.push_str(&header("aurbuild_releases", "Published releases on record."));
+ o.push_str(&format!("aurbuild_releases {}\n", self.releases));
+ o.push_str(&header("aurbuild_subscriptions", "Subscribed pkgbases."));
+ o.push_str(&format!("aurbuild_subscriptions {}\n", self.subscriptions));
+ o.push_str(&header("aurbuild_notices_unseen", "Notices no human has looked at."));
+ o.push_str(&format!("aurbuild_notices_unseen {}\n", self.notices_unseen));
+
+ o.push_str("# HELP aurbuild_stale_releases Releases whose recorded world no longer matches the index, by reason.\n# TYPE aurbuild_stale_releases gauge\n");
+ o.push_str(&format!("aurbuild_stale_releases{{reason=\"outdated\"}} {}\n", self.stale_outdated));
+ o.push_str(&format!("aurbuild_stale_releases{{reason=\"missing\"}} {}\n", self.stale_missing));
+ o.push_str(&header("aurbuild_downgrades", "Subscriptions where AUR offers a lower version than we serve."));
+ o.push_str(&format!("aurbuild_downgrades {}\n", self.downgrades));
+
+ o.push_str(&header("aurbuild_sqlite_size_bytes", "Main database file size."));
+ o.push_str(&format!("aurbuild_sqlite_size_bytes {}\n", self.db_bytes));
+ o.push_str(&header("aurbuild_sqlite_wal_size_bytes", "Write-ahead log size — large means nobody is checkpointing."));
+ o.push_str(&format!("aurbuild_sqlite_wal_size_bytes {}\n", self.wal_bytes));
+ o.push_str(&header("aurbuild_artifact_bytes", "Bytes held in the content-addressed store."));
+ o.push_str(&format!("aurbuild_artifact_bytes {}\n", self.artifact_bytes));
+ o.push_str(&header("aurbuild_staging_bytes", "Bytes in disposable staging directories."));
+ o.push_str(&format!("aurbuild_staging_bytes {}\n", self.staging_bytes));
+ o.push_str(&format!("# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}\n", self.staging_dirs));
+
+ match self.poll_lag_age_secs {
+ Some(a) => {
+ o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source."));
+ o.push_str(&format!("aurbuild_poll_lag_seconds {a}\n"));
+ }
+ None => {
+ o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source."));
+ o.push_str("aurbuild_poll_lag_seconds nan\n");
+ }
+ }
+ match self.last_gc_age_secs {
+ Some(a) => {
+ o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run."));
+ o.push_str(&format!("aurbuild_last_gc_age_seconds {a}\n"));
+ }
+ None => {
+ o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run."));
+ o.push_str("aurbuild_last_gc_age_seconds nan\n");
+ }
+ }
+ o
+ }
+}
+
+/// Compute every metric from live state.
+pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
+ let mut m = Metrics::default();
+ let now = time::now();
+
+ m.builds = db.read(|c| {
+ let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok::<_, crate::error::Error>(out)
+ })?;
+ let count = |state: &str| -> i64 {
+ m.builds.iter().find(|(s, _)| s == state).map(|(_, n)| *n).unwrap_or(0)
+ };
+ m.queue_depth = count("queued");
+ m.succeeded = count("succeeded");
+ m.failed = count("failed");
+ m.blocked_missing_dep = count("blocked_missing_dep");
+
+ let oldest = db.read(|c| {
+ c.query_row(
+ "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'",
+ rusqlite::params![now],
+ |r| r.get::<_, Option<f64>>(0),
+ )
+ .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64)
+ .map_err(|e| crate::error::Error::db(e.to_string()))
+ })?;
+ m.oldest_queued_age_secs = oldest.max(0);
+
+ m.pending_review = scalar(db, "SELECT count(*) FROM candidate WHERE state='pending_review'")?;
+ m.review_ages = db.read(|c| {
+ let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?;
+ let rows = st.query_map(rusqlite::params![now], |r| r.get::<_, Option<f64>>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push((r?.unwrap_or(0.0) * 86400.0) as i64);
+ }
+ Ok::<_, crate::error::Error>(out)
+ })?;
+ m.review_ages.sort();
+
+ m.index_packages = scalar(db, "SELECT count(*) FROM package WHERE state='in_index'")?;
+ m.releases = scalar(db, "SELECT count(*) FROM release WHERE state='published'")?;
+ m.subscriptions = scalar(db, "SELECT count(*) FROM subscription")?;
+ m.notices_unseen = scalar(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL")?;
+
+ let stale = crate::watch::staleness::stale_rows(db)?;
+ m.stale_outdated = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Outdated).count() as i64;
+ m.stale_missing = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Missing).count() as i64;
+ m.downgrades = crate::watch::staleness::downgrades(db)?.len() as i64;
+
+ m.db_bytes = file_len(&cfg.db_path());
+ m.wal_bytes = file_len(&PathBuf::from(format!("{}-wal", cfg.db_path().display())));
+ m.artifact_bytes = db.read(|c| {
+ c.query_row(
+ "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL",
+ [],
+ |r| r.get::<_, i64>(0),
+ )
+ .map(|v| v.max(0) as u64)
+ .map_err(|e| crate::error::Error::db(e.to_string()))
+ })?;
+ let (dirs, bytes) = staging_usage(&cfg.staging_dir());
+ m.staging_dirs = dirs;
+ m.staging_bytes = bytes;
+
+ m.last_gc_age_secs = db
+ .read(|c| {
+ c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option<String>>(0))
+ .map_err(|e| crate::error::Error::db(e.to_string()))
+ })?
+ .and_then(|t| time::delta_secs(&now, &t));
+ m.poll_lag_age_secs = db
+ .read(|c| {
+ c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0))
+ .map_err(|e| crate::error::Error::db(e.to_string()))
+ })?
+ .and_then(|t| time::delta_secs(&now, &t));
+ let _ = cfg;
+ Ok(m)
+}
+
+/// A Prometheus family header. Kept as a function rather than a closure over the
+/// output buffer so the borrow checker does not object to interleaving.
+fn header(name: &str, help: &str) -> String {
+ format!("# HELP {name} {help}\n# TYPE {name} gauge\n")
+}
+
+fn scalar(db: &Db, sql: &str) -> Result<i64> {
+ let sql = sql.to_string();
+ db.read(move |c| c.query_row(&sql, [], |r| r.get::<_, i64>(0)).map_err(|e| crate::error::Error::db(e.to_string())))
+}
+
+fn file_len(p: &Path) -> u64 {
+ std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)
+}
+
+/// `(dir count, total bytes)` under a directory, tolerating concurrent removal.
+fn staging_usage(root: &Path) -> (usize, u64) {
+ let mut dirs = 0;
+ let mut bytes = 0;
+ let Ok(entries) = std::fs::read_dir(root) else { return (0, 0) };
+ for e in entries.flatten() {
+ if e.path().is_dir() {
+ dirs += 1;
+ bytes += dir_bytes(&e.path());
+ }
+ }
+ (dirs, bytes)
+}
+
+fn dir_bytes(path: &Path) -> u64 {
+ let mut total = 0;
+ let Ok(entries) = std::fs::read_dir(path) else { return 0 };
+ for e in entries.flatten() {
+ let p = e.path();
+ if p.is_dir() {
+ total += dir_bytes(&p);
+ } else if let Ok(m) = std::fs::metadata(&p) {
+ total += m.len();
+ }
+ }
+ total
+}
+
+/// Which releases of a pkgbase keep their files, and which lose them.
+///
+/// The rule is "newest N, plus anything that would be a lie to evict": the
+/// currently accepted release and any release still backing an `in_index`
+/// package are kept regardless of how far down the list they sit. Evicting those
+/// would delete the bytes the index is actively pointing at, which is the one
+/// thing retention must never do — a rollback target is worth disk, a served
+/// package is not optional.
+pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> {
+ let keep = keep.max(1);
+ let pkgbases: Vec<(i64, Option<i64>)> = db.read(|c| {
+ let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok::<_, crate::error::Error>(out)
+ })?;
+
+ let mut kept = Vec::new();
+ let mut evict = Vec::new();
+ for (pb_id, accepted) in pkgbases {
+ let releases: Vec<i64> = db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC",
+ )?;
+ let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok::<_, crate::error::Error>(out)
+ })?;
+ // Still in the index? Then it is being served and is not a candidate for
+ // eviction no matter how old it is.
+ let serving: Vec<i64> = db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id
+ WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC",
+ )?;
+ let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok::<_, crate::error::Error>(out)
+ })?;
+
+ let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect();
+ if let Some(a) = accepted {
+ keep_set.insert(a);
+ }
+ for id in releases.iter().take(keep) {
+ keep_set.insert(*id);
+ }
+ for id in &releases {
+ if keep_set.contains(id) {
+ kept.push(*id);
+ } else {
+ evict.push(EvictPlan { release_id: *id });
+ }
+ }
+ }
+ Ok((kept, evict))
+}
+
+#[derive(Debug, Clone)]
+pub struct EvictPlan {
+ pub release_id: i64,
+}
+
+/// Run retention: evict files for releases beyond the keep window, then sweep
+/// abandoned staging directories.
+///
+/// Files are only removed when no *retained* release still references them. The
+/// store is content-addressed, so two releases built from the same source share
+/// one cached archive; deleting it because one release aged out would corrupt a
+/// release that is still current.
+pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<RetentionReport> {
+ let keep = keep.unwrap_or_else(|| setting_usize(db, "retention_versions", DEFAULT_KEEP));
+ let (kept, evict) = plan_retention(db, keep)?;
+
+ // Everything still held by a kept release, so we do not evict a shared file.
+ let mut retained_files: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
+ for id in &kept {
+ for f in release_files(cfg, db, *id)? {
+ retained_files.insert(f);
+ }
+ }
+
+ let mut report = RetentionReport { releases_kept: kept.len(), ..Default::default() };
+ for e in &evict {
+ let files = release_files(cfg, db, e.release_id)?;
+ let mut removed = 0usize;
+ let mut freed = 0u64;
+ for f in &files {
+ if retained_files.contains(f) {
+ continue;
+ }
+ if let Ok(m) = std::fs::metadata(f) {
+ freed += m.len();
+ // A missing file is the state we are trying to reach, not an error.
+ let _ = std::fs::remove_file(f);
+ removed += 1;
+ }
+ }
+ report.files_removed += removed;
+ report.bytes_freed += freed;
+ if removed > 0 || !files.is_empty() {
+ report.releases_evicted += 1;
+ mark_purged(db, e.release_id)?;
+ }
+ }
+
+ let (swept, swept_bytes) = sweep_staging(cfg, db, STAGING_GRACE_SECS)?;
+ report.staging_swept = swept;
+ report.bytes_freed += swept_bytes;
+
+ record_run(db, &report)?;
+ let _ = db::audit(
+ &db.writer,
+ "system",
+ "gc",
+ "retention",
+ "gc_run",
+ "",
+ serde_json::json!({
+ "keep": keep,
+ "kept": report.releases_kept,
+ "evicted": report.releases_evicted,
+ "files_removed": report.files_removed,
+ "bytes_freed": report.bytes_freed,
+ "staging_swept": report.staging_swept,
+ }),
+ );
+ Ok(report)
+}
+
+/// Grace period before an abandoned staging dir is swept. Anything younger could
+/// belong to a build that is still running right now.
+pub const STAGING_GRACE_SECS: i64 = 3600;
+
+/// The files a release holds on disk: package, signature, build log, and the
+/// cached sources it was built from.
+///
+/// These are returned as a unit because that is how they must be treated. A
+/// package without its build log is a byte nobody can explain, and a package
+/// without its sources cannot be rebuilt — keeping one and dropping the others
+/// is how a store ends up full of orphans and empty of answers.
+pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathBuf>> {
+ let mut out = Vec::new();
+ let rows: Vec<(Option<String>, Option<String>, Option<String>)> = db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a
+ JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1",
+ )?;
+ let rows = st.query_map(rusqlite::params![release_id], |r| {
+ Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok::<_, crate::error::Error>(out)
+ })?;
+ for (path, sig, log) in rows {
+ if let Some(p) = path {
+ out.push(PathBuf::from(p));
+ }
+ if let Some(p) = sig {
+ out.push(PathBuf::from(p));
+ }
+ if let Some(p) = log {
+ out.push(PathBuf::from(p));
+ }
+ }
+ // Cached sources, by content digest (§5.1a: the mirror and the source cache
+ // are what make an old release rebuildable).
+ let digests: String = db
+ .read(|c| {
+ c.query_row(
+ "SELECT source_digests_json FROM release WHERE id=?1",
+ rusqlite::params![release_id],
+ |r| r.get::<_, String>(0),
+ )
+ .map_err(|e| crate::error::Error::db(e.to_string()))
+ })
+ .unwrap_or_else(|_| "[]".into());
+ if let Ok(list) = serde_json::from_str::<Vec<db::SourceDigest>>(&digests) {
+ for d in list {
+ if !d.digest.is_empty() {
+ out.push(cfg.source_cache_path(&d.digest));
+ }
+ }
+ }
+ Ok(out)
+}
+
+fn mark_purged(db: &Db, release_id: i64) -> Result<()> {
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE release SET purged_at=?1 WHERE id=?2",
+ rusqlite::params![at, release_id],
+ )?;
+ tx.execute(
+ "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN
+ (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)",
+ rusqlite::params![at, release_id],
+ )?;
+ Ok(())
+ })
+}
+
+/// Remove staging directories whose build is finished or unknown (§8.2: staging
+/// is disposable, and a GC pass sweeps what was abandoned).
+///
+/// "Abandoned" is derived, not guessed: a dir is swept when its build row is in a
+/// terminal state, or when no build row exists at all, and the dir is older than
+/// the grace period. A dir belonging to a live build is left alone no matter how
+/// old it looks, because a long build is not an abandoned one.
+pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> {
+ let root = cfg.staging_dir();
+ let Ok(entries) = std::fs::read_dir(&root) else { return Ok((0, 0)) };
+ let now = time::now();
+ let mut swept = 0usize;
+ let mut freed = 0u64;
+ for e in entries.flatten() {
+ let path = e.path();
+ if !path.is_dir() {
+ continue;
+ }
+ let Some(build_id) = path.file_name().map(|s| s.to_string_lossy().to_string()) else {
+ continue;
+ };
+ let state: Option<String> = db
+ .read(|c| {
+ Ok(c.query_row("SELECT state FROM build WHERE id=?1", rusqlite::params![build_id], |r| {
+ r.get::<_, String>(0)
+ })
+ .ok())
+ })
+ .unwrap_or(None);
+ let abandonable = match &state {
+ // No build row: staging left over from a crash before the row was
+ // written, or from a build id that no longer exists.
+ None => true,
+ Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"),
+ };
+ if !abandonable {
+ continue;
+ }
+ let age = dir_age_secs(&path).unwrap_or(0);
+ if age < grace_secs {
+ continue;
+ }
+ let bytes = dir_bytes(&path);
+ if std::fs::remove_dir_all(&path).is_ok() {
+ swept += 1;
+ freed += bytes;
+ }
+ }
+ let _ = now;
+ Ok((swept, freed))
+}
+
+fn dir_age_secs(path: &Path) -> Option<i64> {
+ let m = std::fs::metadata(path).ok()?;
+ let t = m.modified().ok()?;
+ let age = std::time::SystemTime::now().duration_since(t).ok()?;
+ Some(age.as_secs() as i64)
+}
+
+fn record_run(db: &Db, r: &RetentionReport) -> Result<()> {
+ let at = time::now();
+ let (kept, evicted, files, bytes, swept) = (
+ r.releases_kept as i64,
+ r.releases_evicted as i64,
+ r.files_removed as i64,
+ r.bytes_freed as i64,
+ r.staging_swept as i64,
+ );
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept)
+ VALUES (?1,?2,?3,?4,?5,?6)",
+ rusqlite::params![at, kept, evicted, files, bytes, swept],
+ )?;
+ Ok(())
+ })
+}
+
+fn setting_usize(db: &Db, key: &str, default: usize) -> usize {
+ db.read(|c| {
+ Ok(c.query_row("SELECT value FROM settings WHERE key=?1", rusqlite::params![key], |r| r.get::<_, String>(0)).ok())
+ })
+ .ok()
+ .flatten()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(default)
+}
+
+/// A consistent snapshot of the database, written to `dest`.
+///
+/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave
+/// with a write, and it produces a compacted single file with no WAL — which is
+/// what you want to be holding at 3am when the main file is gone. A `cp` of a
+/// live WAL database gives you a main file and a sidecar log that may or may not
+/// belong to it, and you find out which during the restore.
+pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> {
+ let dest = dest.to_path_buf();
+ if dest.exists() {
+ return Err(crate::error::Error::not_found(format!(
+ "refusing to overwrite an existing backup: {}",
+ dest.display()
+ )));
+ }
+ if let Some(parent) = dest.parent() {
+ if !parent.as_os_str().is_empty() && !parent.exists() {
+ std::fs::create_dir_all(parent)?;
+ }
+ }
+ let sql = format!("VACUUM INTO '{}'", dest.display().to_string().replace('\'', "''"));
+ db.writer.call(move |conn| {
+ conn.execute_batch(&sql)
+ .map_err(|e| crate::error::Error::db(format!("VACUUM INTO: {e}")))?;
+ Ok(())
+ })?;
+ // The snapshot must be readable on its own: if it does not open and report
+ // the same schema version, the backup is a file, not a backup.
+ let probe = rusqlite::Connection::open(&dest)
+ .map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?;
+ let version: i64 = probe
+ .query_row("PRAGMA user_version", [], |r| r.get(0))
+ .map_err(|e| crate::error::Error::db(format!("backup has no schema: {e}")))?;
+ if version <= 0 {
+ return Err(crate::error::Error::db("backup does not contain a migrated database"));
+ }
+ let _ = db::audit_system(
+ &db.writer,
+ "backup",
+ "vacuum_into",
+ &dest.display().to_string(),
+ serde_json::json!({ "bytes": file_len(&dest), "schema_version": version }),
+ );
+ Ok(dest)
+}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 8d5497e..661e248 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -523,7 +523,15 @@ impl Web {
Err(e) => panic!("GET {path}: {e}"),
};
let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default();
- (vec![("set-cookie".to_string(), cookie)], r.into_string().unwrap_or_default())
+ let mut headers = vec![("set-cookie".to_string(), cookie)];
+ // ureq 2 will not hand out the whole header map, but it will answer for a
+ // named one, which is all the assertions below need.
+ for name in ["content-type", "content-encoding", "location"] {
+ if let Some(v) = r.header(name) {
+ headers.push((name.to_string(), v.to_string()));
+ }
+ }
+ (headers, r.into_string().unwrap_or_default())
}
pub fn get(&self, path: &str) -> Page {
diff --git a/tests/db.rs b/tests/db.rs
index 15c8319..e2608a1 100644
--- a/tests/db.rs
+++ b/tests/db.rs
@@ -39,7 +39,7 @@ fn migrations_apply_from_empty_and_are_idempotent() {
Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?)
})
.unwrap();
- assert_eq!(v, 7, "all migrations applied");
+ assert_eq!(v as usize, db::MIGRATIONS.len(), "all migrations applied");
// Re-running migration over an existing DB is a no-op, not an error.
assert_eq!(db::migrate(&env.cfg.db_path()).unwrap(), 0);
let journal: String = env
diff --git a/tests/ops.rs b/tests/ops.rs
new file mode 100644
index 0000000..305976e
--- /dev/null
+++ b/tests/ops.rs
@@ -0,0 +1,381 @@
+//! Retention, metrics and backups (§15).
+//!
+//! These are the features that only get tested when something goes wrong, which
+//! is why they are specified here as behaviour rather than as functions that
+//! exist. The load-bearing claims: retention never evicts a byte the index is
+//! serving, it treats a package and its log and its sources as one unit, and it
+//! never deletes the history that explains the bytes. Metrics are computed from
+//! live state, so they cannot drift. Backups are `VACUUM INTO`, so they restore.
+
+mod common;
+
+use std::path::{Path, PathBuf};
+
+use aur_build::ops;
+use aur_build::pipeline;
+use aur_build::review::{candidates, diff};
+use common::*;
+
+fn approve_and_build(env: &Env, name: &str) {
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ pipeline::run(&env.cfg, &env.db, &id).unwrap();
+}
+
+/// Publish the same pkgbase N times, each at a higher version.
+fn publish_versions(env: &Env, fx: &Fixture, name: &str, n: usize) {
+ approve_and_build(env, name);
+ for i in 1..n {
+ fx.bump(&[("pkgver", &format!("1.{i}"))]);
+ approve_and_build(env, name);
+ }
+}
+
+fn artifact_paths(env: &Env) -> Vec<PathBuf> {
+ env.db
+ .read(|c| {
+ let mut st = c.prepare("SELECT path FROM artifact ORDER BY id")?;
+ let rows = st.query_map([], |r| r.get::<_, String>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(PathBuf::from(r?));
+ }
+ Ok::<_, aur_build::Error>(out)
+ })
+ .unwrap()
+}
+
+#[test]
+fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() {
+ let (env, fx) = env_with_fixture("plain-make");
+ publish_versions(&env, &fx, "plain-make", 5);
+ let before = artifact_paths(&env);
+ assert_eq!(before.len(), 5, "five published versions");
+ for p in &before {
+ assert!(p.exists(), "every published artifact should be on disk: {}", p.display());
+ }
+
+ let report = ops::retention(&env.cfg, &env.db, Some(2)).unwrap();
+ assert_eq!(report.releases_evicted, 3, "5 versions, keep 2: {report:?}");
+ assert!(report.files_removed >= 3, "each evicted release removes its package: {report:?}");
+
+ // The newest two survive; the older three lose their bytes.
+ let kept: Vec<PathBuf> = env
+ .db
+ .read(|c| {
+ let mut st = c.prepare("SELECT path FROM artifact WHERE purged_at IS NULL ORDER BY id")?;
+ let rows = st.query_map([], |r| r.get::<_, String>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(PathBuf::from(r?));
+ }
+ Ok::<_, aur_build::Error>(out)
+ })
+ .unwrap();
+ assert_eq!(kept.len(), 2, "exactly the keep window survives: {kept:?}");
+ for p in &kept {
+ assert!(p.exists(), "a retained artifact must still be on disk: {}", p.display());
+ }
+ for p in before.iter().rev().skip(2) {
+ assert!(!p.exists(), "an evicted artifact should be gone: {}", p.display());
+ }
+
+ // Nothing was forgotten: the rows are all still there, marked as purged
+ // rather than removed, so "which bytes produced this" stays answerable as
+ // history even once the bytes are gone.
+ assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5));
+ assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5));
+ assert_eq!(
+ env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]),
+ Some(3)
+ );
+ assert_eq!(
+ env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]),
+ Some(3)
+ );
+ // And the run itself is on the record.
+ assert_eq!(env.query_i64("SELECT count(*) FROM gc_run", &[]), Some(1));
+ assert!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]) == Some(1));
+}
+
+#[test]
+fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() {
+ let (env, fx) = env_with_fixture("plain-make");
+ publish_versions(&env, &fx, "plain-make", 4);
+ let oldest = env
+ .db
+ .read(|c| {
+ Ok(c.query_row(
+ "SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1",
+ [],
+ |r| r.get::<_, i64>(0),
+ )?)
+ })
+ .unwrap();
+ let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap();
+ // Compare against what the database says the release holds, rather than
+ // guessing from filename shapes: the store is content-addressed, so the
+ // package file is a bare hex name and "does it look like a package" is not
+ // a question the path can answer.
+ let held: Vec<(Option<String>, Option<String>, Option<String>)> = env
+ .db
+ .read(|c| {
+ let mut st = c.prepare(
+ "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a
+ JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1",
+ )?;
+ let rows = st.query_map(rusqlite::params![oldest], |r| {
+ Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok::<_, aur_build::Error>(out)
+ })
+ .unwrap();
+ assert_eq!(held.len(), 1, "one artifact for this release: {held:?}");
+ let (pkg, sig, log) = &held[0];
+ for (what, p) in [("package", pkg), ("signature", sig), ("build log", log)] {
+ let p = p.as_ref().unwrap_or_else(|| panic!("the release should hold a {what}"));
+ assert!(
+ files.iter().any(|f| f == Path::new(p)),
+ "release_files must include the {what} ({p}): {files:?}"
+ );
+ assert!(Path::new(p).exists(), "the {what} should exist before eviction");
+ }
+
+ // Eviction removes them together. A package whose log is gone but whose bytes
+ // remain is the worst outcome: full price, no explanation.
+ ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
+ let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect();
+ assert!(
+ still_there.is_empty(),
+ "evicting a release must take its log and signature with it: {still_there:?}"
+ );
+}
+
+#[test]
+fn retention_never_evicts_the_version_the_index_is_serving() {
+ // The interesting case: the accepted release is *not* the newest one, because
+ // the newest build has not happened yet. A naive "keep the newest N" would
+ // delete the bytes the index is pointing at.
+ let (env, fx) = env_with_fixture("plain-make");
+ publish_versions(&env, &fx, "plain-make", 2);
+ let served = env
+ .db
+ .read(|c| {
+ Ok(c.query_row(
+ "SELECT a.path FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.state='in_index'",
+ [],
+ |r| r.get::<_, String>(0),
+ )?)
+ })
+ .unwrap();
+ let served_release = env
+ .db
+ .read(|c| {
+ Ok(c.query_row(
+ "SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1",
+ [],
+ |r| r.get::<_, i64>(0),
+ )?)
+ })
+ .unwrap();
+
+ // Publish a third version, then pretend the index still serves the first by
+ // withdrawing the newer ones from the index.
+ env.exec("UPDATE package SET state='removed' WHERE state='in_index'", &[]);
+ env.exec(
+ "UPDATE package SET state='in_index' WHERE release_id=?1",
+ &[P::I(served_release)],
+ );
+ let report = ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
+ assert!(report.releases_evicted >= 1, "something should have been evicted: {report:?}");
+ assert!(
+ Path::new(&served).exists(),
+ "retention deleted the artifact the index is serving: {served}"
+ );
+}
+
+#[test]
+fn staging_dirs_are_swept_only_when_their_build_is_finished() {
+ let (env, fx) = env_with_fixture("plain-make");
+ approve_and_build(&env, "plain-make");
+
+ // An old dir belonging to a finished build: disposable.
+ let done = env.cfg.staging_dir().join("finished-build");
+ // An old dir with no build row at all: left over from a crash.
+ let orphan = env.cfg.staging_dir().join("no-such-build");
+ // An old dir whose build is still running: NOT disposable, however old it is.
+ let live = env.cfg.staging_dir().join("live-build");
+ for d in [&done, &orphan, &live] {
+ std::fs::create_dir_all(d).unwrap();
+ std::fs::write(d.join("pkg.tar.zst"), vec![b'x'; 4096]).unwrap();
+ backdate(d, 7200);
+ }
+ env.exec(
+ "INSERT INTO build (id, pkgbase_id, candidate_id, kind, build_profile, state, attempt, created_at, updated_at)
+ VALUES ('live-build', 1, 1, 'new_version', 'default', 'running', 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z')",
+ &[],
+ );
+ let _ = fx;
+
+ let (swept, freed) = ops::sweep_staging(&env.cfg, &env.db, ops::STAGING_GRACE_SECS).unwrap();
+ assert_eq!(swept, 2, "the finished and the orphaned dir go; the running one stays");
+ assert_eq!(freed, 8192, "two dirs of 4 KiB each");
+ assert!(!done.exists(), "a finished build's staging is disposable");
+ assert!(!orphan.exists(), "a staging dir with no build row is abandoned");
+ assert!(live.exists(), "a long-running build is not an abandoned one");
+}
+
+#[test]
+fn metrics_reports_the_operating_numbers_in_prometheus_format() {
+ let (env, fx) = env_with_fixture("plain-make");
+ approve_and_build(&env, "plain-make");
+ // Leave one review unapproved so there is review debt to measure.
+ fx.bump(&[("pkgver", "9.9")]);
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
+ // And a queued build that has never run, so queue depth is not vacuously zero.
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let _ = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c);
+
+ let m = ops::metrics(&env.cfg, &env.db).unwrap();
+ let text = m.to_prometheus();
+
+ // Every family the contract names, and each one parseable as a Prometheus
+ // sample: `name{labels} value`, preceded by its TYPE line.
+ for family in [
+ "aurbuild_queue_depth",
+ "aurbuild_pending_review_candidates",
+ "aurbuild_pending_review_age_seconds_bucket",
+ "aurbuild_build_success_rate",
+ "aurbuild_sqlite_wal_size_bytes",
+ "aurbuild_builds_total",
+ "aurbuild_index_packages",
+ "aurbuild_stale_releases",
+ ] {
+ assert!(text.contains(family), "missing metric {family}: {text}");
+ }
+ for line in text.lines().filter(|l| !l.starts_with('#')) {
+ let tail = line.rsplit(' ').next().unwrap_or("");
+ assert!(
+ tail.parse::<f64>().is_ok(),
+ "not a prometheus sample: {line:?}"
+ );
+ }
+ for line in text.lines().filter(|l| l.starts_with("# TYPE")) {
+ let name = line.split_whitespace().nth(2).unwrap();
+ assert!(
+ text.contains(&format!("{name} ")) || text.contains(&format!("{name}{{")),
+ "family {name} declared but never sampled"
+ );
+ }
+
+ assert_eq!(m.queue_depth, 1, "one queued build");
+ assert_eq!(m.pending_review, 1, "one review waiting");
+ assert_eq!(m.review_ages.len(), 1);
+ assert_eq!(m.succeeded, 1);
+ assert_eq!(m.failed, 0);
+ assert!((m.build_success_rate() - 1.0).abs() < 1e-9);
+ assert!(m.db_bytes > 0, "the database file has a size");
+ assert!(
+ text.contains("aurbuild_pending_review_age_seconds_bucket{le=\"+Inf\"} 1"),
+ "histograms need a +Inf bucket: {text}"
+ );
+ assert!(text.contains("aurbuild_pending_review_age_seconds_count 1"));
+ assert!(text.contains("aurbuild_pending_review_age_seconds_sum"));
+}
+
+#[test]
+fn a_fresh_install_reports_a_clean_sheet_not_a_division_by_zero() {
+ // A brand-new install has no builds at all. Success rate has to be something
+ // an alert rule can read, not NaN and not 0% (which would page).
+ let env = Env::new();
+ let m = ops::metrics(&env.cfg, &env.db).unwrap();
+ assert_eq!(m.succeeded + m.failed, 0);
+ assert!((m.build_success_rate() - 1.0).abs() < 1e-9, "no builds yet should read as healthy");
+ assert!(m.to_prometheus().contains("aurbuild_up 1"));
+}
+
+#[test]
+fn the_http_metrics_endpoint_serves_scrapeable_text() {
+ let web = Web::new("plain-make");
+ let page = web.get("/metrics");
+ assert_eq!(page.status, 200);
+ assert!(page.body.contains("# TYPE aurbuild_queue_depth gauge"));
+ assert!(page.body.contains("aurbuild_sqlite_wal_size_bytes"));
+ // No session needed: a scraper cannot log in. Check it with a bare socket.
+ let (headers, body) = web.raw_get("/metrics");
+ assert!(body.contains("aurbuild_up 1"), "metrics should be reachable unauthenticated");
+ let ct = headers
+ .iter()
+ .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
+ .map(|(_, v)| v.clone())
+ .unwrap_or_default();
+ assert!(ct.starts_with("text/plain"), "a scraper wants text/plain, got {ct}");
+}
+
+#[test]
+fn backup_is_a_consistent_single_file_that_reopens_and_matches() {
+ let (env, _fx) = env_with_fixture("plain-make");
+ approve_and_build(&env, "plain-make");
+ let dest = env.root().join("backup/aur-build.db");
+ let out = ops::backup(&env.db, &dest).unwrap();
+ assert_eq!(out, dest);
+
+ // A single file: `VACUUM INTO` produces a compacted database with no WAL, so
+ // the backup is one object that can be copied while the server keeps running.
+ assert!(dest.exists());
+ assert!(!Path::new(&format!("{}-wal", dest.display())).exists(), "a backup must not need a sidecar");
+ assert!(!Path::new(&format!("{}-shm", dest.display())).exists());
+
+ // It is a real database with the same schema and the same crown jewel: the
+ // approval trail.
+ let probe = rusqlite::Connection::open(&dest).unwrap();
+ let version: i64 = probe.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();
+ assert!(version >= 8, "the snapshot carries the migrated schema, got {version}");
+ let approvals: i64 = probe.query_row("SELECT count(*) FROM approval", [], |r| r.get(0)).unwrap();
+ assert_eq!(approvals, 1, "the approval history is the reason backups exist");
+ let releases: i64 = probe.query_row("SELECT count(*) FROM release", [], |r| r.get(0)).unwrap();
+ assert_eq!(releases, 1);
+ drop(probe);
+
+ // The live database is untouched and still in WAL mode — the backup did not
+ // checkpoint it out from under the running server.
+ let mode: String = env
+ .db
+ .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?))
+ .unwrap();
+ assert_eq!(mode.to_lowercase(), "wal", "the live db should still be WAL");
+ assert!(env.query_i64("SELECT count(*) FROM approval", &[]) == Some(1));
+}
+
+#[test]
+fn backup_refuses_to_overwrite_an_existing_snapshot() {
+ // A backup that silently replaces last week's backup is not a backup; it is a
+ // way of losing the only copy on the day you need it.
+ let (env, _fx) = env_with_fixture("plain-make");
+ approve_and_build(&env, "plain-make");
+ let dest = env.root().join("snap.db");
+ ops::backup(&env.db, &dest).unwrap();
+ let second = ops::backup(&env.db, &dest);
+ assert!(second.is_err(), "overwriting an existing backup must be refused");
+ assert!(dest.exists(), "the refusal must not have truncated the existing file");
+ assert!(std::fs::metadata(&dest).unwrap().len() > 0);
+}
+
+/// Set a directory's mtime into the past, so the grace period can be exercised
+/// without sleeping for an hour.
+fn backdate(path: &Path, secs: u64) {
+ let old = std::time::SystemTime::now() - std::time::Duration::from_secs(secs);
+ for f in std::fs::read_dir(path).into_iter().flatten().flatten() {
+ let _ = std::fs::File::open(f.path()).and_then(|f| f.set_modified(old));
+ }
+ let _ = std::fs::File::open(path).and_then(|f| f.set_modified(old));
+}