summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.pi/.goals-pool-snapshot.json2
-rw-r--r--.pi/goals/.goal-ledger-checkpoint.json2
-rw-r--r--.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md28
-rw-r--r--.pi/goals/goal_events.jsonl3
-rw-r--r--Cargo.lock1
-rw-r--r--Cargo.toml1
-rw-r--r--src/config.rs18
-rw-r--r--src/db/builds.rs62
-rw-r--r--src/main.rs6
-rw-r--r--src/pipeline/dispatch.rs203
-rw-r--r--src/pipeline/mod.rs1
-rw-r--r--src/pipeline/publish.rs13
-rw-r--r--tests/dispatch.rs281
13 files changed, 606 insertions, 15 deletions
diff --git a/.pi/.goals-pool-snapshot.json b/.pi/.goals-pool-snapshot.json
index e74c75d..ab03d25 100644
--- a/.pi/.goals-pool-snapshot.json
+++ b/.pi/.goals-pool-snapshot.json
@@ -1 +1 @@
-{"version":1,"dirMtimeMs":1794990189939.1113,"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":4907415,"activeSeconds":9918},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-18T08:23:09.937Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":527,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"dfbaf4f2-dad9-4dc6-9717-5038550aa75e","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"kickoff"},"dispatch":{"id":"27430841-6f83-4343-a9fa-dd1c866de9d3","kind":"kickoff","claimedAt":1794985072841}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"complete","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"complete","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test.","completedAt":"2026-11-17T21:31:09.120Z","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO"},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"complete","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction.","completedAt":"2026-11-17T21:20:02.693Z","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi"},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"complete","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected.","completedAt":"2026-11-17T22:10:06.063Z","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi"},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"complete","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap.","completedAt":"2026-11-17T21:58:00.936Z","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean"},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"complete","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8).","completedAt":"2026-11-18T07:01:31.398Z","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re"}],"completedAt":"2026-11-18T07:02:29.831Z","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit"},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"complete","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"complete","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry.","completedAt":"2026-11-18T07:16:40.077Z","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma"},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"complete","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD.","completedAt":"2026-11-18T07:17:57.387Z","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o"},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"complete","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped.","completedAt":"2026-11-18T07:29:10.456Z","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-"}],"completedAt":"2026-11-18T07:30:36.958Z","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri"},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"complete","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled.","completedAt":"2026-11-18T08:06:45.433Z","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr"},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"complete","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane.","completedAt":"2026-11-18T08:07:10.624Z","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r"},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"complete","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable.","completedAt":"2026-11-18T08:07:36.401Z","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written"},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"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-p2-surfaces"}]} \ No newline at end of file
+{"version":1,"dirMtimeMs":1794990989630.7246,"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":5396378,"activeSeconds":10692},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-18T08:36:29.628Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":573,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"dfbaf4f2-dad9-4dc6-9717-5038550aa75e","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"kickoff"},"dispatch":{"id":"27430841-6f83-4343-a9fa-dd1c866de9d3","kind":"kickoff","claimedAt":1794985072841}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"complete","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"complete","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test.","completedAt":"2026-11-17T21:00:03.122Z","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, "},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"complete","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test.","completedAt":"2026-11-17T21:31:09.120Z","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO"},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"complete","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction.","completedAt":"2026-11-17T21:20:02.693Z","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi"},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"complete","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected.","completedAt":"2026-11-17T22:10:06.063Z","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi"},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"complete","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap.","completedAt":"2026-11-17T21:58:00.936Z","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean"},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"complete","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8).","completedAt":"2026-11-18T07:01:31.398Z","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re"}],"completedAt":"2026-11-18T07:02:29.831Z","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit"},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"complete","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"complete","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry.","completedAt":"2026-11-18T07:16:40.077Z","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma"},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"complete","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD.","completedAt":"2026-11-18T07:17:57.387Z","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o"},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"complete","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped.","completedAt":"2026-11-18T07:29:10.456Z","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-"}],"completedAt":"2026-11-18T07:30:36.958Z","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri"},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"complete","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"complete","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled.","completedAt":"2026-11-18T08:06:45.433Z","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr"},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"complete","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane.","completedAt":"2026-11-18T08:07:10.624Z","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r"},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"complete","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable.","completedAt":"2026-11-18T08:07:36.401Z","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written"},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"complete","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6).","completedAt":"2026-11-18T08:23:18.650Z","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down"}],"completedAt":"2026-11-18T08:24:11.640Z","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a"},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"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-p3-dispatch"}]} \ No newline at end of file
diff --git a/.pi/goals/.goal-ledger-checkpoint.json b/.pi/goals/.goal-ledger-checkpoint.json
index 1e5844b..0709c23 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-18T08:08:13.922Z","coveredBytes":9920,"coveredEvents":29,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z","resumedAt":"2026-11-18T06:57:52.837Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma","at":"2026-11-18T07:16:40.078Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma","at":"2026-11-18T07:16:40.078Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma","at":"2026-11-18T07:16:40.078Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"}],"oracle":[],"lifecycle":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"}}]]} \ No newline at end of file
+{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-18T08:25:05.562Z","coveredBytes":10674,"coveredEvents":32,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z","resumedAt":"2026-11-18T06:57:52.837Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down","at":"2026-11-18T08:23:18.652Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a","at":"2026-11-18T08:24:11.640Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down","at":"2026-11-18T08:23:18.652Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a","at":"2026-11-18T08:24:11.640Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","evidence":"tests/db.rs: 10 tests pass — migrations from empty + idempotent + WAL, default settings, I7 partial unique index rejects 2nd pending_review, candidate identity uniqueness, audit append-only triggers, ","at":"2026-11-17T21:00:03.124Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","at":"2026-11-17T21:00:47.994Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-detect","evidence":"tests/detect.rs: 16 tests pass against real file:// git fixtures — clone+ls-remote poll with fetch only on SHA move (Sync::Unchanged vs Fetched), snapshot records aur_commit + recipe_hash covering shi","at":"2026-11-17T21:20:02.693Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","at":"2026-11-17T21:21:27.981Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-shims","evidence":"src/shims + src/bin/{mkarchroot,makechrootpkg,makepkg,repo-add,gpg,pacman}: shims record invocations to AUR_SHIM_DIR/invocations.jsonl, obey AUR_SHIM_MANIFEST, and emit real .pkg.tar.zst with .PKGINFO","at":"2026-11-17T21:31:09.121Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","at":"2026-11-17T21:32:52.768Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-build","evidence":"tests/pipeline.rs: 17 shim-driven e2e tests pass (fail-closed recipe_hash + pkgver, kill-mid-publish I4, crash-resume I5, CAS pointer, signed db+pkgs); cargo clippy clean","at":"2026-11-17T21:58:00.937Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","at":"2026-11-17T21:58:43.315Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-approve","evidence":"tests/approve.rs: 10 tests pass incl. both-hash immutable approval row (migration 0006 trigger), stale identity/diff refused, collapse-in-place revision bump, viewed→superseded freeze, rejected identi","at":"2026-11-17T22:10:06.063Z"},{"type":"goal_paused","goalId":"mwl5tehk-xhe7fk","reason":"user","status":"paused","at":"2026-11-17T22:12:03.674Z"},{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-invariants","evidence":"tests/invariants.rs: 10 named invariant tests pass as post-conditions on real runs (I1 approval trace, I2 base after 5 detections, I3 recipe pin, I4 byte-identical index after mid-publish crash, I5 re","at":"2026-11-18T07:01:31.400Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0","evidence":"All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit","at":"2026-11-18T07:02:29.831Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","at":"2026-11-18T07:04:12.225Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageA","evidence":"tests/vcs.rs: stage_a_probes_every_vcs_source_not_just_the_first (git-multi → 2 pins matching both repo HEADs), stage_a_respects_a_tag_pin, stage_a_short_circuits_before_stage_b_when_nothing_moved (ma","at":"2026-11-18T07:16:40.078Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-stageB","evidence":"tests/vcs.rs: stage_b_resolves_pkgver_and_captures_the_pins (pins in identity_hash via Identity hash comparison), stage_b_is_cached_on_pkgbase_recipe_and_tip (cache row reuse + cooldown + re-resolve o","at":"2026-11-18T07:17:57.387Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","at":"2026-11-18T07:19:15.892Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1-notices","evidence":"tests/notices.rs: 8 tests — digest-drift fixture → high-severity integrity_alert + no candidate, pin-drift → info notice + no candidate, recipe drift → warning, skip-checksum → HIGH risk signal 'skip-","at":"2026-11-18T07:29:10.457Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p1","evidence":"All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri","at":"2026-11-18T07:30:36.958Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","at":"2026-11-18T07:32:27.434Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-http","evidence":"tests/http.rs (14 tests, all pass): every_surface_renders covers all §12 routes on a live tiny_http server; every_post_requires_a_csrf_token asserts 403 for missing and forged tokens with zero rows wr","at":"2026-11-18T08:06:45.433Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down","at":"2026-11-18T08:23:18.652Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a","at":"2026-11-18T08:24:11.640Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"}],"oracle":[],"lifecycle":{"type":"goal_resumed","goalId":"mwl5tehk-xhe7fk","reason":"user","at":"2026-11-18T06:57:52.837Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"}}]]} \ 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 c228f43..4a64017 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": 4907415,
- "activeSeconds": 9918
+ "tokensUsed": 5396378,
+ "activeSeconds": 10692
},
"sisyphus": false,
"createdAt": "2026-11-17T20:43:24.440Z",
- "updatedAt": "2026-11-18T08:23:09.937Z",
+ "updatedAt": "2026-11-18T08:36:29.628Z",
"activePath": ".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md",
- "revision": 527,
+ "revision": 573,
"scheduler": {
"version": 1,
"owner": "01a1eb32-2e3f-757c-a79a-21ac993facc5",
@@ -133,7 +133,7 @@
{
"id": "task-p2",
"title": "P2 — review surface (§12, §13, §6)",
- "status": "pending",
+ "status": "complete",
"subtasks": [
{
"id": "task-p2-http",
@@ -162,10 +162,14 @@
{
"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)."
+ "status": "complete",
+ "verificationContract": "Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6).",
+ "completedAt": "2026-11-18T08:23:18.650Z",
+ "evidence": "tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down"
}
- ]
+ ],
+ "completedAt": "2026-11-18T08:24:11.640Z",
+ "evidence": "All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a"
},
{
"id": "task-p3",
@@ -233,7 +237,7 @@
"blockCompletion": true,
"proposedAt": "2026-11-17T20:39:23.165Z"
},
- "currentTaskId": "task-p2-surfaces"
+ "currentTaskId": "task-p3-dispatch"
}
# Goal Prompt
@@ -266,15 +270,15 @@ 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: 2h45m18s
-- Tokens used: 4.9M (4,907,415) tokens
+- Time spent: 2h58m12s
+- Tokens used: 5.4M (5,396,378) tokens
## Tasks
<!-- blockCompletion: true -->
- [x] task-setup: Provision toolchain (pacman rustup + devtools) and initialize git — evidence: rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu
- [x] task-p0: P0 — walking skeleton + test harness (§17 P0, §16a) — evidence: All P0 children complete: schema+writer actor, shims+corpus, mirror watcher, approval semantics+CLI, 10-step pipeline with signed atomic publish, invariant index. 81 tests pass, clippy clean, 7 commit
- [x] task-p1: P1 — VCS / computed pkgver detection (§5.2, §3) — evidence: All three P1 children complete: Stage A probe (every VCS source, #tag/#commit, short-circuit), Stage B resolution (pin capture, cache on pkgbase+recipe_hash+tip, cooldown, concurrency cap), notices+ri
-- [ ] task-p2: P2 — review surface (§12, §13, §6)
+- [x] task-p2: P2 — review surface (§12, §13, §6) — evidence: All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a
- [ ] task-p3: P3 — durability (§8.2, §8.3, §8.4)
- [ ] task-p4: P4 — staleness, retention, metrics (§10, §15)
- [ ] task-verify: Final verification pass, real-chroot attempt, and documentation — contract: 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.
diff --git a/.pi/goals/goal_events.jsonl b/.pi/goals/goal_events.jsonl
index 519cb08..a6fc260 100644
--- a/.pi/goals/goal_events.jsonl
+++ b/.pi/goals/goal_events.jsonl
@@ -27,3 +27,6 @@
{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-inbox","evidence":"src/review/diff.rs now emits all eight §6 panels (recipe, version, source-digest, upstream, source, dependency, build-env, install-hook), each computed accepted→candidate; commit ab8d33d. tests/http.r","at":"2026-11-18T08:07:10.624Z"}
{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-approve409","evidence":"tests/http.rs: a_stale_approval_is_a_409_that_renders_the_current_diff (upstream moves mid-review → 409, body explains the ground moved, re-render shows the new 9.9 version, zero approval rows written","at":"2026-11-18T08:07:36.401Z"}
{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","at":"2026-11-18T08:08:13.901Z"}
+{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2-surfaces","evidence":"tests/surfaces.rs (7 tests): attention_lists_outdated_dependencies_from_the_recorded_world (dep-client stale after plain-make moves, dependency + built-against + now all named); attention_lists_a_down","at":"2026-11-18T08:23:18.652Z"}
+{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-p2","evidence":"All four P2 children complete: tiny_http server + CSRF/session gate, inbox with the full eight-panel diff set, optimistic-concurrency approve/reject with 409-on-stale and per-item bulk confirmation, a","at":"2026-11-18T08:24:11.640Z"}
+{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p3-dispatch","at":"2026-11-18T08:25:05.524Z"}
diff --git a/Cargo.lock b/Cargo.lock
index 9bc62ae..f353721 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -132,6 +132,7 @@ dependencies = [
"crossbeam-channel",
"flate2",
"hex",
+ "libc",
"rusqlite",
"serde",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index 7a687f6..b74dbab 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -55,6 +55,7 @@ chrono = { version = "0.4", features = ["serde"] }
walkdir = "2"
tar = "0.4"
zstd = "0.13"
+libc = "0"
flate2 = "1"
[lints.cargo]
diff --git a/src/config.rs b/src/config.rs
index 5bcb5aa..270c81e 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -55,6 +55,19 @@ pub struct Config {
pub publish_fault: Option<String>,
/// Test hook: the named shim must fail, e.g. `makechrootpkg`.
pub shim_fail: Option<String>,
+ /// How many builds may run at once (§8.2 backpressure). Default 1, which
+ /// also means the chroot pool only needs one warm root.
+ pub max_concurrent_builds: usize,
+ /// Seconds of lease a worker takes when it claims a build (§8.2).
+ pub lease_secs: i64,
+ /// A build is not admitted unless at least this much free space remains
+ /// on the filesystem holding `root` (§8.2 disk headroom).
+ pub min_free_disk_mb: u64,
+ /// Transient step failures are retried up to this many attempts; a
+ /// deterministic build failure is never retried (§8.4).
+ pub max_transient_attempts: i64,
+ /// Seconds between dispatcher passes.
+ pub dispatch_tick_secs: u64,
}
impl Default for Config {
@@ -80,6 +93,11 @@ impl Default for Config {
shim_dir: None,
publish_fault: None,
shim_fail: None,
+ max_concurrent_builds: 1,
+ lease_secs: 90,
+ min_free_disk_mb: 1024,
+ max_transient_attempts: 3,
+ dispatch_tick_secs: 2,
}
}
}
diff --git a/src/db/builds.rs b/src/db/builds.rs
index d251566..0a7013c 100644
--- a/src/db/builds.rs
+++ b/src/db/builds.rs
@@ -422,3 +422,65 @@ pub fn current_state(c: &Connection, id: &str) -> Result<String> {
.optional()?
.unwrap_or_default())
}
+
+/// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and
+/// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one
+/// writer the claim cannot race: the SELECT and the UPDATE are the same
+/// transaction, so no other claimer can see a row in between.
+pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> {
+ if limit == 0 {
+ return Ok(Vec::new());
+ }
+ let owner = owner.to_string();
+ let exp = time::secs_ahead(lease_secs);
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ let ids: Vec<String> = {
+ let mut stmt = tx.prepare(
+ "SELECT id FROM build WHERE state='queued'
+ ORDER BY priority DESC, created_at LIMIT ?1",
+ )?;
+ let rows = stmt.query_map(params![limit as i64], |r| r.get::<_, String>(0))?;
+ rows.filter_map(|r| r.ok()).collect()
+ };
+ for id in &ids {
+ 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='queued'",
+ params![owner, exp, at, id],
+ )?;
+ }
+ Ok(ids)
+ })
+}
+
+/// A newer approved release for the same pkgbase makes an in-flight build
+/// pointless (§8.2 cancellation). Workers notice at the next step boundary and
+/// stop; nothing is killed mid-step, which is what keeps the checkpoints honest.
+pub fn cancel_superseded(db: &Db) -> Result<usize> {
+ db.writer.tx(move |tx| {
+ let n = tx.execute(
+ "UPDATE build SET cancel_requested=1
+ WHERE state IN ('queued','leased','running')
+ AND candidate_id IN (SELECT id FROM candidate WHERE state='superseded')",
+ [],
+ )?;
+ Ok(n)
+ })
+}
+
+/// Put a build back on the queue after a transient failure, keeping the attempt
+/// count so the retry cap can bite (§8.4).
+pub fn requeue_transient(db: &Db, id: &str) -> Result<()> {
+ let id = id.to_string();
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL,
+ error=NULL, updated_at=?1 WHERE id=?2",
+ params![at, id],
+ )?;
+ Ok(())
+ })
+}
diff --git a/src/main.rs b/src/main.rs
index b88e757..7297a96 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -125,8 +125,12 @@ fn main() -> anyhow::Result<()> {
// behind the database, close the gap before anyone asks for it.
let _ = pipeline::publish::reconcile(&cfg, &db);
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop);
+ aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone());
let _server = aur_build::http::spawn(cfg.clone(), db.clone())?;
+ // The dispatcher reaps expired leases before its first claim, so a
+ // restart recovers whatever a crash left leased without any special
+ // startup routine (§8.2).
+ let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone());
println!("serving on http://{} — ctrl-c to stop", cfg.bind);
// Single process, thread per connection: the main thread has nothing to
// do but wait to be killed.
diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs
new file mode 100644
index 0000000..62052fd
--- /dev/null
+++ b/src/pipeline/dispatch.rs
@@ -0,0 +1,203 @@
+//! The dispatcher actor, the worker pool and the reaper (§8.2).
+//!
+//! Shape: one dispatcher thread, N worker threads, one crossbeam channel
+//! between them. The dispatcher's loop is
+//!
+//! ```text
+//! reaper: expired leases -> queued, in-flight step -> interrupted
+//! cancel: superseded in-flight builds -> cancel_requested
+//! claim: BEGIN IMMEDIATE { SELECT queued LIMIT admissible; UPDATE leased }
+//! send: build_tx.send(id) for each
+//! ```
+//!
+//! Nothing lives only in a worker's memory. If the process is killed, the lease
+//! expires and the next dispatcher pass puts the build back; the step
+//! checkpoint decides where it resumes (I5). That is the whole crash-recovery
+//! story, and it is why there is no separate "recover on startup" routine — the
+//! reaper pass *is* the recovery, and it runs first in every loop.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::thread::JoinHandle;
+
+use crossbeam_channel::{bounded, Sender};
+
+use crate::config::Config;
+use crate::db::{self, builds, Db};
+use crate::pipeline::{self, Outcome};
+
+/// Handle on a running pool. Dropping without `shutdown` leaves the threads
+/// running; call `shutdown` to join them cleanly.
+pub struct Pool {
+ stop: Arc<AtomicBool>,
+ handles: Vec<JoinHandle<()>>,
+}
+
+impl Pool {
+ /// Start the dispatcher and `max_concurrent_builds` workers.
+ pub fn spawn(cfg: Arc<Config>, db: Db) -> Pool {
+ let stop = Arc::new(AtomicBool::new(false));
+ let workers = cfg.max_concurrent_builds.max(1);
+ // Bounded at the worker count: the dispatcher must not run ahead and
+ // lease builds that no worker has picked up yet, because a leased build
+ // whose worker never starts would sit until its lease expires.
+ let (tx, rx) = bounded::<String>(workers);
+ let mut handles = Vec::new();
+
+ for n in 0..workers {
+ let cfg = cfg.clone();
+ let db = db.clone();
+ let stop = stop.clone();
+ let rx = rx.clone();
+ handles.push(
+ std::thread::Builder::new()
+ .name(format!("worker-{n}"))
+ .spawn(move || worker(cfg, db, rx, stop))
+ .expect("spawn worker"),
+ );
+ }
+ drop(rx);
+
+ let cfg2 = cfg.clone();
+ let db2 = db.clone();
+ let stop2 = stop.clone();
+ handles.push(
+ std::thread::Builder::new()
+ .name("dispatcher".into())
+ .spawn(move || dispatcher(cfg2, db2, stop2, tx))
+ .expect("spawn dispatcher"),
+ );
+
+ Pool { stop, handles }
+ }
+
+ /// Ask the threads to stop and wait for them. A build that is mid-step will
+ /// finish that step, fail its lease, and be requeued by the next process's
+ /// reaper — which is the designed behaviour, not a bug to wait out.
+ pub fn shutdown(self) {
+ self.stop.store(true, Ordering::SeqCst);
+ for h in self.handles {
+ let _ = h.join();
+ }
+ }
+}
+
+fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) {
+ // The reaper pass runs first on every loop, including the very first one, so
+ // "recover from a crash" and "notice an expired lease" are the same code
+ // path. There is no special startup recovery to get wrong.
+ while !stop.load(Ordering::SeqCst) {
+ dispatch_once(&cfg, &db, &tx);
+ let mut slept = 0u64;
+ while slept < cfg.dispatch_tick_secs && !stop.load(Ordering::SeqCst) {
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ slept += 1;
+ }
+ }
+}
+
+/// One dispatcher pass. Returns the ids handed to workers. Public so a test can
+/// drive one pass deterministically instead of racing a thread.
+pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> {
+ let reaped = builds::reap_expired(db).unwrap_or(0);
+ if reaped > 0 {
+ db::audit_system(
+ &db.writer,
+ "build.reaped",
+ "build",
+ "*",
+ serde_json::json!({"requeued": reaped}),
+ )
+ .ok();
+ }
+ // Blocked builds become eligible again when the blocking package arrives.
+ let _ = builds::requeue_blocked(db);
+ // A newer approval makes an in-flight build pointless (§8.2).
+ let _ = builds::cancel_superseded(db);
+
+ let room = admissible(cfg, db);
+ if room == 0 {
+ return Vec::new();
+ }
+ let owner = format!("worker-{}", std::process::id());
+ let ids = builds::claim_batch(db, &owner, room, cfg.lease_secs).unwrap_or_default();
+ for id in &ids {
+ if tx.send(id.clone()).is_err() {
+ // No worker to take it: give the lease back rather than let it
+ // expire with nobody holding it.
+ let _ = builds::requeue_transient(db, id);
+ }
+ }
+ ids
+}
+
+/// How many builds may be admitted right now (§8.2 backpressure):
+/// `min(max_concurrent - in_flight, disk headroom)`. A build that cannot fit on
+/// disk is not admitted — it stays queued rather than filling the filesystem
+/// halfway through a compile.
+pub fn admissible(cfg: &Config, db: &Db) -> usize {
+ let in_flight = builds::in_flight(db).unwrap_or(0) as usize;
+ let slots = cfg.max_concurrent_builds.saturating_sub(in_flight);
+ if slots == 0 {
+ return 0;
+ }
+ let free = free_disk_mb(&cfg.root);
+ if free < cfg.min_free_disk_mb {
+ return 0;
+ }
+ slots
+}
+
+/// Megabytes free on the filesystem holding `path`.
+pub fn free_disk_mb(path: &std::path::Path) -> u64 {
+ use std::ffi::CString;
+ let c = match CString::new(path.as_os_str().to_string_lossy().as_bytes()) {
+ Ok(c) => c,
+ Err(_) => return u64::MAX,
+ };
+ let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
+ let rc = unsafe { libc::statvfs(c.as_ptr(), &mut stat) };
+ if rc != 0 {
+ // If we cannot find out, do not block the queue over a measurement
+ // problem; the pipeline's own disk guard is the backstop.
+ return u64::MAX;
+ }
+ let bsize = stat.f_frsize as u64;
+ let avail = stat.f_bavail as u64;
+ avail * bsize / (1024 * 1024)
+}
+
+fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, stop: Arc<AtomicBool>) {
+ for id in rx.iter() {
+ if stop.load(Ordering::SeqCst) {
+ let _ = builds::requeue_transient(&db, &id);
+ continue;
+ }
+ let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1);
+ match pipeline::run(&cfg, &db, &id) {
+ Ok(Outcome::Failed { transient, .. }) => {
+ // §8.4: transient failures (network, mirror 5xx) retry with a
+ // bounded number of attempts. A deterministic build failure
+ // does NOT retry — the release stays approved_but_unbuilt and
+ // the UI says "index still serving v1". Retrying that would burn
+ // a chroot to produce the same failure.
+ if transient && attempt < cfg.max_transient_attempts {
+ let _ = builds::requeue_transient(&db, &id);
+ db::audit_system(
+ &db.writer,
+ "build.retry",
+ "build",
+ &id,
+ serde_json::json!({"attempt": attempt, "max": cfg.max_transient_attempts}),
+ )
+ .ok();
+ }
+ }
+ Ok(Outcome::Cancelled) => {}
+ Ok(Outcome::Blocked { .. }) | Ok(Outcome::Succeeded { .. }) | Err(_) => {}
+ }
+ if stop.load(Ordering::SeqCst) {
+ break;
+ }
+ }
+}
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index 37aae77..459cea6 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -6,6 +6,7 @@
//! is serialized per repo (I4).
pub mod publish;
+pub mod dispatch;
mod steps;
use std::path::PathBuf;
diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs
index 5d03a06..d54314e 100644
--- a/src/pipeline/publish.rs
+++ b/src/pipeline/publish.rs
@@ -58,7 +58,20 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> {
}
/// Publish the collected artifacts of a build. Returns the new release id.
+/// One publish at a time per repo (§8.2, §9). With `max_concurrent_builds > 1`
+/// two workers could otherwise interleave the index rewrite; the critical
+/// section is the db file rewrite only, never a build.
+static PUBLISH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
pub fn publish(ctx: &Ctx) -> Result<i64> {
+ let _guard = match PUBLISH_LOCK.lock() {
+ Ok(g) => g,
+ // A previous publish panicked while holding it. The index on disk is
+ // still whatever was last renamed into place — atomic publish means a
+ // poisoned lock cannot have left a half-written db — so we clear the
+ // poison and continue rather than wedge the queue forever.
+ Err(p) => p.into_inner(),
+ };
let collect = Collect::load(&ctx.collect_path)?;
if collect.packages.is_empty() {
return Err(Error::invalid("nothing to publish"));
diff --git a/tests/dispatch.rs b/tests/dispatch.rs
new file mode 100644
index 0000000..c70dd6b
--- /dev/null
+++ b/tests/dispatch.rs
@@ -0,0 +1,281 @@
+//! The dispatcher, the worker pool and the reaper (§8.2), plus the retry policy
+//! (§8.4). These drive the real threads and the real claim transaction — the
+//! crash-recovery claims in §2 are only worth anything if the lease machinery is
+//! actually exercised, not asserted in a comment.
+
+mod common;
+
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+
+use aur_build::config::Config;
+use aur_build::db::{self, builds, model::*};
+use aur_build::pipeline::{self, dispatch};
+use aur_build::review::{candidates, diff};
+use common::*;
+
+/// Approve a fixture's candidate and enqueue its build without running it.
+fn queued_build(env: &Env, name: &str) -> String {
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap()
+}
+
+fn pass(env: &Env) -> Vec<String> {
+ let (tx, _rx) = crossbeam_channel::bounded::<String>(8);
+ dispatch::dispatch_once(&env.cfg, &env.db, &tx)
+}
+
+#[test]
+fn the_deterministic_build_id_makes_re_enqueue_a_noop() {
+ // §8.2: re-submitting the same intent is an INSERT OR IGNORE no-op, which is
+ // what makes a careless "rebuild that again" harmless.
+ let (env, _fx) = env_with_fixture("plain-make");
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ let first = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ let again = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ assert_eq!(first, again, "the same intent produced two build ids");
+ assert_eq!(env.query_i64("SELECT count(*) FROM build", &[]), Some(1));
+}
+
+#[test]
+fn backpressure_admits_no_more_than_max_concurrent_builds() {
+ let (mut env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client");
+ env.cfg.max_concurrent_builds = 1;
+ let a = queued_build(&env, "plain-make");
+ let b = queued_build(&env, "dep-client");
+ assert_ne!(a, b);
+
+ let claimed = pass(&env);
+ assert_eq!(claimed.len(), 1, "one slot must admit exactly one build");
+ // The dispatcher will not run ahead into the second slot while the first is
+ // still in flight.
+ assert_eq!(pass(&env).len(), 0, "admitted a second build while one is in flight");
+ assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='leased'", &[]), Some(1));
+ assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='queued'", &[]), Some(1));
+
+ // Widen the pool and the second one goes.
+ env.cfg.max_concurrent_builds = 2;
+ assert_eq!(pass(&env).len(), 1);
+}
+
+#[test]
+fn disk_headroom_is_part_of_backpressure() {
+ let (mut env, _fx) = env_with_fixture("plain-make");
+ queued_build(&env, "plain-make");
+ // Ask for more free space than any machine has: nothing is admitted. A build
+ // that cannot fit on disk stays queued instead of filling the filesystem
+ // halfway through a compile (§8.2).
+ env.cfg.min_free_disk_mb = u64::MAX / 2;
+ assert_eq!(dispatch::admissible(&env.cfg, &env.db), 0);
+ assert!(pass(&env).is_empty(), "claimed a build with no disk headroom");
+ assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='queued'", &[]), Some(1));
+ // And the measurement itself is real, not a stub returning zero.
+ env.cfg.min_free_disk_mb = 1;
+ assert!(dispatch::free_disk_mb(&env.cfg.root) > 0, "free_disk_mb never measures anything");
+ assert_eq!(dispatch::admissible(&env.cfg, &env.db), 1);
+}
+
+#[test]
+fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() {
+ // The reaper pass is the whole crash-recovery story: a worker that died
+ // mid-step leaves a leased row and a running step, and the next pass turns
+ // that back into queued + interrupted so the checkpoint decides where it
+ // resumes (I5).
+ let (env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ assert_eq!(pass(&env), vec![id.clone()]);
+ builds::begin_step(&env.db, &id, "build", 1).unwrap();
+ assert_eq!(builds::step_status(&env.db, &id, "build").unwrap().as_deref(), Some("running"));
+
+ // Time passes — the lease expires, as it would if the process were killed.
+ env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z'", &[]);
+
+ // A fresh dispatcher (as after a restart) reaps it before claiming anything.
+ let reaped = builds::reap_expired(&env.db).unwrap();
+ assert_eq!(reaped, 1, "the expired lease was not requeued");
+ assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::QUEUED);
+ assert_eq!(
+ builds::step_status(&env.db, &id, "build").unwrap().as_deref(),
+ Some("interrupted"),
+ "the in-flight step was not marked interrupted"
+ );
+ // And it is claimable again.
+ assert_eq!(pass(&env), vec![id.clone()]);
+ assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().attempt, 2, "the retry was not counted");
+}
+
+#[test]
+fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() {
+ // §8.2 cancellation: a superseded candidate marks the running build
+ // cancel_requested; the worker stops at the next boundary rather than
+ // finishing work nobody asked for.
+ let (env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ pass(&env);
+ assert!(!builds::cancel_requested(&env.db, &id).unwrap());
+ env.exec("UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)", &params(vec![id.as_str()]));
+ assert_eq!(builds::cancel_superseded(&env.db).unwrap(), 1);
+ assert!(builds::cancel_requested(&env.db, &id).unwrap());
+ // run() honours it at the step boundary rather than mid-step.
+ let out = pipeline::run(&env.cfg, &env.db, &id).unwrap();
+ assert!(matches!(out, pipeline::Outcome::Cancelled), "run ignored the cancellation");
+ assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::CANCELLED);
+}
+
+#[test]
+fn a_deterministic_build_failure_is_not_retried() {
+ // §8.4: a build that fails for a deterministic reason stays failed at
+ // attempt 1. Burning another chroot to reproduce the same failure helps
+ // nobody; the release stays approved_but_unbuilt and the UI says so.
+ let (env, _fx) = env_with_fixture("build-fails");
+ let id = queued_build(&env, "build-fails");
+ let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone());
+ let state = wait_for(&env, &id, &["failed", "succeeded"]);
+ pool.shutdown();
+ assert_eq!(state, build_state::FAILED, "a deterministic failure should not succeed");
+ let b = builds::get(&env.db, &id).unwrap().unwrap();
+ assert_eq!(b.attempt, 1, "a deterministic failure must not be retried");
+ assert!(b.error.unwrap_or_default().contains("build"), "no step named in the error");
+ // And the old version keeps looking served: nothing was published.
+ assert_eq!(db::index_version(&env.db, "build-fails").unwrap(), None);
+}
+
+#[test]
+fn a_transient_failure_is_retried_up_to_the_cap() {
+ // §8.4: transient failures (network, mirror 5xx) retry with a bounded
+ // number of attempts. Here the toolchain itself is missing, which surfaces
+ // as an IO error — the same class as a flaky mirror.
+ let (mut env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ env.cfg.makechrootpkg_bin = "/nonexistent/makechrootpkg-for-test".into();
+ env.cfg.max_transient_attempts = 3;
+ env.cfg.dispatch_tick_secs = 0;
+ let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone());
+ // The state flickers to 'failed' between retries; what settles is the
+ // attempt count reaching the cap with the build left failed.
+ let b = wait_attempt(&env, &id, 3);
+ pool.shutdown();
+ assert_eq!(b.state, build_state::FAILED);
+ assert_eq!(b.attempt, 3, "a transient failure should retry up to the cap");
+}
+
+#[test]
+fn the_pool_takes_a_queued_build_all_the_way_to_publication() {
+ // The threads, not a test calling run() directly: dispatcher claims, worker
+ // runs the ten steps, publish lands the release.
+ let (env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ let cfg = Arc::new(env.cfg.clone());
+ let pool = dispatch::Pool::spawn(cfg, env.db.clone());
+ let state = wait_for(&env, &id, &["succeeded", "failed"]);
+ pool.shutdown();
+ assert_eq!(state, build_state::SUCCEEDED, "the pool did not finish the build");
+ assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_some(), "nothing was published");
+ assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1"));
+}
+
+#[test]
+fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() {
+ // I5 through the dispatcher rather than a direct run(): a build that dies
+ // late is requeued, re-claimed, and finishes from its checkpoints — the
+ // expensive steps are not done again.
+ let (mut env, fx) = env_with_fixture("plain-make");
+ let c = queued_candidate(&env, "plain-make");
+ let first = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ pipeline::run(&env.cfg, &env.db, &first).unwrap();
+
+ fx.bump(&[("pkgver", "1.0.1")]);
+ let c2 = queued_candidate(&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_before = aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", "");
+
+ // The worker "died" at publish: the row is leased with a lease nobody will
+ // extend. A fresh dispatcher reaps it and a worker finishes from the
+ // checkpoints.
+ env.clear_publish_fault();
+ // The crash shape: the row is leased to a worker that is no longer running,
+ // with a lease nobody will extend. A fresh dispatcher reaps it and a worker
+ // finishes from the checkpoints.
+ env.exec(
+ "UPDATE build SET state='leased', lease_owner='dead-worker',
+ lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1",
+ &params(vec![id.as_str()]),
+ );
+
+ let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone());
+ let state = wait_for(&env, &id, &["succeeded", "failed"]);
+ pool.shutdown();
+ assert_eq!(state, build_state::SUCCEEDED, "the resumed build did not finish");
+
+ assert_eq!(
+ aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", ""),
+ builds_before,
+ "I5: resuming must not rebuild"
+ );
+ let steps = builds::steps(&env.db, &id).unwrap();
+ let done = steps
+ .iter()
+ .filter(|s| s.status == step_state::SUCCEEDED || s.status == step_state::SKIPPED)
+ .count();
+ assert_eq!(done, BUILD_STEPS.len(), "not every step ended succeeded or skipped: {steps:?}");
+ assert_eq!(
+ env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
+ Some(1),
+ "the resume published twice"
+ );
+ assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0.1-1"));
+}
+
+/// Approve a fixture's candidate and hand back the approved row.
+fn queued_candidate(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();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap()
+}
+
+/// Poll until the build has been attempted `n` times and settled.
+fn wait_attempt(env: &Env, id: &str, n: i64) -> builds::BuildRow {
+ for _ in 0..600 {
+ if let Some(b) = builds::get(&env.db, id).unwrap() {
+ if b.attempt >= n && b.state == build_state::FAILED {
+ return b;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ panic!("build {id} never reached {n} attempts in state failed");
+}
+
+/// Poll until the build reaches one of `want` (or the test gives up).
+fn wait_for(env: &Env, id: &str, want: &[&str]) -> String {
+ for _ in 0..600 {
+ if let Some(b) = builds::get(&env.db, id).unwrap() {
+ if want.contains(&b.state.as_str()) {
+ return b.state;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ panic!("build {id} never reached {want:?}");
+}
+
+#[allow(dead_code)]
+fn unused(_: AtomicBool, _: Config) {}