diff options
| -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 | 20 | ||||
| -rw-r--r-- | .pi/goals/goal_events.jsonl | 2 | ||||
| -rw-r--r-- | src/config.rs | 10 | ||||
| -rw-r--r-- | src/db/builds.rs | 424 | ||||
| -rw-r--r-- | src/db/migrations.rs | 9 | ||||
| -rw-r--r-- | src/db/mod.rs | 1 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/pipeline/mod.rs | 322 | ||||
| -rw-r--r-- | src/pipeline/publish.rs | 399 | ||||
| -rw-r--r-- | src/pipeline/steps.rs | 456 | ||||
| -rw-r--r-- | src/review/approve.rs | 2 | ||||
| -rw-r--r-- | src/review/diff.rs | 24 | ||||
| -rw-r--r-- | tests/common/mod.rs | 12 | ||||
| -rw-r--r-- | tests/db.rs | 2 | ||||
| -rw-r--r-- | tests/pipeline.rs | 439 |
17 files changed, 2114 insertions, 13 deletions
diff --git a/.pi/.goals-pool-snapshot.json b/.pi/.goals-pool-snapshot.json index 2267dfc..62ca13b 100644 --- a/.pi/.goals-pool-snapshot.json +++ b/.pi/.goals-pool-snapshot.json @@ -1 +1 @@ -{"version":1,"dirMtimeMs":1794951010773.5957,"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":1174285,"activeSeconds":2746},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-17T21:30:10.771Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":134,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"c7162450-1294-427e-aa34-597ba566e462","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"ready"},"dispatch":{"id":"b07063cc-4112-4b45-b62f-b597761e0d52","kind":"ready","claimedAt":1794948204539}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"pending","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"pending","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test."},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"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":"pending","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected."},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"pending","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap."},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"pending","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8)."}]},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"pending","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"pending","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry."},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"pending","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD."},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"pending","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped."}]},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"pending","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled."},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"pending","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane."},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"pending","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable."},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"pending","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6)."}]},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"pending","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"pending","verificationContract":"Dispatcher claims with BEGIN IMMEDIATE + lease expiry, requeues expired leases on startup, marks in-flight steps interrupted; the deterministic build id makes re-enqueue an INSERT OR IGNORE no-op; backpressure respects max_concurrent_builds and disk headroom."},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"pending","verificationContract":"A test kills the process mid-step and asserts resume at the next incomplete step with no duplicate side effects; cancel_requested stops a worker at a step boundary; deterministic build failures do not auto-retry and the release stays approved_but_unbuilt with the UI showing 'index still serving v1'."},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"pending","verificationContract":"GET /builds/:id/log.stream streams appended log bytes from a blocking thread; the builds table refreshes via htmx every 3s; vendored htmx is the only JS shipped and total vendored JS stays under 20 KB."}]},{"id":"task-p4","title":"P4 — staleness, retention, metrics (§10, §15)","status":"pending","subtasks":[{"id":"task-p4-world","title":".PKGINFO/.BUILDINFO parsing and world_snapshot filtered to our own repo","status":"pending","verificationContract":"Ingest parses tar+text without libalpm; world_snapshot members are intersected with our index at ingest time (not query time); split pkgbases produce N package rows from one approval."},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"pending","verificationContract":"stale_outdated and stale_missing are derived purely on read; a build with an unresolvable dep enters blocked_missing_dep, appears on Attention with the blocking pkgbase named, and the review page warns about missing deps before approval; the dep_edge view answers 'approving this marks N packages stale'."},{"id":"task-p4-ops","title":"Retention/GC, metrics endpoint, and backup helper","status":"pending","verificationContract":"Retention keeps N versions with logs and sources as a unit and sweeps abandoned staging dirs; GET /metrics emits prometheus text including queue depth, pending-review age histogram, build success rate and WAL size; backup uses VACUUM INTO (never cp of a live WAL db)."},{"id":"task-p4-deps","title":"vercmp + dependency-string parser and version-delta flagging (§4, §6)","status":"pending","verificationContract":"Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests."}]},{"id":"task-verify","title":"Final verification pass, real-chroot attempt, and documentation","status":"pending","verificationContract":"Full `cargo test` and `cargo clippy` run clean; every §2 invariant maps to a named passing test (list produced); README + docs/DECISIONS.md written; git history reviewed for incremental commits; the gated real-chroot integration attempt against devtools is run or explicitly recorded as skipped with the reason."}],"blockCompletion":true,"proposedAt":"2026-11-17T20:39:23.165Z"},"currentTaskId":"task-p0-shims"}]}
\ No newline at end of file +{"version":1,"dirMtimeMs":1794952630571.538,"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":1848360,"activeSeconds":4224},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-17T21:57:10.569Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":201,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"c7162450-1294-427e-aa34-597ba566e462","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"ready"},"dispatch":{"id":"b07063cc-4112-4b45-b62f-b597761e0d52","kind":"ready","claimedAt":1794948204539}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"pending","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"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":"pending","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected."},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"pending","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap."},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"pending","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8)."}]},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"pending","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"pending","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry."},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"pending","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD."},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"pending","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped."}]},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"pending","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled."},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"pending","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane."},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"pending","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable."},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"pending","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6)."}]},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"pending","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"pending","verificationContract":"Dispatcher claims with BEGIN IMMEDIATE + lease expiry, requeues expired leases on startup, marks in-flight steps interrupted; the deterministic build id makes re-enqueue an INSERT OR IGNORE no-op; backpressure respects max_concurrent_builds and disk headroom."},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"pending","verificationContract":"A test kills the process mid-step and asserts resume at the next incomplete step with no duplicate side effects; cancel_requested stops a worker at a step boundary; deterministic build failures do not auto-retry and the release stays approved_but_unbuilt with the UI showing 'index still serving v1'."},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"pending","verificationContract":"GET /builds/:id/log.stream streams appended log bytes from a blocking thread; the builds table refreshes via htmx every 3s; vendored htmx is the only JS shipped and total vendored JS stays under 20 KB."}]},{"id":"task-p4","title":"P4 — staleness, retention, metrics (§10, §15)","status":"pending","subtasks":[{"id":"task-p4-world","title":".PKGINFO/.BUILDINFO parsing and world_snapshot filtered to our own repo","status":"pending","verificationContract":"Ingest parses tar+text without libalpm; world_snapshot members are intersected with our index at ingest time (not query time); split pkgbases produce N package rows from one approval."},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"pending","verificationContract":"stale_outdated and stale_missing are derived purely on read; a build with an unresolvable dep enters blocked_missing_dep, appears on Attention with the blocking pkgbase named, and the review page warns about missing deps before approval; the dep_edge view answers 'approving this marks N packages stale'."},{"id":"task-p4-ops","title":"Retention/GC, metrics endpoint, and backup helper","status":"pending","verificationContract":"Retention keeps N versions with logs and sources as a unit and sweeps abandoned staging dirs; GET /metrics emits prometheus text including queue depth, pending-review age histogram, build success rate and WAL size; backup uses VACUUM INTO (never cp of a live WAL db)."},{"id":"task-p4-deps","title":"vercmp + dependency-string parser and version-delta flagging (§4, §6)","status":"pending","verificationContract":"Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests."}]},{"id":"task-verify","title":"Final verification pass, real-chroot attempt, and documentation","status":"pending","verificationContract":"Full `cargo test` and `cargo clippy` run clean; every §2 invariant maps to a named passing test (list produced); README + docs/DECISIONS.md written; git history reviewed for incremental commits; the gated real-chroot integration attempt against devtools is run or explicitly recorded as skipped with the reason."}],"blockCompletion":true,"proposedAt":"2026-11-17T20:39:23.165Z"},"currentTaskId":"task-p0-build"}]}
\ No newline at end of file diff --git a/.pi/goals/.goal-ledger-checkpoint.json b/.pi/goals/.goal-ledger-checkpoint.json index 91c7f6e..b27d986 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-17T21:21:28.005Z","coveredBytes":5181,"coveredEvents":9,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"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"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"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"}],"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"}],"oracle":[],"lifecycle":{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"}}]]}
\ No newline at end of file +{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-17T21:32:52.781Z","coveredBytes":5612,"coveredEvents":11,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"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"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"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"}],"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"}],"oracle":[],"lifecycle":{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"}}]]}
\ 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 ffbe5ca..04fdf9e 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": 1174285, - "activeSeconds": 2746 + "tokensUsed": 1848360, + "activeSeconds": 4224 }, "sisyphus": false, "createdAt": "2026-11-17T20:43:24.440Z", - "updatedAt": "2026-11-17T21:30:10.771Z", + "updatedAt": "2026-11-17T21:57:10.569Z", "activePath": ".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md", - "revision": 134, + "revision": 201, "scheduler": { "version": 1, "owner": "01a1eb32-2e3f-757c-a79a-21ac993facc5", @@ -56,8 +56,10 @@ { "id": "task-p0-shims", "title": "Toolchain PATH shims + fake-package corpus (§16a)", - "status": "pending", - "verificationContract": "Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test." + "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", @@ -209,7 +211,7 @@ "blockCompletion": true, "proposedAt": "2026-11-17T20:39:23.165Z" }, - "currentTaskId": "task-p0-shims" + "currentTaskId": "task-p0-build" } # Goal Prompt @@ -242,8 +244,8 @@ IF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninsta - Status: running - Auto-continue: on - Sisyphus mode: no -- Time spent: 45m46s -- Tokens used: 1.2M (1,174,285) tokens +- Time spent: 1h10m24s +- Tokens used: 1.8M (1,848,360) tokens ## Tasks <!-- blockCompletion: true --> diff --git a/.pi/goals/goal_events.jsonl b/.pi/goals/goal_events.jsonl index 3748eec..8bbabc3 100644 --- a/.pi/goals/goal_events.jsonl +++ b/.pi/goals/goal_events.jsonl @@ -7,3 +7,5 @@ {"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"} diff --git a/src/config.rs b/src/config.rs index 05f9a74..5bcb5aa 100644 --- a/src/config.rs +++ b/src/config.rs @@ -50,6 +50,11 @@ pub struct Config { pub shim_manifest: Option<PathBuf>, /// Where shims record their invocations, exported as `AUR_SHIM_DIR`. pub shim_dir: Option<PathBuf>, + /// Test hook: abort publish at a named point so I4 (atomic publish) can be + /// exercised for real. Never set in production. + pub publish_fault: Option<String>, + /// Test hook: the named shim must fail, e.g. `makechrootpkg`. + pub shim_fail: Option<String>, } impl Default for Config { @@ -73,6 +78,8 @@ impl Default for Config { path_prepend: None, shim_manifest: None, shim_dir: None, + publish_fault: None, + shim_fail: None, } } } @@ -115,6 +122,9 @@ impl Config { if let Some(d) = &self.shim_dir { cmd.env("AUR_SHIM_DIR", d); } + if let Some(f) = &self.shim_fail { + cmd.env("AUR_SHIM_FAIL", f); + } } /// Create the directory tree the server needs. Idempotent. diff --git a/src/db/builds.rs b/src/db/builds.rs new file mode 100644 index 0000000..d251566 --- /dev/null +++ b/src/db/builds.rs @@ -0,0 +1,424 @@ +//! Build queue rows: deterministic ids, leases, step checkpoints (§8.1, §8.2). + +use rusqlite::{params, Connection, OptionalExtension}; + +use crate::db::Db; +use crate::error::Result; +use crate::time; + +#[derive(Debug, Clone)] +pub struct BuildRow { + pub id: String, + pub pkgbase_id: i64, + pub candidate_id: Option<i64>, + pub release_id: Option<i64>, + pub kind: String, + pub world_snapshot_id: Option<i64>, + pub build_profile: String, + pub state: String, + pub blocked_on_json: String, + pub current_step: Option<String>, + pub lease_owner: Option<String>, + pub lease_expires_at: Option<String>, + pub attempt: i64, + pub priority: i64, + pub cancel_requested: bool, + pub error: Option<String>, +} + +const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_snapshot_id, \ + build_profile, state, blocked_on_json, current_step, lease_owner, lease_expires_at, \ + attempt, priority, cancel_requested, error"; + +fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> { + Ok(BuildRow { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + candidate_id: r.get(2)?, + release_id: r.get(3)?, + kind: r.get(4)?, + world_snapshot_id: r.get(5)?, + build_profile: r.get(6)?, + state: r.get(7)?, + blocked_on_json: r.get(8)?, + current_step: r.get(9)?, + lease_owner: r.get(10)?, + lease_expires_at: r.get(11)?, + attempt: r.get(12)?, + priority: r.get(13)?, + cancel_requested: r.get::<_, i64>(14)? != 0, + error: r.get(15)?, + }) +} + +/// Deterministic build id (§8.2): re-submitting the same intent is a no-op, +/// which is what makes manual rebuilds safe to enqueue carelessly. +pub fn build_id(pkgbase: &str, identity_hash: &str, world_hash: &str, profile: &str) -> String { + crate::hash::hex_str(&format!("{pkgbase}|{identity_hash}|{world_hash}|{profile}")) +} + +/// Enqueue a build intent. `INSERT OR IGNORE` on the deterministic id. +#[allow(clippy::too_many_arguments)] +pub fn enqueue( + db: &Db, + id: &str, + pkgbase_id: i64, + candidate_id: Option<i64>, + kind: &str, + world_snapshot_id: Option<i64>, + profile: &str, + priority: i64, +) -> Result<bool> { + let (id, kind, profile) = (id.to_string(), kind.to_string(), profile.to_string()); + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "INSERT INTO build (id, pkgbase_id, candidate_id, kind, world_snapshot_id, build_profile, + state, created_at, updated_at, priority) + VALUES (?1,?2,?3,?4,?5,?6,'queued',?7,?7,?8) + ON CONFLICT(id) DO NOTHING", + params![id, pkgbase_id, candidate_id, kind, world_snapshot_id, profile, at, priority], + )?; + Ok(n == 1) + }) +} + +pub fn get(db: &Db, id: &str) -> Result<Option<BuildRow>> { + let id = id.to_string(); + db.read(move |c| { + Ok(c.query_row( + &format!("SELECT {BUILD_COLS} FROM build WHERE id=?1"), + params![id], + row_to_build, + ) + .optional()?) + }) +} + +pub fn list(db: &Db, states: &[&str], limit: i64) -> Result<Vec<BuildRow>> { + let states = states.iter().map(|s| s.to_string()).collect::<Vec<_>>(); + db.read(move |c| { + let placeholders = states.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "SELECT {BUILD_COLS} FROM build WHERE state IN ({placeholders}) + ORDER BY priority DESC, created_at LIMIT ?{}", + states.len() + 1 + ); + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map( + rusqlite::params_from_iter(states.iter().chain(std::iter::once(&limit.to_string())).map(|s| s as &dyn rusqlite::ToSql)), + row_to_build, + )?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn queued(db: &Db, limit: i64) -> Result<Vec<String>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at LIMIT ?1", + )?; + let rows = stmt.query_map(params![limit], |r| r.get::<_, String>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// Claim a build for a worker: the lease is what makes a crash recoverable. +pub fn claim(db: &Db, owner: &str, id: &str, lease_secs: i64) -> Result<bool> { + let (owner, id) = (owner.to_string(), id.to_string()); + let exp = time::secs_ahead(lease_secs); + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "UPDATE build SET state='leased', lease_owner=?1, lease_expires_at=?2, + attempt=attempt+1, updated_at=?3 + WHERE id=?4 AND state IN ('queued','leased')", + params![owner, exp, at, id], + )?; + Ok(n == 1) + }) +} + +pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> { + let id = id.to_string(); + let exp = time::secs_ahead(lease_secs); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE build SET lease_expires_at=?1 WHERE id=?2", + params![exp, id], + )?; + Ok(()) + }) +} + +/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight +/// step is marked interrupted, so the checkpoint decides where it resumes. +pub fn reap_expired(db: &Db) -> Result<usize> { + let now = time::now(); + db.writer.tx(move |tx| { + let ids: Vec<String> = { + let mut stmt = tx.prepare( + "SELECT id FROM build WHERE state='leased' AND lease_expires_at IS NOT NULL + AND lease_expires_at < ?1", + )?; + let rows = stmt.query_map(params![now], |r| r.get::<_, String>(0))?; + rows.filter_map(|r| r.ok()).collect() + }; + for id in &ids { + tx.execute( + "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL + WHERE id=?1", + params![id], + )?; + tx.execute( + "UPDATE build_step SET status='interrupted', finished_at=?2 + WHERE build_id=?1 AND status='running'", + params![id, now], + )?; + } + Ok(ids.len()) + }) +} + +pub fn set_state(db: &Db, id: &str, state: &str, error: Option<&str>) -> Result<()> { + let (id, state) = (id.to_string(), state.to_string()); + let error = error.map(|e| e.to_string()); + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE build SET state=?1, error=?2, updated_at=?3, lease_owner=NULL, + lease_expires_at=NULL WHERE id=?4", + params![state, error, at, id], + )?; + Ok(()) + }) +} + +pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { + let id = id.to_string(); + let json = serde_json::to_string(blocked_on)?; + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE build SET state='blocked_missing_dep', blocked_on_json=?1, updated_at=?2, + lease_owner=NULL, lease_expires_at=NULL WHERE id=?3", + params![json, at, id], + )?; + Ok(()) + }) +} + +/// Re-check blocked builds whenever a publish lands (§10.4). +pub fn requeue_blocked(db: &Db) -> Result<usize> { + db.writer.tx(|tx| { + let n = tx.execute( + "UPDATE build SET state='queued', updated_at=?1 WHERE state='blocked_missing_dep'", + params![time::now()], + )?; + Ok(n) + }) +} + +pub fn request_cancel(db: &Db, id: &str) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET cancel_requested=1 WHERE id=?1", params![id])?; + Ok(()) + }) +} + +pub fn cancel_requested(db: &Db, id: &str) -> Result<bool> { + let id = id.to_string(); + db.read(move |c| { + Ok(c.query_row("SELECT cancel_requested FROM build WHERE id=?1", params![id], |r| { + Ok(r.get::<_, i64>(0)? != 0) + }) + .optional()? + .unwrap_or(false)) + }) +} + +// ------------------------------------------------------------- step rows -- + +#[derive(Debug, Clone)] +pub struct StepRow { + pub step: String, + pub status: String, + pub attempt: i64, + pub error: Option<String>, +} + +pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> { + let id = id.to_string(); + db.read(move |c| { + let mut stmt = c.prepare( + "SELECT step, status, attempt, error FROM build_step WHERE build_id=?1 ORDER BY rowid", + )?; + let rows = stmt.query_map(params![id], |r| { + Ok(StepRow { step: r.get(0)?, status: r.get(1)?, attempt: r.get(2)?, error: r.get(3)? }) + })?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result<Option<String>> { + let (b, s) = (build_id.to_string(), step.to_string()); + db.read(move |c| { + Ok(c.query_row( + "SELECT status FROM build_step WHERE build_id=?1 AND step=?2", + params![b, s], + |r| r.get(0), + ) + .optional()?) + }) +} + +pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<()> { + let (b, s) = (build_id.to_string(), step.to_string()); + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "INSERT INTO build_step (build_id, step, status, attempt, started_at) + VALUES (?1,?2,'running',?3,?4) + ON CONFLICT(build_id, step) DO UPDATE SET status='running', attempt=?3, started_at=?4, + error=NULL", + params![b, s, attempt, at], + )?; + tx.execute("UPDATE build SET current_step=?1 WHERE id=?2", params![s, b])?; + Ok(()) + }) +} + +pub fn finish_step(db: &Db, build_id: &str, step: &str, status: &str, output_digest: Option<&str>, error: Option<&str>) -> Result<()> { + let (b, s, st) = (build_id.to_string(), step.to_string(), status.to_string()); + let od = output_digest.map(|s| s.to_string()); + let err = error.map(|s| s.to_string()); + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE build_step SET status=?1, output_digest=?2, error=?3, finished_at=?4 + WHERE build_id=?5 AND step=?6", + params![st, od, err, at, b, s], + )?; + Ok(()) + }) +} + +/// Builds in flight (leased or running), for the backpressure calculation. +pub fn in_flight(db: &Db) -> Result<usize> { + db.read(|c| { + Ok(c.query_row( + "SELECT count(*) FROM build WHERE state IN ('leased','running')", + [], + |r| r.get::<_, i64>(0), + )? as usize) + }) +} + +pub fn queue_depth(db: &Db) -> Result<usize> { + db.read(|c| { + Ok(c.query_row("SELECT count(*) FROM build WHERE state='queued'", [], |r| r.get::<_, i64>(0))? as usize) + }) +} + +pub fn blocked_builds(db: &Db) -> Result<Vec<(String, String, Vec<String>)>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT b.id, p.name, b.blocked_on_json FROM build b + JOIN pkgbase p ON p.id = b.pkgbase_id WHERE b.state='blocked_missing_dep'", + )?; + let rows = stmt.query_map([], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)) + })?; + let mut out = Vec::new(); + for r in rows { + let (id, name, json) = r?; + let blocked: Vec<String> = serde_json::from_str(&json).unwrap_or_default(); + out.push((id, name, blocked)); + } + Ok(out) + }) +} + +pub fn touch(db: &Db, id: &str) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET updated_at=?1 WHERE id=?2", params![time::now(), id])?; + Ok(()) + }) +} + +pub fn set_release(db: &Db, id: &str, release_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?; + Ok(()) + }) +} + +pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET world_snapshot_id=?1 WHERE id=?2", params![world_id, id])?; + Ok(()) + }) +} + +pub fn set_candidate(db: &Db, id: &str, candidate_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET candidate_id=?1 WHERE id=?2", params![candidate_id, id])?; + Ok(()) + }) +} + +pub fn set_pkgbase(db: &Db, id: &str, pkgbase_id: i64) -> Result<()> { + let id = id.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET pkgbase_id=?1 WHERE id=?2", params![pkgbase_id, id])?; + Ok(()) + }) +} + +pub fn set_profile(db: &Db, id: &str, profile: &str) -> Result<()> { + let (id, p) = (id.to_string(), profile.to_string()); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET build_profile=?1 WHERE id=?2", params![p, id])?; + Ok(()) + }) +} + +pub fn set_kind(db: &Db, id: &str, kind: &str) -> Result<()> { + let (id, k) = (id.to_string(), kind.to_string()); + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET kind=?1 WHERE id=?2", params![k, id])?; + Ok(()) + }) +} + +pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { + let id = id.to_string(); + let json = serde_json::to_string(blocked_on)?; + db.writer.tx(move |tx| { + tx.execute("UPDATE build SET blocked_on_json=?1 WHERE id=?2", params![json, id])?; + Ok(()) + }) +} + +pub fn current_state(c: &Connection, id: &str) -> Result<String> { + Ok(c.query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) + .optional()? + .unwrap_or_default()) +} diff --git a/src/db/migrations.rs b/src/db/migrations.rs index e0c1cb3..dddb301 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -274,11 +274,20 @@ BEGIN END; "#; +/// `artifact.build_id` lets the publish step find what `ingest` recorded without +/// re-scanning the disposable staging directory, so a worker that dies between +/// ingest and publish resumes cleanly (I5). +const M_0005_ARTIFACT_BUILD: &str = r#" +ALTER TABLE artifact ADD COLUMN build_id TEXT; +CREATE INDEX artifact_by_build ON artifact (build_id); +"#; + pub static MIGRATIONS: &[Migration] = &[ Migration { version: 1, name: "core", sql: M_0001_CORE }, Migration { version: 2, name: "build", sql: M_0002_BUILD }, Migration { version: 3, name: "notices", sql: M_0003_NOTICES }, Migration { version: 4, name: "audit-triggers", sql: M_0004_TRIGGERS }, + Migration { version: 5, name: "artifact-build", sql: M_0005_ARTIFACT_BUILD }, ]; /// Default settings seeded into `settings` (DESIGN.md §11). diff --git a/src/db/mod.rs b/src/db/mod.rs index a841fec..b810453 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -8,6 +8,7 @@ //! design entirely. Readers are thread-local, read-only connections; WAL lets //! them proceed concurrently with the writer. +pub mod builds; pub mod migrations; pub mod model; pub mod queries; @@ -11,6 +11,7 @@ pub mod error; pub mod fetch; pub mod git; pub mod hash; +pub mod pipeline; pub mod pkgver; pub mod recipe; pub mod review; diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs new file mode 100644 index 0000000..37aae77 --- /dev/null +++ b/src/pipeline/mod.rs @@ -0,0 +1,322 @@ +//! The build pipeline (§8). +//! +//! Ten steps, each idempotent and checkpointed in `build_step`. A worker can die +//! at any instant and the pipeline resumes at the next incomplete step with no +//! duplicate side effects (I5). Only the last step is externally visible, and it +//! is serialized per repo (I4). + +pub mod publish; +mod steps; + +use std::path::PathBuf; + +use crate::config::Config; +use crate::db::{self, builds, Db, Pkgbase}; +use crate::db::model::*; +use crate::error::{Error, Result}; + +/// The approved source identity a build must reproduce. +/// +/// For a new version it comes from the candidate; for a manual rebuild it comes +/// from the accepted release, which is what makes I6 true: a rebuild reuses the +/// approved source identity and never needs a new approval. +#[derive(Debug, Clone)] +pub struct SourceIdentity { + pub aur_commit: String, + pub recipe_hash: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub identity_hash: String, +} + +impl SourceIdentity { + pub fn from_candidate(c: &CandidateRow) -> Self { + Self { + aur_commit: String::new(), + recipe_hash: String::new(), + upstream_pins_json: c.upstream_pins_json.clone(), + source_digests_json: c.source_digests_json.clone(), + epoch: c.epoch.clone(), + pkgver: c.pkgver.clone(), + pkgrel: c.pkgrel.clone(), + identity_hash: c.identity_hash.clone(), + } + } + pub fn from_release(r: &ReleaseRow) -> Self { + Self { + aur_commit: r.aur_commit.clone(), + recipe_hash: r.recipe_hash.clone(), + upstream_pins_json: r.upstream_pins_json.clone(), + source_digests_json: r.source_digests_json.clone(), + epoch: r.epoch.clone(), + pkgver: r.pkgver.clone(), + pkgrel: r.pkgrel.clone(), + identity_hash: String::new(), + } + } + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } +} + +/// One package produced by the build, as recorded by `collect` and `ingest`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct CollectedPkg { + pub name: String, + pub version: String, + pub arch: String, + /// Where the artifact lives: staging until `ingest`, the store afterwards. + pub path: String, + pub digest: String, + pub size: u64, + pub signature_path: Option<String>, + pub depends: Vec<String>, + pub makedepends: Vec<String>, + pub provides: Vec<String>, + pub conflicts: Vec<String>, + /// The full installed set from `.BUILDINFO`, unfiltered (§10.1). + pub installed: Vec<(String, String)>, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub struct Collect { + pub packages: Vec<CollectedPkg>, +} + +impl Collect { + pub fn load(path: &std::path::Path) -> Result<Self> { + if !path.exists() { + return Ok(Self::default()); + } + Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?) + } + pub fn save(&self, path: &std::path::Path) -> Result<()> { + std::fs::write(path, serde_json::to_string_pretty(self)?)?; + Ok(()) + } +} + +/// Everything a step needs. Built once per build run, cheap to clone handles. +pub struct Ctx { + pub cfg: Config, + pub db: Db, + pub build: builds::BuildRow, + pub pb: Pkgbase, + pub src: SourceIdentity, + pub staging: PathBuf, + pub srcdir: PathBuf, + pub collect_path: PathBuf, + pub log: PathBuf, + pub profile: String, + pub attempt: i64, +} + +impl Ctx { + pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result<Self> { + let build = builds::get(db, build_id)? + .ok_or_else(|| Error::not_found(format!("build {build_id}")))?; + let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)? + .ok_or_else(|| Error::not_found("pkgbase for build"))?; + let src = match build.candidate_id { + Some(cid) => { + let c = crate::review::candidates::candidate_by_id(db, cid)? + .ok_or_else(|| Error::not_found("candidate for build"))?; + let mut si = SourceIdentity::from_candidate(&c); + if let Some(s) = db::snapshot_by_id(db, c.snapshot_id)? { + si.aur_commit = s.aur_commit; + si.recipe_hash = s.recipe_hash; + } + si + } + None => { + let rid = build + .release_id + .ok_or_else(|| Error::invalid("build has neither candidate nor release"))?; + let r = db::release_by_id(db, rid)? + .ok_or_else(|| Error::not_found("release for rebuild"))?; + SourceIdentity::from_release(&r) + } + }; + let attempt = build.attempt; + let profile = build.build_profile.clone(); + let staging = cfg.staging_build_dir(build_id); + let srcdir = staging.join("src"); + let collect_path = staging.join("collect.json"); + Ok(Self { + cfg: cfg.clone(), + db: db.clone(), + build, + pb, + src, + staging, + srcdir, + collect_path, + log: cfg.build_log_path(build_id), + profile, + attempt, + }) + } + + /// Append to the build log; the SSE tail reads this file (§12). + pub fn log_line(&self, line: &str) { + use std::io::Write; + if let Some(parent) = self.log.parent() { + let _ = std::fs::create_dir_all(parent); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.log) { + let _ = writeln!(f, "{line}"); + } + } +} + +/// What a full run produced. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Succeeded { release_id: i64 }, + Failed { step: String, error: String, transient: bool }, + Blocked { on: Vec<String> }, + Cancelled, +} + +/// Run a build to completion, resuming at the first incomplete step (I5). +pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result<Outcome> { + let ctx = Ctx::new(cfg, db, build_id)?; + db::audit_system( + &db.writer, + "build.start", + "build", + build_id, + serde_json::json!({"pkgbase": ctx.pb.name, "version": ctx.src.version(), "attempt": ctx.attempt}), + )?; + run_with(&ctx) +} + +pub fn run_with(ctx: &Ctx) -> Result<Outcome> { + std::fs::create_dir_all(&ctx.staging)?; + for step in crate::db::model::BUILD_STEPS { + if crate::db::builds::cancel_requested(&ctx.db, &ctx.build.id)? { + builds::set_state(&ctx.db, &ctx.build.id, build_state::CANCELLED, Some("cancelled"))?; + return Ok(Outcome::Cancelled); + } + let status = builds::step_status(&ctx.db, &ctx.build.id, step)?; + if status.as_deref() == Some(step_state::SUCCEEDED) || status.as_deref() == Some(step_state::SKIPPED) { + continue; // checkpoint says we already did this + } + builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?; + builds::set_state(&ctx.db, &ctx.build.id, build_state::RUNNING, None)?; + ctx.log_line(&format!("==> step {step} (attempt {})", ctx.attempt)); + match steps::run_step(ctx, step) { + Ok(StepResult::Done(digest)) => { + builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::SUCCEEDED, digest.as_deref(), None)?; + builds::extend_lease(&ctx.db, &ctx.build.id, 90)?; + } + Ok(StepResult::Skipped(why)) => { + ctx.log_line(&format!(" skipped: {why}")); + builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::SKIPPED, None, None)?; + } + Ok(StepResult::Blocked(on)) => { + builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::PENDING, None, Some("blocked"))?; + builds::block_on(&ctx.db, &ctx.build.id, &on)?; + ctx.log_line(&format!(" blocked on: {}", on.join(", "))); + return Ok(Outcome::Blocked { on }); + } + Err(e) => { + let transient = e.is_transient(); + builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::FAILED, None, Some(&e.to_string()))?; + builds::set_state( + &ctx.db, + &ctx.build.id, + build_state::FAILED, + Some(&format!("{step}: {e}")), + )?; + ctx.log_line(&format!("!! {step} failed: {e}")); + // A failed build must not leave the old version looking healthy: + // the release stays approved_but_unbuilt and the UI says so. + if let Some(cid) = ctx.build.candidate_id { + if ctx.build.release_id.is_none() { + mark_approved_but_unbuilt(&ctx.db, cid)?; + } + } + return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient }); + } + } + } + let release_id = ctx + .release_id() + .ok_or_else(|| Error::other("publish produced no release"))?; + builds::set_state(&ctx.db, &ctx.build.id, build_state::SUCCEEDED, None)?; + db::audit_system( + &ctx.db.writer, + "build.succeeded", + "build", + &ctx.build.id, + serde_json::json!({"release": release_id}), + )?; + Ok(Outcome::Succeeded { release_id }) +} + +impl Ctx { + fn release_id(&self) -> Option<i64> { + builds::get(&self.db, &self.build.id).ok().flatten().and_then(|b| b.release_id) + } +} + +/// A failed build must not make the old version look healthy (§8.4). The +/// candidate stays `approved`; what the UI renders is the *absence* of a +/// published release behind it: "v2 approved, build failed, index still +/// serving v1". Nothing here mutates the accepted pointer. +fn mark_approved_but_unbuilt(_db: &Db, _candidate_id: i64) -> Result<()> { + Ok(()) +} + +/// Enqueue the build an approval implies. Deterministic id, so calling this +/// twice is a no-op (§8.2). +pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<String> { + let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)? + .ok_or_else(|| Error::not_found("pkgbase"))?; + let world = publish::index_world(db)?; + let world_hash = crate::hash::canonical_json(&world); + let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile); + let world_id = db::put_world_snapshot(&db.writer, &world)?; + builds::enqueue(db, &id, pb.id, Some(c.id), "new_version", Some(world_id), &cfg.build_profile, 0)?; + Ok(id) +} + +/// Manual rebuild of the current accepted version (I6): same source identity, +/// no new approval, same version. +pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> { + let pb = db::get_pkgbase(db, pkgbase)? + .ok_or_else(|| Error::not_found(format!("pkgbase {pkgbase}")))?; + let rel = db::accepted_release(db, pkgbase)? + .ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?; + let identity = crate::hash::hex_str(&format!( + "{}|{}|manual", + rel.aur_commit, rel.recipe_hash + )); + let world = publish::index_world(db)?; + let world_hash = crate::hash::canonical_json(&world); + let id = builds::build_id(pkgbase, &identity, &world_hash, &cfg.build_profile); + let world_id = db::put_world_snapshot(&db.writer, &world)?; + builds::enqueue(db, &id, pb.id, None, "manual_rebuild", Some(world_id), &cfg.build_profile, 1)?; + let id_for_tx = id.clone(); + let rid = rel.id; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE build SET release_id=?1 WHERE id=?2", + rusqlite::params![rid, id_for_tx], + )?; + Ok(()) + })?; + Ok(id) +} + +/// What one step produced. +pub enum StepResult { + Done(Option<String>), + Skipped(String), + /// A dependency we publish is not in the index yet (§10.4). + Blocked(Vec<String>), +} diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs new file mode 100644 index 0000000..639d717 --- /dev/null +++ b/src/pipeline/publish.rs @@ -0,0 +1,399 @@ +//! Publishing and serving the index (§9). +//! +//! Publishing is the only externally visible step, and it is atomic and +//! serialized per repo (I4). The served database is a materialized view of the +//! DB: we render it to `.tmp`, fsync, commit the DB, then `rename` over the real +//! one. A crash anywhere in there leaves the *old* index intact, and +//! [`reconcile`] re-materializes from the DB on startup. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Mutex; + +use rusqlite::OptionalExtension; + +use crate::config::Config; +use crate::db::{self, builds, Db, WorldMember}; +use crate::error::{Error, Result}; +use crate::pipeline::{Collect, Ctx}; +use crate::time; + +/// One publish per repo at a time. In one process a mutex is exactly the +/// single-writer guarantee the design asks for; the publisher thread in P3 keeps +/// the critical section tiny (db file rewrite only), never the build. +static REPO_LOCK: Mutex<()> = Mutex::new(()); + +/// The world a build is admitted against: every pkgbase's accepted version. +pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { + let rels = db::all_published_releases(db)?; + let mut out = Vec::new(); + for r in rels { + let pb = db::get_pkgbase_by_id(db, r.pkgbase_id)?; + if let Some(pb) = pb { + out.push(WorldMember { pkgbase: pb.name, version: r.version() }); + } + } + Ok(out) +} + +/// Package files that belong in the served index right now, plus the extra ones +/// being published (which are not in the DB yet when we render `.tmp`). +fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { + let mut out: Vec<PathBuf> = Vec::new(); + for p in db::index_packages(db)? { + if let Some(aid) = p.artifact_id { + let path: Option<String> = db.read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", rusqlite::params![aid], |r| r.get(0)) + .optional()?) + })?; + if let Some(p) = path.map(PathBuf::from).filter(|p| p.exists()) { + out.push(p); + } + } + } + out.extend(extra.iter().cloned()); + Ok(out) +} + +/// Publish the collected artifacts of a build. Returns the new release id. +pub fn publish(ctx: &Ctx) -> Result<i64> { + let collect = Collect::load(&ctx.collect_path)?; + if collect.packages.is_empty() { + return Err(Error::invalid("nothing to publish")); + } + let repo_row = repo_for(&ctx.db)?; + let arch_dir = ctx.cfg.repo_arch_dir(); + std::fs::create_dir_all(&arch_dir)?; + + // Artifacts are copied into the served tree under their real filenames. + let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); + for p in &collect.packages { + let from = PathBuf::from(&p.path); + let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); + let dest = arch_dir.join(&filename); + std::fs::copy(&from, &dest)?; + if let Some(sig) = &p.signature_path { + let s = PathBuf::from(sig); + if s.exists() { + std::fs::copy(&s, arch_dir.join(format!("{filename}.sig")))?; + } + } + staged.push((dest, from)); + } + + let _guard = REPO_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + + // 1. render the new database to .tmp and fsync it. The old one is untouched. + let db_name = ctx.cfg.repo_db_name(); + let final_db = arch_dir.join(format!("{db_name}.tar.gz")); + let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); + let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; + // Deduplicate: the same package name must appear once, newest wins. + pkgs = dedupe_by_name(pkgs); + run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; + fsync_file(&tmp_db)?; + + // Fault injection so I4 can be tested for real: die between the tmp write + // and the rename, and the old index must still be what consumers get. + if ctx.cfg.publish_fault.as_deref() == Some("before-rename") { + return Err(Error::other("injected fault: before-rename")); + } + + // 2. commit the DB: release + package rows + the accepted pointer, in one + // transaction, with the pointer moved by compare-and-swap. + let release_id = commit_release(ctx, &collect)?; + + // 3. atomic swap: rename over the real database, then sign and swap the sig. + std::fs::rename(&tmp_db, &final_db)?; + fsync_dir(&arch_dir)?; + sign(&ctx.cfg, &final_db)?; + let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); + let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); + if tmp_sig.exists() { + std::fs::rename(&tmp_sig, &sig)?; + } + + // 4. a publish can unblock builds waiting on a dependency we just added. + let unblocked = builds::requeue_blocked(&ctx.db)?; + db::audit_system( + &ctx.db.writer, + "publish", + "repo", + &repo_row, + serde_json::json!({ + "release": release_id, + "packages": collect.packages.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>(), + "unblocked_builds": unblocked, + }), + )?; + if ctx.cfg.publish_fault.as_deref() == Some("after-rename") { + return Err(Error::other("injected fault: after-rename")); + } + Ok(release_id) +} + +fn repo_for(db: &Db) -> Result<String> { + let id = db::repo_id(db)?; + Ok(id.to_string()) +} + +/// Insert the release and its package rows, and move the accepted pointer. +fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { + let at = time::now(); + let pkgbase_id = ctx.pb.id; + let candidate_id = ctx.build.candidate_id; + let approval_id: Option<i64> = match candidate_id { + Some(cid) => crate::review::approve::approval_for(&ctx.db, cid)?.map(|(id, _)| id), + None => None, + }; + // I1: nothing publishes without an approval. A manual rebuild inherits the + // approval of the release it rebuilds. + let approval_id = match (approval_id, ctx.build.kind.as_str()) { + (Some(a), _) => Some(a), + (None, "manual_rebuild") => ctx + .build + .release_id + .and_then(|rid| db::release_by_id(&ctx.db, rid).ok().flatten()) + .and_then(|r| r.approval_id), + (None, other) => { + return Err(Error::fail_closed(format!( + "refusing to publish a {other} build with no approval behind it" + ))) + } + }; + let build_id = ctx.build.id.clone(); + let packages = collect.packages.clone(); + let names: Vec<String> = packages.iter().map(|p| p.name.clone()).collect(); + let src = ctx.src.clone(); + let world_id = builds::get(&ctx.db, &build_id) + .ok() + .flatten() + .and_then(|b| b.world_snapshot_id); + let repo_id = db::repo_id(&ctx.db)?; + // The compare-and-swap baseline is the release the *approval* was taken + // against, not whatever the pointer happens to say now. If they differ, + // someone accepted a newer version while we were building, and publishing + // this one would roll it back. + let expected_base: Option<i64> = match ctx.build.kind.as_str() { + "manual_rebuild" => ctx.build.release_id, + _ => ctx + .build + .candidate_id + .and_then(|cid| crate::review::candidates::candidate_by_id(&ctx.db, cid).ok().flatten()) + .and_then(|c| c.base_release_id), + }; + + ctx.db.writer.tx(move |tx| { + // Compare-and-swap on the accepted pointer, inside the write + // transaction: two publishes cannot both land (I4). + let actual_base: Option<i64> = tx.query_row( + "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", + rusqlite::params![pkgbase_id], + |r| r.get(0), + )?; + if actual_base != expected_base { + return Err(Error::conflict( + "accepted pointer moved while this build was running; refusing to publish", + )); + } + // Retire whatever the index held for these names *before* inserting the + // new rows: the index holds exactly the accepted pointer, nothing else. + if !names.is_empty() { + let ph = names.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE package SET state='removed' WHERE state='in_index' AND name IN ({ph})" + ); + let mut stmt = tx.prepare(&sql)?; + stmt.execute(rusqlite::params_from_iter(names.iter().map(|n| n as &dyn rusqlite::ToSql)))?; + } + tx.execute( + "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, + upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, + world_snapshot_id, state, build_id, published_at, created_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'published',?12,?13,?13)", + rusqlite::params![ + pkgbase_id, candidate_id, approval_id, src.aur_commit, src.recipe_hash, + src.upstream_pins_json, src.source_digests_json, src.epoch, src.pkgver, src.pkgrel, + world_id, build_id, at + ], + )?; + let release_id = tx.last_insert_rowid(); + for p in &packages { + let artifact_id: Option<i64> = tx + .query_row( + "SELECT id FROM artifact WHERE digest=?1", + rusqlite::params![p.digest], + |r| r.get(0), + ) + .optional()?; + tx.execute( + "INSERT INTO package (repo_id, release_id, name, arch, version, artifact_id, state) + VALUES (?1,?2,?3,?4,?5,?6,'in_index')", + rusqlite::params![repo_id, release_id, p.name, p.arch, p.version, artifact_id], + )?; + } + let moved = tx.execute( + "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3", + rusqlite::params![release_id, pkgbase_id, expected_base], + )?; + if moved != 1 { + return Err(Error::conflict( + "accepted pointer moved while this build was running; refusing to publish", + )); + } + tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", rusqlite::params![release_id, build_id])?; + if let Some(cid) = candidate_id { + tx.execute("UPDATE candidate SET state='approved' WHERE id=?1", rusqlite::params![cid])?; + } + Ok(release_id) + }) +} + +/// `repo-add -s -p <key> -R <db> <pkgs...>` (§9: both packages and the database +/// are signed so consumers can run `SigLevel = Required`). +fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { + let mut cmd = Command::new(&cfg.repo_add_bin); + cmd.arg("-R"); + if !cfg.signing_key_id.is_empty() { + cmd.args(["-s", "-p", &cfg.signing_key_id]); + } + cmd.arg(db_path); + for p in pkgs { + cmd.arg(p); + } + cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: cfg.repo_add_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + Ok(()) +} + +fn sign(cfg: &Config, path: &Path) -> Result<()> { + if cfg.signing_key_id.is_empty() { + return Ok(()); + } + let mut cmd = Command::new(&cfg.gpg_bin); + cmd.args(["--batch", "--yes", "--detach-sign", "--local-user", &cfg.signing_key_id]); + cmd.arg("-o"); + let tmp = format!("{}.tmp", path.display()); + cmd.arg(&tmp); + cmd.arg(path); + cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: cfg.gpg_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + std::fs::rename(&tmp, format!("{}.sig", path.display()))?; + Ok(()) +} + +fn fsync_file(p: &Path) -> Result<()> { + if let Ok(f) = std::fs::File::open(p) { + let _ = f.sync_all(); + } + Ok(()) +} + +fn fsync_dir(p: &Path) -> Result<()> { + if let Ok(d) = std::fs::File::open(p) { + let _ = d.sync_all(); + } + Ok(()) +} + + +/// Keep one entry per package name; the newest file wins. The name comes from +/// `.PKGINFO` inside the tarball, not from the filename, because package names +/// contain dashes. +fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { + let mut seen: BTreeSet<String> = BTreeSet::new(); + let mut out: Vec<PathBuf> = Vec::new(); + for p in paths.into_iter().rev() { + let name = package_name(&p).unwrap_or_else(|| { + p.file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + }); + if seen.insert(name) { + out.push(p); + } + } + out.reverse(); + out +} + +fn package_name(path: &Path) -> Option<String> { + let bytes = std::fs::read(path).ok()?; + let info = crate::shims::read_pkginfo(&bytes).ok()?; + for line in info.lines() { + if let Some(v) = line.strip_prefix("pkgname =") { + return Some(v.trim().to_string()); + } + } + None +} + +/// Re-materialize the served index from the DB. Run at startup: if a crash left +/// the DB ahead of the file, this closes the gap without inventing anything. +pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> { + let pkgs = db::index_packages(db)?; + let mut files = Vec::new(); + for p in &pkgs { + if let Some(aid) = p.artifact_id { + let path: Option<String> = db.read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", rusqlite::params![aid], |r| r.get(0)) + .optional()?) + })?; + if let Some(path) = path.map(PathBuf::from).filter(|p| p.exists()) { + let arch_dir = cfg.repo_arch_dir(); + let _ = std::fs::create_dir_all(&arch_dir); + let dest = arch_dir.join(format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch)); + if !dest.exists() { + let _ = std::fs::copy(&path, &dest); + } + files.push(dest); + } + } + } + if files.is_empty() { + return Ok(0); + } + let arch_dir = cfg.repo_arch_dir(); + let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + run_repo_add(cfg, &tmp, &dedupe_by_name(files.clone()))?; + std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + Ok(files.len()) +} + +/// Remove a package from the served index (§9 withdrawal path). +pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> { + let _guard = REPO_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let rid = db::repo_id(db)?; + let n = name.to_string(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", + rusqlite::params![rid, n], + )?; + Ok(()) + })?; + let arch_dir = cfg.repo_arch_dir(); + let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + let files = index_artifacts(db, &[])?; + run_repo_add(cfg, &tmp, &dedupe_by_name(files))?; + std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + db::audit(&db.writer, "human", "cli", "withdraw.publish", "package", name, serde_json::json!({}))?; + Ok(()) +} diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs new file mode 100644 index 0000000..b925afb --- /dev/null +++ b/src/pipeline/steps.rs @@ -0,0 +1,456 @@ +//! The ten pipeline steps (§8.1). +//! +//! Every step is idempotent and records its result in one short transaction; +//! the long-running child process happens outside any transaction (§11a). + +use std::path::Path; +use std::process::Command; + +use crate::db::{self, builds, model::*}; +use crate::error::{Error, Result}; +use crate::git; +use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult}; +use crate::watch::digests::cached_path; + +pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> { + match step { + "materialize" => materialize(ctx), + "plan" => plan(ctx), + "chroot" => chroot(ctx), + "sources" => sources(ctx), + "pkgver" => pkgver(ctx), + "build" => build(ctx), + "collect" => collect(ctx), + "verify" => verify(ctx), + "ingest" => ingest(ctx), + "publish" => publish(ctx), + other => Err(Error::invalid(format!("unknown step {other}"))), + } +} + +/// Step 0 — materialize from the local mirror only, never the network, and +/// re-hash what we got. This is the `aur_commit` pin doing its job: there is no +/// path from "AUR moved since the review" to "we built it anyway". +fn materialize(ctx: &Ctx) -> Result<StepResult> { + let mirror = ctx + .pb + .mirror_path + .as_ref() + .map(Path::new) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name)); + if !mirror.exists() { + return Err(Error::fail_closed(format!( + "mirror {} missing; refusing to fetch a recipe from the network at build time", + mirror.display() + ))); + } + if ctx.src.aur_commit.is_empty() { + return Err(Error::fail_closed("no aur_commit on the source identity")); + } + let _ = std::fs::remove_dir_all(&ctx.srcdir); + git::materialize(&mirror, &ctx.src.aur_commit, &ctx.srcdir)?; + let tree = crate::watch::mirror::read_tree(&mirror, &ctx.src.aur_commit)?; + let computed = tree.recipe_hash(); + if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash { + return Err(Error::fail_closed(format!( + "recipe_hash mismatch: approved {}, materialized {}", + ctx.src.recipe_hash, computed + ))); + } + ctx.log_line(&format!( + " materialized {} at {} (recipe_hash {})", + ctx.pb.name, + short(&ctx.src.aur_commit), + short(&computed) + )); + Ok(StepResult::Done(Some(computed))) +} + +/// A display-safe prefix; hashes are 64 hex chars but world digests can be tiny. +fn short(s: &str) -> String { + s.chars().take(12).collect() +} + +/// Step 1 — resolve dependencies against the current accepted index and compute +/// the intended world. Unresolvable means "a pkgbase we subscribe to that we have +/// not published yet": block and wait, do not fail (§10.4). +fn plan(ctx: &Ctx) -> Result<StepResult> { + let recipe = recipe_at(&ctx.srcdir)?; + let mut wanted: Vec<String> = Vec::new(); + for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] { + wanted.extend(crate::pkgver::dep_names(list)); + } + wanted.sort(); + wanted.dedup(); + + let ours = db::our_package_names(&ctx.db)?; + let mut missing = Vec::new(); + let mut official = 0; + for dep in &wanted { + if ours.contains(dep) || ctx.pb.name == *dep || recipe.pkgnames.contains(dep) { + continue; // satisfied by our own index, or by this very build + } + // Anything else is only a problem if we are supposed to be publishing it. + if db::get_subscription(&ctx.db, dep)?.is_some() || db::get_pkgbase(&ctx.db, dep)?.is_some() { + missing.push(dep.clone()); + } else { + official += 1; + } + } + if !missing.is_empty() { + builds::set_blocked_on(&ctx.db, &ctx.build.id, &missing)?; + return Ok(StepResult::Blocked(missing)); + } + let world = crate::pipeline::publish::index_world(&ctx.db)?; + let hash = crate::hash::canonical_json(&world); + ctx.log_line(&format!( + " deps: {} ours/official, {} from official repos, world {}", + wanted.len() - official, + official, + short(&hash) + )); + Ok(StepResult::Done(Some(hash))) +} + +/// Step 2 — warm chroot seed, created once per profile and never mutated; each +/// build gets a copy-on-write snapshot from it (§8.3). +fn chroot(ctx: &Ctx) -> Result<StepResult> { + let seed = ctx.cfg.chroot_seed(&ctx.profile); + if !seed.exists() { + std::fs::create_dir_all(seed.parent().unwrap_or(&ctx.cfg.chroot_dir()))?; + let mut cmd = Command::new(&ctx.cfg.mkarchroot_bin); + cmd.args(["-N", &seed.display().to_string()]); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.mkarchroot_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + ctx.log_line(&format!(" created chroot seed {}", seed.display())); + } + Ok(StepResult::Done(Some(seed.display().to_string()))) +} + +/// Step 3 — make sure every source we reviewed is on disk and hashes to what the +/// candidate recorded. For a `SKIP` source this is the only verification that +/// exists, and it closes the window between "we hashed it at review time" and +/// "makepkg downloaded something else just now" (§8.1). +fn sources(ctx: &Ctx) -> Result<StepResult> { + let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default(); + let mut verified = 0; + for d in &digests { + match d.kind.as_str() { + // Already materialized from the mirror at the pinned commit. + "local" => verified += 1, + // VCS kinds (git/svn/hg/bzr): honouring upstream_pins at build time + // is deferred to P1 (§20); the pkgver assertion is the interim guard. + "vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1, + _ => { + let (digest, _size) = match cached_path(&ctx.db, &d.url, &d.digest) { + Some(p) => crate::hash::digest_file(&p)?, + None => crate::watch::digests::download_and_cache(&ctx.cfg, &ctx.db, &d.url)?, + }; + if digest != d.digest { + return Err(Error::fail_closed(format!( + "source {} hashed to {digest} but the candidate recorded {}", + d.url, d.digest + ))); + } + verified += 1; + } + } + } + ctx.log_line(&format!(" {}/{} source digests verified", verified, digests.len())); + Ok(StepResult::Done(Some(crate::hash::hex_str( + &ctx.src.source_digests_json, + )))) +} + +/// Step 4 — the belt-and-braces assertion that what we build is what was +/// approved. If upstream moved between approval and build, fail with both +/// versions instead of silently shipping the new one (§8.1). +fn pkgver(ctx: &Ctx) -> Result<StepResult> { + let recipe = recipe_at(&ctx.srcdir)?; + let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs()); + if !has_vcs { + let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone()); + let got = (recipe.pkgver.clone(), recipe.pkgrel.clone()); + if want != got { + return Err(Error::fail_closed(format!( + "approved {}-{} but the recipe says {}-{}", + want.0, want.1, got.0, got.1 + ))); + } + return Ok(StepResult::Skipped("no VCS sources; pkgver is static".into())); + } + let mut cmd = Command::new(&ctx.cfg.makepkg_bin); + cmd.current_dir(&ctx.srcdir).arg("--vercheck"); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.makepkg_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); + let (got_ver, got_rel) = match text.rsplit_once('-') { + Some((v, r)) => (v.to_string(), r.to_string()), + None => (text.clone(), "1".into()), + }; + if got_ver != ctx.src.pkgver || got_rel != ctx.src.pkgrel { + return Err(Error::fail_closed(format!( + "approved {}-{}, upstream now resolves to {got_ver}-{got_rel}", + ctx.src.pkgver, ctx.src.pkgrel + ))); + } + ctx.log_line(&format!(" pkgver resolves as approved: {text}")); + Ok(StepResult::Done(Some(text))) +} + +/// Step 5 — `makechrootpkg -c -r <chroot> -- -si<key> -f`, with the log going to +/// the file the SSE tail reads. +fn build(ctx: &Ctx) -> Result<StepResult> { + let seed = ctx.cfg.chroot_seed(&ctx.profile); + let mut cmd = Command::new(&ctx.cfg.makechrootpkg_bin); + cmd.current_dir(&ctx.srcdir); + cmd.args(["-c", "-r", &seed.display().to_string(), "--"]); + if !ctx.cfg.signing_key_id.is_empty() { + cmd.arg(format!("-si{}", ctx.cfg.signing_key_id)); + } + cmd.arg("-f"); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + // Capture the child's output into the build log regardless of outcome. + if let Some(parent) = ctx.log.parent() { + let _ = std::fs::create_dir_all(parent); + } + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log) { + let _ = f.write_all(&out.stdout); + let _ = f.write_all(&out.stderr); + } + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.makechrootpkg_bin.clone(), + detail: tail(&out.stderr), + }); + } + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( + "build:{}", + ctx.build.id + ))))) +} + +fn tail(b: &[u8]) -> String { + let s = String::from_utf8_lossy(b).trim().to_string(); + let lines: Vec<&str> = s.lines().collect(); + lines[lines.len().saturating_sub(6)..].join(" | ") +} + +/// Step 6 — parse `.PKGINFO`/`.BUILDINFO` out of the produced artifacts (§10.1: +/// plain text in a tar, no libalpm needed). +fn collect(ctx: &Ctx) -> Result<StepResult> { + let mut pkgs = Vec::new(); + let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst")) + .collect(); + entries.sort(); + for path in entries { + let bytes = std::fs::read(&path)?; + let (digest, size) = crate::hash::digest_file(&path)?; + let pkginfo = crate::shims::read_pkginfo(&bytes) + .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; + let buildinfo = crate::shims::read_buildinfo(&bytes).unwrap_or_default(); + let meta = parse_pkginfo(&pkginfo); + let sig = path.with_extension("pkg.tar.zst.sig"); + pkgs.push(CollectedPkg { + name: meta.get("pkgname").cloned().unwrap_or_default(), + version: meta.get("pkgver").cloned().unwrap_or_default(), + arch: meta.get("pkgarch").cloned().unwrap_or_else(|| ctx.cfg.arch.clone()), + path: path.display().to_string(), + digest, + size, + signature_path: sig.exists().then(|| sig.display().to_string()), + depends: meta_multi(&pkginfo, "depend"), + makedepends: meta_multi(&pkginfo, "makedepend"), + provides: meta_multi(&pkginfo, "provides"), + conflicts: meta_multi(&pkginfo, "conflict"), + installed: parse_installed(&buildinfo), + }); + } + if pkgs.is_empty() { + return Err(Error::invalid("build produced no packages")); + } + let collect = Collect { packages: pkgs.clone() }; + collect.save(&ctx.collect_path)?; + // A split pkgbase is one approval and N index entries (§3). + ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", "))); + Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?)))) +} + +/// Step 7 — signature present, dependencies satisfiable, no downgrade. +fn verify(ctx: &Ctx) -> Result<StepResult> { + let collect = Collect::load(&ctx.collect_path)?; + let ours = db::our_package_names(&ctx.db)?; + for p in &collect.packages { + if p.signature_path.is_none() && !ctx.cfg.signing_key_id.is_empty() { + return Err(Error::fail_closed(format!("{} has no signature", p.name))); + } + if crate::pkgver::is_downgrade( + &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), + &p.version, + ) { + // Downgrades are allowed but flagged (§16); the review already shows it. + ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name)); + } + let mut provided: std::collections::BTreeSet<String> = ours.clone(); + provided.extend(collect.packages.iter().map(|q| q.name.clone())); + provided.extend(p.provides.iter().flat_map(|v| crate::pkgver::dep_names(std::slice::from_ref(v)))); + for dep in crate::pkgver::dep_names(&p.depends) { + if !provided.contains(&dep) && db::get_pkgbase(&ctx.db, &dep)?.is_some() { + return Err(Error::fail_closed(format!( + "{} depends on {dep}, which is not satisfiable in the target repo", + p.name + ))); + } + } + } + Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string( + &collect.packages.iter().map(|p| (&p.name, &p.version)).collect::<Vec<_>>(), + )?)))) +} + +/// Step 8 — move artifacts into the content-addressed store and record rows. +/// Staging stays disposable; a GC pass sweeps abandoned directories (§8.2). +fn ingest(ctx: &Ctx) -> Result<StepResult> { + let mut collect = Collect::load(&ctx.collect_path)?; + for p in &mut collect.packages { + let from = Path::new(&p.path); + let dest = ctx.cfg.store_path(&p.digest); + if !dest.exists() { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::copy(from, &dest)?; + } + p.path = dest.display().to_string(); + if let Some(sig) = p.signature_path.clone() { + let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest)); + if !sigdest.exists() && Path::new(&sig).exists() { + std::fs::copy(&sig, &sigdest)?; + } + p.signature_path = Some(sigdest.display().to_string()); + } + } + collect.save(&ctx.collect_path)?; + + let at = crate::time::now(); + let packages = collect.packages.clone(); + let packages_for_db = packages.clone(); + let build_id = ctx.build.id.clone(); + let log_path = ctx.log.display().to_string(); + ctx.db.writer.tx(move |tx| { + for p in &packages_for_db { + tx.execute( + "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at) + VALUES (?1,?2,?3,?4,?5,?6,?7) + ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id", + rusqlite::params![p.digest, p.size as i64, p.path, p.signature_path, log_path, build_id, at], + )?; + } + Ok(()) + })?; + + // §10.1: the world snapshot is the build's installed set INTERSECTED with our + // own packages, filtered at ingest time, not at query time. Left unfiltered, + // every package would be permanently stale because Arch never stops moving. + let ours = db::our_package_names(&ctx.db)?; + let mut members: Vec<WorldMember> = Vec::new(); + for p in &collect.packages { + for (name, version) in &p.installed { + if ours.contains(name) { + members.push(WorldMember { pkgbase: name.clone(), version: version.clone() }); + } + } + } + let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?; + builds::set_world(&ctx.db, &ctx.build.id, world_id)?; + ctx.log_line(&format!(" ingested {} artifact(s), world has {} of our packages", packages.len(), members.len())); + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( + "ingest:{}", + packages.len() + ))))) +} + +/// Step 9 — the only externally visible step, serialized per repo (§9). +fn publish(ctx: &Ctx) -> Result<StepResult> { + let release_id = crate::pipeline::publish::publish(ctx)?; + Ok(StepResult::Done(Some(format!("release:{release_id}")))) +} + +// ---------------------------------------------------------------- helpers -- + +use std::path::PathBuf; + +/// Read the recipe from a materialized tree, preferring `.SRCINFO`. +pub fn recipe_at(dir: &Path) -> Result<Recipe> { + let mut files = std::collections::BTreeMap::new(); + for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) { + let p = entry.path(); + if !p.is_file() { + continue; + } + let rel = p.strip_prefix(dir).unwrap_or(p).display().to_string(); + if let Ok(body) = std::fs::read_to_string(p) { + files.insert(rel, body); + } + } + crate::recipe::recipe_from_tree(&files) +} + +fn parse_pkginfo(text: &str) -> std::collections::HashMap<String, String> { + let mut m = std::collections::HashMap::new(); + for line in text.lines() { + if let Some((k, v)) = line.split_once('=') { + m.insert(k.trim().to_string(), v.trim().to_string()); + } + } + m +} + +fn meta_multi(text: &str, key: &str) -> Vec<String> { + text.lines() + .filter_map(|l| l.split_once('=')) + .filter(|(k, _)| k.trim() == key) + .map(|(_, v)| v.trim().to_string()) + .collect() +} + +/// `.BUILDINFO` `installed =` block: ` name version arch sig` per line. +fn parse_installed(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut in_block = false; + for line in text.lines() { + if line.trim_start().starts_with("installed") { + in_block = true; + continue; + } + if in_block { + if !line.starts_with(' ') && !line.starts_with('\t') { + in_block = false; + continue; + } + let mut it = line.split_whitespace(); + if let (Some(name), Some(version)) = (it.next(), it.next()) { + out.push((name.to_string(), version.to_string())); + } + } + } + out +} diff --git a/src/review/approve.rs b/src/review/approve.rs index b62adec..0fdf2b2 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -72,7 +72,7 @@ pub fn approve( let row: Option<CandidateState> = tx .query_row( "SELECT c.id, c.state, c.identity_hash, c.base_release_id, p.current_accepted_release_id, - c.risk_level, b.name + c.risk_level, p.name FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id WHERE c.id = ?1", rusqlite::params![candidate_id], diff --git a/src/review/diff.rs b/src/review/diff.rs index cfce3fe..df6318c 100644 --- a/src/review/diff.rs +++ b/src/review/diff.rs @@ -154,3 +154,27 @@ pub fn full_recipe_text(db: &Db, c: &CandidateRow) -> Result<String> { let r: Recipe = serde_json::from_str(&snap.srcinfo_json).unwrap_or_default(); Ok(r.pkgbuild) } + +/// Render the panels, store the resulting `diff_digest` on the candidate, and +/// hand it back. The approve POST must echo this value, which is what makes +/// "we build exactly what was displayed" checkable (§7.1a). +pub fn render_and_store(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<String> { + let base = match c.base_release_id { + Some(id) => db::release_by_id(db, id)?, + None => None, + }; + let ps = panels(cfg, db, c, base.as_ref())?; + let digest = diff_digest(&ps); + crate::review::candidates::set_diff_digest(db, c.id, &digest)?; + Ok(digest) +} + +/// Re-render for a 409 response: show the reviewer what the candidate is now. +pub fn render_current(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<(String, String)> { + let base = match c.base_release_id { + Some(id) => db::release_by_id(db, id)?, + None => None, + }; + let ps = panels(cfg, db, c, base.as_ref())?; + Ok((render_text(&ps), diff_digest(&ps))) +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index d5a4f81..0dc5396 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -125,6 +125,18 @@ impl Env { .unwrap() } + /// Make the next publish abort at a named point (I4 / I5 tests). + pub fn set_publish_fault(&mut self, at: &str) { + self.cfg.publish_fault = Some(at.to_string()); + } + pub fn clear_publish_fault(&mut self) { + self.cfg.publish_fault = None; + } + /// Make the named shim fail (the "build failed" path, §8.4). + pub fn set_shim_fail(&mut self, tool: &str) { + self.cfg.shim_fail = Some(tool.to_string()); + } + pub fn query_i64(&self, sql: &str, params: &[P]) -> Option<i64> { let sql = sql.to_string(); let params: Vec<P> = params.to_vec(); diff --git a/tests/db.rs b/tests/db.rs index 60c9256..b455603 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, 4, "all four migrations applied"); + assert_eq!(v, 5, "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/pipeline.rs b/tests/pipeline.rs new file mode 100644 index 0000000..835dcf0 --- /dev/null +++ b/tests/pipeline.rs @@ -0,0 +1,439 @@ +//! End-to-end pipeline tests driven entirely by the toolchain shims (§16a): +//! no root, no network, no real chroot — but the *real* step machine runs. + +mod common; + +use aur_build::db::{self, builds, model::*}; +use aur_build::pipeline::{self, publish}; +use aur_build::review::{approve, candidates, diff}; +use common::*; + +/// subscribe -> detect -> render the review -> approve. +fn approve_fixture(env: &Env, name: &str) -> CandidateRow { + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + approve::approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); + candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap() +} + +/// Re-detect and approve whatever is pending now (a later version). +fn approve_pending(env: &Env, name: &str) -> CandidateRow { + approve_fixture(env, name) +} + +fn run_for(env: &Env, c: &CandidateRow) -> pipeline::Outcome { + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, c).unwrap(); + pipeline::run(&env.cfg, &env.db, &id).unwrap() +} + +fn in_index(env: &Env) -> Vec<(String, String)> { + env.db + .read(|c| { + let mut st = + c.prepare("SELECT name, version FROM package WHERE state='in_index' ORDER BY name")?; + let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?; + let mut v = Vec::new(); + for r in rows { + v.push(r?); + } + Ok(v) + }) + .unwrap() +} + +fn step_rows(env: &Env) -> Vec<(String, String)> { + env.db + .read(|c| { + let mut st = c.prepare("SELECT step, status FROM build_step ORDER BY rowid")?; + let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?; + let mut v = Vec::new(); + for r in rows { + v.push(r?); + } + Ok(v) + }) + .unwrap() +} + +#[test] +fn end_to_end_publishes_a_signed_index() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + let out = run_for(&env, &c); + assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}"); + + let rel = db::accepted_release(&env.db, "plain-make").unwrap().unwrap(); + assert_eq!(rel.state, release_state::PUBLISHED); + assert_eq!(rel.pkgver, "1.0"); + assert_eq!(rel.version(), "1.0-1"); + + // Both the packages and the database are signed (§9). + let arch = env.cfg.repo_arch_dir(); + assert!(arch.join("plain-make-1.0-1-x86_64.pkg.tar.zst").exists()); + assert!(arch.join("plain-make-1.0-1-x86_64.pkg.tar.zst.sig").exists()); + assert!(arch.join("aur-build.db.tar.gz").exists()); + assert!(arch.join("aur-build.db.tar.gz.sig").exists()); + + // One checkpoint row per step, all green (§8.1). + let all = step_rows(&env); + assert_eq!(all.len(), BUILD_STEPS.len(), "one row per step: {all:?}"); + assert!( + all.iter().all(|(_, s)| s == "succeeded" || s == "skipped"), + "{all:?}" + ); +} + +#[test] +fn i1_no_index_entry_without_an_approval() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + let orphans: i64 = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT count(*) FROM package p + LEFT JOIN release r ON r.id = p.release_id + WHERE p.state='in_index' AND (r.id IS NULL OR r.approval_id IS NULL)", + [], + |r| r.get(0), + )?) + }) + .unwrap(); + assert_eq!(orphans, 0, "I1: index entry with no approval behind it"); +} + +#[test] +fn i8_served_index_holds_exactly_the_accepted_pointers() { + let (env, fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); + + fx.bump(&[("pkgver", "1.0.1")]); + let c2 = approve_pending(&env, "plain-make"); + run_for(&env, &c2); + + // The old version is gone from the index, not merely superseded in place. + assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]); + let rel = db::accepted_release(&env.db, "plain-make").unwrap().unwrap(); + assert_eq!(rel.pkgver, "1.0.1"); + let old: i64 = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'", + [], + |r| r.get(0), + )?) + }) + .unwrap(); + assert_eq!(old, 0, "the previous release must leave the index"); +} + +#[test] +fn step0_fails_closed_when_the_recipe_hash_drifts() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + // The mirror no longer matches what was approved. There is no path from + // "AUR moved since the review" to "we built it anyway" (I3). + env.exec( + "UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1", + ¶ms(vec![c.snapshot_id]), + ); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + match pipeline::run(&env.cfg, &env.db, &id).unwrap() { + pipeline::Outcome::Failed { step, error, .. } => { + assert_eq!(step, "materialize"); + assert!(error.contains("recipe_hash mismatch"), "{error}"); + } + other => panic!("expected a fail-closed failure, got {other:?}"), + } + assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none()); + assert!(in_index(&env).is_empty()); +} + +#[test] +fn step4_fails_closed_when_pkgver_no_longer_matches() { + let (env, fx) = env_with_fixture("git-sourced"); + let c = approve_fixture(&env, "git-sourced"); + assert_eq!(c.pkgver, "r1.0"); + // Upstream moves after approval: the tool now resolves a different pkgver. + // The build must refuse rather than silently ship the newer one (§8.1). + let mut m = fx.manifest_json(); + m["vercheck"] = serde_json::json!("r9.9-1"); + std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap(); + + match run_for(&env, &c) { + pipeline::Outcome::Failed { step, error, .. } => { + assert_eq!(step, "pkgver"); + assert!(error.contains("r9.9") && error.contains("r1.0"), "{error}"); + } + other => panic!("expected a fail-closed pkgver failure, got {other:?}"), + } + assert!(in_index(&env).is_empty()); +} + +#[test] +fn step4_passes_when_the_vcs_pkgver_still_matches() { + let (env, _fx) = env_with_fixture("git-sourced"); + let c = approve_fixture(&env, "git-sourced"); + assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); + assert_eq!(in_index(&env), vec![("git-sourced".into(), "r1.0-1".into())]); +} + +#[test] +fn i4_kill_mid_publish_leaves_the_old_index_intact() { + let (mut env, fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + let v1 = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz"); + let before = std::fs::read(&v1).unwrap(); + + fx.bump(&[("pkgver", "1.0.1")]); + let c2 = approve_pending(&env, "plain-make"); + env.set_publish_fault("before-rename"); + let out = run_for(&env, &c2); + assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); + + // The served database is byte-for-byte the old one, and the DB never + // recorded the new release: consumers saw either the old world or the new + // one, never a half-written index (I4). + assert_eq!(std::fs::read(&v1).unwrap(), before); + assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); + assert_eq!( + env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), + Some(0) + ); +} + +#[test] +fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { + let (mut env, fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + + fx.bump(&[("pkgver", "1.0.1")]); + let c2 = approve_pending(&env, "plain-make"); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap(); + env.set_publish_fault("before-rename"); + assert!(matches!( + pipeline::run(&env.cfg, &env.db, &id).unwrap(), + pipeline::Outcome::Failed { .. } + )); + let builds_after_crash = + aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", ""); + assert_eq!(builds_after_crash, 2, "one real build before the crash"); + + // "Restart": same build row, no fault. Steps 0-8 are checkpointed as + // succeeded, so only publish re-runs — the expensive step is not repeated. + env.clear_publish_fault(); + match pipeline::run(&env.cfg, &env.db, &id).unwrap() { + pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0), + other => panic!("{other:?}"), + } + assert_eq!( + aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", ""), + builds_after_crash, + "I5: resuming must not rebuild" + ); + assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]); + // Exactly one release row per version: no duplicates from the resume. + assert_eq!( + env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), + Some(1) + ); +} + +#[test] +fn split_pkgbase_is_one_approval_and_many_index_rows() { + let (env, _fx) = env_with_fixture("split-pkgbase"); + let c = approve_fixture(&env, "split-pkgbase"); + assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); + let names: Vec<String> = in_index(&env).into_iter().map(|(n, _)| n).collect(); + assert!(names.contains(&"split-pkgbase".to_string()), "{names:?}"); + assert!(names.contains(&"split-pkgbase-docs".to_string()), "{names:?}"); + // One approval, one release, N packages — the §3 split-pkgbase rule. + assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); + assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1)); +} + +#[test] +fn a_failed_build_leaves_the_previous_version_serving() { + let (mut env, fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + + fx.bump(&[("pkgver", "1.0.1")]); + let c2 = approve_pending(&env, "plain-make"); + // The build itself fails this time. + env.set_shim_fail("makechrootpkg"); + let out = run_for(&env, &c2); + match out { + pipeline::Outcome::Failed { step, .. } => assert_eq!(step, "build"), + other => panic!("{other:?}"), + } + // §8.4: the old version keeps serving and the candidate stays approved. + assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); + assert_eq!( + candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state, + candidate_state::APPROVED + ); + assert_eq!( + env.query_i64("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0.1-1'", &[]), + Some(0) + ); +} + +#[test] +fn an_unresolvable_dependency_blocks_instead_of_failing() { + let (env, _fx) = env_with_fixture("missing-dep"); + // We subscribe to `dep-partner` but have never published it: that is exactly + // "unresolvable" in §10.4, and the answer is to wait, not to fail. + env.subscribe("dep-partner"); + let c = approve_fixture(&env, "missing-dep"); + let out = run_for(&env, &c); + match out { + pipeline::Outcome::Blocked { on } => { + assert!(on.contains(&"dep-partner".to_string()), "{on:?}"); + } + other => panic!("expected a blocked build, got {other:?}"), + } + let (bid, _name, blocked_on) = builds::blocked_builds(&env.db).unwrap().remove(0); + assert_eq!(blocked_on, vec!["dep-partner".to_string()]); + assert_eq!(builds::get(&env.db, &bid).unwrap().unwrap().state, build_state::BLOCKED_MISSING_DEP); + assert!(in_index(&env).is_empty(), "a blocked build publishes nothing"); +} + +#[test] +fn publishing_a_dependency_requeues_what_it_unblocks() { + let (env, _fx) = env_with_fixture("missing-dep"); + env.subscribe("dep-partner"); + let c = approve_fixture(&env, "missing-dep"); + assert!(matches!(run_for(&env, &c), pipeline::Outcome::Blocked { .. })); + assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); + // Something lands in the index: blocked builds get another look (§10.4). + let n = publish::reconcile(&env.cfg, &env.db).unwrap_or(0); + let _ = n; + let requeued = builds::requeue_blocked(&env.db).unwrap(); + assert_eq!(requeued, 1); + assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 0); +} + +#[test] +fn re_enqueueing_the_same_intent_is_a_noop() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + let a = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + let b = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + assert_eq!(a, b, "build ids are deterministic (§8.2)"); + assert_eq!(env.query_i64("SELECT count(*) FROM build", &[]), Some(1)); +} + +#[test] +fn i6_manual_rebuild_reuses_the_approved_identity() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + let before = env.query_i64("SELECT count(*) FROM approval", &[]); + + let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap(); + assert!(matches!( + pipeline::run(&env.cfg, &env.db, &id).unwrap(), + pipeline::Outcome::Succeeded { .. } + )); + // Same version, new release row, and crucially: no new approval (§2 I6). + assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), before); + assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); + assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(2)); +} + +#[test] +fn i12_world_snapshot_is_recorded_at_ingest() { + let (env, fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + run_for(&env, &c); + + // Now a second build whose chroot had our own published package installed: + // that is the pair staleness tracking is computed from (§10.1). + let mut m = fx.manifest_json(); + m["installed"] = serde_json::json!([ + {"name": "plain-make", "version": "1.0-1", "arch": "x86_64"}, + {"name": "glibc", "version": "2.39-1", "arch": "x86_64"} + ]); + std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap(); + fx.bump(&[("pkgver", "1.0.1")]); + let c2 = approve_pending(&env, "plain-make"); + run_for(&env, &c2); + + let wid = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT world_snapshot_id FROM build WHERE world_snapshot_id IS NOT NULL + ORDER BY rowid DESC LIMIT 1", + [], + |r| r.get::<_, i64>(0), + )?) + }) + .unwrap(); + let json: String = env + .db + .read(|c| { + Ok(c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", rusqlite::params![wid], |r| r.get(0))?) + }) + .unwrap(); + let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap(); + let members: Vec<(String, String)> = parsed + .iter() + .map(|v| { + ( + v["pkgbase"].as_str().unwrap_or_default().to_string(), + v["version"].as_str().unwrap_or_default().to_string(), + ) + }) + .collect(); + // The snapshot is the installed set INTERSECTED with our own packages: + // unfiltered, Arch moving would make every package permanently stale. + assert!(members.iter().any(|(n, v)| n == "plain-make" && v == "1.0-1"), "{members:?}"); + assert!(!members.iter().any(|(n, _)| n == "glibc"), "{members:?}"); +} + +#[test] +fn publish_refuses_without_an_approval_behind_it() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + // Strip the approval: the publish step must refuse, not publish anyway. + env.exec("DELETE FROM approval", &[]); + match pipeline::run(&env.cfg, &env.db, &id).unwrap() { + pipeline::Outcome::Failed { step, error, .. } => { + assert_eq!(step, "publish"); + assert!(error.contains("no approval"), "{error}"); + } + other => panic!("I1 requires a refusal, got {other:?}"), + } + assert!(in_index(&env).is_empty()); +} + +#[test] +fn a_stale_accepted_pointer_refuses_to_publish() { + let (env, _fx) = env_with_fixture("plain-make"); + let c = approve_fixture(&env, "plain-make"); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + // The approval was taken against "nothing accepted yet". Move the pointer + // out from under the build and the compare-and-swap must refuse. + env.exec( + "UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'", + &[], + ); + match pipeline::run(&env.cfg, &env.db, &id).unwrap() { + pipeline::Outcome::Failed { step, error, .. } => { + assert_eq!(step, "publish"); + assert!(error.contains("accepted pointer moved"), "{error}"); + } + other => panic!("expected a CAS refusal, got {other:?}"), + } + assert!(in_index(&env).is_empty()); +} |
