diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 07:16:36 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 07:16:36 +0000 |
| commit | 0b3cb443e70b46ec61455255c3ddfc2a26997613 (patch) | |
| tree | 457d5e0bf3b1733b79829de3c146e1cabcc85e8c | |
| parent | d7c386a703a9b69211d83854547218d6e1da9a51 (diff) | |
| download | aur-build-0b3cb443e70b46ec61455255c3ddfc2a26997613.tar.gz aur-build-0b3cb443e70b46ec61455255c3ddfc2a26997613.zip | |
watch: two-stage VCS watcher — ls-remote probe, pkgver() resolution, pin capture (§5.2)
Stage A probes every VCS source in source=() with git ls-remote,
respecting #commit/#tag/#branch fragments, and returns one UpstreamPin
per source. If the tip set equals the accepted release's pins, nothing
can have changed and Stage B never runs — the common case costs one
round trip per source and no clone. svn/hg have no cheap universal probe,
so they are reported as unprobed and force Stage B rather than being
silently treated as unchanged.
Stage B runs only on movement: it fetches into a persistent vcs_cache
(rather than re-cloning a multi-gigabyte upstream daily), runs makepkg
--vercheck, and captures the pins from the clone it already has. Results
are cached on (pkgbase, recipe_hash, upstream_tip) with a per-pkgbase
cooldown, and a process-wide slot cap bounds concurrent resolutions.
The resolved epoch:pkgver-pkgrel plus the pins go into identity_hash, so
a different commit is a different thing to approve.
Also fixes a misclassification the new path exposed: a VCS source's
digest is its pin, so upstream movement showed up as an integrity_alert.
Integrity events are now restricted to fixed downloads; VCS movement
under a frozen pkgver is pin_drift, as §5.2 specifies.
New fixtures git-multi (two upstreams) and git-tagged (#tag pin). 10
tests in tests/vcs.rs.
| -rw-r--r-- | .pi/.goals-pool-snapshot.json | 2 | ||||
| -rw-r--r-- | .pi/goals/.goal-ledger-checkpoint.json | 2 | ||||
| -rw-r--r-- | .pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md | 29 | ||||
| -rw-r--r-- | .pi/goals/goal_events.jsonl | 3 | ||||
| -rw-r--r-- | src/db/migrations.rs | 22 | ||||
| -rw-r--r-- | src/db/queries.rs | 85 | ||||
| -rw-r--r-- | src/error.rs | 10 | ||||
| -rw-r--r-- | src/watch/detect.rs | 62 | ||||
| -rw-r--r-- | src/watch/mod.rs | 1 | ||||
| -rw-r--r-- | src/watch/upstream.rs | 293 | ||||
| -rw-r--r-- | testcorpus/git-multi/PKGBUILD | 19 | ||||
| -rw-r--r-- | testcorpus/git-multi/manifest.json | 12 | ||||
| -rw-r--r-- | testcorpus/git-tagged/PKGBUILD | 15 | ||||
| -rw-r--r-- | testcorpus/git-tagged/manifest.json | 12 | ||||
| -rw-r--r-- | tests/common/mod.rs | 35 | ||||
| -rw-r--r-- | tests/db.rs | 2 | ||||
| -rw-r--r-- | tests/vcs.rs | 263 |
17 files changed, 841 insertions, 26 deletions
diff --git a/.pi/.goals-pool-snapshot.json b/.pi/.goals-pool-snapshot.json index 3e286ed..47866f8 100644 --- a/.pi/.goals-pool-snapshot.json +++ b/.pi/.goals-pool-snapshot.json @@ -1 +1 @@ -{"version":1,"dirMtimeMs":1794985286895.4468,"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":2375516,"activeSeconds":5307},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-18T07:01:26.894Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":253,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"dfbaf4f2-dad9-4dc6-9717-5038550aa75e","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"kickoff"},"dispatch":{"id":"27430841-6f83-4343-a9fa-dd1c866de9d3","kind":"kickoff","claimedAt":1794985072841}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"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":"complete","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test.","completedAt":"2026-11-17T21:31:09.120Z","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO"},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"complete","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction.","completedAt":"2026-11-17T21:20:02.693Z","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi"},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"complete","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected.","completedAt":"2026-11-17T22:10:06.063Z","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi"},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"complete","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap.","completedAt":"2026-11-17T21:58:00.936Z","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean"},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"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"}}]}
\ No newline at end of file +{"version":1,"dirMtimeMs":1794986189728.4663,"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":2777693,"activeSeconds":6191},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-18T07:16:29.726Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":288,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"dfbaf4f2-dad9-4dc6-9717-5038550aa75e","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"kickoff"},"dispatch":{"id":"27430841-6f83-4343-a9fa-dd1c866de9d3","kind":"kickoff","claimedAt":1794985072841}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"complete","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"complete","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test.","completedAt":"2026-11-17T21:31:09.120Z","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO"},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"complete","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction.","completedAt":"2026-11-17T21:20:02.693Z","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi"},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"complete","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected.","completedAt":"2026-11-17T22:10:06.063Z","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi"},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"complete","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap.","completedAt":"2026-11-17T21:58:00.936Z","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean"},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"complete","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8).","completedAt":"2026-11-18T07:01:31.398Z","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re"}],"completedAt":"2026-11-18T07:02:29.831Z","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit"},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"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-p1-stageA"}]}
\ No newline at end of file diff --git a/.pi/goals/.goal-ledger-checkpoint.json b/.pi/goals/.goal-ledger-checkpoint.json index 7b9f9e4..cbc7498 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-18T06:57:52.838Z","coveredBytes":6557,"coveredEvents":16,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z","resumedAt":"2026-11-18T06:57:52.837Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"}],"oracle":[],"lifecycle":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},"lastActivityEvent":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"}}]]}
\ No newline at end of file +{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-18T07:04:12.255Z","coveredBytes":7311,"coveredEvents":19,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z","resumedAt":"2026-11-18T06:57:52.837Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"}],"oracle":[],"lifecycle":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"}}]]}
\ 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 f11d934..900925a 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": 2375516, - "activeSeconds": 5307 + "tokensUsed": 2777693, + "activeSeconds": 6191 }, "sisyphus": false, "createdAt": "2026-11-17T20:43:24.440Z", - "updatedAt": "2026-11-18T07:01:26.894Z", + "updatedAt": "2026-11-18T07:16:29.726Z", "activePath": ".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md", - "revision": 253, + "revision": 288, "scheduler": { "version": 1, "owner": "01a1eb32-2e3f-757c-a79a-21ac993facc5", @@ -43,7 +43,7 @@ { "id": "task-p0", "title": "P0 — walking skeleton + test harness (§17 P0, §16a)", - "status": "pending", + "status": "complete", "subtasks": [ { "id": "task-p0-schema", @@ -88,10 +88,14 @@ { "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)." + "status": "complete", + "verificationContract": "cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8).", + "completedAt": "2026-11-18T07:01:31.398Z", + "evidence": "tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re" } - ] + ], + "completedAt": "2026-11-18T07:02:29.831Z", + "evidence": "All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit" }, { "id": "task-p1", @@ -214,7 +218,8 @@ ], "blockCompletion": true, "proposedAt": "2026-11-17T20:39:23.165Z" - } + }, + "currentTaskId": "task-p1-stageA" } # Goal Prompt @@ -247,13 +252,13 @@ 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: 1h28m27s -- Tokens used: 2.4M (2,375,516) tokens +- Time spent: 1h43m11s +- Tokens used: 2.8M (2,777,693) tokens ## Tasks <!-- blockCompletion: true --> - [x] task-setup: Provision toolchain (pacman rustup + devtools) and initialize git — 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 -- [ ] task-p0: P0 — walking skeleton + test harness (§17 P0, §16a) +- [x] task-p0: P0 — walking skeleton + test harness (§17 P0, §16a) — evidence: All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit - [ ] task-p1: P1 — VCS / computed pkgver detection (§5.2, §3) - [ ] task-p2: P2 — review surface (§12, §13, §6) - [ ] task-p3: P3 — durability (§8.2, §8.3, §8.4) diff --git a/.pi/goals/goal_events.jsonl b/.pi/goals/goal_events.jsonl index f595116..2d2e398 100644 --- a/.pi/goals/goal_events.jsonl +++ b/.pi/goals/goal_events.jsonl @@ -14,3 +14,6 @@ {"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"} {"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"} {"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"} +{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"} +{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"} +{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"} diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 8ba925c..bb8974f 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -299,6 +299,26 @@ BEGIN END; "#; +/// Stage B results, keyed on `(pkgbase, recipe_hash, upstream_tip)` (§5.2). +/// Re-resolving means cloning an upstream repo and running makepkg, so the +/// answer is worth keeping; the same key also implements the per-pkgbase +/// cooldown, because a fresh tip inside the window reuses the old answer. +const M_0007_STAGE_B_CACHE: &str = r#" +CREATE TABLE stage_b_cache ( + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + recipe_hash TEXT NOT NULL, + tip_hash TEXT NOT NULL, + epoch TEXT NOT NULL, + pkgver TEXT NOT NULL, + pkgrel TEXT NOT NULL, + pins_json TEXT NOT NULL, + resolved_at TEXT NOT NULL, + PRIMARY KEY (pkgbase_id, recipe_hash, tip_hash) +); + +CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); +"#; + pub static MIGRATIONS: &[Migration] = &[ Migration { version: 1, name: "core", sql: M_0001_CORE }, Migration { version: 2, name: "build", sql: M_0002_BUILD }, @@ -306,6 +326,7 @@ pub static MIGRATIONS: &[Migration] = &[ Migration { version: 4, name: "audit-triggers", sql: M_0004_TRIGGERS }, Migration { version: 5, name: "artifact-build", sql: M_0005_ARTIFACT_BUILD }, Migration { version: 6, name: "approval-immutable", sql: M_0006_APPROVAL_IMMUTABLE }, + Migration { version: 7, name: "stage-b-cache", sql: M_0007_STAGE_B_CACHE }, ]; /// Default settings seeded into `settings` (DESIGN.md §11). @@ -314,6 +335,7 @@ pub const DEFAULT_SETTINGS: &[(&str, &str)] = &[ ("build_timeout", "5400"), ("poll_interval", "86400"), ("stage_b_cooldown", "86400"), + ("stage_b_concurrency", "1"), ("retention_versions", "3"), ("dry_run", "0"), ("review_budget_days", "14"), diff --git a/src/db/queries.rs b/src/db/queries.rs index b1f7e4d..fe3109a 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -575,6 +575,91 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> }) } +// --------------------------------------------------------- stage B cache -- + +/// Exact cache hit: same recipe, same upstream tips (§5.2). +pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result<Option<crate::watch::upstream::StageB>> { + let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); + db.read(move |c| { + use rusqlite::OptionalExtension; + Ok(c.query_row( + "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache + WHERE pkgbase_id=?1 AND recipe_hash=?2 AND tip_hash=?3", + params![pkgbase_id, rh, th], + |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, String>(3)?, + )) + }, + ) + .optional()? + .map(|(epoch, pkgver, pkgrel, pins_json)| crate::watch::upstream::StageB { + epoch, + pkgver, + pkgrel, + pins: serde_json::from_str(&pins_json).unwrap_or_default(), + cached: true, + })) + }) +} + +/// The most recent answer for this pkgbase, if it is inside the cooldown window. +pub fn stage_b_recent(db: &Db, pkgbase_id: i64, cooldown_secs: i64) -> Result<Option<crate::watch::upstream::StageB>> { + let cutoff = crate::time::secs_ago(cooldown_secs); + db.read(move |c| { + use rusqlite::OptionalExtension; + Ok(c.query_row( + "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache + WHERE pkgbase_id=?1 AND resolved_at > ?2 + ORDER BY resolved_at DESC LIMIT 1", + params![pkgbase_id, cutoff], + |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, String>(3)?, + )) + }, + ) + .optional()? + .map(|(epoch, pkgver, pkgrel, pins_json)| crate::watch::upstream::StageB { + epoch, + pkgver, + pkgrel, + pins: serde_json::from_str(&pins_json).unwrap_or_default(), + cached: true, + })) + }) +} + +pub fn stage_b_cache_put( + db: &Db, + pkgbase_id: i64, + recipe_hash: &str, + tip_hash: &str, + r: &crate::watch::upstream::StageB, +) -> Result<()> { + let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); + let (epoch, pkgver, pkgrel) = (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone()); + let pins = serde_json::to_string(&r.pins)?; + let at = crate::time::now(); + db.writer.tx(move |tx| { + tx.execute( + "INSERT INTO stage_b_cache (pkgbase_id, recipe_hash, tip_hash, epoch, pkgver, pkgrel, pins_json, resolved_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8) + ON CONFLICT(pkgbase_id, recipe_hash, tip_hash) DO UPDATE SET + epoch=excluded.epoch, pkgver=excluded.pkgver, pkgrel=excluded.pkgrel, + pins_json=excluded.pins_json, resolved_at=excluded.resolved_at", + params![pkgbase_id, rh, th, epoch, pkgver, pkgrel, pins, at], + )?; + Ok(()) + }) +} + // ----------------------------------------------------------------- notice -- pub fn put_notice( diff --git a/src/error.rs b/src/error.rs index a60843c..ac47fc8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -30,6 +30,11 @@ pub enum Error { Invalid(String), #[error("blocked: {0}")] Blocked(String), + /// A failure the outside world caused and a retry may clear: an unreachable + /// upstream, a half-written mirror. Distinct from a deterministic failure, + /// which must never be retried into a different answer (§8.4). + #[error("transient: {0}")] + Transient(String), #[error("{0}")] Other(String), } @@ -59,11 +64,14 @@ impl Error { pub fn other(s: impl fmt::Display) -> Self { Error::Other(s.to_string()) } + pub fn transient(s: impl fmt::Display) -> Self { + Error::Transient(s.to_string()) + } /// True when a retry could plausibly help (network, mirror 5xx). Deterministic /// build failures must not auto-retry (§8.4). pub fn is_transient(&self) -> bool { - matches!(self, Error::Http(_) | Error::Io(_)) + matches!(self, Error::Http(_) | Error::Io(_) | Error::Transient(_)) } } diff --git a/src/watch/detect.rs b/src/watch/detect.rs index e00a2f9..d5f5c46 100644 --- a/src/watch/detect.rs +++ b/src/watch/detect.rs @@ -118,14 +118,47 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor 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<UpstreamPin> = Vec::new(); // P1 fills this in for VCS sources + + // §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and + // costs no clone; if the tip set is what the accepted release was built + // from, nothing can have changed and Stage B never runs. + let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs()); + let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default(); + // A recipe with no VCS sources states its own version; there is nothing to + // probe and nothing to resolve. + let stage_a = if has_vcs { + Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) + } else { + None + }; + let resolved = if !has_vcs { + None + } else if stage_a.as_ref().unwrap().needs_stage_b() { + crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())? + } else { + // Upstream has not moved. The version we serve is still the answer, and + // reusing its pins is what makes the next pass cheap too. + accepted.as_ref().map(|a| crate::watch::upstream::StageB { + epoch: a.epoch.clone(), + pkgver: a.pkgver.clone(), + pkgrel: a.pkgrel.clone(), + pins: accepted_pins.clone(), + cached: true, + }) + }; + // For a VCS package the literal `pkgver=` is frozen; the resolved one is the + // only version a consumer could actually install. + let (epoch, pkgver, pkgrel, pins) = match &resolved { + Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()), + None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()), + }; + let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &pins)?; let identity = Identity { aur_commit: head.to_string(), - epoch: recipe.epoch.clone(), - pkgver: recipe.pkgver.clone(), - pkgrel: recipe.pkgrel.clone(), + epoch: epoch.clone(), + pkgver: pkgver.clone(), + pkgrel: pkgrel.clone(), upstream_pins: pins.clone(), source_digests: digests.clone(), }; @@ -141,9 +174,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor let nc = NewCandidate { snapshot_id: snap_id, - epoch: recipe.epoch.clone(), - pkgver: recipe.pkgver.clone(), - pkgrel: recipe.pkgrel.clone(), + epoch: epoch.clone(), + pkgver: pkgver.clone(), + pkgrel: pkgrel.clone(), upstream_pins_json: serde_json::to_string(&pins)?, source_digests_json: serde_json::to_string(&digests)?, identity_hash: identity_hash.clone(), @@ -216,9 +249,19 @@ fn non_publishable( // 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). + // A VCS source's digest *is* its pin, so upstream moving shows up there too + // — but that is ordinary drift, handled by the pin check below, not an + // integrity event. Integrity means "the bytes we built are gone and the + // version says nothing moved", which only applies to fixed downloads. + let vcs_indices: std::collections::BTreeSet<usize> = recipe + .source_entries + .iter() + .filter(|e| e.is_vcs()) + .map(|e| e.index) + .collect(); let changed_remote: Vec<&SourceDigest> = new_digests .iter() - .filter(|n| n.kind != "local") + .filter(|n| n.kind != "local" && !vcs_indices.contains(&n.index)) .filter(|n| match old_digests.iter().find(|o| o.index == n.index) { Some(o) => o.digest != n.digest, None => true, @@ -271,7 +314,6 @@ fn non_publishable( } // 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, diff --git a/src/watch/mod.rs b/src/watch/mod.rs index 3f0d217..2016166 100644 --- a/src/watch/mod.rs +++ b/src/watch/mod.rs @@ -5,6 +5,7 @@ pub mod detect; pub mod digests; pub mod mirror; pub mod scheduler; +pub mod upstream; pub use detect::{check_pkgbase, CheckReport, Outcome}; pub use digests::{cached_path, download_and_cache, resolve_sources, skip_on_non_vcs}; diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs new file mode 100644 index 0000000..442647c --- /dev/null +++ b/src/watch/upstream.rs @@ -0,0 +1,293 @@ +//! The two-stage VCS watcher (§5.2) — the expensive path, made cheap. +//! +//! For a `-git` package the `pkgver=` field is frozen and the real version is +//! computed by `pkgver()` at build time, so detection cannot read it off the +//! recipe. Running the real thing every poll would be absurd, so: +//! +//! **Stage A** asks each upstream where its tip is now (`git ls-remote`, which +//! costs one network round trip and no clone). If the set of tips is identical +//! to the set recorded on the accepted release, *nothing can have changed* and +//! we stop. This is the common case: most days, nothing moves. +//! +//! **Stage B** runs only when Stage A saw movement: clone/fetch into the +//! persistent cache, run `makepkg --vercheck` against the recipe, and read back +//! the computed `epoch:pkgver-pkgrel` — the only correct answer, because +//! `pkgver()` can do arbitrary things. The clone is already there, so this is +//! also where the pins are captured. + +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::process::Command; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Condvar, Mutex}; + +use crate::config::Config; +use crate::db::{self, model::*, Db, Pkgbase}; +use crate::error::{Error, Result}; +use crate::git; + +/// What Stage A found. +#[derive(Debug, Clone)] +pub struct StageA { + /// One pin per VCS source, in `source=()` order. + pub pins: Vec<UpstreamPin>, + /// URLs we could not probe cheaply (svn, hg, or a dead remote). Treated as + /// "assume it moved" — we would rather run Stage B than miss a release. + pub unprobed: Vec<String>, + /// True when the tip set differs from the accepted release's pins. + pub moved: bool, +} + +impl StageA { + /// Stage B is worth running: something upstream moved, or we cannot prove + /// that nothing did. + pub fn needs_stage_b(&self) -> bool { + self.moved || !self.unprobed.is_empty() + } +} + +/// Probe every VCS source in the recipe. **Every** one, not just the first: a +/// pkgbase can build from two upstream repos and either can move alone. +pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> { + let mut pins = Vec::new(); + let mut unprobed = Vec::new(); + for entry in recipe.source_entries.iter().filter(|e| e.is_vcs()) { + let want = if let Some(c) = &entry.commit { + // Pinned to a commit by the recipe itself: it cannot move. + pins.push(UpstreamPin { + index: entry.index, + url: entry.url.clone(), + ref_: format!("commit={c}"), + branch: entry.branch.clone(), + commit: c.clone(), + }); + continue; + } else if let Some(t) = &entry.tag { + (format!("refs/tags/{t}"), t.clone()) + } else if let Some(b) = &entry.branch { + (format!("refs/heads/{b}"), b.clone()) + } else { + ("HEAD".into(), "HEAD".into()) + }; + + match entry.vcs.as_deref() { + Some("git") | None => { + let sha = match want.0.as_str() { + "HEAD" => git::ls_remote_head(&entry.url)?, + refname => git::ls_remote_ref(&entry.url, refname)?, + }; + match sha { + Some(sha) => pins.push(UpstreamPin { + index: entry.index, + url: entry.url.clone(), + ref_: want.1, + branch: entry.branch.clone(), + commit: sha, + }), + // The remote is gone or the ref vanished: that is movement + // we must not swallow, and Stage B will report it properly. + None => unprobed.push(entry.url.clone()), + } + } + // svn/hg/bzr: no cheap universal probe. Be honest about it and let + // Stage B decide, rather than claiming nothing moved. + Some(other) => { + unprobed.push(format!("{other}:{}", entry.url)); + pins.push(UpstreamPin { + index: entry.index, + url: entry.url.clone(), + ref_: want.1, + branch: entry.branch.clone(), + commit: String::new(), + }); + } + } + } + let now: BTreeSet<(usize, String)> = pins.iter().map(|p| (p.index, p.commit.clone())).collect(); + let then: BTreeSet<(usize, String)> = accepted.iter().map(|p| (p.index, p.commit.clone())).collect(); + Ok(StageA { pins, unprobed, moved: now != then }) +} + +/// What Stage B produced: the authoritative version plus the pins it was +/// computed from. +#[derive(Debug, Clone)] +pub struct StageB { + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub pins: Vec<UpstreamPin>, + /// True when the answer came from the cache instead of a fresh resolution. + pub cached: bool, +} + +impl StageB { + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } +} + +/// A process-wide cap on concurrent Stage B resolutions (§5.2 "a global +/// concurrency cap"). Each one clones repositories and runs a chroot-less +/// makepkg; letting twenty run at once would be silly. +static RUNNING: AtomicUsize = AtomicUsize::new(0); +static SLOT_FREE: Condvar = Condvar::new(); +static SLOT_LOCK: Mutex<()> = Mutex::new(()); + +pub struct StageBSlot(()); + +impl StageBSlot { + /// Take a Stage B slot, blocking until one is free. + pub fn acquire(cap: usize) -> Self { + let cap = cap.max(1); + let guard = SLOT_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = guard; + loop { + let n = RUNNING.load(Ordering::SeqCst); + if n < cap { + RUNNING.fetch_add(1, Ordering::SeqCst); + drop(guard); + return StageBSlot(()); + } + guard = SLOT_FREE.wait(guard).unwrap_or_else(|e| e.into_inner()); + } + } +} + +impl Drop for StageBSlot { + fn drop(&mut self) { + RUNNING.fetch_sub(1, Ordering::SeqCst); + SLOT_FREE.notify_one(); + } +} + +/// Stage B: resolve the real `pkgver` for a VCS pkgbase. +/// +/// `None` means "there is nothing to resolve" — the recipe has no VCS sources, +/// so the literal `pkgver=` is already the answer. +pub fn resolve( + cfg: &Config, + db: &Db, + pb: &Pkgbase, + recipe: &Recipe, + recipe_hash: &str, + stage_a: &StageA, +) -> Result<Option<StageB>> { + if !recipe.source_entries.iter().any(|e| e.is_vcs()) { + return Ok(None); + } + let tip_hash = tip_hash(&stage_a.pins); + + // Cache hit: same recipe, same upstream tips. Keyed on + // (pkgbase, recipe_hash, upstream_tip) exactly as §5.2 asks. + if let Some(hit) = db::stage_b_cache_get(db, pb.id, recipe_hash, &tip_hash)? { + return Ok(Some(hit)); + } + + // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve + // the same pkgbase more than once per cooldown window. The previous answer + // is reused, so a chatty upstream cannot turn detection into a build loop. + let cooldown = db::setting_i64(db, "stage_b_cooldown", 86400); + if let Some(recent) = db::stage_b_recent(db, pb.id, cooldown)? { + return Ok(Some(recent)); + } + + let _slot = StageBSlot::acquire(db::setting_i64(db, "stage_b_concurrency", 1) as usize); + let resolved = run(cfg, db, pb, recipe, recipe_hash, &tip_hash, stage_a)?; + db::stage_b_cache_put(db, pb.id, recipe_hash, &tip_hash, &resolved)?; + Ok(Some(resolved)) +} + +/// The actual work: warm the clone cache, then ask `makepkg` what it computes. +fn run( + cfg: &Config, + db: &Db, + pb: &Pkgbase, + recipe: &Recipe, + recipe_hash: &str, + tip_hash: &str, + stage_a: &StageA, +) -> Result<StageB> { + // Clone reuse: fetch into a persistent bare cache rather than re-cloning a + // multi-gigabyte upstream every day (§5.2). + let mut pins = stage_a.pins.clone(); + for pin in &mut pins { + if pin.commit.is_empty() { + continue; + } + let cache = cfg.vcs_cache_path(&pin.url); + if !cache.exists() { + git::clone_bare(&pin.url, &cache) + .map_err(|e| Error::transient(format!("vcs_cache clone {}: {e}", pin.url)))?; + } else { + let _ = git::fetch_and_head(&cache); + } + // The clone is here anyway, so confirm the tip locally: that also proves + // the commit we probed actually exists and is reachable. + if let Ok(local) = git::head(&cache) { + if !local.is_empty() && git::has_commit(&cache, &pin.commit) { + pin.branch = pin.branch.clone().or_else(|| default_branch(&cache)); + let _ = local; + } + } + } + + // Run `makepkg --vercheck` against the recipe in a scratch directory. The + // real tool clones the sources itself; the shim reports the fixture value. + let scratch = scratch_dir(cfg, &pb.name, recipe_hash, tip_hash); + let _ = std::fs::remove_dir_all(&scratch); + std::fs::create_dir_all(&scratch)?; + std::fs::write(scratch.join("PKGBUILD"), &recipe.pkgbuild)?; + if let Some(srcinfo) = &recipe.srcinfo { + std::fs::write(scratch.join(".SRCINFO"), srcinfo)?; + } + let mut cmd = Command::new(&cfg.makepkg_bin); + cmd.current_dir(&scratch).arg("--vercheck"); + cfg.child_env(&mut cmd); + let out = cmd.output()?; + let _ = std::fs::remove_dir_all(&scratch); + if !out.status.success() { + return Err(Error::transient(format!( + "makepkg --vercheck: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); + let (pkgver, pkgrel) = match text.rsplit_once('-') { + Some((v, r)) => (v.to_string(), r.to_string()), + None => (text.clone(), "1".to_string()), + }; + if pkgver.is_empty() { + return Err(Error::other(format!("makepkg --vercheck produced {text:?}"))); + } + let _ = db; + Ok(StageB { + epoch: recipe.epoch.clone(), + pkgver, + pkgrel, + pins, + cached: false, + }) +} + +fn default_branch(cache: &std::path::Path) -> Option<String> { + git::git(Some(cache), &["symbolic-ref", "--short", "HEAD"]) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +/// A stable hash of the upstream tip set — the cache key's third component. +pub fn tip_hash(pins: &[UpstreamPin]) -> String { + let mut v: Vec<String> = pins + .iter() + .map(|p| format!("{}:{}:{}", p.index, p.url, p.commit)) + .collect(); + v.sort(); + crate::hash::hex_str(&v.join("\n")) +} + +fn scratch_dir(cfg: &Config, pkgbase: &str, recipe_hash: &str, tip_hash: &str) -> PathBuf { + cfg.staging_dir() + .join("vercheck") + .join(format!("{pkgbase}-{}-{}", &recipe_hash[..8.min(recipe_hash.len())], &tip_hash[..8.min(tip_hash.len())])) +} diff --git a/testcorpus/git-multi/PKGBUILD b/testcorpus/git-multi/PKGBUILD new file mode 100644 index 0000000..3f55f20 --- /dev/null +++ b/testcorpus/git-multi/PKGBUILD @@ -0,0 +1,19 @@ +pkgbase=git-multi +pkgver=r1.0 +pkgrel=1 +pkgdesc="synthetic fixture with two upstream repos" +url="https://example.invalid/git-multi" +license=(MIT) +arch=(x86_64) +source=("git+file://@UPSTREAM_DIR@" "git+file://@UPSTREAM2_DIR@") +sha256sums=("SKIP" "SKIP") +makedepends=("git") +build() { + echo building git-multi +} +package_git-multi() { + echo packaging git-multi +} +pkgver() { + printf "r%s" "$(git -C @UPSTREAM_DIR@ rev-list --count HEAD)" +} diff --git a/testcorpus/git-multi/manifest.json b/testcorpus/git-multi/manifest.json new file mode 100644 index 0000000..bedfd29 --- /dev/null +++ b/testcorpus/git-multi/manifest.json @@ -0,0 +1,12 @@ +{ + "name": "git-multi", + "build": "succeed", + "sig": true, + "packages": [], + "installed": [ + { "name": "glibc", "version": "2.39-1", "arch": "x86_64" } + ], + "log_lines": ["==> Making package."], + "vercheck": "r1-1", + "expect": { "notes": "two VCS sources, two pin entries (§5.2: probe every source, not just the first)" } +} diff --git a/testcorpus/git-tagged/PKGBUILD b/testcorpus/git-tagged/PKGBUILD new file mode 100644 index 0000000..aed4c58 --- /dev/null +++ b/testcorpus/git-tagged/PKGBUILD @@ -0,0 +1,15 @@ +pkgbase=git-tagged +pkgver=1.0 +pkgrel=1 +pkgdesc="synthetic fixture pinned to a tag" +url="https://example.invalid/git-tagged" +license=(MIT) +arch=(x86_64) +source=("git+file://@UPSTREAM_DIR@#tag=v1") +sha256sums=("SKIP") +build() { + echo building git-tagged +} +package_git-tagged() { + echo packaging git-tagged +} diff --git a/testcorpus/git-tagged/manifest.json b/testcorpus/git-tagged/manifest.json new file mode 100644 index 0000000..9c6b890 --- /dev/null +++ b/testcorpus/git-tagged/manifest.json @@ -0,0 +1,12 @@ +{ + "name": "git-tagged", + "build": "succeed", + "sig": true, + "packages": [], + "installed": [ + { "name": "glibc", "version": "2.39-1", "arch": "x86_64" } + ], + "log_lines": ["==> Making package."], + "vercheck": "1.0-1", + "expect": { "notes": "#tag=v1 respected: upstream movement must not move this pin" } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 0dc5396..d2582c9 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -245,10 +245,13 @@ pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { std::fs::create_dir_all(&aur).unwrap(); let upstream = root.join(format!("upstream/{name}")); + let upstream2 = root.join(format!("upstream/{name}-2")); let subs = [ ("@AUR_DIR@".to_string(), data.display().to_string()), ("@UPSTREAM_DIR@".to_string(), upstream.display().to_string()), + ("@UPSTREAM2_DIR@".to_string(), upstream2.display().to_string()), ]; + let mut has_upstream2 = false; let mut recipe_files: Vec<(String, String)> = Vec::new(); let mut has_upstream_ref = false; @@ -261,6 +264,7 @@ pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { let body = std::fs::read_to_string(&path).unwrap_or_default(); let body = subs.iter().fold(body, |b, (from, to)| b.replace(from, to)); has_upstream_ref |= body.contains(&upstream.display().to_string()); + has_upstream2 |= body.contains(&upstream2.display().to_string()); if matches!(fname.as_str(), "payload.bin" | "data.bin") { std::fs::write(data.join(&fname), &body).unwrap(); } else { @@ -270,6 +274,16 @@ pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { if has_upstream_ref { make_git_repo(&upstream, &[("README", "upstream\n")], "upstream: initial"); } + if has_upstream2 { + make_git_repo(&upstream2, &[("README", "second upstream\n")], "upstream: initial"); + } + // A `#tag=v1` source needs the tag to exist. + if std::fs::read_to_string(src.join("PKGBUILD")) + .unwrap_or_default() + .contains("#tag=") + { + git(&upstream, &["tag", "v1"]); + } make_git_repo( &aur, &recipe_files.iter().map(|(n, b)| (n.as_str(), b.as_str())).collect::<Vec<_>>(), @@ -282,6 +296,7 @@ pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { data, manifest, upstream: has_upstream_ref.then_some(upstream), + upstream2: has_upstream2.then_some(upstream2), } } @@ -292,6 +307,8 @@ pub struct Fixture { pub data: PathBuf, pub manifest: PathBuf, pub upstream: Option<PathBuf>, + /// A second upstream repo, for pkgbases that build from two of them. + pub upstream2: Option<PathBuf>, } impl Fixture { @@ -333,6 +350,24 @@ impl Fixture { git(&up, &["rev-parse", "HEAD"]) } + /// Add a commit to the second upstream repo. + pub fn upstream2_commit(&self, body: &str) -> String { + let up = self.upstream2.clone().expect("fixture has no second upstream repo"); + git_add_commit(&up, &[(("README"), body)], body); + git(&up, &["rev-parse", "HEAD"]) + } + + /// HEAD of the (first) upstream repo. + pub fn upstream_head(&self) -> String { + let up = self.upstream.clone().expect("fixture has no upstream repo"); + git(&up, &["rev-parse", "HEAD"]) + } + + pub fn upstream2_head(&self) -> String { + let up = self.upstream2.clone().expect("fixture has no second upstream repo"); + git(&up, &["rev-parse", "HEAD"]) + } + pub fn manifest_json(&self) -> serde_json::Value { serde_json::from_str(&std::fs::read_to_string(&self.manifest).unwrap()).unwrap() } diff --git a/tests/db.rs b/tests/db.rs index f64262a..15c8319 100644 --- a/tests/db.rs +++ b/tests/db.rs @@ -39,7 +39,7 @@ fn migrations_apply_from_empty_and_are_idempotent() { Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?) }) .unwrap(); - assert_eq!(v, 6, "all migrations applied"); + assert_eq!(v, 7, "all migrations applied"); // Re-running migration over an existing DB is a no-op, not an error. assert_eq!(db::migrate(&env.cfg.db_path()).unwrap(), 0); let journal: String = env diff --git a/tests/vcs.rs b/tests/vcs.rs new file mode 100644 index 0000000..2572c60 --- /dev/null +++ b/tests/vcs.rs @@ -0,0 +1,263 @@ +//! Stage A / Stage B: the VCS watcher (§5.2). +//! +//! The whole point of the two-stage funnel is that the expensive thing (clone + +//! run `pkgver()`) happens only when the cheap thing (`git ls-remote`) says +//! something moved. These tests assert both halves: that the answer is right, +//! and that it was paid for only once. + +mod common; + +use aur_build::db::{self, model::*}; +use aur_build::review::approve::approve as do_approve; +use aur_build::review::{candidates, diff}; +use aur_build::watch::{detect, upstream}; +use common::*; + +fn detect_and_take(env: &Env, name: &str) -> (detect::Outcome, Option<CandidateRow>) { + let r = detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().pop(); + (r.outcome, c) +} + +fn stage_b_rows(env: &Env) -> i64 { + env.query_i64("SELECT count(*) FROM stage_b_cache", &[]).unwrap() +} + +fn makepkg_calls(env: &Env) -> usize { + aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makepkg", "--vercheck") +} + +#[test] +fn stage_a_probes_every_vcs_source_not_just_the_first() { + let (env, fx) = env_with_fixture("git-multi"); + // Two upstream repos, two pins — a pkgbase that builds from more than one + // upstream can have either one move alone (§5.2). + let (outcome, c) = detect_and_take(&env, "git-multi"); + assert!(matches!(outcome, detect::Outcome::Candidate { .. }), "{outcome:?}"); + let c = c.unwrap(); + let pins: Vec<UpstreamPin> = serde_json::from_str(&c.upstream_pins_json).unwrap(); + assert_eq!(pins.len(), 2, "one pin per VCS source: {pins:?}"); + assert_eq!(pins[0].commit, fx.upstream_head(), "first source pin"); + assert_eq!(pins[1].commit, fx.upstream2_head(), "second source pin"); + assert_eq!(pins[0].index, 0); + assert_eq!(pins[1].index, 1); + // The resolved version came from Stage B, not from the frozen pkgver= line. + assert_eq!(c.pkgver, "r1"); +} + +#[test] +fn stage_a_respects_a_tag_pin() { + let (env, fx) = env_with_fixture("git-tagged"); + let head_at_tag = git(&fx.upstream.clone().unwrap(), &["rev-parse", "v1"]); + let (_outcome, c) = detect_and_take(&env, "git-tagged"); + let pins: Vec<UpstreamPin> = serde_json::from_str(&c.unwrap().upstream_pins_json).unwrap(); + assert_eq!(pins.len(), 1); + assert_eq!(pins[0].ref_, "v1", "the #tag=v1 fragment is the ref we asked for"); + assert_eq!(pins[0].commit, head_at_tag, "the tag resolved to its commit"); + + // Upstream moves; a tagged pin must not follow it. + fx.upstream_commit("upstream: moved past the tag\n"); + let (outcome, _) = detect_and_take(&env, "git-tagged"); + assert!( + matches!(outcome, detect::Outcome::NoChange), + "a tag pin does not drift with the branch: {outcome:?}" + ); +} + +#[test] +fn stage_a_short_circuits_before_stage_b_when_nothing_moved() { + let (env, _fx) = env_with_fixture("git-sourced"); + let (_outcome, c) = detect_and_take(&env, "git-sourced"); + let c = c.unwrap(); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + do_approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap(); + let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); + + // Now poll again with nothing changed. Stage A finds the same tip set, so + // Stage B must not run at all — this is the common case, every day. + let before = makepkg_calls(&env); + let cache_before = stage_b_rows(&env); + let r = detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); + assert!(matches!(r.outcome, detect::Outcome::NoChange), "{:?}", r.outcome); + assert_eq!(makepkg_calls(&env), before, "Stage B ran on an unchanged tip set"); + assert_eq!(stage_b_rows(&env), cache_before, "the cache was rewritten"); +} + +#[test] +fn stage_b_resolves_pkgver_and_captures_the_pins() { + let (env, fx) = env_with_fixture("git-sourced"); + let head = fx.upstream_head(); + let (_outcome, c) = detect_and_take(&env, "git-sourced"); + let c = c.unwrap(); + // The candidate's version is what `pkgver()` computed, not the frozen field. + assert_eq!(c.pkgver, "r1.0"); + assert_eq!(c.pkgrel, "1"); + // And the pins it will be built from are recorded now, while the clone is + // already there — not later, which would mean cloning again. + let pins: Vec<UpstreamPin> = serde_json::from_str(&c.upstream_pins_json).unwrap(); + assert_eq!(pins[0].commit, head); + // The pins are part of the identity: a different commit is a different + // thing to approve, even under the same version string. + let with_pins = Identity { + aur_commit: "x".into(), + epoch: "0".into(), + pkgver: "r1.0".into(), + pkgrel: "1".into(), + upstream_pins: pins.clone(), + source_digests: vec![], + }; + let without = Identity { upstream_pins: vec![], ..with_pins.clone() }; + assert_ne!(with_pins.hash(), without.hash(), "pins must be in identity_hash"); +} + +#[test] +fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { + let (env, fx) = env_with_fixture("git-sourced"); + detect_and_take(&env, "git-sourced"); + assert_eq!(stage_b_rows(&env), 1); + let calls = makepkg_calls(&env); + assert!(calls >= 1, "Stage B must actually run once"); + + // Same recipe, same tip: the cached answer is reused, no new resolution. + detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); + assert_eq!(makepkg_calls(&env), calls, "cache miss on an unchanged key"); + assert_eq!(stage_b_rows(&env), 1); + + // A new tip is a new key, so it resolves again — but the cooldown window + // holds it back, which is what keeps a chatty upstream from turning + // detection into a build loop. + fx.upstream_commit("upstream: new tip\n"); + detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); + assert_eq!(stage_b_rows(&env), 1, "cooldown should suppress the re-resolve"); + // Outside the window it resolves again. + env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); + detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); + assert_eq!(stage_b_rows(&env), 2, "a new tip outside cooldown must resolve"); + assert_eq!(makepkg_calls(&env), calls + 1); +} + +#[test] +fn stage_b_concurrency_cap_is_enforced() { + // The cap is a process-wide guard; with the default of 1 a second caller + // waits for the first. Two threads, one slot: the second must not enter + // until the first releases. + let (env, _fx) = env_with_fixture("git-sourced"); + let slots = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let s1 = slots.clone(); + let held = upstream::StageBSlot::acquire(1); + let entered = std::thread::spawn(move || { + let _g = upstream::StageBSlot::acquire(1); + s1.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }); + std::thread::sleep(std::time::Duration::from_millis(80)); + assert_eq!( + slots.load(std::sync::atomic::Ordering::SeqCst), + 0, + "a second Stage B entered while the only slot was held" + ); + drop(held); + entered.join().unwrap(); + assert_eq!(slots.load(std::sync::atomic::Ordering::SeqCst), 1); + let _ = env; +} + +#[test] +fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { + // svn/hg have no cheap universal probe. The honest answer is "we do not + // know", which means Stage B runs; claiming "nothing moved" would be a lie + // that silently stops detection. + let recipe = aur_build::recipe::parse_pkgbuild( + &std::fs::read_to_string(corpus_root().join("git-sourced/PKGBUILD")).unwrap(), + ) + .unwrap(); + let mut recipe = recipe; + recipe.source_entries = vec![aur_build::db::model::SourceEntry { + index: 0, + url: "svn+svn://example.invalid/repo".into(), + filename: None, + commit: None, + tag: None, + branch: None, + vcs: Some("svn".into()), + local: false, + }]; + let a = upstream::probe(&recipe, &[]).unwrap(); + assert!(!a.unprobed.is_empty(), "svn must be reported as unprobed"); + assert!(a.needs_stage_b(), "unprobed must force Stage B, not short-circuit"); +} + +#[test] +fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { + // §5.2: pins moved, version frozen — pacman cannot offer an upgrade, so + // there is nothing to approve. It becomes a notice, and is never dropped. + let (env, fx) = env_with_fixture("pin-drift"); + let (_outcome, c) = detect_and_take(&env, "pin-drift"); + let c = c.unwrap(); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + do_approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap(); + let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); + + // Upstream moves. The shim still reports the same pkgver (that is what a + // degenerate `pkgver()` does), so nothing is publishable. + fx.upstream_commit("upstream: 14 more commits\n"); + env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); + let (outcome, new_candidate) = detect_and_take(&env, "pin-drift"); + match outcome { + detect::Outcome::Notice { kind, .. } => assert_eq!(kind, notice_kind::PIN_DRIFT), + other => panic!("expected a pin_drift notice, got {other:?}"), + } + assert!(new_candidate.is_none(), "a non-publishable change opens no review"); + // But it is recorded, and says why (§5.2 wording). + let notices = db::list_notices(&env.db, false).unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].kind, notice_kind::PIN_DRIFT); + let detail = notices[0].detail_json.clone(); + assert!(detail.contains("nothing publishable"), "{detail}"); + // The index keeps serving the artifact built from the old pins (I11). + assert_eq!( + env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]), + Some(1) + ); +} + +#[test] +fn a_moved_tip_with_a_changed_pkgver_is_a_normal_candidate() { + let (env, fx) = env_with_fixture("git-sourced"); + let (_outcome, c) = detect_and_take(&env, "git-sourced"); + let c = c.unwrap(); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + do_approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap(); + let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); + + fx.upstream_commit("upstream: a real release\n"); + env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); + // The tool now computes a different version from the new tip. + let mut m = fx.manifest_json(); + m["vercheck"] = serde_json::json!("r2.0-1"); + std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap(); + + let (outcome, c2) = detect_and_take(&env, "git-sourced"); + assert!(matches!(outcome, detect::Outcome::Candidate { .. } | detect::Outcome::Collapsed { .. }), "{outcome:?}"); + let c2 = c2.unwrap(); + assert_eq!(c2.pkgver, "r2.0"); + let pins: Vec<UpstreamPin> = serde_json::from_str(&c2.upstream_pins_json).unwrap(); + assert_eq!(pins[0].commit, fx.upstream_head(), "the new candidate pins the new tip"); +} + +#[test] +fn the_vcs_cache_is_reused_across_polls() { + let (env, fx) = env_with_fixture("git-sourced"); + detect_and_take(&env, "git-sourced"); + let cache = env.cfg.vcs_cache_path(&format!("file://{}", fx.upstream.clone().unwrap().display())); + assert!(cache.exists(), "Stage B should leave a persistent clone behind (§5.2 clone reuse)"); + let mtime_before = std::fs::metadata(&cache).ok().and_then(|m| m.modified().ok()); + // A second resolution reuses it rather than re-cloning. + env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); + fx.upstream_commit("upstream: again\n"); + detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); + assert!(cache.exists()); + let _ = mtime_before; +} |
