From f586d11f6a1711145ba4804787217a1bab58751d Mon Sep 17 00:00:00 2001 From: aur-build Date: Tue, 17 Nov 2026 21:19:35 +0000 Subject: feat: AUR mirror watcher, recipe parsing, candidate creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The detection path (§5.1, §5.1a, §5.3, §7.1): * git helpers, all subprocess git in one auditable place. Mirrors are cloned with --mirror and polled with git ls-remote, fetching only when the tip actually moved; --no-prune keeps history we may need forever. * .SRCINFO parsing (authoritative) with a PKGBUILD fallback, and source=() parsing that keeps VCS kind, #commit/#tag/#branch refs and the filename:: form. * recipe_hash over the whole snapshot tree, so a shipped patch is part of the recipe and cannot change silently. * source digest resolution: declared checksums are trusted-as-declared (makepkg enforces them, no bandwidth), local files are hashed from the mirror, and SKIP sources are downloaded and stream-hashed into the content-addressed source cache. Detection always re-fetches SKIP sources — answering from our own cache would defeat drift detection. * candidate creation with base = current_accepted_release, collapse in place while unviewed, supersede only once a human has looked, and a previously rejected identity is not re-raised. * non-publishable change handling (I11): unchanged version string means no review, but never silence — recipe drift and pin drift become notices, and a changed digest on a remote source with an unchanged version becomes a high-severity integrity_alert. Also vercmp + dep-string parsing with the ALPM test vectors, and the approval record with optimistic concurrency (§7.1a) that the CLI and web layers will both call. 16 detection tests against real file:// git fixtures, incl. I2 across three unattended detections and I11 for all three drift kinds. Part of P0 (DESIGN.md §17). --- .pi/.goals-pool-snapshot.json | 2 +- .pi/goals/.goal-ledger-checkpoint.json | 2 +- ...active_goal_2026111720432444_mwl5tehk-xhe7fk.md | 20 +- .pi/goals/goal_events.jsonl | 2 + src/db/mod.rs | 6 +- src/db/model.rs | 3 + src/fetch.rs | 65 ++++ src/git.rs | 238 ++++++++++++ src/lib.rs | 5 + src/pkgver/mod.rs | 59 +++ src/recipe.rs | 426 ++++++++++++++++++++ src/review/approve.rs | 267 +++++++++++++ src/review/candidates.rs | 293 ++++++++++++++ src/review/diff.rs | 156 ++++++++ src/review/mod.rs | 8 + src/watch/detect.rs | 288 ++++++++++++++ src/watch/digests.rs | 193 ++++++++++ src/watch/mirror.rs | 119 ++++++ src/watch/mod.rs | 12 + src/watch/scheduler.rs | 71 ++++ tests/common/mod.rs | 48 +++ tests/detect.rs | 428 +++++++++++++++++++++ 22 files changed, 2697 insertions(+), 14 deletions(-) create mode 100644 src/fetch.rs create mode 100644 src/git.rs create mode 100644 src/recipe.rs create mode 100644 src/review/approve.rs create mode 100644 src/review/candidates.rs create mode 100644 src/review/diff.rs create mode 100644 src/review/mod.rs create mode 100644 src/watch/detect.rs create mode 100644 src/watch/digests.rs create mode 100644 src/watch/mirror.rs create mode 100644 src/watch/mod.rs create mode 100644 src/watch/scheduler.rs create mode 100644 tests/detect.rs diff --git a/.pi/.goals-pool-snapshot.json b/.pi/.goals-pool-snapshot.json index 11f0b89..bf2cb53 100644 --- a/.pi/.goals-pool-snapshot.json +++ b/.pi/.goals-pool-snapshot.json @@ -1 +1 @@ -{"version":1,"dirMtimeMs":1794949184563.521,"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":342691,"activeSeconds":955},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-17T20:59:44.561Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":57,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"c7162450-1294-427e-aa34-597ba566e462","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"ready"},"dispatch":{"id":"b07063cc-4112-4b45-b62f-b597761e0d52","kind":"ready","claimedAt":1794948204539}},"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":"pending","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"pending","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."},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"pending","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."},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"pending","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."},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"pending","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."},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"pending","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."},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"pending","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)."}]},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"pending","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"pending","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."},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"pending","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."},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"pending","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."}]},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"pending","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."},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"pending","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."},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"pending","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."},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"pending","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)."}]},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"pending","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"pending","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."},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"pending","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'."},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"pending","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."}]},{"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":"pending","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."},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"pending","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'."},{"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-p0-schema"}]} \ No newline at end of file +{"version":1,"dirMtimeMs":1794950339520.5022,"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":790359,"activeSeconds":2083},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-17T21:18:59.512Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":113,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"c7162450-1294-427e-aa34-597ba566e462","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"ready"},"dispatch":{"id":"b07063cc-4112-4b45-b62f-b597761e0d52","kind":"ready","claimedAt":1794948204539}},"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":"pending","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":"pending","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."},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"pending","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."},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"pending","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."},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"pending","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."},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"pending","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)."}]},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"pending","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"pending","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."},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"pending","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."},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"pending","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."}]},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"pending","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."},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"pending","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."},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"pending","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."},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"pending","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)."}]},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"pending","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"pending","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."},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"pending","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'."},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"pending","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."}]},{"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":"pending","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."},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"pending","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'."},{"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-p0-detect"}]} \ No newline at end of file diff --git a/.pi/goals/.goal-ledger-checkpoint.json b/.pi/goals/.goal-ledger-checkpoint.json index 1de8283..c6dc2ea 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-17T20:48:42.928Z","coveredBytes":4312,"coveredEvents":5,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"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_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":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"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"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_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":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"}],"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"}],"oracle":[],"lifecycle":{"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"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"}}]]} \ No newline at end of file +{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-17T21:00:48.001Z","coveredBytes":4747,"coveredEvents":7,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"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_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":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"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"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_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":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"}],"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"}],"oracle":[],"lifecycle":{"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"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"}}]]} \ 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 a54de59..957cea5 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": 342691, - "activeSeconds": 955 + "tokensUsed": 790359, + "activeSeconds": 2083 }, "sisyphus": false, "createdAt": "2026-11-17T20:43:24.440Z", - "updatedAt": "2026-11-17T20:59:44.561Z", + "updatedAt": "2026-11-17T21:18:59.512Z", "activePath": ".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md", - "revision": 57, + "revision": 113, "scheduler": { "version": 1, "owner": "01a1eb32-2e3f-757c-a79a-21ac993facc5", @@ -48,8 +48,10 @@ { "id": "task-p0-schema", "title": "SQLite schema, migrations, and single writer actor (§11, §11a)", - "status": "pending", - "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." + "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", @@ -205,7 +207,7 @@ "blockCompletion": true, "proposedAt": "2026-11-17T20:39:23.165Z" }, - "currentTaskId": "task-p0-schema" + "currentTaskId": "task-p0-detect" } # Goal Prompt @@ -238,8 +240,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: 15m55s -- Tokens used: 343K (342,691) tokens +- Time spent: 34m43s +- Tokens used: 790K (790,359) tokens ## Tasks diff --git a/.pi/goals/goal_events.jsonl b/.pi/goals/goal_events.jsonl index 271fe31..3551e1a 100644 --- a/.pi/goals/goal_events.jsonl +++ b/.pi/goals/goal_events.jsonl @@ -3,3 +3,5 @@ {"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"} diff --git a/src/db/mod.rs b/src/db/mod.rs index c11bf5a..a841fec 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -8,9 +8,9 @@ //! design entirely. Readers are thread-local, read-only connections; WAL lets //! them proceed concurrently with the writer. -mod migrations; -mod model; -mod queries; +pub mod migrations; +pub mod model; +pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; diff --git a/src/db/model.rs b/src/db/model.rs index 599fc21..66674ab 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -197,6 +197,9 @@ pub struct Recipe { pub srcinfo: Option, /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, + /// Parsed `source=()` entries. Derived from `source`, so not serialized. + #[serde(skip, default)] + pub source_entries: Vec, } impl Recipe { diff --git a/src/fetch.rs b/src/fetch.rs new file mode 100644 index 0000000..c1c4575 --- /dev/null +++ b/src/fetch.rs @@ -0,0 +1,65 @@ +//! Outbound HTTP. `ureq` is blocking, which is the whole point of this stack +//! (DESIGN.md §4: "`reqwest` pulls in tokio even in blocking mode — avoid"). +//! +//! `file://` is supported as a first-class scheme so the test corpus can serve +//! sources from disk with no network (§16a). + +use std::io::{Read, Write}; +use std::path::PathBuf; + +use crate::error::{Error, Result}; + +pub enum Body { + File(std::fs::File), + Http(Box), +} + +impl Read for Body { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + match self { + Body::File(f) => f.read(buf), + Body::Http(r) => r.read(buf), + } + } +} + +/// Open a URL for streaming. Never buffers the whole body: sources are hashed +/// while they are written into the cache (§5.3). +pub fn open(url: &str) -> Result<(Body, Option)> { + if let Some(path) = url.strip_prefix("file://") { + let p = path.trim_start_matches('/'); + let p = PathBuf::from(format!("/{p}")); + let f = std::fs::File::open(&p).map_err(|e| Error::Http(format!("{url}: {e}")))?; + let len = f.metadata().map(|m| m.len()).ok(); + return Ok((Body::File(f), len)); + } + if url.starts_with("http://") || url.starts_with("https://") { + let resp = ureq::get(url) + .timeout(std::time::Duration::from_secs(300)) + .call() + .map_err(|e| Error::Http(format!("{url}: {e}")))?; + let len = resp + .header("content-length") + .and_then(|v| v.parse::().ok()); + return Ok((Body::Http(resp.into_reader()), len)); + } + Err(Error::invalid(format!("unsupported url scheme: {url}"))) +} + +/// Fetch `url` into `dest`, returning `(sha256, size)`. +pub fn fetch_to(url: &str, dest: &std::path::Path) -> Result<(String, u64)> { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + let (body, _len) = open(url)?; + let mut tmp = dest.as_os_str().to_os_string(); + tmp.push(".part"); + let tmp = PathBuf::from(tmp); + let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?); + let (digest, size) = crate::hash::digest_reader(std::io::BufReader::new(body), Some(&mut file)) + .map_err(|e| Error::Http(format!("{url}: {e}")))?; + file.flush()?; + // Rename into place: a half-written cache entry must never be visible. + std::fs::rename(&tmp, dest)?; + Ok((digest, size)) +} diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..6c1f442 --- /dev/null +++ b/src/git.rs @@ -0,0 +1,238 @@ +//! Shelling out to `git` (DESIGN.md §4: "shell out to git ... avoids libgit2 +//! build pain"). +//! +//! Every git operation the system performs goes through here so the subprocess +//! surface is auditable in one place. + +use std::path::Path; +use std::process::{Command, Output}; + +use crate::error::{Error, Result}; + +/// Run git and capture output; non-zero status becomes `Error::Git`. +pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result { + let mut cmd = Command::new("git"); + if let Some(c) = cwd { + cmd.current_dir(c); + } + cmd.args(args); + // Never let a stray terminal prompt hang a watcher thread. + cmd.env("GIT_TERMINAL_PROMPT", "0"); + cmd.env("GIT_CONFIG_NOSYSTEM", "1"); + cmd.env("LC_ALL", "C"); + let out = cmd.output().map_err(|e| Error::git(format!("git {args:?}: {e}")))?; + ok(out, args) +} + +fn ok(out: Output, args: &[&str]) -> Result { + if !out.status.success() { + return Err(Error::git(format!( + "git {args:?} exited {}: {}", + out.status, + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + Ok(String::from_utf8_lossy(&out.stdout).to_string()) +} + +/// Run git, discarding output, returning success/failure without allocating. +pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool { + git(cwd, args).is_ok() +} + +/// `git ls-remote HEAD` — the cheap poll (§5.1). Returns the remote HEAD +/// SHA, or `None` when the remote is gone (deletion / orphan handling). +pub fn ls_remote_head(url: &str) -> Result> { + match git(None, &["ls-remote", url, "HEAD"]) { + Ok(out) => { + let sha = out + .split_whitespace() + .next() + .filter(|s| s.len() >= 7) + .map(|s| s.to_string()); + Ok(sha) + } + Err(e) if is_missing_remote(&e) => Ok(None), + Err(e) => Err(e), + } +} + +/// `ls-remote --heads `: every branch tip, as `(refname, sha)`. +pub fn ls_remote_heads(url: &str) -> Result> { + let out = git(None, &["ls-remote", "--heads", url])?; + let mut v = Vec::new(); + for line in out.lines() { + let mut it = line.split_whitespace(); + if let (Some(sha), Some(name)) = (it.next(), it.next()) { + v.push((name.to_string(), sha.to_string())); + } + } + Ok(v) +} + +/// Ask a single remote ref for its SHA, e.g. `refs/tags/v1.2` or a full commit. +pub fn ls_remote_ref(url: &str, refname: &str) -> Result> { + match git(None, &["ls-remote", url, refname]) { + Ok(out) => Ok(out + .lines() + .next() + .and_then(|l| l.split_whitespace().next()) + .map(|s| s.to_string())), + Err(e) if is_missing_remote(&e) => Ok(None), + Err(e) => Err(e), + } +} + +fn is_missing_remote(e: &Error) -> bool { + let s = e.to_string(); + s.contains("not found") + || s.contains("does not appear to be a git repository") + || s.contains("Repository not found") + || s.contains("404") +} + +/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs +/// (a plain clone would leave HEAD on the original commit), and **never** +/// `--filter=blob:none`: a partial clone can lazily drop blobs and we must be +/// able to materialize any historical commit forever (§5.1). +pub fn clone(url: &str, dest: &Path) -> Result<()> { + if dest.exists() { + return Ok(()); + } + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + git(None, &["clone", "--quiet", "--mirror", url, &dest.display().to_string()])?; + Ok(()) +} + +/// `git clone --bare` for the upstream VCS cache. +pub fn clone_bare(url: &str, dest: &Path) -> Result<()> { + if dest.exists() { + return Ok(()); + } + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + git( + None, + &["clone", "--quiet", "--bare", url, &dest.display().to_string()], + )?; + Ok(()) +} + +/// Fetch into an existing mirror. Returns the new HEAD. +pub fn fetch_head(mirror: &Path) -> Result { + // `--no-prune` mirrors the "never GC a commit we may need" rule (§5.1a). + git(Some(mirror), &["fetch", "--quiet", "--no-prune", "origin"])?; + head(mirror) +} + +pub fn head(mirror: &Path) -> Result { + Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string()) +} + +/// True if `commit` exists in the local mirror. Guards against a force-pushed +/// AUR history making a pin vanish (§16 mirror divergence). +pub fn has_commit(mirror: &Path, commit: &str) -> bool { + git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")]) +} + +/// `git ls-tree -r `: every `(path, blob-sha)` in the tree. +pub fn ls_tree(mirror: &Path, commit: &str) -> Result> { + let out = git(Some(mirror), &["ls-tree", "-r", commit])?; + let mut v = Vec::new(); + for line in out.lines() { + // " blob \t" + if let Some(rest) = line.strip_prefix("100644 blob ").or_else(|| line.strip_prefix("100755 blob ")) { + if let Some((sha, path)) = rest.split_once('\t') { + v.push((path.to_string(), sha.to_string())); + } + } + } + Ok(v) +} + +pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result> { + let spec = format!("{commit}:{path}"); + let out = Command::new("git") + .current_dir(mirror) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_CONFIG_NOSYSTEM", "1") + .args(["cat-file", "blob", &spec]) + .output() + .map_err(|e| Error::git(e.to_string()))?; + if !out.status.success() { + return Err(Error::not_found(format!("{spec} not in mirror"))); + } + Ok(out.stdout) +} + +/// Materialize a commit into `dest` using the local mirror only — no network +/// (§8.1 step 0). `git archive` + tar keeps it dependency-free. +pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { + std::fs::create_dir_all(dest)?; + let out = Command::new("git") + .current_dir(mirror) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_CONFIG_NOSYSTEM", "1") + .args(["archive", "--format=tar", commit]) + .output() + .map_err(|e| Error::git(e.to_string()))?; + if !out.status.success() { + return Err(Error::git(format!( + "git archive {commit}: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + let mut ar = tar::Archive::new(std::io::Cursor::new(&out.stdout)); + ar.set_preserve_permissions(true); + ar.unpack(dest) + .map_err(|e| Error::git(format!("unpack {commit}: {e}")))?; + Ok(()) +} + +/// `git log --oneline range` — review context (§5.1) and the upstream delta +/// panel (§6). +pub fn log_oneline(mirror: &Path, range: &str) -> Result> { + let out = git(Some(mirror), &["log", "--oneline", range])?; + Ok(out.lines().map(|l| l.to_string()).collect()) +} + +/// `git diff range -- `; empty `paths` means everything. +pub fn diff(mirror: &Path, range: &str, paths: &[&str]) -> Result { + let mut args: Vec<&str> = vec!["diff", "--no-color", range, "--"]; + args.extend(paths); + git(Some(mirror), &args) +} + +/// `git rev-list --count range`. +pub fn count_commits(mirror: &Path, range: &str) -> Result { + let out = git(Some(mirror), &["rev-list", "--count", range])?; + Ok(out.trim().parse().unwrap_or(0)) +} + +/// Clone a VCS source the way a PKGBUILD would (depth/ref aware) into `dest`. +pub fn clone_source(url: &str, dest: &Path, depth: Option, branch: Option<&str>) -> Result<()> { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + let mut args: Vec = vec!["clone".into(), "--quiet".into()]; + if let Some(d) = depth { + args.push(format!("--depth={d}")); + } + if let Some(b) = branch { + args.push(format!("--branch={b}")); + } + args.push(url.to_string()); + args.push(dest.display().to_string()); + let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); + git(None, &refs)?; + Ok(()) +} + +/// Fetch into an existing clone and return HEAD. +pub fn fetch_and_head(repo: &Path) -> Result { + git(Some(repo), &["fetch", "--quiet", "--no-prune", "origin"])?; + head(repo) +} diff --git a/src/lib.rs b/src/lib.rs index f87c598..f60f941 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,8 +8,13 @@ pub mod config; pub mod db; pub mod error; +pub mod fetch; +pub mod git; pub mod hash; pub mod pkgver; +pub mod recipe; +pub mod review; pub mod time; +pub mod watch; pub use error::{Error, Result}; diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs index a940dc0..75be308 100644 --- a/src/pkgver/mod.rs +++ b/src/pkgver/mod.rs @@ -271,3 +271,62 @@ pub fn parse_deps(list: &[String]) -> Vec { pub fn dep_names(list: &[String]) -> Vec { parse_deps(list).into_iter().map(|d| d.name).collect() } + +#[cfg(test)] +mod tests { + use super::*; + + fn ord(a: &str, b: &str) -> Ordering { + vercmp(a, b) + } + + #[test] + fn alpm_version_ordering() { + // The classic ALPM test vectors. + assert_eq!(ord("1.0-1", "1.0-1"), Ordering::Equal); + assert_eq!(ord("1.0-1", "1.0-2"), Ordering::Less); + assert_eq!(ord("1.1-1", "1.0-1"), Ordering::Greater); + assert_eq!(ord("1.10-1", "1.9-1"), Ordering::Greater, "numeric chunks compare numerically"); + assert_eq!(ord("1.0.a-1", "1.0.1-1"), Ordering::Greater, "alpha sorts after numeric"); + assert_eq!(ord("1.5-1", "1.5.0-1"), Ordering::Less, "a trailing numeric chunk is newer"); + assert_eq!(ord("1:1.0-1", "2.0-1"), Ordering::Greater, "epoch dominates"); + assert_eq!(ord("1.0-1", "1.0_2-1"), Ordering::Less, "non-alnum separators are ignored"); + assert_eq!(ord("1.0.0-1", "1.0-1"), Ordering::Greater, "a trailing numeric chunk is newer"); + assert_eq!(ord("01.0-1", "1.0-1"), Ordering::Equal, "leading zeros are not significant"); + } + + #[test] + fn full_version_formatting() { + assert_eq!(full_version("0", "1.0", "1"), "1.0-1"); + assert_eq!(full_version("", "1.0", "1"), "1.0-1"); + assert_eq!(full_version("2", "1.0", "3"), "2:1.0-3"); + assert_eq!(split_full_version("2:1.0-3").0, "2"); + assert_eq!(split_full_version("1.0-3"), ("0".into(), "1.0".into(), "3".into())); + } + + #[test] + fn pkgrel_reset_is_a_new_version() { + // §3: a pkgrel reset is a major signal. + assert_eq!(ord("1.0-7", "1.0-1"), Ordering::Greater); + assert!(is_downgrade("1.0-7", "1.0-1")); + } + + #[test] + fn dep_strings_parse() { + assert_eq!(Dep::parse("foo").unwrap(), Dep { name: "foo".into(), op: DepOp::Any, version: None }); + assert_eq!(Dep::parse("foo>=1.2").unwrap().op, DepOp::Ge); + assert_eq!(Dep::parse("foo<=1.2").unwrap().op, DepOp::Le); + assert_eq!(Dep::parse("foo=1.2-3").unwrap().version.as_deref(), Some("1.2-3")); + assert_eq!(Dep::parse("python-numpy").unwrap().name, "python-numpy"); + assert_eq!(Dep::parse("cmake: for building").unwrap().name, "cmake"); + assert!(Dep::parse("").is_none()); + } + + #[test] + fn version_constraints_are_checked() { + let d = Dep::parse("python>=3.11").unwrap(); + assert!(d.satisfied_by("3.12-1")); + assert!(!d.satisfied_by("3.10-1")); + assert!(Dep::parse("foo").unwrap().satisfied_by("anything")); + } +} diff --git a/src/recipe.rs b/src/recipe.rs new file mode 100644 index 0000000..a43059d --- /dev/null +++ b/src/recipe.rs @@ -0,0 +1,426 @@ +//! Recipe parsing: `.SRCINFO` (authoritative, present in every AUR repo) with a +//! `PKGBUILD` fallback, plus `source=()` parsing. +//! +//! The recipe is what a human reviews, so parsing failures are loud: a recipe we +//! cannot read must never silently produce a candidate with an empty source list. + +use std::collections::BTreeMap; + +use crate::db::model::{Recipe, SourceEntry}; +use crate::error::{Error, Result}; + +/// Parse `.SRCINFO`. Sections are `pkgbase = X` followed by `key = value` lines, +/// then one `pkgname = Y` section per emitted package. +pub fn parse_srcinfo(text: &str) -> Result { + let mut r = Recipe::default(); + let mut current: Option = None; // Some(pkgname) when inside a pkgname section + let mut base_seen = false; + for line in text.lines() { + let line = line.trim_end(); + if line.is_empty() { + continue; + } + let indented = line.starts_with('\t') || line.starts_with(' '); + let (k, v) = match line.split_once('=') { + Some((k, v)) => (k.trim().to_string(), v.trim().to_string()), + None => continue, + }; + if !indented { + if k == "pkgbase" { + r.pkgbase = v; + base_seen = true; + current = None; + } else if k == "pkgname" { + current = Some(v.clone()); + r.pkgnames.push(v.clone()); + r.pkg_depends.push((v, Vec::new())); + } + continue; + } + if !base_seen { + return Err(Error::invalid(".SRCINFO has no pkgbase line")); + } + let in_pkg = current.is_some(); + push_field(&mut r, in_pkg, current.as_deref(), &k, &v); + } + if r.pkgnames.is_empty() { + r.pkgnames.push(r.pkgbase.clone()); + let deps = r.depends.clone(); + r.pkg_depends.push((r.pkgbase.clone(), deps)); + } + r.srcinfo = Some(text.to_string()); + r.source_entries = parse_source_entries(&r.source)?; + Ok(r) +} + +#[allow(clippy::too_many_arguments)] +fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str) { + // Fields that belong to the base only are ignored inside pkgname sections. + match k { + "pkgver" if !in_pkg => r.pkgver = v.into(), + "pkgrel" if !in_pkg => r.pkgrel = v.into(), + "epoch" if !in_pkg => r.epoch = v.into(), + "pkgdesc" => r.pkgdesc = v.into(), + "url" if !in_pkg => r.url = v.into(), + "arch" => r.arch.push(v.into()), + "license" => r.license.push(v.into()), + "groups" => r.groups.push(v.into()), + "depends" => { + r.depends.push(v.into()); + if let Some(p) = pkg { + if let Some((_, d)) = r.pkg_depends.iter_mut().find(|(n, _)| n == p) { + d.push(v.into()); + } + } + } + "makedepends" => r.makedepends.push(v.into()), + "checkdepends" => r.checkdepends.push(v.into()), + "optdepends" => r.optdepends.push(v.into()), + "provides" => r.provides.push(v.into()), + "conflicts" => r.conflicts.push(v.into()), + "source" => r.source.push(v.into()), + "sha256sums" => r.sha256sums.push(v.into()), + "b2sums" => r.b2sums.push(v.into()), + "validpgpkeys" => r.validpgpkeys.push(v.into()), + "options" => r.options.push(v.into()), + "backup" => r.backup.push(v.into()), + "install" => r.install = Some(v.into()), + _ => {} + } +} + +/// Minimal `PKGBUILD` variable reader: top-level `var=value` and `var=(...)` +/// assignments, including arrays spanning several lines and quoted elements. +/// +/// This is a fallback for recipes without `.SRCINFO`; it deliberately does not +/// try to evaluate bash. Anything it cannot read is reported, not guessed. +pub fn parse_pkgbuild(text: &str) -> Result { + let vars = pkgbuild_vars(text); + let mut r = Recipe::default(); + let get = |k: &str| vars.get(k).cloned().unwrap_or_default(); + r.pkgbase = get("pkgbase").into_iter().next().unwrap_or_default(); + if r.pkgbase.is_empty() { + // A PKGBUILD without pkgbase emits one package named pkgname[0]. + r.pkgbase = get("pkgname").into_iter().next().unwrap_or_default(); + } + if r.pkgbase.is_empty() { + return Err(Error::invalid("PKGBUILD declares no pkgbase or pkgname")); + } + r.pkgver = get("pkgver").into_iter().next().unwrap_or_default(); + r.pkgrel = get("pkgrel").into_iter().next().unwrap_or_default(); + r.epoch = get("epoch").into_iter().next().unwrap_or_default(); + if r.epoch.is_empty() { + r.epoch = "0".into(); + } + if r.pkgver.is_empty() { + return Err(Error::invalid("PKGBUILD declares no pkgver")); + } + if r.pkgrel.is_empty() { + r.pkgrel = "1".into(); + } + r.pkgdesc = get("pkgdesc").into_iter().next().unwrap_or_default(); + r.url = get("url").into_iter().next().unwrap_or_default(); + r.arch = get("arch"); + r.license = get("license"); + r.groups = get("groups"); + r.depends = get("depends"); + r.makedepends = get("makedepends"); + r.checkdepends = get("checkdepends"); + r.optdepends = get("optdepends"); + r.provides = get("provides"); + r.conflicts = get("conflicts"); + r.source = get("source"); + r.sha256sums = get("sha256sums"); + r.b2sums = get("b2sums"); + r.validpgpkeys = get("validpgpkeys"); + r.options = get("options"); + r.backup = get("backup"); + r.install = get("install").into_iter().next(); + let pkgnames = get("pkgname"); + r.pkgnames = if pkgnames.is_empty() { + vec![r.pkgbase.clone()] + } else { + pkgnames.clone() + }; + r.pkg_depends = r + .pkgnames + .iter() + .map(|n| (n.clone(), r.depends.clone())) + .collect(); + r.skipgpcheck = text.contains("--skippgpcheck"); + r.pkgbuild = text.to_string(); + r.source_entries = parse_source_entries(&r.source)?; + Ok(r) +} + +/// Extract top-level assignments from a PKGBUILD. +fn pkgbuild_vars(text: &str) -> BTreeMap> { + let mut out: BTreeMap> = BTreeMap::new(); + let mut lines = text.lines().peekable(); + while let Some(line) = lines.next() { + let t = line.trim_start(); + if t.starts_with('#') || t.is_empty() { + continue; + } + // Stop at the first function definition: variables inside functions are + // not part of the recipe metadata we diff. + if t.contains("()") && t.contains('{') { + break; + } + let Some((name, rest)) = split_assign(t) else { continue }; + let rest = rest.trim(); + if let Some(inner) = rest.strip_prefix('(') { + // Array: may close on this line or later ones. + let mut buf = String::from(inner); + while !buf.contains(')') { + match lines.next() { + Some(l) => { + buf.push(' '); + buf.push_str(l.trim()); + } + None => break, + } + } + let inner = buf.split(')').next().unwrap_or(&buf).to_string(); + out.entry(name).or_default().extend(split_array_elements(&inner)); + } else { + let v = unquote(rest); + if !v.is_empty() { + out.entry(name).or_default().push(v); + } + } + } + out +} + +/// `name=value` where the line is an assignment (no spaces before `=`). +fn split_assign(t: &str) -> Option<(String, String)> { + let (name, rest) = t.split_once('=')?; + let name = name.trim(); + if name.is_empty() + || !name + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return None; + } + // `foo[1]=x` and similar are not metadata. + if name.contains('[') { + return None; + } + Some((name.to_string(), rest.to_string())) +} + +fn unquote(s: &str) -> String { + let s = s.trim(); + let s = s.strip_prefix('"').unwrap_or(s); + let s = s.strip_suffix('"').unwrap_or(s); + let s = s.strip_prefix('\'').unwrap_or(s); + s.strip_suffix('\'').unwrap_or(s).to_string() +} + +/// Split `(a "b c" 'd e')` into elements. +fn split_array_elements(s: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut quote: Option = None; + let mut pushed = false; + for c in s.chars() { + match quote { + Some(q) => { + if c == q { + quote = None; + } else { + cur.push(c); + } + } + None => match c { + '\'' | '"' => quote = Some(c), + c if c.is_whitespace() => { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + pushed = true; + } + c => { + cur.push(c); + pushed = false; + } + }, + } + } + let _ = pushed; + if !cur.is_empty() { + out.push(cur); + } + out.into_iter().filter(|e| !e.is_empty()).collect() +} + +/// Parse `source=()` entries into structured form (§5.2 needs the VCS refs, +/// §5.3 needs the kind of each entry). +pub fn parse_source_entries(list: &[String]) -> Result> { + let mut out = Vec::new(); + for (index, raw) in list.iter().enumerate() { + let s = raw.trim(); + if s.is_empty() { + return Err(Error::invalid("empty source entry")); + } + // `filename::url` (filename first, per makepkg). + let (filename, url) = match s.split_once("::") { + Some((f, u)) => (Some(f.to_string()), u.to_string()), + None => (None, s.to_string()), + }; + let (url, frag) = match url.split_once('#') { + Some((u, f)) => (u.to_string(), Some(f.to_string())), + None => (url.clone(), None), + }; + let (vcs, clean) = match url.split_once('+') { + Some((scheme, rest)) if ["git", "svn", "hg", "bzr", "fossil"].contains(&scheme) => { + (Some(scheme.to_string()), rest.to_string()) + } + _ => (None, url.clone()), + }; + let mut commit = None; + let mut tag = None; + let mut branch = None; + if let Some(f) = frag { + for pair in f.split('&') { + let (k, v) = match pair.split_once('=') { + Some((k, v)) => (k, v), + None => continue, + }; + match k { + "commit" => commit = Some(v.to_string()), + "tag" => tag = Some(v.to_string()), + "branch" => branch = Some(v.to_string()), + _ => {} + } + } + } + let local = vcs.is_none() && !clean.contains("://"); + let filename = filename.or_else(|| { + if local { + clean.rsplit('/').next().map(|s| s.to_string()) + } else { + None + } + }); + out.push(SourceEntry { + index, + url: clean, + filename, + commit, + tag, + branch, + vcs, + local, + }); + } + Ok(out) +} + +/// Build a recipe from a materialized AUR tree. +/// +/// `.SRCINFO` wins when present — it is what `makepkg` itself reports and every +/// real AUR repo ships it. Otherwise we fall back to reading the `PKGBUILD`. +pub fn recipe_from_tree(files: &BTreeMap) -> Result { + let pkgbuild_path = files + .keys() + .find(|k| k.ends_with("PKGBUILD")) + .cloned() + .ok_or_else(|| Error::invalid("snapshot tree contains no PKGBUILD"))?; + let pkgbuild = files.get(&pkgbuild_path).cloned().unwrap_or_default(); + let mut r = match files.iter().find(|(k, _)| k.ends_with(".SRCINFO")) { + Some((_, srcinfo)) => parse_srcinfo(srcinfo)?, + None => parse_pkgbuild(&pkgbuild)?, + }; + if r.pkgbuild.is_empty() { + r.pkgbuild = pkgbuild; + } + if r.pkgbase.is_empty() { + return Err(Error::invalid("recipe has no pkgbase")); + } + Ok(r) +} + +/// Text files we render diffs for (§6 "recipe diff" panel). +pub fn is_diffable(path: &str) -> bool { + let ext = path.rsplit('.').next().unwrap_or(""); + !matches!( + ext, + "png" | "jpg" | "gif" | "ico" | "pdf" | "gz" | "zst" | "xz" | "bz2" | "zip" | "deb" | "rpm" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pkgbuild_arrays_span_lines_and_quotes() { + let r = parse_pkgbuild( + r#"# comment +pkgbase=foo +pkgver=1.0 +pkgrel=2 +pkgdesc="a package" +arch=(x86_64) +depends=('glibc' openssl + zlib) +source=(git+https://example.invalid/foo.git + fix.patch::https://example.invalid/fix.patch) +sha256sums=('SKIP' 'abc') +build() { + local pkgver=not-this +} +"#, + ) + .unwrap(); + assert_eq!(r.pkgbase, "foo"); + assert_eq!(r.full_version(), "1.0-2"); + assert_eq!(r.depends, vec!["glibc", "openssl", "zlib"]); + assert_eq!(r.source.len(), 2); + assert_eq!(r.sha256sums, vec!["SKIP", "abc"]); + assert_eq!(r.pkgnames, vec!["foo"]); + } + + #[test] + fn source_entries_carry_kind_and_refs() { + let e = parse_source_entries(&[ + "git+https://github.com/foo/bar.git#commit=deadbeef".into(), + "git+https://github.com/foo/bar.git#branch=next".into(), + "hg+https://example.invalid/x".into(), + "name::https://example.invalid/file.tar.gz".into(), + "local.patch".into(), + ]) + .unwrap(); + assert_eq!(e[0].vcs.as_deref(), Some("git")); + assert_eq!(e[0].commit.as_deref(), Some("deadbeef")); + assert_eq!(e[0].url, "https://github.com/foo/bar.git"); + assert_eq!(e[1].branch.as_deref(), Some("next")); + assert_eq!(e[2].vcs.as_deref(), Some("hg")); + assert_eq!(e[3].filename.as_deref(), Some("name")); + assert!(!e[3].local); + assert!(e[4].local); + assert_eq!(e[4].filename.as_deref(), Some("local.patch")); + } + + #[test] + fn srcinfo_sections_describe_split_pkgbases() { + let r = parse_srcinfo( + "pkgbase = foo\n\tpkgver = 1.0\n\tpkgrel = 1\n\tmakedepends = cmake\n\tsource = x.tar\n\tsha256sums = SKIP\npkgname = foo\n\tdepends = glibc\npkgname = foo-lua\n\tdepends = lua\n", + ) + .unwrap(); + assert_eq!(r.pkgbase, "foo"); + assert_eq!(r.pkgnames, vec!["foo", "foo-lua"]); + assert_eq!(r.makedepends, vec!["cmake"]); + assert_eq!(r.pkg_depends[1].1, vec!["lua"]); + } + + #[test] + fn a_recipe_without_a_version_is_an_error_not_a_guess() { + assert!(parse_pkgbuild("pkgbase=foo\n").is_err()); + } +} diff --git a/src/review/approve.rs b/src/review/approve.rs new file mode 100644 index 0000000..b62adec --- /dev/null +++ b/src/review/approve.rs @@ -0,0 +1,267 @@ +//! Approval semantics (§7.1, §7.1a, §7.2, §7.4). +//! +//! Rule of the system: **we build exactly what was displayed, or nothing.** +//! The approve POST carries the `identity_hash` and `diff_digest` that were +//! rendered; if either has moved under the reviewer, the approval is refused +//! with a conflict (HTTP 409) and a re-render, never silently retargeted. + +use rusqlite::OptionalExtension; + +use crate::db::{self, *}; +use crate::error::{Error, Result}; +use crate::time; + +/// Why an approval was refused (§7.1a). Rendered as HTTP 409 with the current +/// diff, plus a CLI message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stale { + NotPending { state: String }, + Identity { expected: String, actual: String }, + Diff { expected: String, actual: String }, + Base { expected: Option, actual: Option }, +} + +impl std::fmt::Display for Stale { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Stale::NotPending { state } => write!(f, "review is no longer pending (state: {state})"), + Stale::Identity { expected, actual } => write!( + f, + "the candidate changed while you were looking: you were shown {expected}, it is now {actual}" + ), + Stale::Diff { expected, actual } => write!( + f, + "the diff changed while you were looking (shown {expected}, now {actual})" + ), + Stale::Base { .. } => write!( + f, + "a newer version was accepted since this review was opened" + ), + } + } +} + +#[derive(Debug, Clone)] +pub struct Approval { + pub id: i64, + pub candidate_id: i64, + pub base_release_id: Option, + pub decision: String, + pub diff_digest: String, + pub identity_hash: String, +} + +/// Approve a candidate. Returns the approval row on success, or the reason the +/// approval was refused. +pub fn approve( + db: &Db, + actor: &str, + candidate_id: i64, + identity_hash: &str, + diff_digest: &str, + note: Option<&str>, +) -> std::result::Result { + let actor = actor.to_string(); + let ih = identity_hash.to_string(); + let dd = diff_digest.to_string(); + let note = note.map(|s| s.to_string()); + let at = time::now(); + + db.writer.tx(move |tx| -> Result> { + type CandidateState = (i64, String, String, Option, Option, String, String); + let row: Option = tx + .query_row( + "SELECT c.id, c.state, c.identity_hash, c.base_release_id, p.current_accepted_release_id, + c.risk_level, b.name + FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id + WHERE c.id = ?1", + rusqlite::params![candidate_id], + |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + r.get(6)?, + )) + }, + ) + .optional()?; + let (id, state, actual_identity, base, current_base, risk, _pkgbase) = + row.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; + + // 1. still open + if state != candidate_state::PENDING { + return Ok(Err(Stale::NotPending { state })); + } + // 2. same candidate bytes + if actual_identity != ih { + return Ok(Err(Stale::Identity { expected: ih.clone(), actual: actual_identity })); + } + // 3. same rendered diff + let stored_diff: String = tx.query_row( + "SELECT diff_digest FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + )?; + if stored_diff != dd { + return Ok(Err(Stale::Diff { expected: dd.clone(), actual: stored_diff })); + } + // 4. base is still the accepted release (I2, end to end) + if base != current_base { + return Ok(Err(Stale::Base { expected: base, actual: current_base })); + } + + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, + diff_digest, identity_hash, note) + VALUES (?1,?2,?3,'approved',?4,?5,?6,?7)", + rusqlite::params![id, base, at, risk, dd, ih, note], + )?; + let approval_id = tx.last_insert_rowid(); + tx.execute( + "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, id], + )?; + let pkgbase_id: i64 = tx.query_row( + "SELECT pkgbase_id FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'approve','candidate',?3,?4)", + rusqlite::params![ + at, + actor, + id.to_string(), + serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": pkgbase_id}) + .to_string() + ], + )?; + Ok(Ok(Approval { + id: approval_id, + candidate_id: id, + base_release_id: base, + decision: "approved".into(), + diff_digest: dd, + identity_hash: ih, + })) + }) + .map_err(|e| Stale::NotPending { state: e.to_string() })? +} + +/// Reject a candidate. Rejection is remembered per identity so the watcher stops +/// nagging about the same version (§7.1), and can be re-opened later. +pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> { + let actor = actor.to_string(); + let note = note.to_string(); + let at = time::now(); + db.writer.tx(move |tx| { + let state: String = tx + .query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![candidate_id], |r| r.get(0)) + .optional()? + .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; + if state != candidate_state::PENDING { + return Err(Error::conflict(format!("candidate is {state}, not pending"))); + } + let identity: String = tx.query_row( + "SELECT identity_hash FROM candidate WHERE id=?1", + rusqlite::params![candidate_id], + |r| r.get(0), + )?; + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, + diff_digest, identity_hash, note) + SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3 + FROM candidate WHERE id=?4", + rusqlite::params![at, identity, note, candidate_id], + )?; + tx.execute( + "UPDATE candidate SET state='rejected', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, candidate_id], + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'reject','candidate',?3,?4)", + rusqlite::params![at, actor, candidate_id.to_string(), serde_json::json!({"note": note}).to_string()], + )?; + Ok(()) + }) +} + +/// §7.4 bulk decision. High-risk items are refused unless confirmed individually. +pub fn bulk( + db: &Db, + actor: &str, + items: &[(i64, String, String)], // (candidate_id, identity_hash, diff_digest) + decision: &str, + confirm_high_risk: bool, +) -> Result>> { + let mut out = Vec::new(); + for (id, ih, dd) in items { + let risk: String = db.read(|c| { + Ok(c.query_row( + "SELECT risk_level FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + ) + .optional()?) + })? + .unwrap_or_default(); + if decision == "approve" && risk == "high" && !confirm_high_risk { + out.push(Err(Stale::NotPending { + state: "high-risk: needs individual confirmation".into(), + })); + continue; + } + out.push(match decision { + "approve" => approve(db, actor, *id, ih, dd, Some("bulk")), + "reject" => reject(db, actor, *id, "bulk") + .map(|_| Approval { id: 0, candidate_id: *id, base_release_id: None, decision: "rejected".into(), diff_digest: dd.clone(), identity_hash: ih.clone() }) + .map_err(|e| Stale::NotPending { state: e.to_string() }), + other => Err(Stale::NotPending { state: format!("unknown decision {other}") }), + }); + } + Ok(out) +} + +/// The approval behind a candidate, if any. +pub fn approval_for(db: &Db, candidate_id: i64) -> Result> { + db.read(|c| { + Ok(c.query_row( + "SELECT id, decision FROM approval WHERE candidate_id=?1", + rusqlite::params![candidate_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?) + }) +} + +/// Withdraw a published release (§9 `repo-remove` path, decision 23: warns, +/// does not block). +pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<()> { + let actor = actor.to_string(); + let reason = reason.to_string(); + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", rusqlite::params![release_id])?; + tx.execute( + "UPDATE package SET state='removed' WHERE release_id=?1", + rusqlite::params![release_id], + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'withdraw','release',?3,?4)", + rusqlite::params![at, actor, release_id.to_string(), serde_json::json!({"reason": reason}).to_string()], + )?; + Ok(()) + }) +} + +/// The pkgbase's accepted release pointer, exposed for callers that need it. +pub fn current_accepted(db: &Db, pkgbase: &str) -> Result> { + db::accepted_release(db, pkgbase) +} diff --git a/src/review/candidates.rs b/src/review/candidates.rs new file mode 100644 index 0000000..4dc6c4f --- /dev/null +++ b/src/review/candidates.rs @@ -0,0 +1,293 @@ +//! Candidate creation and the collapse-in-place rule (§7.1). +//! +//! One review object per pkgbase at a time. A newer detection **collapses into** +//! the open review rather than queueing beside it, and the review's `base` is +//! fixed at creation to the pkgbase's `current_accepted_release` — that is what +//! makes "diff against the last accepted version, never the last seen one" (I2) +//! true no matter how many detections arrive while nobody is looking. + +use rusqlite::OptionalExtension; + +use crate::db::{self, *}; +use crate::error::Result; +use crate::time; + +#[derive(Debug, Clone)] +pub struct NewCandidate { + pub snapshot_id: i64, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub identity_hash: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Upsert { + /// A new review row was opened. + Created { id: i64, kind: String }, + /// The open review was updated in place; no new row, `base` untouched (I7). + Collapsed { id: i64, revision: i64 }, + /// A human had already seen the old diff, so it was frozen as `superseded` + /// and a fresh review opened (decision 8). + Superseded { old: i64, new: i64 }, + /// This exact identity was rejected before; do not nag (§7.1). + PreviouslyRejected, + /// Nothing changed relative to what is already recorded. + Unchanged, +} + +/// Insert-or-collapse a candidate for `pb`. +/// +/// `accepted` is the pkgbase's current accepted release, or `None` when this is +/// a first introduction (§7.1b). +pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result { + let kind = if accepted.is_some() { candidate_kind::NEW_VERSION } else { candidate_kind::FIRST_INTRODUCTION }; + let base = accepted.map(|a| a.id); + let pkgbase_id = pb.id; + let nc = nc.clone(); + + db.writer.tx(move |tx| { + let existing: Option<(i64, String, Option, i64)> = tx + .query_row( + "SELECT id, identity_hash, viewed_at, revision FROM candidate + WHERE pkgbase_id=?1 AND state='pending_review'", + rusqlite::params![pkgbase_id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .optional()?; + + if let Some((id, identity, viewed, revision)) = existing { + if identity == nc.identity_hash { + return Ok(Upsert::Unchanged); + } + if viewed.is_none() { + // Collapse in place: same base, no new row, revision bumped. + tx.execute( + "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4, + upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7, + revision=?8, detected_at=?9, diff_digest='' + WHERE id=?10", + rusqlite::params![ + nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel, + nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, + revision + 1, time::now(), id + ], + )?; + return Ok(Upsert::Collapsed { id, revision: revision + 1 }); + } + // A human saw the old diff: freeze it for the audit trail and open a + // fresh review against the same base. + tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2", + rusqlite::params![time::now(), id], + )?; + let new_id = insert(tx, pkgbase_id, base, kind, &nc)?; + return Ok(Upsert::Superseded { old: id, new: new_id }); + } + + // No open review. A previously rejected identity must not be re-raised. + let rejected: Option = tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected' + ORDER BY id DESC LIMIT 1", + rusqlite::params![pkgbase_id, nc.identity_hash], + |r| r.get(0), + ) + .optional()?; + if rejected.is_some() { + return Ok(Upsert::PreviouslyRejected); + } + // Same identity already approved/recorded: nothing to do. + let same: Option = tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 + ORDER BY id DESC LIMIT 1", + rusqlite::params![pkgbase_id, nc.identity_hash], + |r| r.get(0), + ) + .optional()?; + if same.is_some() { + return Ok(Upsert::Unchanged); + } + let id = insert(tx, pkgbase_id, base, kind, &nc)?; + Ok(Upsert::Created { id, kind: kind.to_string() }) + }) +} + +fn insert( + tx: &mut rusqlite::Transaction<'_>, + pkgbase_id: i64, + base: Option, + kind: &str, + nc: &NewCandidate, +) -> Result { + tx.execute( + "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel, + upstream_pins_json, source_digests_json, identity_hash, state, detected_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)", + rusqlite::params![ + pkgbase_id, base, kind, nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel, + nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, time::now() + ], + )?; + Ok(tx.last_insert_rowid()) +} + +impl NewCandidate { + /// The `epoch:pkgver-pkgrel` this candidate would publish. + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } +} + +/// Mark a candidate `viewed` the first time a human opens it. That timestamp is +/// what decides whether a later detection collapses or supersedes (§7.1). +pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", + rusqlite::params![at, id], + )?; + Ok(()) + }) +} + +pub fn pending_candidates(db: &Db) -> Result> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id + WHERE c.state='pending_review' + ORDER BY (c.risk_level='high') DESC, c.detected_at", + )?; + let rows = stmt.query_map([], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn candidate_by_id(db: &Db, id: i64) -> Result> { + db.read(|c| { + Ok(c.query_row( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1", + rusqlite::params![id], + row_to_candidate, + ) + .optional()?) + }) +} + +fn row_to_candidate(r: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(CandidateRow { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + base_release_id: r.get(2)?, + kind: r.get(3)?, + snapshot_id: r.get(4)?, + epoch: r.get(5)?, + pkgver: r.get(6)?, + pkgrel: r.get(7)?, + upstream_pins_json: r.get(8)?, + source_digests_json: r.get(9)?, + identity_hash: r.get(10)?, + diff_digest: r.get(11)?, + revision: r.get(12)?, + viewed_at: r.get(13)?, + risk_level: r.get(14)?, + risk_signals_json: r.get(15)?, + missing_deps_json: r.get(16)?, + state: r.get(17)?, + detected_at: r.get(18)?, + resolved_at: r.get(19)?, + pkgbase: r.get(20)?, + }) +} + +/// Open reviews for a pkgbase (usually zero or one, by I7). +pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id + WHERE c.pkgbase_id=?1 AND c.state='pending_review'", + )?; + let rows = stmt.query_map(rusqlite::params![pkgbase_id], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops +/// suppressing the identity, and the next detection opens a fresh review. +pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'", + rusqlite::params![at, id], + )?; + if n == 0 { + return Err(crate::error::Error::conflict("candidate is not rejected")); + } + Ok(()) + }) +} + +/// Record the risk assessment computed at review time. +pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> { + let lvl = level.to_string(); + let sig = serde_json::to_string(signals)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", + rusqlite::params![lvl, sig, id], + )?; + Ok(()) + }) +} + +pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> { + let m = serde_json::to_string(missing)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", + rusqlite::params![m, id], + )?; + Ok(()) + }) +} + +pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> { + let d = digest.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", rusqlite::params![d, id])?; + Ok(()) + }) +} + +/// Convenience used by the watcher: the accepted release of a pkgbase row. +pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result> { + match pb.current_accepted_release_id { + Some(id) => db::release_by_id(db, id), + None => Ok(None), + } +} diff --git a/src/review/diff.rs b/src/review/diff.rs new file mode 100644 index 0000000..cfce3fe --- /dev/null +++ b/src/review/diff.rs @@ -0,0 +1,156 @@ +//! Diff rendering (§6). +//! +//! A review is not one diff, it is a panel set, and **every** panel compares what +//! the accepted release recorded against what the candidate records now — never +//! "last seen". The rendered text is hashed into `diff_digest`, which is what +//! makes "we build exactly what was displayed, or nothing" (§7.1a) provable. + +use crate::config::Config; +use crate::db::{self, *}; +use crate::error::Result; +use crate::git; + +#[derive(Debug, Clone)] +pub struct Panel { + pub name: &'static str, + pub title: &'static str, + /// Unified-diff text, or a readable rendering for panels that are not diffs. + pub body: String, +} + +/// Everything a reviewer needs for one candidate. +pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow>) -> Result> { + let mut out = Vec::new(); + let snap = db::snapshot_by_id(db, c.snapshot_id)?; + let mirror = std::path::PathBuf::from( + db::get_pkgbase_by_id(db, c.pkgbase_id)? + .and_then(|p| p.mirror_path) + .unwrap_or_else(|| cfg.mirror_path(&c.pkgbase).display().to_string()), + ); + + out.push(version_delta(base, c)); + + if let Some(base) = base { + if let Some(s) = &snap { + let range = format!("{}..{}", base.aur_commit, s.aur_commit); + let body = git::diff(&mirror, &range, &[]).unwrap_or_else(|e| { + format!("(diff unavailable: {e})\n\n--- base {}\n+++ candidate {}", base.aur_commit, s.aur_commit) + }); + out.push(Panel { name: "recipe", title: "Recipe diff", body }); + } + out.push(digest_delta(base, c)); + out.push(pin_delta(base, c)); + } else { + // §7.1b first_introduction: no diff pane. The full recipe is rendered + // readably instead, by the template. + out.push(Panel { + name: "recipe_full", + title: "Full recipe", + body: snap + .map(|s| s.srcinfo_json.clone()) + .unwrap_or_else(|| "(no snapshot)".into()), + }); + } + Ok(out) +} + +fn version_delta(base: Option<&ReleaseRow>, c: &CandidateRow) -> Panel { + let mut body = String::new(); + match base { + Some(b) => { + let (bv, cv) = (b.version(), c.version()); + body.push_str(&format!("{bv} -> {cv}\n")); + let ord = crate::pkgver::vercmp(&bv, &cv); + if b.epoch != c.epoch { + body.push_str(&format!("epoch bump: {} -> {}\n", b.epoch, c.epoch)); + } + if b.pkgrel != c.pkgrel && b.pkgver == c.pkgver { + body.push_str(&format!("pkgrel change: {} -> {}\n", b.pkgrel, c.pkgrel)); + } + if crate::pkgver::is_downgrade(&bv, &cv) { + body.push_str("DOWNGRADE: AUR now offers a lower version than we serve\n"); + } + let _ = ord; + } + None => body.push_str(&format!("first introduction: {}\n", c.version())), + } + Panel { name: "version", title: "Version delta", body } +} + +fn digest_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel { + let mut body = String::new(); + let old: Vec = base.digests(); + let new: Vec = c.digests(); + for n in &new { + match old.iter().find(|o| o.index == n.index) { + Some(o) if o.digest != n.digest => { + body.push_str(&format!( + "! [{}] {} {} -> {}\n", + n.index, n.url, short(&o.digest), short(&n.digest) + )); + } + Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)), + None => body.push_str(&format!( + "+ [{}] {} NEW ({}{})\n", + n.index, + n.url, + n.kind, + if n.skip_declared { ", sha256sums=SKIP" } else { "" } + )), + } + } + for o in &old { + if !new.iter().any(|n| n.index == o.index) { + body.push_str(&format!("- [{}] {} REMOVED\n", o.index, o.url)); + } + } + Panel { name: "digests", title: "Source digest delta", body } +} + +fn pin_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel { + let mut body = String::new(); + let old: Vec = base.pins(); + let new: Vec = c.pins(); + if old.is_empty() && new.is_empty() { + body.push_str("no VCS sources\n"); + } + for n in &new { + match old.iter().find(|o| o.index == n.index) { + Some(o) if o.commit != n.commit => { + body.push_str(&format!( + "! [{}] {} {} -> {} (branch {})\n", + n.index, n.url, short(&o.commit), short(&n.commit), n.branch.as_deref().unwrap_or("?") + )); + } + Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)), + None => body.push_str(&format!("+ [{}] {} at {}\n", n.index, n.url, short(&n.commit))), + } + } + Panel { name: "upstream", title: "Upstream delta", body } +} + +fn short(s: &str) -> String { + if s.len() > 12 { s[..12].to_string() } else { s.to_string() } +} + +/// Flatten the rendered panels into one canonical string. +pub fn render_text(ps: &[Panel]) -> String { + let mut s = String::new(); + for p in ps { + s.push_str(&format!("### {}\n{}\n", p.title, p.body)); + } + s +} + +/// `diff_digest`: hash of the exact rendered diff the human was shown (§7.2). +pub fn diff_digest(ps: &[Panel]) -> String { + crate::hash::hex_str(&render_text(ps)) +} + +/// The recipe text a reviewer reads for a first introduction (§7.1b). +pub fn full_recipe_text(db: &Db, c: &CandidateRow) -> Result { + let snap = db::snapshot_by_id(db, c.snapshot_id)?; + let snap = snap.ok_or_else(|| crate::error::Error::not_found("snapshot missing"))?; + let r: Recipe = serde_json::from_str(&snap.srcinfo_json).unwrap_or_default(); + Ok(r.pkgbuild) +} diff --git a/src/review/mod.rs b/src/review/mod.rs new file mode 100644 index 0000000..25abca8 --- /dev/null +++ b/src/review/mod.rs @@ -0,0 +1,8 @@ +//! Review lifecycle: candidate creation and collapse-in-place (§7.1), the +//! approval record (§7.2), diffing (§6) and risk scoring (§6). + +pub mod approve; +pub mod candidates; +pub mod diff; + +pub use candidates::{upsert_candidate, NewCandidate, Upsert}; diff --git a/src/watch/detect.rs b/src/watch/detect.rs new file mode 100644 index 0000000..e00a2f9 --- /dev/null +++ b/src/watch/detect.rs @@ -0,0 +1,288 @@ +//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3). +//! +//! The decision that matters is *what counts as a change*. A candidate exists +//! only if something **publishable** changed — if the version string is +//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve. +//! Those events become `notice` rows instead, and are never silently dropped +//! (I11). + +use crate::config::Config; +use crate::db::{self, *}; +use crate::error::Result; +use crate::pkgver; +use crate::recipe::recipe_from_tree; +use crate::review::candidates::{upsert_candidate, NewCandidate, Upsert}; +use crate::time; +use crate::watch::digests::resolve_sources; +use crate::watch::mirror::{read_tree, sync_mirror, Sync}; + +#[derive(Debug, Clone)] +pub enum Outcome { + /// Nothing moved at all. + NoChange, + /// A new review was opened. + Candidate { id: i64, kind: String }, + /// The open review was updated in place (I7). + Collapsed { id: i64, revision: i64 }, + /// The seen-but-unresolved review was frozen and a new one opened. + Superseded { old: i64, new: i64 }, + /// Identical to something a human already rejected. + PreviouslyRejected, + /// Something changed but nothing is publishable (I11). + Notice { kind: String, detail: serde_json::Value }, + /// The package vanished from AUR. + Gone, + /// Detection could not complete; the watcher will back off. + Blocked(String), +} + +#[derive(Debug, Clone)] +pub struct CheckReport { + pub pkgbase: String, + pub head: String, + pub outcome: Outcome, +} + +/// One full detection pass for a subscribed pkgbase. +pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result { + let pb = get_pkgbase(db, name)? + .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?; + let sync = sync_mirror(cfg, db, name, &pb.aur_url)?; + let head = match &sync { + Sync::Gone => { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DELETED, + "high", + serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}), + )?; + db::set_subscription_state(&db.writer, name, subscription_state::ORPHANED)?; + return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); + } + // The cheap poll saved us a fetch, but we still have to look: a source + // can change its bytes without the recipe moving at all, and that is the + // digest-drift case §5.3 calls the single most valuable detection. + Sync::Unchanged { head } => head.clone(), + Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(), + }; + let r = analyse(cfg, db, &pb, &head); + schedule_next(db, name, &pb); + r +} + +fn schedule_next(db: &Db, name: &str, pb: &Pkgbase) { + let interval = db + .read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row( + "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1", + rusqlite::params![name], + |r| r.get::<_, Option>(0), + ) + .optional()?) + }) + .ok() + .flatten() + .flatten() + .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); + let next = time::secs_ahead(interval); + let _ = db::note_check(&db.writer, name, &next, None); + let _ = pb; +} + +/// Everything after the mirror is up to date. +fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result { + let mirror = cfg.mirror_path(&pb.name); + let report = |outcome: Outcome| CheckReport { pkgbase: pb.name.clone(), head: head.to_string(), outcome }; + + // §16 mirror divergence: if the accepted pin has vanished from our own + // mirror, hard-fail this pkgbase rather than silently re-pinning. + let accepted = crate::review::candidates::accepted_for(db, pb)?; + if let Some(a) = &accepted { + if !crate::git::has_commit(&mirror, &a.aur_commit) { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DELETED, + "high", + serde_json::json!({"mirror_divergence": a.aur_commit}), + )?; + return Ok(report(Outcome::Blocked(format!( + "accepted pin {} missing from local mirror", + a.aur_commit + )))); + } + } + + let tree = read_tree(&mirror, head)?; + let recipe = recipe_from_tree(&tree.files)?; + let recipe_hash = tree.recipe_hash(); + let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &[])?; + let pins: Vec = Vec::new(); // P1 fills this in for VCS sources + + let identity = Identity { + aur_commit: head.to_string(), + epoch: recipe.epoch.clone(), + pkgver: recipe.pkgver.clone(), + pkgrel: recipe.pkgrel.clone(), + upstream_pins: pins.clone(), + source_digests: digests.clone(), + }; + let identity_hash = identity.hash(); + let snap_id = db::put_snapshot( + &db.writer, + pb.id, + head, + &recipe_hash, + &serde_json::to_string(&recipe)?, + &tree.json_list(), + )?; + + let nc = NewCandidate { + snapshot_id: snap_id, + epoch: recipe.epoch.clone(), + pkgver: recipe.pkgver.clone(), + pkgrel: recipe.pkgrel.clone(), + upstream_pins_json: serde_json::to_string(&pins)?, + source_digests_json: serde_json::to_string(&digests)?, + identity_hash: identity_hash.clone(), + }; + + let Some(base) = accepted else { + // §7.1b: nothing to diff against — this is a first introduction. + return match upsert_candidate(db, pb, None, &nc)? { + Upsert::Created { id, kind } => Ok(report(Outcome::Candidate { id, kind })), + other => Ok(report(outcome_of(other))), + }; + }; + + // Same identity as what we already serve: nothing happened. + if base.aur_commit == head + && base.epoch == nc.epoch + && base.pkgver == nc.pkgver + && base.pkgrel == nc.pkgrel + && base.upstream_pins_json == nc.upstream_pins_json + && base.source_digests_json == nc.source_digests_json + { + return Ok(report(Outcome::NoChange)); + } + + let new_version = nc.version(); + let publishable = pkgver::vercmp(&base.version(), &new_version) != std::cmp::Ordering::Equal; + + if !publishable { + // §5.2 / §5.3: nothing pacman could offer as an upgrade. Record it + // loudly instead of inventing a pkgrel bump. + return Ok(report(non_publishable(db, pb, &base, &nc, &recipe)?)); + } + + if pkgver::is_downgrade(&base.version(), &new_version) { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DOWNGRADE, + "warning", + serde_json::json!({"served": base.version(), "aur": new_version}), + )?; + } + + let up = upsert_candidate(db, pb, Some(&base), &nc)?; + Ok(report(outcome_of(up))) +} + +fn outcome_of(up: Upsert) -> Outcome { + match up { + Upsert::Created { id, kind } => Outcome::Candidate { id, kind }, + Upsert::Collapsed { id, revision } => Outcome::Collapsed { id, revision }, + Upsert::Superseded { old, new } => Outcome::Superseded { old, new }, + Upsert::PreviouslyRejected => Outcome::PreviouslyRejected, + Upsert::Unchanged => Outcome::NoChange, + } +} + +/// The version string did not move, so there is no review to open — but the +/// change is recorded, because a silently drifting tarball is exactly the kind +/// of thing that must not be invisible (§5.3). +fn non_publishable( + db: &Db, + pb: &Pkgbase, + base: &ReleaseRow, + nc: &NewCandidate, + recipe: &Recipe, +) -> Result { + let old_digests: Vec = base.digests(); + let new_digests: Vec = serde_json::from_str(&nc.source_digests_json).unwrap_or_default(); + // A local source is part of the recipe: when its bytes move, that *is* the + // recipe drift, not an integrity event. The integrity alert is specifically + // "the bytes upstream serves no longer match what we built" (§5.3). + let changed_remote: Vec<&SourceDigest> = new_digests + .iter() + .filter(|n| n.kind != "local") + .filter(|n| match old_digests.iter().find(|o| o.index == n.index) { + Some(o) => o.digest != n.digest, + None => true, + }) + .collect(); + let digest_changed = !changed_remote.is_empty(); + let old_pins: Vec = base.pins(); + let new_pins: Vec = serde_json::from_str(&nc.upstream_pins_json).unwrap_or_default(); + let pins_changed = old_pins != new_pins; + + if digest_changed { + // The single most valuable detection in the system: the artifact in the + // index was built from bytes upstream no longer serves, and the version + // string is unchanged. An approval would be useless (approving it would + // not let us publish anything), so this is an alert, not a review. + let changed: Vec = changed_remote + .iter() + .map(|n| { + serde_json::json!({"index": n.index, "url": n.url, + "old": old_digests.iter().find(|o| o.index == n.index) + .map(|o| o.digest.clone()).unwrap_or_default(), + "new": n.digest}) + }) + .collect(); + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::INTEGRITY_ALERT, + "high", + serde_json::json!({ + "version": nc.version(), + "changed": changed, + "message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged", + }), + )?; + return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) }); + } + if pins_changed { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::PIN_DRIFT, + "info", + serde_json::json!({ + "version": nc.version(), + "message": "upstream moved; pkgver unchanged, nothing publishable", + }), + )?; + return Ok(Outcome::Notice { kind: notice_kind::PIN_DRIFT.into(), detail: serde_json::json!({}) }); + } + // The recipe drifted under a static version: the maintainer probably forgot + // to bump pkgrel, and the user should know. + let _ = recipe; + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::RECIPE_DRIFT, + "warning", + serde_json::json!({ + "version": nc.version(), + "accepted_aur_commit": base.aur_commit, + "aur_commit": "moved", + "message": "recipe changed but the version did not; the maintainer may have forgotten to bump pkgrel", + }), + )?; + Ok(Outcome::Notice { kind: notice_kind::RECIPE_DRIFT.into(), detail: serde_json::json!({}) }) +} diff --git a/src/watch/digests.rs b/src/watch/digests.rs new file mode 100644 index 0000000..07551ca --- /dev/null +++ b/src/watch/digests.rs @@ -0,0 +1,193 @@ +//! Source digest resolution (§5.3). +//! +//! `sha256sums=('SKIP')` is the hole in the integrity story. We resolve and +//! record the digest of *every* source ourselves, at detection time, regardless +//! of what the PKGBUILD declares — which turns a silent artifact swap into a +//! reviewable (or at least alertable) event. +//! +//! Cost control: only `SKIP`-declared static sources cost bandwidth. Declared +//! checksums are trusted-as-declared for identity because makepkg enforces them +//! at build time; VCS digests come free from the pin we already resolved; local +//! files are already in the mirror. + +use crate::config::Config; +use crate::db::*; +use crate::error::Result; +use crate::time; +use crate::watch::mirror::Tree; + +const SKIP: &str = "SKIP"; + +fn declared_sums(recipe: &Recipe, index: usize) -> Option { + recipe + .sha256sums + .get(index) + .or_else(|| recipe.b2sums.get(index)) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +fn is_hex_digest(s: &str) -> bool { + (s.len() == 64 || s.len() == 128) && s.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// Resolve the digest of every `source=()` entry. +pub fn resolve_sources( + cfg: &Config, + db: &Db, + mirror: &std::path::Path, + commit: &str, + tree: &Tree, + recipe: &Recipe, + pins: &[UpstreamPin], +) -> Result> { + let mut out = Vec::new(); + for entry in &recipe.source_entries { + let declared = declared_sums(recipe, entry.index); + let skip_declared = match &declared { + Some(d) => d == SKIP || !is_hex_digest(d), + None => true, + }; + + if entry.is_vcs() { + // The resolved commit *is* the digest; captured during Stage B where + // we clone anyway (§5.2), so near-free. + let pin = pins.iter().find(|p| p.index == entry.index); + let digest = pin + .map(|p| p.commit.clone()) + .or_else(|| entry.commit.clone()) + .unwrap_or_default(); + out.push(SourceDigest { + index: entry.index, + url: entry.url.clone(), + kind: entry.vcs.clone().unwrap_or_else(|| "vcs".into()), + digest, + size: 0, + skip_declared: true, + }); + continue; + } + + if entry.local { + let name = entry.filename.clone().unwrap_or_default(); + let path = tree + .blobs + .iter() + .find(|(p, _)| p == &name || p.ends_with(&format!("/{name}"))) + .map(|(p, _)| p.clone()); + let (digest, size) = match path { + Some(p) => { + let bytes = crate::watch::mirror::read_file(mirror, commit, &p)?; + let d = crate::hash::hex(&bytes); + (d, bytes.len() as u64) + } + // A "local" file that is not in the tree is the recipe's bug; + // record the absence rather than inventing a digest. + None => (String::new(), 0), + }; + out.push(SourceDigest { + index: entry.index, + url: entry.url.clone(), + kind: "local".into(), + digest, + size, + skip_declared, + }); + continue; + } + + // Static source. + if !skip_declared { + // Trusted-as-declared: makepkg verifies it at build time. + out.push(SourceDigest { + index: entry.index, + url: entry.url.clone(), + kind: "static".into(), + digest: declared.unwrap_or_default(), + size: 0, + skip_declared: false, + }); + continue; + } + + // The paid path: download and stream-hash into the cache, which the + // build then reuses so the bytes are paid for once. + let (digest, size) = download_and_cache(cfg, db, &entry.url)?; + out.push(SourceDigest { + index: entry.index, + url: entry.url.clone(), + kind: "static".into(), + digest, + size, + skip_declared: true, + }); + } + Ok(out) +} + +/// Download `url`, hashing as we go, and record it in `source_cache`. +/// +/// This always goes to the network. That is deliberate: the whole point of §5.3 +/// is to notice that the bytes behind a `SKIP` source changed while the version +/// did not, and answering from our own cache would make that impossible. The +/// cache exists so the *build* can reuse the bytes it was reviewed against +/// ([`cached_path`]), not so detection can skip looking. +pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> { + let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16))); + let (digest, size) = crate::fetch::fetch_to(url, &tmp)?; + let dest = cfg.source_cache_path(&digest); + if !dest.exists() { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::rename(&tmp, &dest)?; + } else { + let _ = std::fs::remove_file(&tmp); + } + let at = time::now(); + let dest_s = dest.display().to_string(); + let u = url.to_string(); + let digest_for_row = digest.clone(); + db.writer.tx(move |tx| { + tx.execute( + "INSERT INTO source_cache (url, digest, size, fetched_at, path) VALUES (?1,?2,?3,?4,?5) + ON CONFLICT(url, digest) DO UPDATE SET fetched_at=excluded.fetched_at", + rusqlite::params![u, digest_for_row, size as i64, at, dest_s], + )?; + Ok(()) + })?; + Ok((digest, size)) +} + +/// The cached file holding `digest`, if we still have it. The build uses this +/// so the bytes it consumes are the bytes that were hashed at detection time. +pub fn cached_path(db: &Db, url: &str, digest: &str) -> Option { + let p: Option = db + .read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row( + "SELECT path FROM source_cache WHERE url=?1 AND digest=?2", + rusqlite::params![url, digest], + |r| r.get(0), + ) + .optional()?) + }) + .ok() + .flatten(); + p.map(std::path::PathBuf::from).filter(|p| p.exists()) +} + +/// True when a `SKIP` on a non-VCS source means the recipe permanently refuses +/// to verify its input — itself a risk signal (§5.3). +pub fn skip_on_non_vcs(recipe: &Recipe) -> Vec { + recipe + .source_entries + .iter() + .filter(|e| !e.is_vcs()) + .filter(|e| match declared_sums(recipe, e.index) { + Some(d) => d == SKIP || !is_hex_digest(&d), + None => true, + }) + .map(|e| e.index) + .collect() +} diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs new file mode 100644 index 0000000..989b968 --- /dev/null +++ b/src/watch/mirror.rs @@ -0,0 +1,119 @@ +//! The local AUR git mirror (§5.1). +//! +//! Clone, don't scrape. The mirror is load-bearing rather than a cache: every +//! build materializes its recipe from it at the pinned commit and never asks +//! the network for a recipe (§5.1a), so losing it would mean losing the ability +//! to reproduce any historical release. + +use std::collections::BTreeMap; +use std::path::Path; + +use crate::config::Config; +use crate::db::{self, Db}; +use crate::error::{Error, Result}; +use crate::git; + +/// Result of a cheap poll. `Unchanged` means we did **not** fetch — the poll is +/// `git ls-remote`, one request per pkgbase (§5.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Sync { + /// Remote is gone (deleted from AUR). + Gone, + /// `ls-remote` matched the local tip; no fetch performed. + Unchanged { head: String }, + /// The tip moved; we fetched and now have `head`. + Fetched { head: String, previous: Option }, + /// We had no local mirror yet. + Cloned { head: String }, +} + +/// Ensure a mirror exists and is polled. Updates `pkgbase.aur_head`. +pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result { + let mirror = cfg.mirror_path(name); + let known_head = db::get_pkgbase(db, name)?.and_then(|p| p.aur_head.clone()); + + if !mirror.exists() { + git::clone(url, &mirror)?; + let head = git::head(&mirror)?; + record(db, name, &head, &mirror)?; + return Ok(Sync::Cloned { head }); + } + + let remote = match git::ls_remote_head(url)? { + Some(h) => h, + None => return Ok(Sync::Gone), + }; + let local = git::head(&mirror).ok(); + if let Some(l) = &local { + if *l == remote { + return Ok(Sync::Unchanged { head: remote }); + } + } + let head = git::fetch_head(&mirror)?; + record(db, name, &head, &mirror)?; + Ok(Sync::Fetched { head, previous: known_head }) +} + +fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> { + let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(format!("pkgbase {name}")))?; + db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string()) +} + +/// A materialized snapshot tree: blob ids for hashing, text bodies for parsing +/// and diffing. +#[derive(Debug, Clone)] +pub struct Tree { + /// `(path, git blob id)` for every file in the tree — the input to + /// `recipe_hash`. Covers PKGBUILD, .SRCINFO, *.install and shipped patches + /// (§3): a patch file is part of the recipe. + pub blobs: Vec<(String, String)>, + /// Text bodies, keyed by path. Binary files are omitted from this map but + /// still counted in `blobs`. + pub files: BTreeMap, +} + +impl Tree { + pub fn recipe_hash(&self) -> String { + crate::hash::recipe_hash(&self.blobs) + } + pub fn get(&self, suffix: &str) -> Option<&String> { + self.files + .iter() + .find(|(k, _)| k.ends_with(suffix)) + .map(|(_, v)| v) + } + pub fn json_list(&self) -> String { + serde_json::to_string(&self.blobs).unwrap_or_else(|_| "[]".into()) + } +} + +/// Read a commit's tree out of the mirror without touching the network. +pub fn read_tree(mirror: &Path, commit: &str) -> Result { + // §16 mirror divergence: if a pin we are asked to read has vanished, that is + // a hard failure, not a silent re-pin. + if !git::has_commit(mirror, commit) { + return Err(Error::fail_closed(format!( + "commit {commit} is missing from the local mirror; history was rewritten" + ))); + } + let blobs = git::ls_tree(mirror, commit)?; + let mut files = BTreeMap::new(); + for (path, _) in &blobs { + let bytes = git::read_blob(mirror, commit, path)?; + if bytes.len() > 4 * 1024 * 1024 || !looks_textual(&bytes) { + continue; + } + files.insert(path.clone(), String::from_utf8_lossy(&bytes).into_owned()); + } + Ok(Tree { blobs, files }) +} + +fn looks_textual(b: &[u8]) -> bool { + !b[..b.len().min(512)].contains(&0) +} + +/// Raw bytes of one file at a commit — used to hash sources shipped in the AUR +/// repo (§5.3 "local file shipped in the AUR repo"). +pub fn read_file(mirror: &Path, commit: &str, path: &str) -> Result> { + git::read_blob(mirror, commit, path) +} diff --git a/src/watch/mod.rs b/src/watch/mod.rs new file mode 100644 index 0000000..3f0d217 --- /dev/null +++ b/src/watch/mod.rs @@ -0,0 +1,12 @@ +//! Watchers: AUR recipe mirror (§5.1), upstream VCS probe (§5.2), source digest +//! resolution (§5.3), and the scheduler tick. + +pub mod detect; +pub mod digests; +pub mod mirror; +pub mod scheduler; + +pub use detect::{check_pkgbase, CheckReport, Outcome}; +pub use digests::{cached_path, download_and_cache, resolve_sources, skip_on_non_vcs}; +pub use mirror::{read_tree, sync_mirror, Tree}; +pub use scheduler::spawn_scheduler; diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs new file mode 100644 index 0000000..ca42e32 --- /dev/null +++ b/src/watch/scheduler.rs @@ -0,0 +1,71 @@ +//! The scheduler tick (§4: "one tick thread + sweep over `next_check_at`"). +//! +//! Blocking is the right shape here: the tick sleeps between sweeps and each +//! sweep is a sequence of blocking git and HTTP calls. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::thread::JoinHandle; + +use crate::config::Config; +use crate::db::{self, Db}; +use crate::watch::detect::check_pkgbase; + +/// Spawn the watcher tick thread. +pub fn spawn_scheduler(cfg: Arc, db: Db, stop: Arc) -> JoinHandle<()> { + std::thread::Builder::new() + .name("watcher".into()) + .spawn(move || { + while !stop.load(Ordering::SeqCst) { + let tick = crate::db::setting_i64(&db, "poll_tick", 30); + sweep(&cfg, &db); + // Sleep in small slices so shutdown is prompt. + let mut slept = 0; + while slept < tick && !stop.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_secs(1)); + slept += 1; + } + } + }) + .expect("spawn watcher") +} + +/// One sweep over everything that is due. +pub fn sweep(cfg: &Config, db: &Db) -> usize { + let now = crate::time::now(); + let due = match db::due_subscriptions(db, &now) { + Ok(d) => d, + Err(_) => return 0, + }; + let mut n = 0; + for sub in due { + // Mark it checked first so a slow or hanging source cannot make the + // scheduler re-enter it on the next tick. + let interval = sub + .poll_interval_secs + .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); + let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(interval), None); + match check_pkgbase(cfg, db, &sub.pkgbase) { + Ok(report) => { + if matches!(report.outcome, crate::watch::detect::Outcome::Blocked(_)) { + let _ = db::note_check( + &db.writer, + &sub.pkgbase, + &crate::time::secs_ahead(600), + Some(&format!("{:?}", report.outcome)), + ); + } + } + Err(e) => { + let _ = db::note_check( + &db.writer, + &sub.pkgbase, + &crate::time::secs_ahead(600), + Some(&e.to_string()), + ); + } + } + n += 1; + } + n +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 4cf78ec..b598b80 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -73,6 +73,54 @@ impl Env { .unwrap() } + /// Stand in for the build+publish path: turn an approved candidate into a + /// published release and move the accepted pointer. The real path lives in + /// `pipeline`; detection tests need an accepted base without a build. + pub fn accept_as_release(&self, candidate_id: i64) -> i64 { + let at = "2026-01-01T00:00:00Z"; + self.db + .writer + .tx(move |tx| { + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, + risk_level, diff_digest, identity_hash) + SELECT id, base_release_id, ?2, 'approved', risk_level, diff_digest, identity_hash + FROM candidate WHERE id=?1", + rusqlite::params![candidate_id, at], + )?; + let approval_id = tx.last_insert_rowid(); + tx.execute( + "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, + upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, + state, published_at, created_at) + SELECT c.pkgbase_id, c.id, ?2, s.aur_commit, s.recipe_hash, c.upstream_pins_json, + c.source_digests_json, c.epoch, c.pkgver, c.pkgrel, + 'published', ?3, ?3 + FROM candidate c JOIN snapshot s ON s.id = c.snapshot_id WHERE c.id=?1", + rusqlite::params![candidate_id, approval_id, at], + )?; + let release_id = tx.last_insert_rowid(); + tx.execute( + "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, candidate_id], + )?; + tx.execute( + "INSERT INTO package (repo_id, release_id, name, arch, version, state) + SELECT (SELECT id FROM repo ORDER BY id LIMIT 1), ?1, + b.name, 'x86_64', c.pkgver || '-' || c.pkgrel, 'in_index' + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?2", + rusqlite::params![release_id, candidate_id], + )?; + tx.execute( + "UPDATE pkgbase SET current_accepted_release_id=?1 + WHERE id=(SELECT pkgbase_id FROM candidate WHERE id=?2)", + rusqlite::params![release_id, candidate_id], + )?; + Ok(release_id) + }) + .unwrap() + } + pub fn query_i64(&self, sql: &str, params: &[P]) -> Option { let sql = sql.to_string(); let params: Vec

= params.to_vec(); diff --git a/tests/detect.rs b/tests/detect.rs new file mode 100644 index 0000000..939dce1 --- /dev/null +++ b/tests/detect.rs @@ -0,0 +1,428 @@ +//! Detection tests (§5.1, §5.1a, §5.3, §7.1) against a local `file://` "AUR". +//! +//! The fixtures are real git repos so the mirror, the pin and `recipe_hash` are +//! exercised for real; only the network is replaced. + +mod common; + +use common::{git_add_commit, make_git_repo, params, Env, P}; + +use aur_build::db::{self, model::*, ReleaseRow}; +use aur_build::review::{approve, candidates}; +use aur_build::watch::detect::{check_pkgbase, Outcome}; +use aur_build::watch::mirror::{sync_mirror, Sync}; + +/// Path of the fake AUR repo for `name`, matching `Env::subscribe`'s URL. +fn aur(env: &Env, name: &str) -> std::path::PathBuf { + env.path(&format!("aur/{name}.git")) +} + +fn seed(env: &Env, name: &str, pkgver: &str, pkgrel: &str, extra: &str) -> String { + make_git_repo(&aur(env, name), &[("PKGBUILD", &common::pkgbuild(name, pkgver, pkgrel, extra))], "initial") +} + +fn pending(env: &Env, name: &str) -> Option { + let pb = db::get_pkgbase(&env.db, name).unwrap().unwrap(); + candidates::open_reviews_for(&env.db, pb.id).unwrap().into_iter().next() +} + +fn accepted(env: &Env, name: &str) -> Option { + db::accepted_release(&env.db, name).unwrap() +} + +#[test] +fn first_detection_opens_a_first_introduction_with_no_base() { + let env = Env::new(); + env.subscribe("foo"); + let commit = seed(&env, "foo", "1.0", "1", ""); + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + match &rep.outcome { + Outcome::Candidate { kind, .. } => assert_eq!(kind, candidate_kind::FIRST_INTRODUCTION), + other => panic!("expected a candidate, got {other:?}"), + } + assert_eq!(rep.head, commit); + let c = pending(&env, "foo").expect("candidate row"); + assert_eq!(c.kind, candidate_kind::FIRST_INTRODUCTION); + assert_eq!(c.base_release_id, None, "I2 has no referent for a first introduction"); + assert_eq!(c.version(), "1.0-1"); + // The pin is recorded on the snapshot and it is the commit we cloned. + let snap = db::snapshot_by_id(&env.db, c.snapshot_id).unwrap().unwrap(); + assert_eq!(snap.aur_commit, commit); + assert_eq!(snap.recipe_hash.len(), 64); +} + +#[test] +fn cheap_poll_does_not_fetch_when_the_tip_is_unchanged() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + let url = format!("file://{}", aur(&env, "foo").display()); + let first = sync_mirror(&env.cfg, &env.db, "foo", &url).unwrap(); + assert!(matches!(first, Sync::Cloned { .. })); + let again = sync_mirror(&env.cfg, &env.db, "foo", &url).unwrap(); + match again { + Sync::Unchanged { head } => assert_eq!(head, git_head(&aur(&env, "foo"))), + other => panic!("expected Unchanged, got {other:?}"), + } + // A new commit makes it fetch. + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "1.1", "1", ""))], "bump"); + let moved = sync_mirror(&env.cfg, &env.db, "foo", &url).unwrap(); + assert!(matches!(moved, Sync::Fetched { .. }), "SHA moved -> fetch"); +} + +fn git_head(p: &std::path::Path) -> String { + aur_build::git::head(p).unwrap() +} + +/// §3: `recipe_hash` covers the *entire* tree, because a shipped patch is part +/// of the recipe and is a classic silent-change vector. +#[test] +fn recipe_hash_covers_shipped_patches() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", "source=(fix.patch)\nsha256sums=('SKIP')"); + std::fs::write(aur(&env, "foo").join("fix.patch"), "--- a\n+++ b\n@@\n-old\n+new\n").unwrap(); + git_add_commit(&aur(&env, "foo"), &[("fix.patch", "--- a\n+++ b\n@@\n-old\n+new\n")], "patch"); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c1 = pending(&env, "foo").unwrap(); + let h1 = db::snapshot_by_id(&env.db, c1.snapshot_id).unwrap().unwrap().recipe_hash; + env.accept_as_release(c1.id); + + // Same PKGBUILD, different patch bytes. + git_add_commit(&aur(&env, "foo"), &[("fix.patch", "--- a\n+++ b\n@@\n-old\n+EVIL\n")], "patch2"); + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + assert!( + matches!(rep.outcome, Outcome::Notice { ref kind, .. } if kind == notice_kind::RECIPE_DRIFT), + "recipe drift with an unchanged version is a notice, never a candidate (I11): {:?}", + rep.outcome + ); + let pb = db::get_pkgbase(&env.db, "foo").unwrap().unwrap(); + let snap = db::snapshot_by_commit(&env.db, pb.id, &rep.head).unwrap().unwrap(); + assert_ne!(snap.recipe_hash, h1, "patch bytes must change recipe_hash"); +} + +#[test] +fn skip_sources_are_stream_hashed_into_the_cache() { + let env = Env::new(); + env.subscribe("foo"); + let payload = env.path("payload.txt"); + std::fs::write(&payload, b"the bytes that become the package").unwrap(); + let expected = aur_build::hash::hex(b"the bytes that become the package"); + seed( + &env, + "foo", + "1.0", + "1", + &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()), + ); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + let digests = c.digests(); + assert_eq!(digests.len(), 1); + assert_eq!(digests[0].digest, expected, "we hash SKIP sources ourselves (§5.3)"); + assert!(digests[0].skip_declared); + assert_eq!(digests[0].kind, "static"); + // The bytes landed in the content-addressed cache and are recorded. + let cached = env.query_i64( + "SELECT count(*) FROM source_cache WHERE url LIKE '%payload.txt' AND digest=?1", + ¶ms(vec![expected.clone()]), + ); + assert_eq!(cached, Some(1)); + let path = env.cfg.source_cache_path(&expected); + assert!(path.exists(), "cached file is reused by the build"); + // A declared checksum costs no bandwidth: nothing was downloaded for it. +} + +#[test] +fn declared_checksums_are_trusted_without_downloading() { + let env = Env::new(); + env.subscribe("foo"); + let payload = env.path("declared.txt"); + std::fs::write(&payload, b"verified bytes").unwrap(); + let d = aur_build::hash::hex(b"verified bytes"); + seed( + &env, + "foo", + "1.0", + "1", + &format!("source=(file://{})\nsha256sums=('{d}')\n", payload.display()), + ); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + assert_eq!(c.digests()[0].digest, d); + assert!(!c.digests()[0].skip_declared); + assert_eq!( + env.query_i64("SELECT count(*) FROM source_cache", &[]), + Some(0), + "declared sums are enforced by makepkg, not re-downloaded (§5.3)" + ); +} + +/// I2, the headline rule: diffs are always against the last *accepted* version. +#[test] +fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c1 = pending(&env, "foo").unwrap(); + let rel1 = env.accept_as_release(c1.id); + assert_eq!(accepted(&env, "foo").unwrap().id, rel1); + + // v2 arrives and is detected but nobody looks at it. + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2"); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c2 = pending(&env, "foo").unwrap(); + assert_eq!(c2.base_release_id, Some(rel1), "base is the accepted release"); + assert_eq!(c2.version(), "2.0-1"); + + // v3 and v4 arrive while nobody is looking: they collapse into the same + // review, and the base is *still* v1. The human sees v1 -> v4. + for v in ["3.0", "4.0"] { + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", v, "1", ""))], v); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + } + let c = pending(&env, "foo").unwrap(); + assert_eq!(c.id, c2.id, "collapsed in place: no new row (I7)"); + assert_eq!(c.revision, 2, "revision counts the collapsed detections (v3, v4)"); + assert_eq!(c.base_release_id, Some(rel1), "base never moves: the diff is v1 -> v4 (I2)"); + assert_eq!(c.version(), "4.0-1"); + assert_eq!( + env.query_i64("SELECT count(*) FROM candidate WHERE state='pending_review'", &[]), + Some(1) + ); +} + +/// §7.1: `superseded` exists only when a human actually saw the old diff. +#[test] +fn a_viewed_review_is_frozen_and_a_fresh_one_opened() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c1 = pending(&env, "foo").unwrap(); + let rel1 = env.accept_as_release(c1.id); + + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2"); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c2 = pending(&env, "foo").unwrap(); + candidates::mark_viewed(&env.db, c2.id).unwrap(); + + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "3.0", "1", ""))], "v3"); + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + match rep.outcome { + Outcome::Superseded { old, new } => { + assert_eq!(old, c2.id); + assert_ne!(old, new); + } + other => panic!("expected Superseded, got {other:?}"), + } + let c3 = pending(&env, "foo").unwrap(); + assert_eq!(c3.base_release_id, Some(rel1), "the fresh review keeps the same base"); + assert_eq!(c3.version(), "3.0-1"); + let old_state: String = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT state FROM candidate WHERE id=?1", + rusqlite::params![c2.id], + |r| r.get(0), + )?) + }) + .unwrap(); + assert_eq!(old_state, candidate_state::SUPERSEDED); +} + +#[test] +fn a_rejected_identity_is_not_re_raised() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + approve::reject(&env.db, "tester", c.id, "not this one").unwrap(); + // Re-running detection must not nag (§7.1). + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + assert!( + matches!(rep.outcome, Outcome::PreviouslyRejected | Outcome::NoChange), + "{:?}", + rep.outcome + ); + assert!(pending(&env, "foo").is_none()); + // A *newer* version is still detected: rejection does not block (§7.1). + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2"); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + assert!(pending(&env, "foo").is_some()); +} + +/// I11: a change that is not publishable never silently disappears. +#[test] +fn recipe_drift_under_a_static_version_is_a_notice_not_a_candidate() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + env.accept_as_release(c.id); + + // Maintainer edits the PKGBUILD but forgets to bump pkgrel. + git_add_commit( + &aur(&env, "foo"), + &[("PKGBUILD", &common::pkgbuild("foo", "1.0", "1", "# a comment only"))], + "typo fix, no bump", + ); + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + match rep.outcome { + Outcome::Notice { kind, .. } => assert_eq!(kind, notice_kind::RECIPE_DRIFT), + other => panic!("expected a notice, got {other:?}"), + } + assert!(pending(&env, "foo").is_none(), "nothing publishable, so no review"); + let notices = db::list_notices(&env.db, false).unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].kind, notice_kind::RECIPE_DRIFT); + assert_eq!(notices[0].severity, "warning"); +} + +/// §5.3: the single most valuable detection — same version, swapped bytes. +#[test] +fn digest_drift_with_an_unchanged_version_is_an_integrity_alert() { + let env = Env::new(); + env.subscribe("foo"); + let payload = env.path("payload.txt"); + std::fs::write(&payload, b"good release tarball").unwrap(); + seed( + &env, + "foo", + "1.0", + "1", + &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()), + ); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + env.accept_as_release(c.id); + + // The CDN now serves something else and the version did not move. + std::fs::write(&payload, b"EVIL swapped artifact").unwrap(); + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + match rep.outcome { + Outcome::Notice { kind, .. } => assert_eq!(kind, notice_kind::INTEGRITY_ALERT), + other => panic!("expected an integrity alert, got {other:?}"), + } + assert!(pending(&env, "foo").is_none(), "approving it would not let us publish anything"); + let notices = db::list_notices(&env.db, false).unwrap(); + assert_eq!(notices[0].severity, "high"); + assert!(notices[0].detail_json.contains("no longer serves")); + // The index keeps serving the artifact built from the old bytes (I1). + assert_eq!(db::unapproved_index_entries(&env.db).unwrap(), Vec::::new()); +} + +#[test] +fn a_deleted_upstream_marks_the_subscription_and_alerts() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + std::fs::remove_dir_all(aur(&env, "foo")).unwrap(); + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + assert!(matches!(rep.outcome, Outcome::Gone), "{:?}", rep.outcome); + let sub = db::get_subscription(&env.db, "foo").unwrap().unwrap(); + assert_eq!(sub.state, subscription_state::ORPHANED); + assert!(db::list_notices(&env.db, false) + .unwrap() + .iter() + .any(|n| n.kind == notice_kind::DELETED)); +} + +#[test] +fn detection_is_idempotent_and_records_no_duplicate_candidate() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + for _ in 0..3 { + let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + assert!(matches!(rep.outcome, Outcome::NoChange), "{:?}", rep.outcome); + } + assert_eq!( + env.query_i64("SELECT count(*) FROM candidate", &[]), + Some(1), + "I3: two byte-identical inputs never produce two candidates" + ); + assert_eq!(env.query_i64("SELECT count(*) FROM snapshot", &[]), Some(1)); +} + +#[test] +fn srcinfo_is_preferred_over_the_pkgbuild_when_present() { + let env = Env::new(); + env.subscribe("foo"); + // .SRCINFO disagrees with the PKGBUILD, which is what makepkg reports. + make_git_repo( + &aur(&env, "foo"), + &[ + ("PKGBUILD", &common::pkgbuild("foo", "9.9", "9", "")), + ( + ".SRCINFO", + "pkgbase = foo\n\tpkgver = 1.0\n\tpkgrel = 1\n\tarch = x86_64\npkgname = foo\n\tarch = x86_64\n", + ), + ], + "initial", + ); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + assert_eq!(c.version(), "1.0-1", ".SRCINFO is authoritative"); +} + +#[test] +fn split_pkgbase_records_every_emitted_package() { + let env = Env::new(); + env.subscribe("foo"); + make_git_repo( + &aur(&env, "foo"), + &[( + "PKGBUILD", + "pkgbase=foo\npkgver=1.0\npkgrel=1\npkgdesc=split\narch=(x86_64)\npkgname=(foo foo-lua)\nsource=()\nsha256sums=()\n", + )], + "initial", + ); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + let snap = db::snapshot_by_id(&env.db, c.snapshot_id).unwrap().unwrap(); + let r: Recipe = serde_json::from_str(&snap.srcinfo_json).unwrap(); + assert_eq!(r.pkgnames, vec!["foo".to_string(), "foo-lua".to_string()]); +} + +#[test] +fn epoch_and_pkgrel_are_part_of_the_identity() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + env.accept_as_release(c.id); + // pkgrel reset: a major signal, and a new identity. + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "1.0", "7", ""))], "rel"); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c2 = pending(&env, "foo").expect("pkgrel bump is publishable, so it is a candidate"); + assert_eq!(c2.version(), "1.0-7"); + assert_ne!(c2.identity_hash, c.identity_hash); +} + +#[test] +fn notices_are_not_duplicated_by_repeated_polling() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + let c = pending(&env, "foo").unwrap(); + env.accept_as_release(c.id); + git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "1.0", "1", "# x"))], "drift"); + for _ in 0..4 { + check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); + } + assert_eq!( + env.query_i64("SELECT count(*) FROM notice", &[]), + Some(1), + "the same drift polled daily is one alert, not four" + ); + let _ = P::I(0); +} -- cgit v1.2.3