Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/6318e411745bb8e7 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#443 (code only) closed derived `6318e411745bb8e7` #443 Imported from GitHub aien-dev/aien-sovereign-core-mv#443 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `0027a7638efb24481c3e9020c240e9f178554e29` · Head `94f6ff074e075a2d15d7fb2243f72f7871aecb64` ### Fetch it A git bundle of the pull request's head, 87438 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/6318e411745bb8e7.bundle -o 6318e411745bb8e7.bundle git fetch 6318e411745bb8e7.bundle refs/pull/443/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 443 94f6ff074e075a2d15d7fb2243f72f7871aecb64 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":443,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/443","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:12Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 511f14c4..b458a855 100644 --- a/.crumb +++ b/.crumb @@ -113,20 +113,20 @@ }, { "digest": "b244e10fd7d13535400d96fc053a4ca93e78fe573f826188362e4eb7aa77bce1", - "last_commit": "40d01b2", + "last_commit": "0027a76", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], "children_root": "sha256:1a5d56ce42bb2bd03bc0f5bd87ee6009e8971c0cb07294376a3fb32b248071f7", - "compiled_at": "2026-10-11T17:03:07Z", + "compiled_at": "2026-10-11T17:35:26Z", "compiler": "crumb-compile/1", - "digest": "sha256:80def7c3861590ed636d660faf42c16a8efc850e82599b0da39e506d9ca3ef06", + "digest": "sha256:335e229cfac6cf886ab4d4598c317898069bbaa27d336243162424aa57cc1ee2", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 3799, - "generated_at_commit": "1ae008a0a4cc64ebaec5739190ce1a8abd187419", - "source_tree": "sha256:50e1bcb93caa969288bbe3f01d61c41634394bc77a71b1abeb4139eabf990b53" + "files": 3806, + "generated_at_commit": "8d4842d4f1d0a985812a4c83cf6aad6ceebd8dfb", + "source_tree": "sha256:47d5eba81a896b00de3f58c5aa9e0e906f6a92abd23d6168a7652f6ac90611b6" } }, "history": [], diff --git a/tools/aien-test/docs/LOCAL_VERIFICATION.md b/tools/aien-test/docs/LOCAL_VERIFICATION.md new file mode 100644 index 00000000..0a88f902 --- /dev/null +++ b/tools/aien-test/docs/LOCAL_VERIFICATION.md @@ -0,0 +1,313 @@ +# Local verification with aien-test + +ADR 0033 Slices E and H: the planner, the trusted worker, the status and +verify commands, and the sandbox seam. Everything here runs on the Spark, +offline, with no outside service in the loop. GitHub only receives a commit +status when it can be reached; it is never asked for permission. + +## Commands + +| Command | What it does | Exit | +|---|---|---| +| `aien-test plan [--base REF] [--repo NAME] [--operator] [--allow-dirty]` | Which gates BASE..HEAD needs, by section, with the graph digest. BASE defaults to `origin/main`, then `main`. | 0 runnable, 2 NOT_RUN (unmapped path or removed gate), 4 BLOCKED_OPERATOR | +| `aien-test test changed [--base REF]` | Prints the plan, then runs the non-blocked selection through the normal runner. | the campaign verdict (PASS 0, FAIL 1, NOT_RUN 2, BLOCKED 3/4, MISSING 5) | +| `aien-test test crate:NAME` | The gates covering a workspace crate (from `cargo metadata`) and every crate that depends on it. | campaign verdict | +| `aien-test status [--state-dir DIR]` | Pools, GPU lock holder, aien-proof slots, quiet flag, worker heartbeat, pending triggers and outbox, newest bundle per repository. Read-only. | 0 | +| `aien-test verify COMMIT [--repo NAME] [--base REF] [--state-dir DIR] [--release]` | The independent check of a bundle, printed as the fixed report block below. | 0 only on `MERGE ELIGIBILITY: READY`, else 1 | +| `aien-test worker [--once REPO SHA] [--poll SECS] [--repos A,B] [--github] [--iterations N] [--state-dir DIR] [--key FILE] [--clones DIR] [--wt-root DIR] [--wt-tool FILE] [--base REF] [--sandbox user\|none --dev-unsandboxed]` | The trusted worker: one head with `--once`, or the loop. Runs gates in the user sandbox unless told otherwise. | `--once`: the plan verdict; loop: 0; 2 on a refused sandbox mode | +| `aien-test run GATE --sandbox user`, `aien-test test ... --sandbox user` | Any run, with every gate program started through the exec helper. | as before | + +`--release` (run, test, verify): qualification mode. No cache reuse, the tree +must be clean even with `--allow-dirty`, and in `verify` a cached result of a +gate whose `cache_scope` is `hardware` cannot count. + +## The plan + +Selection is the set of gates whose watched paths (declared `inputs`, the +D3 implied inputs, the manifest file, the golden file) cover a changed path, +plus the always set, closed over dependents and then dependencies. Sections: + +- **Required**: runs on this machine now. +- **Cached**: an evidence receipt already settles it (`plan` only; `verify` takes cached entries from the bundle). +- **Needs Spark**: pool `qemu`, or `arch`/`bare_metal` requirements. +- **Needs GB10**: pool `gb10`. +- **Advisory**: exactness ADVISORY; never required, never moves the verdict. +- **Blocked**: `PIPELINE_CONFIG_CHANGED` or `OPERATOR_STEP_PENDING`. + +A changed path no gate covers is listed under `UNMAPPED` and the verdict is +`NOT_RUN UNMAPPED_PATH`. A gate that exists at BASE and is gone at HEAD is +`NOT_RUN GATE_REMOVED`. Both are refusals, not failures: nothing vouches for +that change. + +### Trust rules A1 and A4 + +- **A1**: the always set (`.aien/always`), the unmapped allow-list + (`.aien/unmapped-ok`) and the trusted keys (`.aien/verify.pub`) are read + from BASE through git objects, never from the working tree or from HEAD. A + change under test cannot widen its own allow-list or add its own key. +- **A4**: a change under `.aien/`, `tests/gates/`, `.github/workflows/`, + `.forgejo/` or `tools/aien-test/` is a pipeline configuration change. The + whole plan is `BLOCKED_OPERATOR PIPELINE_CONFIG_CHANGED` unless the operator + passes `--operator`. + +`graph_digest` is sha256 over the canonical `[{gate, check_id, depends_on}]` +of the selected gates, sorted by gate. `verify` recomputes it from the +manifests at COMMIT and rejects a bundle whose digest differs. + +## Manifests: `run.exec` + +`run.exec` is either a repo-relative path or a bare program name: + +- A name **with a slash** (`tools/run.sh`) is resolved against the repository + root. Absolute paths and any `..` component are a manifest reject + (`BAD_MANIFEST`, exit 1), never NOT_RUN and never a silent run. A path that + leaves the repository through a symlink (`tools/run.sh -> /bin/true`) is + treated as absent: `MISSING_IMPLEMENTATION`, never run, never PASS. +- A name **without a slash** (`crumb`, `true`) is a program on a PATH. Under + `--sandbox none` that is the runner's own PATH. Under `--sandbox user` it + is the exec helper's trusted PATH + (`/var/lib/aien-run/cargo/bin:/usr/local/bin:/usr/bin:/bin`, the + `TRUSTED_PATH` constant); the runner resolves the name there itself and + hands the helper the full path, so the program hashed into the receipt and + the cache key (`binary_sha256`) is the program that runs. A name not found + there is `MISSING_IMPLEMENTATION`. + +This is what lets the shared gate template say `exec: crumb` with +`args: [verify, .]`: INFRA installs a pinned `crumb` at `/usr/local/bin/crumb` +(root-owned, on the trusted PATH). Proven end to end on 2026-10-11: a gate +running `crumb verify .` as `aien-run` in a worker checkout passed. + +## The sandbox seam (C8) + +`--sandbox user` rewrites every gate launch into + +``` +sudo -n /usr/local/sbin/aien-run-exec --cwd CWD --timeout SECS --profile host|qemu|gb10 [--env CARGO_TARGET_DIR=...] -- PROGRAM ARGS +``` + +Only `CARGO_TARGET_DIR` is passed through. The runner's own timeout and +kill rules are unchanged; a gb10 timeout stays advisory. For `run` and +`test`, `--sandbox none` (the default) leaves the launch exactly as it was. + +What the helper requires (INFRA, read from the installed script): `--cwd` +canonical, and inside `/var/lib/aien-run` only a worktree +`wt//<40-hex>`; host and qemu checks get a private `/tmp`, so a tree +under `/tmp` is invisible to them; `CARGO_TARGET_DIR` only as +`/var/lib/aien-run/target//pr` or `.../main` (created on demand). +Inside a run everything is read-only except the run's own worktree, its one +target dir and a private `/tmp`. When the helper refuses a call it exits 2 +and its stderr starts with `aien-run-exec:`; nothing ran. The runner records +such a run with no exit status, so it is FAIL and can never meet +`expects.exit`, not even `exit: 2` (`runner::sandbox_refused`). + +## The worker and the sandbox + +The worker runs other people's code, so it uses `--sandbox user` unless told +otherwise. `--sandbox none` runs gates as the worker's own user, who can read +the signing key: the worker refuses it (exit 2) unless `--dev-unsandboxed` is +given, and refuses it with `--github` in every case. The library has the same +rule (`Config.allow_unsandboxed`, default false). Under `--sandbox user` the +worker passes `CARGO_TARGET_DIR=/var/lib/aien-run/target//main` for a +head already on the base line and `.../pr` for any other head (A2). + +Under `--sandbox user` every checkout is made with INFRA's worktree tool +(`--wt-tool`, default `/aien-sovereign-core/tools/aien-local-ci/wt.sh`; +without it the worker refuses to run). `wt.sh sync` refreshes the bare mirror +`/var/lib/aien-run/mirror/.git` from the trusted clone (a head no branch +names is then fetched into the mirror by its id), and `wt.sh add` checks the +head out at `/var/lib/aien-run/wt//`: files owned by `aien-run`, +the `.git` link root-owned and pointing into the mirror. An older tree for +the same head is removed first, never reused. The worker opens that tree +with its own git only after checking the link (a regular root-owned file +nobody else can write, pointing into `/worktrees/`), and then only +through git's command-line `safe.directory` for that one path +(`process::trust_worktree`): every git setting and hook git reads there is +the operator's mirror, never the checked-out code. `wt.sh remove` deletes +the tree afterwards. + +Before it fetches or runs anything the worker refuses a repository name that +is not a plain name (letters, digits, `.`, `_`, `-`, not starting with a +dot), a commit that is not 40 lowercase hex, and a signing key whose mode +gives group or other any access (it must be 0600). + +## The worker + +For one head `REPO SHA`: + +1. The refusals above (names, key mode, sandbox mode). +2. `git fetch --all` in the trusted clone `/` (default + `~/workspace/`); its checkout is never touched. +3. Under `--sandbox user`: `wt.sh sync` and `wt.sh add` (see above). Under + `--sandbox none`: `git worktree add --detach //` + from the clone (default `/var/lib/aien-run/wt`). +4. `crumb claim` on the worktree when it has a `.crumb` (a missing one is a + journal note, not an error). +5. Plan against BASE: `origin/main` (`--base` overrides), or the head's first + parent when the head is already on that line (the tip of main or an older + main commit). `verify` applies the same rule, so both compute one plan. +6. Run the non-blocked selection with the pools and the sandbox; receipts go + to `evidence///`. +7. Build the bundle: one `checks[]` entry per planned gate with status + `run`, `cached`, `blocked` or `not_run`; `tree_digest` is sha256 of the + commit's tree id; the executor is the key's fingerprint with class + `spark`. Sign with `~/.aien/verify.key` and write + `bundles///bundle.json` (canonical bytes). The bundle also + carries a `plan` member (`verdict`, `reason`, `unmapped`, `removed`, + `blocked`): the bundle algebra says PASS when no required check failed, + which is vacuously true for an unmapped change with no checks. The plan + member is signed with the rest, so a reader can tell the vacuous case + apart: `verify-bundle` reports such a bundle as NOT_RUN (see below). +8. Run the independent check on the bundle just written, exactly as + `aien-test verify` does (keys at BASE, signature, graph digest, check ids, + receipts and their manifests, crumb). The journal records `verify: READY` + or `BLOCKED` with the reasons. +9. Heartbeat (`worker.heartbeat`), journal line (`journal.jsonl`), `crumb + close aien-worker . worker test`, remove the worktree (`wt.sh remove` + under `--sandbox user`). A crumb failure is + a journal note, never a verdict change. + +With `--github` the commit status `AIEN Verification (Spark)` is posted: +`success` only when step 8 said READY (which needs the bundle and the plan to +say PASS), `failure` when the bundle or the plan says FAIL, `error` +otherwise; the description names the bundle path. When `gh` cannot reach +GitHub the status is queued as `outbox/...json`, where `` +is a 20-digit number that only grows, and the journal says `publication: +pending`. Every later round replays the outbox first, in queue order; the +first status GitHub refuses stops the replay, so a newer status never +overtakes an older one. A newer status for the same head replaces the queued +one and moves to the end. A file that is not a status is renamed to `*.bad` +and journaled. GitHub being down never fails a local verification. + +The loop (`worker` without `--once`) serves trigger files +`trigger/.` oldest first (by modification time), then, with +`--github`, the open pull request heads and `main` of each `--repos` entry +that has no bundle yet, then sleeps `--poll` seconds. `--iterations N` +bounds the rounds (tests). Trigger names that are not a plain repository +name and a 40-hex commit are ignored. + +## verify-bundle and the vacuous PASS + +`aien-test verify-bundle` (the GitHub thin gate's command) prints and exits +with the gate verdict, not the raw algebra: a bundle with no required check, +or whose signed `plan.verdict` is not PASS, is `NOT_RUN` (exit 2) with the +reason in brackets, even though its `verdict` member says PASS. + +## The verify report + +``` +AIEN LOCAL VERIFICATION +Repository: github.com/aien-dev/ +Commit: <40 hex> +Changed files: N +Affected gates: N (names) | none +Executed gates: ... +Cached gates: ... +Failed gates: ... +Blocked gates: ... +Crumb status: CURRENT | STALE +Evidence status: VERIFIED | INVALID +Hardware status: QUALIFIED | NOT_REQUIRED | BLOCKED +Final verdict: PASS | FAIL | NOT_RUN | BLOCKED +Queue time: N ms | n/a +Build time: n/a +Test time: N ms | n/a +Total time: N ms | n/a +MERGE ELIGIBILITY: READY | BLOCKED +``` + +Lines after the block (`Evidence note`, `Crumb note`, `Verdict reason`, +`Unmapped`, `Problem`, `Bundle`) say why. Checks, in order: the bundle's +shape and signature against the keys at BASE (several keys allowed, one hex +per line, `#` comments; the key the bundle names must be one of them, else +`UNKNOWN_KEY`), repository, commit, executor fingerprint, every required +gate present, the verdict algebra; then the graph digest against a fresh +plan (BASE by the worker's rule above); then every entry's `check_id` must +be the one the plan computes at COMMIT (`CHECK_ID_MISMATCH`); then every +`run` entry's receipt must exist under `evidence///` with the +same gate, commit and verdict (an altered receipt no longer matches its +digest and is reported missing) and with the `manifest_digest` of the gate's +manifest at COMMIT (`MANIFEST_MISMATCH`); then the plan judge. Every +rejection is a `Problem` or `Evidence note` line and leaves READY out of +reach; no path defaults to PASS. Crumb status comes from `crumb verify .` in a temporary +detached worktree at COMMIT, removed afterwards. Queue time is the sum of +`pool_wait_ms`, test time the sum of `duration_ms` over the executed +receipts, total time the bundle's `finished_utc - started_utc`; build time +is not measured yet. + +`READY` requires: evidence VERIFIED, final verdict PASS, crumb CURRENT, no +unmapped path, no blocked gate, no problem line. + +## File layout + +``` +~/.aien/verify.key the worker's signing seed, mode 0600 +/.aien/verify.pub trusted public keys, read at BASE +/.aien/always gates that always run, read at BASE +/.aien/unmapped-ok paths no gate needs to cover, read at BASE +~/.local/state/aien-local-ci/ + evidence///.json receipts of that run + bundles///bundle.json the signed bundle + trigger/. a run request (removed when served) + outbox/...json a commit status waiting for GitHub, in queue order + journal.jsonl one line per finished head + worker.heartbeat pid, phase, repo, sha, utc +/var/lib/aien-run/wt// the worker's detached worktree +/var/lib/aien-run/target//pr|main cargo target dir per trust class (sandbox user) +/usr/local/sbin/aien-run-exec the exec helper (INFRA) +``` + +`` is the last segment of the repository name +(`github.com/aien-dev/aien-sovereign-core` gives `aien-sovereign-core`). + +## Tests + +`cargo test -p aien-test` covers the planner (selection, sections, A1, A4, +removed gates, verdict algebra), the sandbox rewrite, status parsing, the +gate verdict of `verify-bundle`, the worker's name and sandbox rules, and in +`tests/local_ci.rs` the pipeline end to end on a throwaway repository: a +worker run that `verify` reports READY, then the refusals: an altered +receipt, a bad signature, a bundle presented for another commit, a required +check left out of a re-signed bundle, a hardware-scoped cached result under +`--release`, an executor whose key is not in `verify.pub`, a signing key +another uid cannot read, a signing key with mode 0644, an entry for another +check id, a receipt made from another manifest, `--sandbox none` without +`--dev-unsandboxed` or with `--github` (library and CLI), unsafe repository +names and commit ids, a status that is never `success` when the independent +check is not READY, GitHub down then back (fake `gh`), an outbox that +replays in queue order and stops at the first refusal, a trigger file served +by the loop, a head on main checked against its first parent, a bare +`exec: true` running, escaping exec paths refused and a symlinked exec that +leaves the tree never run, and, when the helper is installed, a gate and a +whole worker run in the user sandbox through `wt.sh` (in +`/var/lib/aien-run/wt/aien-test-selftest`, because the sandbox does not share +`/tmp`), a wrong target dir refused by the helper with exit 2 and never +counted as the program's exit, only a root-owned `wt.sh` link trusted, and +the user sandbox refused without the worktree tool. `mutations/run_mutants.sh` must +kill every line of `mutations/aien-test.mutants`. + +## Accepted limits (ENGINE-2 review, 2026-10-11) + +- A head that no branch names is fetched into the `wt.sh` mirror by its id; + its objects stay there unreferenced until git prunes them. The mirror is + readable by `aien-run`, like every other object in it. +- While a worktree is trusted, the worker sets `GIT_CONFIG_COUNT` and + `GIT_CONFIG_KEY_n` / `GIT_CONFIG_VALUE_n` on the git and crumb processes it + starts; a value of these variables in the worker's own environment is + replaced for those processes. +- The `main` target dir is not wiped after a FAIL or timeout yet (A2 asks for + it); the dir is owned by `aien-run`, so the wipe has to run through the + helper or `sudo -n rm -rf`. Until then a poisoned `main` target dir is + cleared by INFRA's `gc.sh` or by hand. +- `--dev-unsandboxed` runs are not marked in the bundle (the executor class + stays `spark`); only the journal and the command line show it. Never use + it on a machine whose bundles are published. +- A `cached` entry is trusted through the bundle signature; `verify` does not + reopen the receipt it was resolved from. +- `verify` has no `--operator`: a pipeline-configuration change is never + READY, also after the operator ran it by hand with `worker --operator`. The + operator merges such a change himself (A1). +- A head whose base is a root commit with no parent cannot be planned on the + base line (the worker reports an error, never PASS). +- Build time is `n/a` in the report. Total time comes from the bundle's + whole-second timestamps, so a run inside one second reports `0 ms`; the + per-gate test time is exact. diff --git a/tools/aien-test/mutations/aien-test.mutants b/tools/aien-test/mutations/aien-test.mutants index baa9b594..6b5257f0 100644 --- a/tools/aien-test/mutations/aien-test.mutants +++ b/tools/aien-test/mutations/aien-test.mutants @@ -1,6 +1,6 @@ # Mutations of tools/aien-test/src/*.rs. Format: idfilesed expressionwhat it models. # Each must be KILLED (a unit test fails) for run_mutants.sh to pass. -dirty_tree_not_refused runner.rs s#!before.is_empty() && !opts.allow_dirty#false# a dirty tree is no longer refused +dirty_tree_not_refused runner.rs s#!before.is_empty() && (!opts.allow_dirty || opts.release)#false# a dirty tree is no longer refused timeout_not_enforced process.rs s#rx.recv_timeout(spec.timeout)#rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected)# the wall-clock timeout never fires rule_mismatch_passes verdict.rs s#position(|r| !r.1)#position(|_r| false)# a failed expectation rule still yields PASS receipt_overwrite_allowed evidence.rs s#opts.write(true).create_new(true).mode(0o444);#opts.write(true).create(true).truncate(true).mode(0o444);# an existing receipt can be overwritten @@ -50,14 +50,14 @@ cache_blob_check_removed cache.rs s#Some(sha) if store.blob_exists(sha) => {}#So cache_never_ignored cache.rs s#if !cache_allowed {#if false {# a gate that says cache: never is reused anyway cache_reuse_keeps_old_commit cache.rs s#core\["commit"\] = json!(commit);#let _ = commit;# a reuse receipt still names the old commit, so the new commit looks unchecked cache_dirty_tree_looks_up runner.rs s#if mode == cache::Mode::Allow \&\& (opts.args_override.is_some() || !tree_clean) {#if false {# a tree with uncommitted changes (or replacement args) still consults the cache -cache_no_cache_ignored runner.rs s#cache::policy(m.cache_allowed, opts.no_cache)#cache::policy(m.cache_allowed, false)# --no-cache does not force a fresh run +cache_no_cache_ignored runner.rs s#cache::policy(m.cache_allowed, opts.no_cache || opts.release)#cache::policy(m.cache_allowed, opts.release)# --no-cache does not force a fresh run identity_machine_scope_ignored identity.rs s#CacheScope::Machine => b.machine_digest.clone(),#CacheScope::Machine => String::new(),# a machine-scoped check id no longer depends on the machine, so a result from another machine is reused identity_dependencies_dropped identity.rs s#"dependency_check_ids": deps,#"dependency_check_ids": Vec::::new(),# a check id ignores the checks it declares it depends on, so a changed dependency leaves it unchanged identity_compiler_ignored identity.rs s#"compiler_identity": compiler_identity,#"compiler_identity": "",# a different compiler gives the same check id identity_flags_ignored identity.rs s#"flags": flags,#"flags": Vec::::new(),# different build flags give the same check id identity_dependency_ids_unsorted identity.rs s#^ deps.sort();# let _ = \&deps;# the order the dependency ids are given in changes the check id identity_missing_input_dropped identity.rs s#rows.entry(spec.to_string()).or_insert(None);#let _ = spec;# a declared input that matches no tracked file leaves no trace in the identity -identity_golden_not_hashed identity.rs s#goldens.push(sha256_hex(&bytes));#let _ = \&bytes;# editing the golden file does not change the check id +identity_golden_not_hashed identity.rs s#Some(bytes) => goldens.push(sha256_hex(bytes)),#Some(bytes) => { let _ = bytes; }# editing the golden file does not change the check id planner_drops_dependencies identity.rs s#graph.with_dependencies(&seeds)#seeds.into_iter().collect()# path filtering selects the changed gate but drops the gates it declares it depends on v2_tolerance_without_bounded_allowed manifest.rs s#if tolerance.is_some() \&\& exactness != Exactness::Bounded {#if false {# a tolerance is accepted on an EXACT check v2_analog_eligible_for_exact manifest.rs s#if is_analog(b) \&\& exactness == Exactness::Exact {#if false {# an analog backend may be eligible for an EXACT check @@ -68,3 +68,13 @@ commit_not_checked bundle.rs s#if commit != expect.commit {#if false {# a bundle repo_not_checked bundle.rs s#if repo != expect.repository {#if false {# a bundle for another repository is accepted key_not_checked bundle.rs s#if pubkey != expect.pubkey_hex.trim() {#if false {# a bundle signed by an unknown key is accepted not_run_counts_as_pass bundle.rs s#if !(ran \&\& verdict == "PASS") {#if verdict == "FAIL" {# a required check that did not run no longer blocks PASS +success_without_ready worker.rs s#"success" if !ready => "error",#"success" if false => "error",# a bundle the independent check did not find READY is still posted as success +outbox_overtakes worker.rs s#Err(_) => return (posted, files.len() - i),#Err(_) => continue,# a newer queued status is posted before an older one that GitHub refused +key_mode_ignored worker.rs s#if mode & 0o077 != 0 {#if false {# the worker signs with a key other users can read +symlink_exec_escapes runner.rs s#(Ok(cp), Ok(cr)) => cp.starts_with(cr),#(Ok(_cp), Ok(_cr)) => true,# a symlinked run.exec that leads out of the repository is run +check_id_mismatch_ignored verify.rs s#if c\["check_id"\].as_str() != Some(e.check_id.as_str()) {#if false {# verify accepts a bundle entry for another check id +receipt_manifest_ignored verify.rs s#&& receipt_manifest(s) == manifest_digest =>#\&\& true =># verify counts a receipt made from another manifest +vacuous_pass_gates bundle.rs s#"PASS" if self.required == 0 => "NOT_RUN",#"PASS" if false => "NOT_RUN",# verify-bundle passes a bundle with no required checks +crumb_close_bad_action worker.rs s#^ "test",$# "done",# the worker closes its crumb claim with an action crumb refuses, so the claim stays open +sandbox_refusal_is_a_result runner.rs s#^ facts.exit_status = None;$# let _ = ();# a refusal by the exec helper (exit 2) counts as the program exiting 2 +wt_link_owner_ignored worker.rs s#|| md.uid() != 0 ## a worktree whose .git link the sandbox user owns is opened with the operator git diff --git a/tools/aien-test/src/bundle.rs b/tools/aien-test/src/bundle.rs index 59db8562..4cb468c8 100644 --- a/tools/aien-test/src/bundle.rs +++ b/tools/aien-test/src/bundle.rs @@ -133,6 +133,23 @@ pub struct Verified { pub checks: usize, pub required: usize, pub cached: usize, + /// The worker's `plan.verdict` member when the bundle carries one (signed + /// with the rest). None for a bundle without a plan member. + pub plan_verdict: Option, +} + +impl Verified { + /// What a gate may act on: PASS only when the algebra says PASS, at least + /// one required check exists (zero required checks is PASS only + /// vacuously: nothing vouches for the commit), and the plan member, when + /// present, says PASS too (an UNMAPPED or BLOCKED plan is NOT_RUN). + pub fn gate_verdict(&self) -> &str { + match self.verdict.as_str() { + "PASS" if self.required == 0 => "NOT_RUN", + "PASS" if self.plan_verdict.as_deref().is_some_and(|p| p != "PASS") => "NOT_RUN", + v => v, + } + } } /// What the gate expects the bundle to be about. @@ -493,6 +510,9 @@ pub fn verify(bundle: &Value, expect: &Expect) -> Result { checks: entries.len(), required: entries.iter().filter(|e| e.1).count(), cached: entries.iter().filter(|e| e.2 == "cached").count(), + plan_verdict: o + .get("plan") + .map(|p| p["verdict"].as_str().unwrap_or("NOT_RUN").to_string()), }) } @@ -594,11 +614,20 @@ fn cli_inner(argv: &[String]) -> Result { }; match verify(&bundle, &expect) { Ok(v) => { + let why = match (v.verdict.as_str(), v.gate_verdict()) { + ("PASS", "NOT_RUN") if v.required == 0 => { + " (no required checks: PASS only vacuously)".to_string() + } + ("PASS", "NOT_RUN") => { + format!(" (plan {})", v.plan_verdict.as_deref().unwrap_or("?")) + } + _ => String::new(), + }; println!( - "AIEN Verification: {} ({} checks, {} required, {} from cache) bundle {}", - v.verdict, v.checks, v.required, v.cached, v.digest + "AIEN Verification: {}{why} ({} checks, {} required, {} from cache) bundle {}", + v.gate_verdict(), v.checks, v.required, v.cached, v.digest ); - Ok(match v.verdict.as_str() { + Ok(match v.gate_verdict() { "PASS" => 0, "FAIL" => 1, _ => 2, @@ -903,4 +932,29 @@ mod tests { assert!(hex_decode("abc").is_none()); assert!(hex_decode("zz").is_none()); } + + #[test] + fn gate_verdict_is_never_a_vacuous_pass() { + let v = |verdict: &str, required: usize, plan: Option<&str>| Verified { + verdict: verdict.to_string(), + digest: String::new(), + checks: required, + required, + cached: 0, + plan_verdict: plan.map(str::to_string), + }; + assert_eq!(v("PASS", 1, None).gate_verdict(), "PASS"); + assert_eq!(v("PASS", 1, Some("PASS")).gate_verdict(), "PASS"); + // Nothing required: PASS only vacuously. + assert_eq!(v("PASS", 0, None).gate_verdict(), "NOT_RUN"); + assert_eq!(v("PASS", 0, Some("PASS")).gate_verdict(), "NOT_RUN"); + // The worker's plan says UNMAPPED or BLOCKED. + assert_eq!(v("PASS", 2, Some("NOT_RUN")).gate_verdict(), "NOT_RUN"); + assert_eq!( + v("PASS", 2, Some("BLOCKED_OPERATOR")).gate_verdict(), + "NOT_RUN" + ); + assert_eq!(v("FAIL", 2, Some("NOT_RUN")).gate_verdict(), "FAIL"); + assert_eq!(v("NOT_RUN", 2, Some("PASS")).gate_verdict(), "NOT_RUN"); + } } diff --git a/tools/aien-test/src/cache.rs b/tools/aien-test/src/cache.rs index 5263a0ed..67170968 100644 --- a/tools/aien-test/src/cache.rs +++ b/tools/aien-test/src/cache.rs @@ -385,7 +385,7 @@ pub fn explain_chain( "cache: miss, it depends on {first}, which would run again, so its receipt would change" )); } else { - match runner::identity(root, &node.path, m, &opts.hardware) { + match runner::identity(root, &node.path, m, &opts.hardware, opts.sandbox) { Err(e) => lines.push(format!("cache: miss, cannot digest the inputs ({e})")), Ok(id) => { let deps: Vec<(String, String)> = m diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs index 7d25d69e..5bb70d97 100644 --- a/tools/aien-test/src/cli.rs +++ b/tools/aien-test/src/cli.rs @@ -1,27 +1,38 @@ -//! Argument parsing for the `aien-test` commands (ADR 0028 Decision 1 and 8). -//! Hand-written; the surface is small. +//! Argument parsing for the `aien-test` commands (ADR 0028 Decision 1 and 8, +//! ADR 0033 Decisions 10 and 12). Hand-written; the surface is small. //! //! ```text //! aien-test run GATE_FILE_OR_NAME [flags] [-- ARGS...] -//! aien-test test ./... | gate:NAME [flags] +//! aien-test test ./... | gate:NAME | changed | crate:NAME [flags] //! aien-test why GATE_FILE_OR_NAME [flags] //! aien-test list [flags] //! aien-test identity GATE_FILE_OR_NAME [--compiler-identity S] [--flag F]... [--hardware-identity S] +//! aien-test plan [--base REF] [--repo NAME] [--operator] [--allow-dirty] +//! aien-test status [--state-dir DIR] +//! aien-test verify COMMIT [--repo NAME] [--base REF] [--state-dir DIR] [--release] +//! aien-test worker [--once REPO SHA] [--poll SECS] [--repos LIST] [--github] [--iterations N] +//! [--state-dir DIR] [--key FILE] [--clones DIR] [--wt-root DIR] [--wt-tool FILE] [--sandbox user|none --dev-unsandboxed] //! ``` //! -//! `test changed`, `test crate:NAME`, `--host/--qemu/--gb10`, `--mutants` and -//! `--release` come in later slices and are refused here. +//! `--host/--qemu/--gb10` and `--mutants` are later slices and are refused. use crate::resources::{parse_jobs, JobsSpec}; +use crate::sandbox::Sandbox; use std::path::PathBuf; pub const USAGE: &str = "usage: aien-test run GATE_FILE_OR_NAME [flags] [-- ARGS...] - aien-test test ./... | gate:NAME [flags] + aien-test test ./... | gate:NAME | changed | crate:NAME [flags] aien-test why GATE_FILE_OR_NAME [flags] aien-test list [flags] aien-test identity GATE_FILE_OR_NAME [--compiler-identity S] [--flag F]... [--hardware-identity S] -flags: --evidence-dir DIR --allow-dirty --no-cache --jobs host=N,qemu=M --wait-gpu"; + aien-test plan [--base REF] [--repo NAME] [--operator] [--allow-dirty] + aien-test status [--state-dir DIR] + aien-test verify COMMIT [--repo NAME] [--base REF] [--state-dir DIR] [--release] + aien-test worker [--once REPO SHA] [--poll SECS] [--repos A,B] [--github] [--iterations N] + [--state-dir DIR] [--key FILE] [--clones DIR] [--wt-root DIR] [--wt-tool FILE] [--sandbox user|none --dev-unsandboxed] +flags: --evidence-dir DIR --allow-dirty --no-cache --release --jobs host=N,qemu=M --wait-gpu + --sandbox none|user --base REF --operator"; /// Which gates `test` runs. #[derive(Debug, Clone, PartialEq, Eq)] @@ -30,6 +41,10 @@ pub enum Selection { All, /// `gate:NAME`: that gate and everything it depends on. Gate(String), + /// `changed`: what the planner selects for BASE..HEAD. + Changed, + /// `crate:NAME`: the gates covering a workspace crate and its dependents. + Crate(String), } #[derive(Debug, Clone, PartialEq, Eq)] @@ -39,6 +54,10 @@ pub enum Command { Why { gate: String }, List, Identity { gate: String }, + Plan, + Status, + Verify { commit: String }, + Worker, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -48,6 +67,9 @@ pub struct Cli { pub allow_dirty: bool, /// `--no-cache`: never reuse an earlier result; run every gate fresh. pub no_cache: bool, + /// `--release`: qualification mode (no cache, clean tree, no + /// hardware-scoped cache entries accepted by `verify`). + pub release: bool, /// Arguments after `--`; they replace `run.args` (CR-061). `run` only. pub args: Option>, /// `--jobs host=N,qemu=M`: the pool sizes that were named. @@ -61,32 +83,93 @@ pub struct Cli { pub flags: Vec, /// `identity` only: needed for `cache_scope: hardware`. pub hardware_identity: Option, + /// `--sandbox none|user` (C8), default none. + pub sandbox: Sandbox, + /// Whether `--sandbox` was given (the worker defaults to `user`). + pub sandbox_given: bool, + /// worker: `--dev-unsandboxed`: allow `--sandbox none` (development only). + pub dev_unsandboxed: bool, + /// `--base REF` for plan, test changed, verify. + pub base: Option, + /// `--repo NAME`: the repository name for bundles. + pub repo: Option, + /// `--operator`: allow a pipeline configuration change. + pub operator: bool, + /// `--state-dir DIR`: the local CI state (default `~/.local/state/aien-local-ci`). + pub state_dir: Option, + /// worker: `--key FILE` (default `~/.aien/verify.key`). + pub key: Option, + /// worker: `--clones DIR` where the trusted clones live (default `~/workspace`). + pub clones: Option, + /// worker: `--wt-root DIR` where detached worktrees go (default `/var/lib/aien-run/wt`). + pub wt_root: Option, + /// worker: `--wt-tool FILE` INFRA's worktree tool (default + /// `/aien-sovereign-core/tools/aien-local-ci/wt.sh`). + pub wt_tool: Option, + /// worker: `--once REPO SHA`. + pub once: Option<(String, String)>, + /// worker: `--poll SECS` (default 30). + pub poll: Option, + /// worker: `--repos A,B`. + pub repos: Vec, + /// worker: `--github`: poll GitHub and post commit statuses. + pub github: bool, + /// worker: `--iterations N`: stop the loop after N rounds (0: forever). + pub iterations: Option, } fn parse_selection(s: &str) -> Result { if s == "./..." { return Ok(Selection::All); } + if s == "changed" { + return Ok(Selection::Changed); + } + if let Some(name) = s.strip_prefix("crate:") { + if name.is_empty() { + return Err("crate: needs a crate name".to_string()); + } + return Ok(Selection::Crate(name.to_string())); + } match s.strip_prefix("gate:") { Some(name) if !name.is_empty() => Ok(Selection::Gate(name.to_string())), _ => Err(format!( - "unsupported test selection {s:?}: only ./... and gate:NAME exist so far" + "unsupported test selection {s:?}: use ./..., gate:NAME, changed or crate:NAME" )), } } +const COMMANDS: [&str; 9] = [ + "run", "test", "why", "list", "identity", "plan", "status", "verify", "worker", +]; +const WORKER_FLAGS: [&str; 12] = [ + "--dev-unsandboxed", + "--key", + "--clones", + "--wt-root", + "--wt-tool", + "--once", + "--poll", + "--repos", + "--github", + "--iterations", + "--state-dir", + "--sandbox", +]; + pub fn parse_args(argv: &[String]) -> Result { let name = argv .first() .map(|s| s.as_str()) .ok_or_else(|| "no command".to_string())?; - if !["run", "test", "why", "list", "identity"].contains(&name) { + if !COMMANDS.contains(&name) { return Err(format!("unknown command {name:?}")); } let mut positional: Option = None; let mut evidence_dir: Option = None; let mut allow_dirty = false; let mut no_cache = false; + let mut release = false; let mut args: Option> = None; let mut jobs = JobsSpec::default(); let mut wait_gpu = false; @@ -94,31 +177,42 @@ pub fn parse_args(argv: &[String]) -> Result { let mut flags: Vec = Vec::new(); let mut hardware_identity: Option = None; let mut identity_flags = false; + let mut sandbox = Sandbox::None; + let mut sandbox_given = false; + let mut dev_unsandboxed = false; + let mut base: Option = None; + let mut repo: Option = None; + let mut operator = false; + let mut state_dir: Option = None; + let mut key: Option = None; + let mut clones: Option = None; + let mut wt_root: Option = None; + let mut wt_tool: Option = None; + let mut once: Option<(String, String)> = None; + let mut poll: Option = None; + let mut repos: Vec = Vec::new(); + let mut github = false; + let mut iterations: Option = None; + let mut worker_flags: Vec<&str> = Vec::new(); let mut i = 1; + let value = |i: &mut usize, a: &str| -> Result { + *i += 1; + argv.get(*i) + .cloned() + .ok_or_else(|| format!("{a} needs a value")) + }; while i < argv.len() { let a = argv[i].as_str(); if a == "--" { args = Some(argv[i + 1..].to_vec()); break; } else if a == "--evidence-dir" { - i += 1; - match argv.get(i) { - Some(v) => evidence_dir = Some(PathBuf::from(v)), - None => return Err("--evidence-dir needs a value".to_string()), - } + evidence_dir = Some(PathBuf::from(value(&mut i, a)?)); } else if a == "--jobs" { - i += 1; - match argv.get(i) { - Some(v) => jobs = parse_jobs(v)?, - None => return Err("--jobs needs a value".to_string()), - } + jobs = parse_jobs(&value(&mut i, a)?)?; } else if a == "--compiler-identity" || a == "--flag" || a == "--hardware-identity" { identity_flags = true; - i += 1; - let v = match argv.get(i) { - Some(v) => v.clone(), - None => return Err(format!("{a} needs a value")), - }; + let v = value(&mut i, a)?; match a { "--compiler-identity" => compiler_identity = v, "--flag" => flags.push(v), @@ -128,8 +222,68 @@ pub fn parse_args(argv: &[String]) -> Result { allow_dirty = true; } else if a == "--no-cache" { no_cache = true; + } else if a == "--release" { + release = true; } else if a == "--wait-gpu" { wait_gpu = true; + } else if a == "--operator" { + operator = true; + } else if a == "--base" { + base = Some(value(&mut i, a)?); + } else if a == "--repo" { + repo = Some(value(&mut i, a)?); + } else if a == "--sandbox" { + sandbox = Sandbox::parse(&value(&mut i, a)?)?; + sandbox_given = true; + } else if a == "--state-dir" { + state_dir = Some(PathBuf::from(value(&mut i, a)?)); + } else if a == "--key" { + worker_flags.push("--key"); + key = Some(PathBuf::from(value(&mut i, a)?)); + } else if a == "--clones" { + worker_flags.push("--clones"); + clones = Some(PathBuf::from(value(&mut i, a)?)); + } else if a == "--wt-root" { + worker_flags.push("--wt-root"); + wt_root = Some(PathBuf::from(value(&mut i, a)?)); + } else if a == "--wt-tool" { + worker_flags.push("--wt-tool"); + wt_tool = Some(PathBuf::from(value(&mut i, a)?)); + } else if a == "--once" { + worker_flags.push("--once"); + let r = value(&mut i, a)?; + let s = value(&mut i, a)?; + if s.len() != 40 || !s.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("--once needs REPO and a 40-hex SHA".to_string()); + } + once = Some((r, s.to_ascii_lowercase())); + } else if a == "--poll" { + worker_flags.push("--poll"); + let v = value(&mut i, a)?; + poll = Some( + v.parse::() + .map_err(|_| format!("--poll needs seconds, not {v:?}"))?, + ); + } else if a == "--iterations" { + worker_flags.push("--iterations"); + let v = value(&mut i, a)?; + iterations = Some( + v.parse::() + .map_err(|_| format!("--iterations needs a number, not {v:?}"))?, + ); + } else if a == "--repos" { + worker_flags.push("--repos"); + repos = value(&mut i, a)? + .split(',') + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect(); + } else if a == "--dev-unsandboxed" { + worker_flags.push("--dev-unsandboxed"); + dev_unsandboxed = true; + } else if a == "--github" { + worker_flags.push("--github"); + github = true; } else if a.starts_with('-') { return Err(format!("unknown argument {a:?}")); } else if positional.is_none() { @@ -142,12 +296,35 @@ pub fn parse_args(argv: &[String]) -> Result { if args.is_some() && name != "run" { return Err("-- ARGS only apply to the run command".to_string()); } - if identity_flags && name != "identity" { + if identity_flags && !["identity", "plan", "verify", "worker"].contains(&name) { return Err( - "--compiler-identity, --flag and --hardware-identity only apply to identity" + "--compiler-identity, --flag and --hardware-identity only apply to identity, plan, verify and worker" .to_string(), ); } + if name != "worker" { + if let Some(f) = worker_flags + .iter() + .find(|f| WORKER_FLAGS.contains(f) && !["--state-dir", "--sandbox"].contains(f)) + { + return Err(format!("{f} only applies to worker")); + } + } + if sandbox != Sandbox::None && !["run", "test", "worker"].contains(&name) { + return Err("--sandbox only applies to run, test and worker".to_string()); + } + if base.is_some() && !["plan", "test", "verify", "worker"].contains(&name) { + return Err("--base only applies to plan, test, verify and worker".to_string()); + } + if operator && !["plan", "test", "worker"].contains(&name) { + return Err("--operator only applies to plan, test and worker".to_string()); + } + if repo.is_some() && !["plan", "verify", "worker"].contains(&name) { + return Err("--repo only applies to plan, verify and worker".to_string()); + } + if state_dir.is_some() && !["status", "verify", "worker"].contains(&name) { + return Err("--state-dir only applies to status, verify and worker".to_string()); + } let command = match name { "identity" => Command::Identity { gate: positional.ok_or("missing GATE_FILE_OR_NAME")?, @@ -159,14 +336,23 @@ pub fn parse_args(argv: &[String]) -> Result { gate: positional.ok_or("missing GATE_FILE_OR_NAME")?, }, "test" => { - let selection = positional.ok_or("missing ./... or gate:NAME")?; + let selection = positional.ok_or("missing ./..., gate:NAME, changed or crate:NAME")?; Command::Test(parse_selection(&selection)?) } + "verify" => { + let commit = positional.ok_or("missing COMMIT")?; + Command::Verify { commit } + } _ => { if let Some(p) = positional { return Err(format!("unexpected argument {p:?}")); } - Command::List + match name { + "plan" => Command::Plan, + "status" => Command::Status, + "worker" => Command::Worker, + _ => Command::List, + } } }; Ok(Cli { @@ -174,12 +360,29 @@ pub fn parse_args(argv: &[String]) -> Result { evidence_dir, allow_dirty, no_cache, + release, args, jobs, wait_gpu, compiler_identity, flags, hardware_identity, + sandbox, + sandbox_given, + dev_unsandboxed, + base, + repo, + operator, + state_dir, + key, + clones, + wt_root, + wt_tool, + once, + poll, + repos, + github, + iterations, }) } @@ -204,10 +407,14 @@ mod tests { assert_eq!(run_gate(&c), "G"); assert!(!c.allow_dirty); assert!(!c.no_cache); + assert!(!c.release); assert!(!c.wait_gpu); assert_eq!(c.args, None); assert_eq!(c.evidence_dir, None); assert_eq!(c.jobs, JobsSpec::default()); + assert_eq!(c.sandbox, Sandbox::None); + assert_eq!(c.base, None); + assert!(!c.operator); } #[test] @@ -230,14 +437,16 @@ mod tests { } #[test] - fn no_cache_flag() { + fn no_cache_and_release_flags() { let c = parse_args(&v(&["run", "G", "--no-cache"])).unwrap(); assert!(c.no_cache); let c = parse_args(&v(&["test", "--no-cache", "./..."])).unwrap(); assert!(c.no_cache); assert_eq!(c.command, Command::Test(Selection::All)); - // --release (qualification mode) is a later slice and stays refused. - assert!(parse_args(&v(&["run", "G", "--release"])).is_err()); + let c = parse_args(&v(&["run", "G", "--release"])).unwrap(); + assert!(c.release && !c.no_cache); + let c = parse_args(&v(&["verify", "a".repeat(40).as_str(), "--release"])).unwrap(); + assert!(c.release); } #[test] @@ -252,11 +461,19 @@ mod tests { assert_eq!(c.command, Command::Test(Selection::All)); let c = parse_args(&v(&["test", "gate:G-1"])).unwrap(); assert_eq!(c.command, Command::Test(Selection::Gate("G-1".to_string()))); + let c = parse_args(&v(&["test", "changed", "--base", "origin/main"])).unwrap(); + assert_eq!(c.command, Command::Test(Selection::Changed)); + assert_eq!(c.base.as_deref(), Some("origin/main")); + let c = parse_args(&v(&["test", "crate:aien-runtime"])).unwrap(); + assert_eq!( + c.command, + Command::Test(Selection::Crate("aien-runtime".into())) + ); } #[test] fn unsupported_selections_are_refused() { - for bad in ["changed", "crate:x", "gate:", "G", "./", "."] { + for bad in ["crate:", "gate:", "G", "./", ".", "changed:x"] { assert!(parse_args(&v(&["test", bad])).is_err(), "{bad}"); } assert!(parse_args(&v(&["test"])).is_err()); @@ -337,6 +554,99 @@ mod tests { assert!(parse_args(&v(&["why", "G", "--", "x"])).is_err()); } + #[test] + fn sandbox_flag() { + let c = parse_args(&v(&["run", "G", "--sandbox", "user"])).unwrap(); + assert_eq!(c.sandbox, Sandbox::User); + let c = parse_args(&v(&["test", "changed", "--sandbox", "none"])).unwrap(); + assert_eq!(c.sandbox, Sandbox::None); + assert!(parse_args(&v(&["run", "G", "--sandbox", "root"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--sandbox"])).is_err()); + assert!(parse_args(&v(&["list", "--sandbox", "user"])).is_err()); + } + + #[test] + fn plan_status_verify() { + let c = parse_args(&v(&[ + "plan", + "--base", + "main", + "--repo", + "github.com/a/b", + "--operator", + "--allow-dirty", + ])) + .unwrap(); + assert_eq!(c.command, Command::Plan); + assert_eq!(c.base.as_deref(), Some("main")); + assert_eq!(c.repo.as_deref(), Some("github.com/a/b")); + assert!(c.operator && c.allow_dirty); + assert!(parse_args(&v(&["plan", "extra"])).is_err()); + let c = parse_args(&v(&["status", "--state-dir", "/s"])).unwrap(); + assert_eq!(c.command, Command::Status); + assert_eq!(c.state_dir, Some(PathBuf::from("/s"))); + let sha = "b".repeat(40); + let c = parse_args(&v(&["verify", &sha, "--repo", "x", "--base", "main"])).unwrap(); + assert_eq!( + c.command, + Command::Verify { + commit: sha.clone() + } + ); + assert!(parse_args(&v(&["verify"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--base", "x"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--operator"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--state-dir", "/s"])).is_err()); + assert!(parse_args(&v(&["list", "--repo", "x"])).is_err()); + } + + #[test] + fn worker_flags() { + let sha = "c".repeat(40); + let c = parse_args(&v(&[ + "worker", + "--once", + "repo", + &sha, + "--poll", + "5", + "--repos", + "a,b", + "--github", + "--iterations", + "3", + "--state-dir", + "/s", + "--key", + "/k", + "--clones", + "/c", + "--wt-root", + "/w", + "--wt-tool", + "/t/wt.sh", + "--sandbox", + "user", + ])) + .unwrap(); + assert_eq!(c.command, Command::Worker); + assert_eq!(c.once, Some(("repo".to_string(), sha.clone()))); + assert_eq!(c.poll, Some(5)); + assert_eq!(c.repos, v(&["a", "b"])); + assert!(c.github); + assert_eq!(c.iterations, Some(3)); + assert_eq!(c.key, Some(PathBuf::from("/k"))); + assert_eq!(c.clones, Some(PathBuf::from("/c"))); + assert_eq!(c.wt_root, Some(PathBuf::from("/w"))); + assert_eq!(c.wt_tool, Some(PathBuf::from("/t/wt.sh"))); + assert_eq!(c.sandbox, Sandbox::User); + assert!(parse_args(&v(&["worker", "--once", "repo", "short"])).is_err()); + assert!(parse_args(&v(&["worker", "--poll", "x"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--poll", "5"])).is_err()); + assert!(parse_args(&v(&["plan", "--github"])).is_err()); + assert!(parse_args(&v(&["worker", "extra"])).is_err()); + } + #[test] fn errors() { assert!(parse_args(&[]).is_err()); diff --git a/tools/aien-test/src/evidence.rs b/tools/aien-test/src/evidence.rs index 1c425e6e..40b222b7 100644 --- a/tools/aien-test/src/evidence.rs +++ b/tools/aien-test/src/evidence.rs @@ -409,6 +409,44 @@ pub fn utc_string(secs: u64) -> String { ) } +/// The inverse of `utc_string`: seconds since the Unix epoch for a +/// `YYYY-MM-DDTHH:MM:SSZ` string; None for anything else. +pub fn utc_secs(s: &str) -> Option { + let b = s.as_bytes(); + if b.len() != 20 + || b[4] != b'-' + || b[7] != b'-' + || b[10] != b'T' + || b[13] != b':' + || b[16] != b':' + || b[19] != b'Z' + { + return None; + } + let num = |from: usize, to: usize| -> Option { + let t = &s[from..to]; + if !t.bytes().all(|c| c.is_ascii_digit()) { + return None; + } + t.parse::().ok() + }; + let (y, m, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); + let (hh, mm, ss) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); + if !(1..=12).contains(&m) || !(1..=31).contains(&d) || hh > 23 || mm > 59 || ss > 59 { + return None; + } + // Howard Hinnant's days-from-civil algorithm. + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y.rem_euclid(400); + let mp = if m > 2 { m - 3 } else { m + 9 }; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + let secs = days * 86_400 + hh * 3600 + mm * 60 + ss; + u64::try_from(secs).ok() +} + #[cfg(test)] mod tests { use super::*; @@ -645,3 +683,35 @@ mod tests { assert_eq!(leftovers, 0, "no temp file may be left behind"); } } + +#[cfg(test)] +mod utc_tests { + use super::*; + + #[test] + fn utc_secs_inverts_utc_string() { + for secs in [ + 0u64, + 1, + 86_399, + 86_400, + 951_782_400, + 1_700_000_000, + 1_791_000_000, + 4_102_444_800, + ] { + assert_eq!(utc_secs(&utc_string(secs)), Some(secs), "{secs}"); + } + assert_eq!(utc_secs("2026-10-11T00:00:00Z"), Some(1_791_676_800)); + for bad in [ + "", + "2026-10-11", + "2026-10-11T00:00:00", + "2026-13-11T00:00:00Z", + "x026-10-11T00:00:00Z", + "2026-10-11T24:00:00Z", + ] { + assert_eq!(utc_secs(bad), None, "{bad}"); + } + } +} diff --git a/tools/aien-test/src/identity.rs b/tools/aien-test/src/identity.rs index 5a18c918..3109689d 100644 --- a/tools/aien-test/src/identity.rs +++ b/tools/aien-test/src/identity.rs @@ -23,7 +23,6 @@ use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::Path; -use std::process::Command; /// What the `scope_binding` member is built from. Only the part the manifest's /// `cache_scope` names is used. @@ -39,7 +38,7 @@ pub struct Binding { } fn git_ls_files(root: &Path, spec: &str) -> Result, String> { - let mut cmd = Command::new("git"); + let mut cmd = process::git_command(); cmd.env("GIT_OPTIONAL_LOCKS", "0") .arg("-C") .arg(root) @@ -115,10 +114,40 @@ pub fn declared_dependencies(m: &Manifest) -> Vec { set.into_iter().collect() } -/// The object that `check_id` hashes. -pub fn identity_object( +/// `input_blob_ids` computed from rows already read from a tree +/// (`git ls-tree -r COMMIT`), so a planner can identify a check at a commit +/// that is not checked out. Same shape and order as `input_blob_ids`. +pub fn input_blob_ids_from_rows(m: &Manifest, tree: &BTreeMap) -> Vec { + let mut rows: BTreeMap> = BTreeMap::new(); + for input in &m.inputs { + let spec = input.trim_end_matches('/'); + let prefix = format!("{spec}/"); + let mut found = false; + for (path, blob) in tree.range(spec.to_string()..) { + if path == spec || path.starts_with(&prefix) { + rows.insert(path.clone(), Some(blob.clone())); + found = true; + } else if !path.starts_with(spec) { + break; + } + } + if !found { + rows.entry(spec.to_string()).or_insert(None); + } + } + rows.into_iter() + .map(|(path, blob)| json!({ "path": path, "blob_id": blob })) + .collect() +} + +/// The identity object from parts already read: `inputs` as `input_blob_ids` +/// gives them, `golden` the bytes of the oracle golden file if the manifest +/// names one. `identity_object` and the planner both build on this so the +/// hashed shape has one definition. +pub fn identity_object_from_parts( m: &Manifest, - root: &Path, + input_blob_ids: Vec, + golden: Option<&[u8]>, compiler_identity: &str, flags: &[String], dependency_check_ids: &[String], @@ -127,14 +156,21 @@ pub fn identity_object( let mut deps: Vec = dependency_check_ids.to_vec(); deps.sort(); let mut goldens: Vec = Vec::new(); - if let Some(g) = &m.oracle.golden { - let bytes = fs::read(root.join(g)).map_err(|e| format!("cannot read golden {g}: {e}"))?; - goldens.push(sha256_hex(&bytes)); + if m.oracle.golden.is_some() { + match golden { + Some(bytes) => goldens.push(sha256_hex(bytes)), + None => { + return Err(format!( + "golden file {} is missing", + m.oracle.golden.as_deref().unwrap_or("") + )) + } + } } goldens.sort(); Ok(json!({ "manifest_digest": m.digest, - "input_blob_ids": input_blob_ids(m, root)?, + "input_blob_ids": input_blob_ids, "compiler_identity": compiler_identity, "flags": flags, "dependency_check_ids": deps, @@ -143,6 +179,32 @@ pub fn identity_object( })) } +/// The object that `check_id` hashes. +pub fn identity_object( + m: &Manifest, + root: &Path, + compiler_identity: &str, + flags: &[String], + dependency_check_ids: &[String], + binding: &Binding, +) -> Result { + let golden = match &m.oracle.golden { + Some(g) => { + Some(fs::read(root.join(g)).map_err(|e| format!("cannot read golden {g}: {e}"))?) + } + None => None, + }; + identity_object_from_parts( + m, + input_blob_ids(m, root)?, + golden.as_deref(), + compiler_identity, + flags, + dependency_check_ids, + binding, + ) +} + pub fn id_of(object: &Value) -> Result { let bytes = canonical(object).map_err(|e| e.to_string())?; Ok(sha256_hex(&bytes)) @@ -246,6 +308,7 @@ mod tests { use crate::graph; use crate::manifest; use crate::testutil::{git, init_repo, write_file, TempDir}; + use std::process::Command; fn gate(id: &str, extra: &str) -> String { format!( @@ -511,3 +574,53 @@ mod tests { assert_eq!(declared_dependencies(&m), ["B", "C"]); } } + +#[cfg(test)] +mod rows_tests { + use super::*; + use crate::manifest; + use crate::testutil::init_repo; + use std::process::Command; + + #[test] + fn rows_from_a_tree_listing_give_the_same_identity_as_the_index() { + let g = "gate: A\nmanifest_version: 2\nowner: t\nrequires:\n - host\ninputs:\n - data/\n - missing.txt\nrun:\n exec: run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 5s\n"; + let t = init_repo( + "ident-rows", + &[ + ("a.gate", g, false), + ("run.sh", "#!/bin/sh\n", true), + ("data/one.txt", "one\n", false), + ("data/sub/two.txt", "two\n", false), + ("data2/three.txt", "three\n", false), + ], + ); + let m = manifest::parse(g.as_bytes()).unwrap(); + let from_index = input_blob_ids(&m, t.path()).unwrap(); + let mut cmd = Command::new("git"); + cmd.arg("-C").arg(t.path()).args(["ls-tree", "-r", "HEAD"]); + let out = process::output_gated(&mut cmd).unwrap(); + let mut tree = BTreeMap::new(); + for line in String::from_utf8_lossy(&out.stdout).lines() { + let (meta, path) = line.split_once('\t').unwrap(); + let blob = meta.split(' ').nth(2).unwrap(); + tree.insert(path.to_string(), blob.to_string()); + } + let from_rows = input_blob_ids_from_rows(&m, &tree); + assert_eq!(from_index, from_rows); + let paths: Vec<&str> = from_rows + .iter() + .map(|r| r["path"].as_str().unwrap()) + .collect(); + assert_eq!(paths, ["data/one.txt", "data/sub/two.txt", "missing.txt"]); + assert!(from_rows[2]["blob_id"].is_null()); + let b = Binding { + arch: "a".into(), + machine_digest: "m".repeat(64), + hardware_identity: String::new(), + }; + let a = identity_object(&m, t.path(), "c", &[], &[], &b).unwrap(); + let r = identity_object_from_parts(&m, from_rows, None, "c", &[], &[], &b).unwrap(); + assert_eq!(a, r); + } +} diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs index 0463dfc6..a2b449b0 100644 --- a/tools/aien-test/src/lib.rs +++ b/tools/aien-test/src/lib.rs @@ -43,11 +43,16 @@ pub mod evidence; pub mod graph; pub mod identity; pub mod manifest; +pub mod plan; pub mod process; pub mod resources; pub mod runner; +pub mod sandbox; +pub mod status; pub mod verdict; +pub mod verify; pub mod why; +pub mod worker; #[cfg(test)] pub mod testutil; diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs index 865f2420..00d94db9 100644 --- a/tools/aien-test/src/main.rs +++ b/tools/aien-test/src/main.rs @@ -9,17 +9,25 @@ //! - `list`: list the gates and their dependencies. //! - `identity GATE`: print the check id (ADR 0033 Decision 3) and the object it //! hashed, for the gate and everything it depends on. +//! - `plan`, `test changed`, `test crate:NAME`: the planner (ADR 0033 Decision 12). +//! - `status`, `verify COMMIT`, `worker`: the local pipeline (Decisions 9, 10). use aien_test::bundle; use aien_test::cli::{parse_args, Cli, Command, Selection, USAGE}; use aien_test::evidence::{Index, Store}; use aien_test::graph::{self, GraphError}; use aien_test::identity; +use aien_test::plan::{self, Request}; use aien_test::runner::{self, CacheNote, Options, RunError}; +use aien_test::sandbox::Sandbox; +use aien_test::status; use aien_test::verdict::Verdict; +use aien_test::verify; use aien_test::why; +use aien_test::worker::{self, StateDir}; use std::collections::BTreeSet; use std::path::{Path, PathBuf}; +use std::time::Duration; fn main() { std::process::exit(real_main()); @@ -52,6 +60,10 @@ fn real_main() -> i32 { Command::Why { gate } => cmd_why(&cli, gate, &cwd), Command::List => cmd_list(&cwd), Command::Identity { gate } => cmd_identity(&cli, gate, &cwd), + Command::Plan => cmd_plan(&cli, &cwd), + Command::Status => cmd_status(&cli), + Command::Verify { commit } => cmd_verify(&cli, commit, &cwd), + Command::Worker => cmd_worker(&cli), } } @@ -73,6 +85,9 @@ fn options(cli: &Cli, root: &Path) -> Result { opts.args_override = cli.args.clone(); opts.pool_sizes = opts.pool_sizes.with(cli.jobs); opts.gpu.wait = cli.wait_gpu; + opts.sandbox = cli.sandbox; + opts.release = cli.release; + opts.cargo_target_dir = std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from); Ok(opts) } @@ -170,6 +185,42 @@ fn cmd_test(cli: &Cli, selection: &Selection, cwd: &Path) -> i32 { return 1; } }, + Selection::Changed => { + let p = match plan_for(cli, &root) { + Ok(p) => p, + Err(code) => return code, + }; + for line in plan::render(&plan::repository_name(&root, cli.repo.as_deref()), &p) { + println!("{line}"); + } + let code = plan::exit_code(&p); + if code != 0 { + println!( + "AIEN_TEST: {}", + if code == 4 { + "BLOCKED_OPERATOR" + } else { + "NOT_RUN" + } + ); + return code; + } + p.entries + .iter() + .filter(|e| e.section != plan::Section::Blocked) + .filter_map(|e| graph.index_of(&e.gate)) + .collect() + } + Selection::Crate(name) => match plan::crate_dirs(&root, name) { + Ok(dirs) => { + println!("CRATE {name} dirs {}", dirs.join(" ")); + plan::select_for_dirs(&graph, &dirs) + } + Err(e) => { + println!("AIEN_TEST: FAIL {e}"); + return 1; + } + }, }; if chosen.is_empty() { println!("AIEN_TEST: NOT_RUN no gates found under {}", root.display()); @@ -317,3 +368,215 @@ fn cmd_list(cwd: &Path) -> i32 { println!("{} gates", graph.len()); 0 } + +/// The planner request for this checkout: BASE from `--base` (default +/// `origin/main`, then `main`), HEAD from the checkout; `--allow-dirty` adds +/// the uncommitted changes. +fn plan_for(cli: &Cli, root: &Path) -> Result { + let head = runner::head(root).map_err(|e| { + println!("AIEN_TEST: FAIL {e}"); + 1 + })?; + let base = match &cli.base { + Some(b) => plan::resolve(root, b), + None => plan::resolve_first(root, &["origin/main", "main"]), + } + .map_err(|e| { + println!("AIEN_TEST: FAIL {e}"); + 1 + })?; + let mut req = Request::new(&base, &head); + req.operator = cli.operator; + req.compiler_identity = cli.compiler_identity.clone(); + req.flags = cli.flags.clone(); + req.hardware_identity = cli.hardware_identity.clone().unwrap_or_default(); + let dirty = plan::uncommitted(root).map_err(|e| { + println!("AIEN_TEST: FAIL {e}"); + 1 + })?; + if !dirty.is_empty() { + if !cli.allow_dirty { + println!( + "AIEN_TEST: NOT_RUN dirty_tree ({} uncommitted paths; use --allow-dirty to plan them)", + dirty.len() + ); + return Err(2); + } + req.dirty = dirty; + } + plan::compute(root, &req).map_err(|e| { + println!("AIEN_TEST: FAIL {e}"); + 1 + }) +} + +fn cmd_plan(cli: &Cli, cwd: &Path) -> i32 { + let root = match repo_root_or_report(cwd) { + Ok(r) => r, + Err(code) => return code, + }; + let mut p = match plan_for(cli, &root) { + Ok(p) => p, + Err(code) => return code, + }; + // Say which selected gates the evidence cache already settles. + if let Ok(opts) = options(cli, &root) { + let cached = plan::probe_cached(&root, &p.graph, &opts); + if !cached.is_empty() { + for e in p.entries.iter_mut() { + if e.section == plan::Section::Required && cached.contains(&e.gate) { + e.section = plan::Section::Cached; + } + } + } + } + for line in plan::render(&plan::repository_name(&root, cli.repo.as_deref()), &p) { + println!("{line}"); + } + plan::exit_code(&p) +} + +fn state_dir(cli: &Cli) -> Result { + match &cli.state_dir { + Some(d) => Ok(StateDir::new(d)), + None => StateDir::default_dir().ok_or_else(|| { + eprintln!("aien-test: HOME is not set and no --state-dir given"); + 2 + }), + } +} + +fn cmd_status(cli: &Cli) -> i32 { + let state = match state_dir(cli) { + Ok(s) => s, + Err(code) => return code, + }; + for line in status::lines(&state) { + println!("{line}"); + } + 0 +} + +fn cmd_verify(cli: &Cli, commit: &str, cwd: &Path) -> i32 { + let root = match repo_root_or_report(cwd) { + Ok(r) => r, + Err(code) => return code, + }; + let state = match state_dir(cli) { + Ok(s) => s, + Err(code) => return code, + }; + let ask = verify::Ask { + state, + commit: commit.to_string(), + // verify applies the worker's rule: a commit on this line is + // checked against its first parent. + base: cli + .base + .clone() + .unwrap_or_else(|| "origin/main".to_string()), + repository: cli.repo.clone(), + release: cli.release, + operator: cli.operator, + hardware_identity: cli.hardware_identity.clone().unwrap_or_default(), + crumb: Some("crumb".to_string()), + keys_override: None, + }; + let report = verify::run(&root, &ask); + for line in &report.lines { + println!("{line}"); + } + if report.ready { + 0 + } else { + 1 + } +} + +fn cmd_worker(cli: &Cli) -> i32 { + let state = match state_dir(cli) { + Ok(s) => s, + Err(code) => return code, + }; + let home = std::env::var_os("HOME").map(PathBuf::from); + let key = match (&cli.key, &home) { + (Some(k), _) => k.clone(), + (None, Some(h)) => h.join(".aien/verify.key"), + (None, None) => { + eprintln!("aien-test: HOME is not set and no --key given"); + return 2; + } + }; + let clones = match (&cli.clones, &home) { + (Some(c), _) => c.clone(), + (None, Some(h)) => h.join("workspace"), + (None, None) => { + eprintln!("aien-test: HOME is not set and no --clones given"); + return 2; + } + }; + let wt_root = cli + .wt_root + .clone() + .unwrap_or_else(|| PathBuf::from("/var/lib/aien-run/wt")); + let mut cfg = worker::Config::new(state, &key, &clones, &wt_root); + // INFRA's worktree tool; the default is the copy in the trusted clone of + // this repository. A missing tool makes `--sandbox user` refuse to run. + cfg.wt_tool = match &cli.wt_tool { + Some(t) => Some(t.clone()), + None => Some(clones.join("aien-sovereign-core/tools/aien-local-ci/wt.sh")) + .filter(|p| p.is_file()), + }; + // The worker runs other people's code: the user sandbox is its default. + // `--sandbox none` is a development mode only, needs + // `--dev-unsandboxed`, and is never allowed with `--github`. + cfg.sandbox = if cli.sandbox_given { + cli.sandbox + } else { + Sandbox::User + }; + cfg.allow_unsandboxed = cli.dev_unsandboxed; + if let Err(e) = cfg.check_sandbox_policy_for(cli.github) { + eprintln!("aien-test: {e}"); + return 2; + } + if let Some(b) = &cli.base { + cfg.base_ref = b.clone(); + } + cfg.github = cli.github; + cfg.poll = Duration::from_secs(cli.poll.unwrap_or(30)); + cfg.repos = cli.repos.clone(); + cfg.operator = cli.operator; + cfg.hardware_identity = cli.hardware_identity.clone().unwrap_or_default(); + if let Some((repo, sha)) = &cli.once { + return match worker::run_once(&cfg, repo, sha) { + Ok(s) => { + for n in &s.notes { + println!("NOTE {n}"); + } + for (g, st, v) in &s.gates { + println!("GATE {g} {st} {}", v.as_str()); + } + println!("BUNDLE {} {}", s.bundle_path.display(), s.bundle_digest); + println!("PUBLICATION {}", s.publication); + if s.reason.is_empty() { + println!("AIEN_TEST: {}", s.verdict.as_str()); + } else { + println!("AIEN_TEST: {} {}", s.verdict.as_str(), s.reason); + } + s.verdict.exit_code() + } + Err(e) => { + println!("AIEN_TEST: FAIL {e}"); + 1 + } + }; + } + let iterations = match cli.iterations { + Some(0) | None => None, + Some(n) => Some(n), + }; + let served = worker::run_loop(&cfg, iterations); + println!("WORKER served {served}"); + 0 +} diff --git a/tools/aien-test/src/manifest.rs b/tools/aien-test/src/manifest.rs index b5a648d9..a7deafc7 100644 --- a/tools/aien-test/src/manifest.rs +++ b/tools/aien-test/src/manifest.rs @@ -825,7 +825,7 @@ pub fn parse(bytes: &[u8]) -> Result { let exec = child_str(c, "exec")?.ok_or_else(|| ManifestError("run.exec missing".into()))?; if !valid_rel_path(&exec) { return Err(ManifestError( - "run.exec must be a repo-relative path".into(), + "run.exec must be a bare program name or a repo-relative path".into(), )); } let args = match child(c, "args") { @@ -1077,6 +1077,20 @@ mod tests { fn paths_must_be_relative() { assert!(parse(GOOD.replace("tools/run.sh", "/bin/sh").as_bytes()).is_err()); assert!(parse(GOOD.replace("tools/run.sh", "../x").as_bytes()).is_err()); + // An exec that escapes the repository is a reject, never a run. + for bad in [ + "../../usr/bin/env", + "/usr/bin/env", + "tools/../../x", + "tools/..", + "", + ] { + let e = parse(GOOD.replace("tools/run.sh", bad).as_bytes()); + assert!(e.is_err(), "{bad:?} must be rejected"); + } + // A bare program name is allowed: it resolves on the PATH. + let m = parse(GOOD.replace("tools/run.sh", "crumb").as_bytes()).unwrap(); + assert_eq!(m.exec, "crumb"); } #[test] diff --git a/tools/aien-test/src/plan.rs b/tools/aien-test/src/plan.rs new file mode 100644 index 00000000..78bc4baa --- /dev/null +++ b/tools/aien-test/src/plan.rs @@ -0,0 +1,1822 @@ +//! The planner (ADR 0033 Decision 12; local pipeline amendments A1 and A4). +//! +//! `aien-test plan [--base REF]` reads two commits of the repository through +//! git objects, never through the working tree, so the same plan can be +//! recomputed later for a commit that is not checked out (`verify COMMIT` +//! does that to check the bundle's `graph_digest`). Only `plan` on a tree +//! with uncommitted changes adds those paths, and only with `--allow-dirty`. +//! +//! What selects a gate at HEAD: +//! - a changed path under one of its `inputs`, under a D3 implied input +//! (`tests//.gate` implies `src//.*` and +//! `tests//_test.*`), its own manifest file, or its golden file; +//! - a changed pin (`*.lock` whose content is one 40-hex line) in its inputs; +//! - crumb ancestry: the `.crumb` of every directory above a changed path is +//! read at HEAD, and the paths named by its `related` or `links` members +//! (if the file has them; today's schema has neither) count as changed; +//! - the always set (`.aien/always` at BASE, trust anchor A1): one gate id per +//! line, selected whatever changed, never excluded by path filtering. +//! +//! The selection is closed over `depends_on` (a dependency is never dropped) +//! and over dependents (a gate whose dependency changed gets a new check id +//! and must run again). +//! +//! Rules that stop a commit from passing: +//! - a changed path that no gate's inputs cover and that `.aien/unmapped-ok` +//! at BASE does not allow is UNMAPPED: the commit verdict is NOT_RUN with +//! reason UNMAPPED_PATH. Manifest files, `.crumb` files and the pipeline's +//! own configuration are always mapped (the next rule covers the latter); +//! - a change under `.aien/`, `tests/gates/`, `.github/workflows/`, +//! `.forgejo/` or `tools/aien-test/` blocks the commit (BLOCKED_OPERATOR, +//! PIPELINE_CONFIG_CHANGED) unless the operator passes `--operator`; +//! - every gate that exists at BASE must exist at HEAD; a deleted gate gives +//! NOT_RUN with reason GATE_REMOVED. +//! +//! The commit verdict algebra (`judge`) is Decision 7 applied to the plan: a +//! required gate whose dependency has no receipt is NOT_RUN +//! (UNVERIFIED_DEPENDENCY), a FAIL propagates (DEPENDENCY_FAILED), and +//! nothing promotes NOT_RUN to PASS. ADVISORY gates never count. +//! +//! Hardware identity: `cache_scope: hardware` gates need one and the ADR does +//! not define its content. When none is given the machine digest stands in, +//! and the plan says so. + +use crate::evidence::{canonical_digest, sha256_hex}; +use crate::graph::{self, Graph}; +use crate::identity::{self, Binding}; +use crate::manifest::{self, Exactness, Manifest}; +use crate::process; +use crate::verdict::Verdict; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Paths whose change blocks a commit unless the operator says otherwise. +pub const PIPELINE_CONFIG: [&str; 5] = [ + ".aien/", + "tests/gates/", + ".github/workflows/", + ".forgejo/", + "tools/aien-test/", +]; +pub const ALWAYS_FILE: &str = ".aien/always"; +pub const UNMAPPED_OK_FILE: &str = ".aien/unmapped-ok"; +const SKIP_DIRS: [&str; 5] = [".git", "target", "build", "vendor", "node_modules"]; + +/// What to plan. +#[derive(Debug, Clone)] +pub struct Request { + /// Any revision git resolves (`origin/main`, a sha, `HEAD~1`). + pub base: String, + pub head: String, + /// Uncommitted changes to add to the changed set (`plan --allow-dirty` + /// only; `verify` never sets them). + pub dirty: Vec, + /// `--operator`: a pipeline configuration change is allowed. + pub operator: bool, + pub compiler_identity: String, + pub flags: Vec, + /// Empty: the machine digest stands in (recorded in the plan). + pub hardware_identity: String, + /// Gates known to have a reusable receipt (filled by `probe_cached`). + pub cached: BTreeSet, +} + +impl Request { + pub fn new(base: &str, head: &str) -> Request { + Request { + base: base.to_string(), + head: head.to_string(), + dirty: Vec::new(), + operator: false, + compiler_identity: String::new(), + flags: Vec::new(), + hardware_identity: String::new(), + cached: BTreeSet::new(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Section { + Required, + Cached, + NeedsSpark, + NeedsGb10, + Advisory, + Blocked, +} + +impl Section { + pub fn title(self) -> &'static str { + match self { + Section::Required => "Required", + Section::Cached => "Cached", + Section::NeedsSpark => "Needs Spark", + Section::NeedsGb10 => "Needs GB10", + Section::Advisory => "Advisory", + Section::Blocked => "Blocked", + } + } + + pub const ALL: [Section; 6] = [ + Section::Required, + Section::Cached, + Section::NeedsSpark, + Section::NeedsGb10, + Section::Advisory, + Section::Blocked, + ]; +} + +/// One selected gate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub gate: String, + pub check_id: String, + pub pool: String, + pub exactness: Exactness, + pub cache_scope: manifest::CacheScope, + /// False only for ADVISORY gates. + pub required: bool, + pub section: Section, + /// Why it is Blocked (empty otherwise). + pub reason: String, + pub depends_on: Vec, + pub always: bool, + /// Why it was selected: the first matching path, `always`, `dependency` + /// or `dependent`. + pub because: String, +} + +#[derive(Debug, Clone)] +pub struct Plan { + pub base: String, + pub head: String, + pub changed: Vec, + /// Paths added by crumb ancestry (not themselves checked for mapping). + pub crumb_paths: Vec, + pub pins: Vec, + pub unmapped: Vec, + /// Gates at BASE that are gone at HEAD. + pub removed: Vec, + pub config_changed: Vec, + /// Set when the whole plan is blocked (PIPELINE_CONFIG_CHANGED). + pub blocked: Option, + /// Selected gates, dependencies first. + pub entries: Vec, + /// sha256 over the canonical `[{gate, check_id, depends_on}]` of the + /// selected gates, sorted by gate. + pub graph_digest: String, + pub notes: Vec, + /// The graph at HEAD (every gate, not only the selected ones). + pub graph: Graph, +} + +// ---------------------------------------------------------------- git + +fn git(root: &Path, args: &[&str]) -> Result, String> { + let mut cmd = process::git_command(); + cmd.env("GIT_OPTIONAL_LOCKS", "0") + .arg("-C") + .arg(root) + .args(args); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run git: {e}"))?; + if !out.status.success() { + return Err(format!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + )); + } + Ok(out.stdout) +} + +fn git_text(root: &Path, args: &[&str]) -> Result { + Ok(String::from_utf8_lossy(&git(root, args)?).into_owned()) +} + +/// The 40-hex commit id of `rev`. +pub fn resolve(root: &Path, rev: &str) -> Result { + let s = git_text( + root, + &[ + "rev-parse", + "--verify", + "--quiet", + &format!("{rev}^{{commit}}"), + ], + ) + .map_err(|_| format!("cannot resolve {rev:?} to a commit"))?; + let s = s.trim().to_string(); + if is_hex(&s, 40) { + Ok(s) + } else { + Err(format!("{rev:?} is not a commit")) + } +} + +/// The first of `candidates` that resolves. +pub fn resolve_first(root: &Path, candidates: &[&str]) -> Result { + for c in candidates { + if let Ok(s) = resolve(root, c) { + return Ok(s); + } + } + Err(format!("none of {candidates:?} resolves to a commit")) +} + +/// The BASE the worker and `verify` plan `head` against: `base_ref` (then +/// `main`); when `head` is already on that line (the tip of main or an older +/// main commit) its first parent, so a push to main verifies what it changed +/// and both sides compute the same plan. The flag says whether `head` is on +/// the base line (the `main` trust class). +pub fn base_for(root: &Path, base_ref: &str, head: &str) -> Result<(String, bool), String> { + let first_parent = format!("{head}~1"); + let base = resolve_first(root, &[base_ref, "main", &first_parent])?; + let on_base = base == head || git(root, &["merge-base", "--is-ancestor", head, &base]).is_ok(); + if on_base { + Ok((resolve(root, &first_parent)?, true)) + } else { + Ok((base, false)) + } +} + +fn is_hex(s: &str, n: usize) -> bool { + s.len() == n + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// Every tracked file of `commit`: path to blob id. +pub fn tree_rows(root: &Path, commit: &str) -> Result, String> { + let out = git(root, &["ls-tree", "-r", "-z", commit])?; + let text = String::from_utf8(out).map_err(|_| "git ls-tree output is not UTF-8".to_string())?; + let mut rows = BTreeMap::new(); + for rec in text.split('\0').filter(|r| !r.is_empty()) { + let (meta, path) = rec + .split_once('\t') + .ok_or_else(|| format!("unparsable ls-tree record {rec:?}"))?; + let f: Vec<&str> = meta.split(' ').collect(); + if f.len() != 3 || f[2].len() != 40 { + return Err(format!("unparsable ls-tree record {rec:?}")); + } + if f[1] == "blob" { + rows.insert(path.to_string(), f[2].to_string()); + } + } + Ok(rows) +} + +/// The bytes of `path` at `commit`, None when it does not exist there. +pub fn show(root: &Path, commit: &str, path: &str) -> Option> { + git(root, &["show", &format!("{commit}:{path}")]).ok() +} + +/// `git diff --name-only BASE...HEAD`: paths changed on HEAD's side since the +/// merge base. +pub fn changed_between(root: &Path, base: &str, head: &str) -> Result, String> { + let out = git( + root, + &["diff", "--name-only", "-z", &format!("{base}...{head}")], + )?; + let text = String::from_utf8_lossy(&out); + let mut v: Vec = text + .split('\0') + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect(); + v.sort(); + v.dedup(); + Ok(v) +} + +/// Paths with uncommitted changes, untracked files included. +pub fn uncommitted(root: &Path) -> Result, String> { + let out = git( + root, + &["status", "--porcelain=v1", "-z", "--untracked-files=all"], + )?; + let text = String::from_utf8_lossy(&out); + let mut v = Vec::new(); + let mut it = text.split('\0').filter(|s| !s.is_empty()); + while let Some(rec) = it.next() { + if rec.len() < 4 { + continue; + } + let xy = &rec[..2]; + v.push(rec[3..].to_string()); + if xy.starts_with('R') || xy.starts_with('C') { + // The original name follows as its own record. + if let Some(orig) = it.next() { + v.push(orig.to_string()); + } + } + } + v.sort(); + v.dedup(); + Ok(v) +} + +fn lines_at(root: &Path, commit: &str, path: &str) -> Vec { + match show(root, commit, path) { + Some(bytes) => String::from_utf8_lossy(&bytes) + .lines() + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .collect(), + None => Vec::new(), + } +} + +/// `.aien/always` at `commit` (A1: read from BASE, never the working tree). +pub fn always_set(root: &Path, commit: &str) -> Vec { + lines_at(root, commit, ALWAYS_FILE) +} + +/// `.aien/unmapped-ok` at `commit`. +pub fn unmapped_ok(root: &Path, commit: &str) -> Vec { + lines_at(root, commit, UNMAPPED_OK_FILE) +} + +// ---------------------------------------------------------------- gates at a commit + +fn skipped(path: &str, rows: &BTreeMap) -> bool { + let parts: Vec<&str> = path.split('/').collect(); + let mut prefix = String::new(); + for dir in &parts[..parts.len() - 1] { + if SKIP_DIRS.contains(dir) { + return true; + } + if !prefix.is_empty() { + prefix.push('/'); + } + prefix.push_str(dir); + if rows.contains_key(&format!("{prefix}/.aien-test-ignore")) { + return true; + } + } + rows.contains_key(".aien-test-ignore") +} + +/// The gate graph of `commit`, read from git objects, plus each gate's +/// manifest path relative to the root. +pub fn graph_at( + root: &Path, + commit: &str, + rows: &BTreeMap, +) -> Result<(Graph, BTreeMap), String> { + let mut entries: Vec<(PathBuf, Manifest)> = Vec::new(); + let mut rel_of: BTreeMap = BTreeMap::new(); + for path in rows.keys() { + if !path.ends_with(".gate") || skipped(path, rows) { + continue; + } + let bytes = + show(root, commit, path).ok_or_else(|| format!("cannot read {path} at {commit}"))?; + let m = manifest::parse(&bytes).map_err(|e| format!("BAD_MANIFEST {path}: {}", e.0))?; + rel_of.insert(m.gate.clone(), path.clone()); + entries.push((root.join(path), m)); + } + let g = graph::build(entries).map_err(|e| e.to_string())?; + Ok((g, rel_of)) +} + +/// Gate ids at `commit`, tolerating manifests that no longer parse (a broken +/// manifest at BASE is still a gate that must not vanish). +fn gate_ids_at(root: &Path, commit: &str, rows: &BTreeMap) -> BTreeSet { + let mut ids = BTreeSet::new(); + for path in rows.keys() { + if !path.ends_with(".gate") || skipped(path, rows) { + continue; + } + if let Some(bytes) = show(root, commit, path) { + if let Ok(m) = manifest::parse(&bytes) { + ids.insert(m.gate); + } else if let Some(id) = String::from_utf8_lossy(&bytes) + .lines() + .find_map(|l| l.strip_prefix("gate:").map(|v| v.trim().to_string())) + { + ids.insert(id); + } + } + } + ids +} + +fn stem_of(path: &str) -> &str { + let name = path.rsplit('/').next().unwrap_or(path); + match name.rfind('.') { + Some(i) if i > 0 => &name[..i], + _ => name, + } +} + +/// D3 implied inputs of a manifest at `rel`, from the tree rows. +pub fn implied_inputs(rel: &str, rows: &BTreeMap) -> Vec { + let mut out = Vec::new(); + let (dir, _) = rel.rsplit_once('/').unwrap_or(("", rel)); + let stem = stem_of(rel).to_string(); + let sub = match dir.strip_prefix("tests") { + Some(s) => s.trim_start_matches('/').to_string(), + None => return out, + }; + let join = |base: &str| { + if sub.is_empty() { + base.to_string() + } else { + format!("{base}/{sub}") + } + }; + for (base, want) in [ + (join("src"), stem.clone()), + (join("tests"), format!("{stem}_test")), + ] { + let prefix = format!("{base}/"); + for path in rows.keys() { + if let Some(name) = path.strip_prefix(&prefix) { + if !name.contains('/') && stem_of(name) == want { + out.push(path.clone()); + } + } + } + } + out +} + +/// Every path a gate watches: explicit inputs, implied inputs, its manifest +/// and its golden file. +pub fn watched(m: &Manifest, rel: &str, rows: &BTreeMap) -> Vec { + let mut v: Vec = m + .inputs + .iter() + .map(|i| i.trim_end_matches('/').to_string()) + .collect(); + v.extend(implied_inputs(rel, rows)); + v.push(rel.to_string()); + if let Some(g) = &m.oracle.golden { + v.push(g.trim_end_matches('/').to_string()); + } + v.sort(); + v.dedup(); + v +} + +/// `input` is `path` or a directory above it. +pub fn covers(input: &str, path: &str) -> bool { + let input = input.trim_end_matches('/'); + input.is_empty() || path == input || path.starts_with(&format!("{input}/")) +} + +/// `*` matches any run of characters (slashes included); a pattern ending in +/// `/` matches everything under that directory; anything else is exact. +pub fn glob_match(pattern: &str, path: &str) -> bool { + if let Some(dir) = pattern.strip_suffix('/') { + return covers(dir, path); + } + fn walk(p: &[u8], s: &[u8]) -> bool { + match p.first() { + None => s.is_empty(), + Some(b'*') => (0..=s.len()).any(|i| walk(&p[1..], &s[i..])), + Some(c) => s.first() == Some(c) && walk(&p[1..], &s[1..]), + } + } + walk(pattern.as_bytes(), path.as_bytes()) +} + +/// A pin: a `*.lock` file holding exactly one 40-hex commit id. +pub fn is_pin(path: &str, bytes: &[u8]) -> bool { + path.ends_with(".lock") && is_hex(String::from_utf8_lossy(bytes).trim(), 40) +} + +fn strings_of(v: &Value) -> Vec { + let mut out = Vec::new(); + if let Some(arr) = v.as_array() { + for item in arr { + if let Some(s) = item.as_str() { + out.push(s.to_string()); + } else if let Some(o) = item.as_object() { + for k in ["path", "target", "dir", "id"] { + if let Some(s) = o.get(k).and_then(Value::as_str) { + out.push(s.to_string()); + break; + } + } + } + } + } + out +} + +/// Crumb ancestry: for every directory above a changed path (the root +/// included), the paths its `.crumb` at `commit` names under `related` or +/// `links`. Today's crumb schema has neither member, so this is empty until +/// one appears; the hook is here so a change under a directory can pull in +/// what its crumb says belongs with it. +pub fn crumb_paths( + root: &Path, + commit: &str, + changed: &[String], + rows: &BTreeMap, +) -> Vec { + let mut dirs: BTreeSet = BTreeSet::new(); + for p in changed { + let mut cur = p.as_str(); + dirs.insert(String::new()); + while let Some((parent, _)) = cur.rsplit_once('/') { + dirs.insert(parent.to_string()); + cur = parent; + } + } + let mut out: BTreeSet = BTreeSet::new(); + for dir in dirs { + let file = if dir.is_empty() { + ".crumb".to_string() + } else { + format!("{dir}/.crumb") + }; + if !rows.contains_key(&file) { + continue; + } + let Some(bytes) = show(root, commit, &file) else { + continue; + }; + let Ok(v) = serde_json::from_slice::(&bytes) else { + continue; + }; + for key in ["related", "links"] { + for s in strings_of(&v[key]) { + let s = s.trim_matches('/').to_string(); + if !s.is_empty() { + out.insert(s); + } + } + } + } + out.into_iter().collect() +} + +fn under_config(path: &str) -> bool { + PIPELINE_CONFIG.iter().any(|c| covers(c, path)) +} + +fn is_crumb_file(path: &str) -> bool { + path == ".crumb" + || path.ends_with("/.crumb") + || path == ".crumb.local" + || path.ends_with("/.crumb.local") +} + +// ---------------------------------------------------------------- the plan + +/// Compute the plan for `req` in the repository at `root`. +pub fn compute(root: &Path, req: &Request) -> Result { + let base = resolve(root, &req.base)?; + let head = resolve(root, &req.head)?; + let mut notes: Vec = Vec::new(); + + let mut changed = changed_between(root, &base, &head)?; + changed.extend(req.dirty.iter().cloned()); + changed.sort(); + changed.dedup(); + + let rows_head = tree_rows(root, &head)?; + let rows_base = tree_rows(root, &base)?; + let (graph, rel_of) = graph_at(root, &head, &rows_head)?; + let ids_base = gate_ids_at(root, &base, &rows_base); + let removed: Vec = ids_base + .iter() + .filter(|id| graph.index_of(id).is_none()) + .cloned() + .collect(); + + let config_changed: Vec = changed + .iter() + .filter(|p| under_config(p)) + .cloned() + .collect(); + let blocked = if !config_changed.is_empty() && !req.operator { + Some("PIPELINE_CONFIG_CHANGED".to_string()) + } else { + None + }; + if !config_changed.is_empty() && req.operator { + notes.push("pipeline configuration changed; allowed by --operator".to_string()); + } + + let crumb = crumb_paths(root, &head, &changed, &rows_head); + let pins: Vec = changed + .iter() + .filter(|p| { + show(root, &head, p) + .or_else(|| show(root, &base, p)) + .is_some_and(|b| is_pin(p, &b)) + }) + .cloned() + .collect(); + let always = always_set(root, &base); + let ok_patterns = unmapped_ok(root, &base); + + // What each gate watches, and which changed path (if any) touches it. + let mut watched_of: Vec> = Vec::with_capacity(graph.len()); + for i in 0..graph.len() { + let node = graph.node(i); + let rel = rel_of.get(&node.id).cloned().unwrap_or_default(); + watched_of.push(watched(&node.manifest, &rel, &rows_head)); + } + let mut all_changed: Vec = changed.clone(); + all_changed.extend(crumb.iter().cloned()); + let mut because: BTreeMap = BTreeMap::new(); + for (i, w) in watched_of.iter().enumerate() { + if let Some(p) = all_changed + .iter() + .find(|p| w.iter().any(|input| covers(input, p))) + { + because.insert(i, p.clone()); + } + } + + let unmapped: Vec = changed + .iter() + .filter(|p| { + let mapped = p.ends_with(".gate") + || is_crumb_file(p) + || under_config(p) + || watched_of + .iter() + .any(|w| w.iter().any(|input| covers(input, p))) + || ok_patterns.iter().any(|pat| glob_match(pat, p)); + !mapped + }) + .cloned() + .collect(); + + let mut seeds: BTreeSet = because.keys().copied().collect(); + let mut always_idx: BTreeSet = BTreeSet::new(); + let mut removed = removed; + for g in &always { + match graph.index_of(g) { + Some(i) => { + always_idx.insert(i); + seeds.insert(i); + } + None => { + if !removed.contains(g) { + removed.push(g.clone()); + } + notes.push(format!("always-set gate {g} does not exist at HEAD")); + } + } + } + let mut with_dependents: BTreeSet = seeds.clone(); + for &s in &seeds { + with_dependents.extend(graph.transitive_dependents(s)); + } + let targets: Vec = with_dependents.iter().copied().collect(); + let selected = graph.with_dependencies(&targets); + + // Check ids for every gate at HEAD, dependencies first. + let mut binding = identity::local_binding(&req.hardware_identity)?; + if binding.hardware_identity.is_empty() { + binding.hardware_identity = binding.machine_digest.clone(); + if graph + .nodes() + .iter() + .any(|n| n.manifest.cache_scope == manifest::CacheScope::Hardware) + { + notes.push("hardware identity not given; the machine digest stands in for cache_scope: hardware".to_string()); + } + } + let ids = check_ids( + root, + &head, + &graph, + &rows_head, + &req.compiler_identity, + &req.flags, + &binding, + )?; + + let mut entries: Vec = Vec::new(); + for &i in graph.order() { + if !selected.contains(&i) { + continue; + } + let node = graph.node(i); + let m = &node.manifest; + let is_always = always_idx.contains(&i); + let required = m.exactness != Exactness::Advisory; + let (section, reason) = if let Some(b) = &blocked { + (Section::Blocked, b.clone()) + } else if m.requires.iter().any(|r| r == "operator") { + (Section::Blocked, "OPERATOR_STEP_PENDING".to_string()) + } else if !required { + (Section::Advisory, String::new()) + } else if m.pool() == "gb10" { + (Section::NeedsGb10, String::new()) + } else if m.pool() == "qemu" + || m.requires + .iter() + .any(|r| r == "aarch64" || r == "bare_metal") + { + (Section::NeedsSpark, String::new()) + } else if req.cached.contains(&node.id) { + (Section::Cached, String::new()) + } else { + (Section::Required, String::new()) + }; + let why = if is_always { + "always".to_string() + } else if let Some(p) = because.get(&i) { + p.clone() + } else if seeds + .iter() + .any(|s| graph.transitive_dependents(*s).contains(&i)) + { + "dependent".to_string() + } else { + "dependency".to_string() + }; + entries.push(Entry { + gate: node.id.clone(), + check_id: ids.get(&node.id).cloned().unwrap_or_default(), + pool: m.pool().to_string(), + exactness: m.exactness, + cache_scope: m.cache_scope, + required, + section, + reason, + depends_on: identity::declared_dependencies(m), + always: is_always, + because: why, + }); + } + let graph_digest = digest_of(&entries)?; + Ok(Plan { + base, + head, + changed, + crumb_paths: crumb, + pins, + unmapped, + removed, + config_changed, + blocked, + entries, + graph_digest, + notes, + graph, + }) +} + +/// sha256 over the canonical `[{gate, check_id, depends_on}]`, sorted by gate. +pub fn digest_of(entries: &[Entry]) -> Result { + let mut rows: Vec<&Entry> = entries.iter().collect(); + rows.sort_by(|a, b| a.gate.cmp(&b.gate)); + let v: Vec = rows + .iter() + .map(|e| json!({ "gate": e.gate, "check_id": e.check_id, "depends_on": e.depends_on })) + .collect(); + canonical_digest(&json!(v)).map_err(|e| e.to_string()) +} + +/// Check ids of every gate of `graph` at `commit`, computed from the tree +/// rows (no working tree), dependencies first. +pub fn check_ids( + root: &Path, + commit: &str, + graph: &Graph, + rows: &BTreeMap, + compiler_identity: &str, + flags: &[String], + binding: &Binding, +) -> Result, String> { + let mut done: BTreeMap = BTreeMap::new(); + for &i in graph.order() { + let m = &graph.node(i).manifest; + let mut dep_ids = Vec::new(); + for d in identity::declared_dependencies(m) { + match done.get(&d) { + Some(id) => dep_ids.push(id.clone()), + None => return Err(format!("gate {} declares unknown dependency {d}", m.gate)), + } + } + let golden = match &m.oracle.golden { + Some(g) => show(root, commit, g), + None => None, + }; + let obj = identity::identity_object_from_parts( + m, + identity::input_blob_ids_from_rows(m, rows), + golden.as_deref(), + compiler_identity, + flags, + &dep_ids, + binding, + )?; + done.insert(m.gate.clone(), identity::id_of(&obj)?); + } + Ok(done) +} + +/// Gates with a reusable receipt right now, for the Cached section. Only +/// meaningful when `head` is the checked-out commit and the tree is clean; +/// the caller checks that. A gate counts as cached only when every gate it +/// depends on would be reused too. +pub fn probe_cached(root: &Path, graph: &Graph, opts: &crate::runner::Options) -> BTreeSet { + use crate::cache::{self, Lookup}; + use crate::evidence::{Index, Store}; + let store = Store::new(&opts.evidence_dir); + let index = Index::load(&store); + let env = crate::runner::captured_env(); + let mut stands_on: BTreeMap> = BTreeMap::new(); + let mut out = BTreeSet::new(); + for &i in graph.order() { + let node = graph.node(i); + let m = &node.manifest; + let mut reuse: Option = None; + let deps_ok = m.depends_on.iter().all(|d| { + graph + .index_of(d) + .and_then(|di| stands_on.get(&di).cloned().flatten()) + .is_some() + }); + if cache::policy(m.cache_allowed, opts.no_cache || opts.release) == cache::Mode::Allow + && deps_ok + { + if let Ok(id) = + crate::runner::identity(root, &node.path, m, &opts.hardware, opts.sandbox) + { + let deps: Vec<(String, String)> = m + .depends_on + .iter() + .filter_map(|d| { + let di = graph.index_of(d)?; + Some((d.clone(), stands_on.get(&di)?.clone()?)) + }) + .collect(); + let now = cache::Experiment { + manifest_digest: m.digest.clone(), + binary_sha256: id.binary_sha.clone(), + build_inputs_digest: id.inputs_digest.clone(), + machine_digest: id.machine_digest.clone(), + dependencies: deps, + pins: json!([]), + args_override: None, + }; + if let Ok(k) = cache::key(&now, &index) { + if let Lookup::Hit(src) = cache::lookup(&index, &store, &k, &env) { + if src.verdict() == Some(Verdict::Pass) { + reuse = Some(src.digest.clone()); + out.insert(node.id.clone()); + } + } + } + } + } + stands_on.insert(i, reuse); + } + out +} + +// ---------------------------------------------------------------- the verdict algebra + +/// What is known about one gate after a run (or from receipts). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Known { + pub verdict: Verdict, + pub reason: String, + /// The receipt digest, when one was written. + pub receipt: Option, +} + +/// The commit verdict and the effective per-gate verdicts (Decision 7). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Judged { + pub verdict: Verdict, + pub reason: String, + pub gates: BTreeMap, +} + +fn worse(a: Verdict, b: Verdict) -> Verdict { + if b.exit_code() > a.exit_code() { + b + } else { + a + } +} + +/// Apply the algebra to a plan and what is known about its gates. Unknown +/// gates are NOT_RUN (no receipt). A required gate is NOT_RUN with +/// UNVERIFIED_DEPENDENCY when a dependency has no PASS receipt, and FAIL with +/// DEPENDENCY_FAILED when a dependency failed. Advisory gates are judged but +/// never move the commit verdict. NOT_RUN is never promoted. +pub fn judge(plan: &Plan, known: &BTreeMap) -> Judged { + let mut gates: BTreeMap = BTreeMap::new(); + for e in &plan.entries { + let mut v = match known.get(&e.gate) { + Some(k) => (k.verdict, k.reason.clone()), + None => (Verdict::NotRun, "NO_RECEIPT".to_string()), + }; + if e.section == Section::Blocked { + v = (Verdict::BlockedOperator, e.reason.clone()); + } + if known + .get(&e.gate) + .is_some_and(|k| k.verdict == Verdict::Pass && k.receipt.is_none()) + { + v = (Verdict::NotRun, "NO_RECEIPT".to_string()); + } + for d in &e.depends_on { + let dep = gates.get(d).cloned().or_else(|| { + known + .get(d) + .filter(|k| k.receipt.is_some() || k.verdict != Verdict::Pass) + .map(|k| (k.verdict, k.reason.clone())) + }); + match dep { + Some((Verdict::Pass, _)) => {} + Some((Verdict::Fail, _)) => { + v = (Verdict::Fail, format!("DEPENDENCY_FAILED:{d}")); + break; + } + Some((other, _)) if other != Verdict::NotRun => { + v = (other, format!("DEP_BLOCKED:{d}")); + break; + } + _ => { + v = (Verdict::NotRun, format!("UNVERIFIED_DEPENDENCY:{d}")); + break; + } + } + } + gates.insert(e.gate.clone(), v); + } + let (verdict, reason) = if let Some(b) = &plan.blocked { + (Verdict::BlockedOperator, b.clone()) + } else if !plan.unmapped.is_empty() { + (Verdict::NotRun, "UNMAPPED_PATH".to_string()) + } else if !plan.removed.is_empty() { + (Verdict::NotRun, "GATE_REMOVED".to_string()) + } else { + let required: Vec<&Entry> = plan.entries.iter().filter(|e| e.required).collect(); + if required.is_empty() { + (Verdict::NotRun, "NO_REQUIRED_GATES".to_string()) + } else { + let mut worst = Verdict::Pass; + let mut reason = String::new(); + let mut any_fail = false; + for e in &required { + let (v, r) = &gates[&e.gate]; + if *v == Verdict::Fail { + any_fail = true; + } + if v.exit_code() > worst.exit_code() { + worst = worse(worst, *v); + reason = format!("{}:{}", e.gate, r); + } + } + if any_fail { + let first = required + .iter() + .find(|e| gates[&e.gate].0 == Verdict::Fail) + .map(|e| format!("{}:{}", e.gate, gates[&e.gate].1)) + .unwrap_or_default(); + (Verdict::Fail, first) + } else { + (worst, reason) + } + } + }; + Judged { + verdict, + reason, + gates, + } +} + +// ---------------------------------------------------------------- crate selection + +/// Directories of workspace crate `name` and of every workspace crate that +/// depends on it (transitively), relative to the root, from `cargo metadata`. +pub fn crate_dirs(root: &Path, name: &str) -> Result, String> { + let mut cmd = Command::new("cargo"); + cmd.arg("metadata") + .args(["--format-version", "1", "--no-deps"]) + .current_dir(root); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run cargo: {e}"))?; + if !out.status.success() { + return Err(format!( + "cargo metadata failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + let v: Value = serde_json::from_slice(&out.stdout) + .map_err(|e| format!("cargo metadata is not JSON: {e}"))?; + crate_dirs_from(&v, root, name) +} + +/// `crate_dirs` on metadata already read (for tests). +pub fn crate_dirs_from(meta: &Value, root: &Path, name: &str) -> Result, String> { + let packages = meta["packages"] + .as_array() + .ok_or("cargo metadata has no packages")?; + let mut dir_of: BTreeMap = BTreeMap::new(); + let mut deps_of: BTreeMap> = BTreeMap::new(); + let root_s = root.display().to_string(); + for p in packages { + let n = p["name"].as_str().unwrap_or("").to_string(); + let mp = p["manifest_path"].as_str().unwrap_or(""); + let dir = Path::new(mp) + .parent() + .map(|d| d.display().to_string()) + .unwrap_or_default(); + let rel = dir + .strip_prefix(&format!("{root_s}/")) + .map(|s| s.to_string()) + .unwrap_or_else(|| { + if dir == root_s { + String::new() + } else { + dir.clone() + } + }); + dir_of.insert(n.clone(), rel); + let deps: Vec = p["dependencies"] + .as_array() + .map(|a| { + a.iter() + .filter(|d| d["path"].is_string()) + .filter_map(|d| d["name"].as_str().map(|s| s.to_string())) + .collect() + }) + .unwrap_or_default(); + deps_of.insert(n, deps); + } + if !dir_of.contains_key(name) { + return Err(format!("no workspace crate named {name}")); + } + let mut wanted: BTreeSet = BTreeSet::new(); + let mut todo = vec![name.to_string()]; + while let Some(n) = todo.pop() { + if !wanted.insert(n.clone()) { + continue; + } + for (other, deps) in &deps_of { + if deps.contains(&n) { + todo.push(other.clone()); + } + } + } + let mut dirs: Vec = wanted + .iter() + .filter_map(|n| dir_of.get(n).cloned()) + .collect(); + dirs.sort(); + dirs.dedup(); + Ok(dirs) +} + +/// Gates whose inputs cover one of `dirs`, or sit under one of them, plus +/// everything they depend on. +pub fn select_for_dirs(graph: &Graph, dirs: &[String]) -> BTreeSet { + let seeds: Vec = (0..graph.len()) + .filter(|&i| { + graph.node(i).manifest.inputs.iter().any(|input| { + dirs.iter() + .any(|d| covers(input, d) || covers(d, input.trim_end_matches('/'))) + }) + }) + .collect(); + graph.with_dependencies(&seeds) +} + +// ---------------------------------------------------------------- rendering + +fn short(s: &str) -> String { + s.chars().take(12).collect() +} + +/// The plan as the operator sees it: exactly the sections Required, Cached, +/// Needs Spark, Needs GB10, Advisory, Blocked, then UNMAPPED. +pub fn render(repository: &str, plan: &Plan) -> Vec { + let mut out = vec![ + "AIEN PLAN".to_string(), + format!("Repository: {repository}"), + format!("Base: {}", plan.base), + format!("Head: {}", plan.head), + format!("Changed files: {}", plan.changed.len()), + ]; + for p in &plan.changed { + out.push(format!(" {p}")); + } + if !plan.crumb_paths.is_empty() { + out.push(format!("Crumb paths: {}", plan.crumb_paths.join(" "))); + } + if !plan.pins.is_empty() { + out.push(format!("Pins: {}", plan.pins.join(" "))); + } + out.push(format!("Graph digest: {}", plan.graph_digest)); + for s in Section::ALL { + out.push(format!("{}:", s.title())); + let mut any = false; + for e in plan.entries.iter().filter(|e| e.section == s) { + any = true; + let mut line = format!( + " {} pool={} exactness={} check={} because={}", + e.gate, + e.pool, + e.exactness.as_str(), + short(&e.check_id), + e.because + ); + if !e.reason.is_empty() { + line.push(' '); + line.push_str(&e.reason); + } + out.push(line); + } + if !any { + out.push(" (none)".to_string()); + } + } + out.push("UNMAPPED:".to_string()); + if plan.unmapped.is_empty() { + out.push(" (none)".to_string()); + } + for p in &plan.unmapped { + out.push(format!(" {p}")); + } + if !plan.removed.is_empty() { + out.push(format!("Removed gates: {}", plan.removed.join(" "))); + } + for n in &plan.notes { + out.push(format!("Note: {n}")); + } + let j = judge(plan, &BTreeMap::new()); + let verdict = if let Some(b) = &plan.blocked { + format!("BLOCKED_OPERATOR {b}") + } else if !plan.unmapped.is_empty() { + "NOT_RUN UNMAPPED_PATH".to_string() + } else if !plan.removed.is_empty() { + "NOT_RUN GATE_REMOVED".to_string() + } else if plan.entries.is_empty() { + "NOTHING_SELECTED".to_string() + } else { + let _ = j; + "RUNNABLE".to_string() + }; + out.push(format!("Plan verdict: {verdict}")); + out +} + +/// Exit code of `aien-test plan`: 0 runnable (or nothing selected), 2 +/// NOT_RUN, 4 BLOCKED_OPERATOR. +pub fn exit_code(plan: &Plan) -> i32 { + if plan.blocked.is_some() { + 4 + } else if !plan.unmapped.is_empty() || !plan.removed.is_empty() { + 2 + } else { + 0 + } +} + +/// The repository name a bundle carries: `--repo`, else the `origin` remote +/// normalised to `github.com/OWNER/REPO`, else `github.com/aien-dev/`. +pub fn repository_name(root: &Path, explicit: Option<&str>) -> String { + if let Some(r) = explicit { + return r.to_string(); + } + if let Ok(url) = git_text(root, &["remote", "get-url", "origin"]) { + if let Some(n) = normalise_remote(url.trim()) { + return n; + } + } + let dir = root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "repo".to_string()); + format!("github.com/aien-dev/{dir}") +} + +/// `git@github.com:o/r.git`, `https://github.com/o/r`, `ssh://git@github.com/o/r.git` +/// all give `github.com/o/r`. Other hosts keep their host name. +pub fn normalise_remote(url: &str) -> Option { + let s = url.trim_end_matches('/'); + let s = s.strip_suffix(".git").unwrap_or(s); + let rest = match s.strip_prefix("git@") { + Some(r) => r.replacen(':', "/", 1), + None => ["ssh://git@", "https://", "http://"] + .iter() + .find_map(|p| s.strip_prefix(p))? + .to_string(), + }; + let parts: Vec<&str> = rest.split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() < 3 { + return None; + } + Some(format!( + "{}/{}/{}", + parts[0], + parts[parts.len() - 2], + parts[parts.len() - 1] + )) +} + +/// Short helper for the worker and verify: sha256 of a string. +pub fn sha_of(s: &str) -> String { + sha256_hex(s.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{git, init_repo, write_file, TempDir}; + + fn gate(id: &str, inputs: &[&str], extra: &str) -> String { + let mut s = format!("gate: {id}\nmanifest_version: 2\nowner: t\nrequires:\n - host\n"); + if !inputs.is_empty() { + s.push_str("inputs:\n"); + for i in inputs { + s.push_str(&format!(" - {i}\n")); + } + } + s.push_str("run:\n exec: run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 5s\n"); + s.push_str(extra); + s + } + + /// A: inputs a/; B: inputs b/, depends on A; C: inputs c/ and shared/; + /// A also watches shared/. S (security) watches sec/. + fn repo() -> TempDir { + let a = gate("A", &["a/", "shared/"], ""); + let b = gate("B", &["b/"], "depends_on:\n - A\n"); + let c = gate("C", &["c/", "shared/"], ""); + let s = gate("S", &["sec/"], ""); + init_repo( + "plan", + &[ + ("gates/a.gate", a.as_str(), false), + ("gates/b.gate", b.as_str(), false), + ("gates/c.gate", c.as_str(), false), + ("gates/s.gate", s.as_str(), false), + ("run.sh", "#!/bin/sh\nexit 0\n", true), + ("a/a.txt", "a\n", false), + ("b/b.txt", "b\n", false), + ("c/c.txt", "c\n", false), + ("sec/s.txt", "s\n", false), + ("shared/iface.txt", "v1\n", false), + ("README.md", "hi\n", false), + (".aien/always", "S\n", false), + (".aien/unmapped-ok", "*.md\ndocs/\n", false), + ], + ) + } + + fn commit(t: &TempDir, files: &[(&str, &str)]) { + for (rel, content) in files { + write_file(t.path(), rel, content, false); + } + git(t.path(), &["add", "-A"]); + git(t.path(), &["commit", "-q", "-m", "change"]); + } + + fn plan_of(t: &TempDir) -> Plan { + compute(t.path(), &Request::new("HEAD~1", "HEAD")).unwrap() + } + + fn gates(p: &Plan, s: Section) -> Vec<&str> { + p.entries + .iter() + .filter(|e| e.section == s) + .map(|e| e.gate.as_str()) + .collect() + } + + fn all_gates(p: &Plan) -> Vec<&str> { + p.entries.iter().map(|e| e.gate.as_str()).collect() + } + + #[test] + fn m7_a_small_change_selects_only_the_affected_gates_plus_the_always_set() { + let t = repo(); + commit(&t, &[("b/b.txt", "b2\n")]); + let p = plan_of(&t); + // B changed: B and its dependency A run; C is untouched; S is always. + assert_eq!(all_gates(&p), ["A", "B", "S"]); + assert!(p.unmapped.is_empty()); + assert!(p.blocked.is_none()); + assert_eq!(gates(&p, Section::Required), ["A", "B", "S"]); + let b = p.entries.iter().find(|e| e.gate == "B").unwrap(); + assert_eq!(b.because, "b/b.txt"); + let a = p.entries.iter().find(|e| e.gate == "A").unwrap(); + assert_eq!(a.because, "dependency"); + assert!(p.entries.iter().find(|e| e.gate == "S").unwrap().always); + assert_eq!(exit_code(&p), 0); + assert_eq!(p.graph_digest.len(), 64); + } + + #[test] + fn m8_a_shared_interface_change_selects_every_gate_that_watches_it_and_their_dependents() { + let t = repo(); + commit(&t, &[("shared/iface.txt", "v2\n")]); + let p = plan_of(&t); + // A and C watch shared/; B depends on A so its check id moves. + assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); + assert_eq!( + p.entries.iter().find(|e| e.gate == "B").unwrap().because, + "dependent" + ); + } + + #[test] + fn m12_the_always_set_survives_path_filtering_and_cannot_be_excluded() { + let t = repo(); + commit(&t, &[("README.md", "changed\n")]); + let p = plan_of(&t); + assert_eq!(all_gates(&p), ["S"]); + assert!(p.unmapped.is_empty(), "*.md is allowed by unmapped-ok"); + // The always set is read from BASE: deleting it at HEAD changes nothing. + commit(&t, &[(".aien/always", "")]); + let p = compute( + t.path(), + &Request { + operator: true, + ..Request::new("HEAD~1", "HEAD") + }, + ) + .unwrap(); + assert_eq!(all_gates(&p), ["S"]); + assert!(p.entries[0].always); + } + + #[test] + fn an_unmapped_path_gives_not_run_unmapped_path() { + let t = repo(); + commit(&t, &[("stray/file.txt", "x\n")]); + let p = plan_of(&t); + assert_eq!(p.unmapped, ["stray/file.txt"]); + assert_eq!(exit_code(&p), 2); + let j = judge(&p, &BTreeMap::new()); + assert_eq!( + (j.verdict, j.reason.as_str()), + (Verdict::NotRun, "UNMAPPED_PATH") + ); + let text = render("github.com/x/y", &p).join("\n"); + assert!(text.contains("UNMAPPED:\n stray/file.txt")); + assert!(text.contains("Plan verdict: NOT_RUN UNMAPPED_PATH")); + // docs/ is allowed, a gate file is always mapped. + commit( + &t, + &[ + ("docs/x.md", "x\n"), + ("gates/z.gate", &gate("Z", &["z/"], "")), + ], + ); + let p = plan_of(&t); + assert!(p.unmapped.is_empty(), "{:?}", p.unmapped); + assert_eq!(all_gates(&p), ["S", "Z"]); + } + + #[test] + fn pipeline_configuration_changes_block_unless_operator() { + let t = repo(); + commit(&t, &[(".aien/always", "S\nA\n"), ("a/a.txt", "a2\n")]); + let p = plan_of(&t); + assert_eq!(p.blocked.as_deref(), Some("PIPELINE_CONFIG_CHANGED")); + assert_eq!(p.config_changed, [".aien/always"]); + assert_eq!(exit_code(&p), 4); + assert!(p.entries.iter().all(|e| e.section == Section::Blocked)); + let j = judge(&p, &BTreeMap::new()); + assert_eq!(j.verdict, Verdict::BlockedOperator); + let p = compute( + t.path(), + &Request { + operator: true, + ..Request::new("HEAD~1", "HEAD") + }, + ) + .unwrap(); + assert!(p.blocked.is_none()); + assert_eq!(gates(&p, Section::Required), ["A", "B", "S"]); + for cfg in [ + "tests/gates/x", + ".github/workflows/ci.yml", + ".forgejo/w.yml", + "tools/aien-test/src/x.rs", + ] { + assert!(under_config(cfg), "{cfg}"); + } + assert!(!under_config("tools/other/x")); + } + + #[test] + fn a_gate_deleted_at_head_is_gate_removed() { + let t = repo(); + std::fs::remove_file(t.path().join("gates/c.gate")).unwrap(); + commit(&t, &[("a/a.txt", "a2\n")]); + let p = plan_of(&t); + assert_eq!(p.removed, ["C"]); + assert!(p.unmapped.is_empty()); + assert_eq!(exit_code(&p), 2); + let j = judge(&p, &BTreeMap::new()); + assert_eq!( + (j.verdict, j.reason.as_str()), + (Verdict::NotRun, "GATE_REMOVED") + ); + } + + #[test] + fn a_changed_pin_selects_every_gate_listing_it() { + let a = gate("A", &["a/", "deps/x.lock"], ""); + let b = gate("B", &["b/"], ""); + let t = init_repo( + "plan-pin", + &[ + ("gates/a.gate", a.as_str(), false), + ("gates/b.gate", b.as_str(), false), + ("run.sh", "#!/bin/sh\n", true), + ("deps/x.lock", &format!("{}\n", "a".repeat(40)), false), + ], + ); + commit(&t, &[("deps/x.lock", &format!("{}\n", "b".repeat(40)))]); + let p = plan_of(&t); + assert_eq!(p.pins, ["deps/x.lock"]); + assert_eq!(all_gates(&p), ["A"]); + assert!(is_pin( + "x.lock", + b"0123456789abcdef0123456789abcdef01234567\n" + )); + assert!(!is_pin("Cargo.lock", b"[[package]]\n")); + assert!(!is_pin( + "x.txt", + b"0123456789abcdef0123456789abcdef01234567\n" + )); + } + + #[test] + fn d3_implied_inputs_select_a_tests_dir_gate() { + let g = gate("K", &[], ""); + let t = init_repo( + "plan-d3", + &[ + ("tests/kern/boot.gate", g.as_str(), false), + ("run.sh", "#!/bin/sh\n", true), + ("src/kern/boot.rs", "fn a(){}\n", false), + ("tests/kern/boot_test.rs", "fn t(){}\n", false), + ("src/kern/other.rs", "x\n", false), + ], + ); + let rows = tree_rows(t.path(), "HEAD").unwrap(); + let mut implied = implied_inputs("tests/kern/boot.gate", &rows); + implied.sort(); + assert_eq!(implied, ["src/kern/boot.rs", "tests/kern/boot_test.rs"]); + commit(&t, &[("src/kern/boot.rs", "fn b(){}\n")]); + let p = plan_of(&t); + assert_eq!(all_gates(&p), ["K"]); + assert!(p.unmapped.is_empty()); + commit(&t, &[("src/kern/other.rs", "y\n")]); + let p = plan_of(&t); + assert!(p.entries.is_empty()); + assert_eq!(p.unmapped, ["src/kern/other.rs"]); + } + + #[test] + fn a_manifest_edit_selects_its_own_gate() { + let t = repo(); + commit( + &t, + &[( + "gates/c.gate", + &gate("C", &["c/", "shared/"], "cache: never\n"), + )], + ); + let p = plan_of(&t); + assert_eq!(all_gates(&p), ["C", "S"]); + } + + #[test] + fn crumb_related_paths_count_as_changed() { + let t = repo(); + commit( + &t, + &[("b/.crumb", "{\"dir_name\":\"b\",\"related\":[\"c/\"]}\n")], + ); + commit(&t, &[("b/b.txt", "b3\n")]); + let p = plan_of(&t); + assert_eq!(p.crumb_paths, ["c"]); + assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); + // A crumb file itself is always mapped. + assert!(is_crumb_file("b/.crumb") && is_crumb_file(".crumb.local")); + // A crumb without related/links adds nothing (today's schema). + commit( + &t, + &[ + ("b/.crumb", "{\"dir_name\":\"b\",\"purpose\":\"x\"}\n"), + ("b/b.txt", "b4\n"), + ], + ); + let p = plan_of(&t); + assert!(p.crumb_paths.is_empty()); + assert_eq!(all_gates(&p), ["A", "B", "S"]); + } + + #[test] + fn uncommitted_changes_are_listed_only_when_asked() { + let t = repo(); + commit(&t, &[("a/a.txt", "a2\n")]); + write_file(t.path(), "c/new.txt", "n\n", false); + write_file(t.path(), "b/b.txt", "edit\n", false); + let mut dirty = uncommitted(t.path()).unwrap(); + dirty.sort(); + assert_eq!(dirty, ["b/b.txt", "c/new.txt"]); + let p = plan_of(&t); + assert_eq!(all_gates(&p), ["A", "B", "S"]); + let p = compute( + t.path(), + &Request { + dirty, + ..Request::new("HEAD~1", "HEAD") + }, + ) + .unwrap(); + assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); + } + + #[test] + fn the_plan_is_the_same_for_a_commit_that_is_not_checked_out() { + let t = repo(); + commit(&t, &[("b/b.txt", "b2\n")]); + let head = resolve(t.path(), "HEAD").unwrap(); + let base = resolve(t.path(), "HEAD~1").unwrap(); + let p1 = compute(t.path(), &Request::new(&base, &head)).unwrap(); + commit( + &t, + &[ + ("c/c.txt", "c2\n"), + ("gates/a.gate", &gate("A", &["a/", "shared/", "x/"], "")), + ], + ); + let p2 = compute(t.path(), &Request::new(&base, &head)).unwrap(); + assert_eq!(p1.graph_digest, p2.graph_digest); + assert_eq!(all_gates(&p1), all_gates(&p2)); + assert_eq!(p1.changed, p2.changed); + // The newest commit's plan differs (A's manifest changed). + let p3 = compute(t.path(), &Request::new(&base, "HEAD")).unwrap(); + assert_ne!(p3.graph_digest, p1.graph_digest); + } + + #[test] + fn sections_follow_exactness_pool_and_operator() { + let adv = gate("ADV", &["adv/"], "exactness: ADVISORY\n"); + let gpu = gate("GPU", &["gpu/"], "").replace(" - host\n", " - gb10\n"); + let q = gate("Q", &["q/"], "").replace(" - host\n", " - qemu\n"); + let op = gate("OP", &["op/"], "").replace(" - host\n", " - host\n - operator\n"); + let t = init_repo( + "plan-sections", + &[ + ("gates/adv.gate", adv.as_str(), false), + ("gates/gpu.gate", gpu.as_str(), false), + ("gates/q.gate", q.as_str(), false), + ("gates/op.gate", op.as_str(), false), + ("run.sh", "#!/bin/sh\n", true), + ("adv/x", "1\n", false), + ("gpu/x", "1\n", false), + ("q/x", "1\n", false), + ("op/x", "1\n", false), + ], + ); + commit( + &t, + &[ + ("adv/x", "2\n"), + ("gpu/x", "2\n"), + ("q/x", "2\n"), + ("op/x", "2\n"), + ], + ); + let mut req = Request::new("HEAD~1", "HEAD"); + req.cached.insert("Q".into()); + let p = compute(t.path(), &req).unwrap(); + assert_eq!(gates(&p, Section::Advisory), ["ADV"]); + assert_eq!(gates(&p, Section::NeedsGb10), ["GPU"]); + assert_eq!( + gates(&p, Section::NeedsSpark), + ["Q"], + "qemu needs the Spark even when cached" + ); + assert_eq!(gates(&p, Section::Blocked), ["OP"]); + assert_eq!( + p.entries.iter().find(|e| e.gate == "OP").unwrap().reason, + "OPERATOR_STEP_PENDING" + ); + assert!(!p.entries.iter().find(|e| e.gate == "ADV").unwrap().required); + let text = render("r", &p).join("\n"); + for title in [ + "Required:", + "Cached:", + "Needs Spark:", + "Needs GB10:", + "Advisory:", + "Blocked:", + "UNMAPPED:", + ] { + assert!(text.contains(&format!("\n{title}\n")), "{title}"); + } + } + + #[test] + fn cached_section_needs_the_probe() { + let t = repo(); + commit(&t, &[("a/a.txt", "a2\n")]); + let mut req = Request::new("HEAD~1", "HEAD"); + req.cached.insert("A".into()); + let p = compute(t.path(), &req).unwrap(); + assert_eq!(gates(&p, Section::Cached), ["A"]); + assert_eq!(gates(&p, Section::Required), ["B", "S"]); + } + + fn known(v: Verdict, receipt: bool) -> Known { + Known { + verdict: v, + reason: String::new(), + receipt: receipt.then(|| "r".repeat(64)), + } + } + + #[test] + fn t5_missing_dependency_receipt_is_unverified_dependency() { + let t = repo(); + commit(&t, &[("b/b.txt", "b2\n")]); + let p = plan_of(&t); + let mut k = BTreeMap::new(); + k.insert("B".to_string(), known(Verdict::Pass, true)); + k.insert("S".to_string(), known(Verdict::Pass, true)); + let j = judge(&p, &k); + assert_eq!(j.gates["A"].0, Verdict::NotRun); + assert_eq!( + j.gates["B"], + (Verdict::NotRun, "UNVERIFIED_DEPENDENCY:A".to_string()) + ); + assert_eq!(j.verdict, Verdict::NotRun); + // A PASS without a receipt is not evidence either. + k.insert("A".to_string(), known(Verdict::Pass, false)); + let j = judge(&p, &k); + assert_eq!(j.gates["A"], (Verdict::NotRun, "NO_RECEIPT".to_string())); + assert_eq!(j.gates["B"].1, "UNVERIFIED_DEPENDENCY:A"); + } + + #[test] + fn t6_a_failed_dependency_propagates_as_dependency_failed() { + let t = repo(); + commit(&t, &[("b/b.txt", "b2\n")]); + let p = plan_of(&t); + let mut k = BTreeMap::new(); + k.insert("A".to_string(), known(Verdict::Fail, true)); + k.insert("B".to_string(), known(Verdict::Pass, true)); + k.insert("S".to_string(), known(Verdict::Pass, true)); + let j = judge(&p, &k); + assert_eq!( + j.gates["B"], + (Verdict::Fail, "DEPENDENCY_FAILED:A".to_string()) + ); + assert_eq!(j.verdict, Verdict::Fail); + assert!(j.reason.starts_with("A:")); + } + + #[test] + fn t7_not_run_is_never_promoted_and_all_pass_is_pass() { + let t = repo(); + commit(&t, &[("b/b.txt", "b2\n")]); + let p = plan_of(&t); + let mut k = BTreeMap::new(); + k.insert("A".to_string(), known(Verdict::Pass, true)); + k.insert("B".to_string(), known(Verdict::Pass, true)); + k.insert("S".to_string(), known(Verdict::Pass, true)); + let j = judge(&p, &k); + assert_eq!(j.verdict, Verdict::Pass); + assert!(j.gates.values().all(|(v, _)| *v == Verdict::Pass)); + // One required gate NOT_RUN: the commit is NOT_RUN however the rest did. + k.insert("S".to_string(), known(Verdict::NotRun, true)); + let j = judge(&p, &k); + assert_eq!(j.verdict, Verdict::NotRun); + assert_eq!(j.reason, "S:"); + // A security gate from the always set cannot be left out: no entry + // for S means no receipt, which is NOT_RUN. + k.remove("S"); + let j = judge(&p, &k); + assert_eq!(j.gates["S"], (Verdict::NotRun, "NO_RECEIPT".to_string())); + assert_eq!(j.verdict, Verdict::NotRun); + // A blocked required gate blocks the commit. + k.insert("S".to_string(), known(Verdict::BlockedHardware, true)); + assert_eq!(judge(&p, &k).verdict, Verdict::BlockedHardware); + } + + #[test] + fn advisory_gates_never_move_the_commit_verdict() { + let adv = gate("ADV", &["a/"], "exactness: ADVISORY\n"); + let a = gate("A", &["a/"], ""); + let t = init_repo( + "plan-adv", + &[ + ("gates/adv.gate", adv.as_str(), false), + ("gates/a.gate", a.as_str(), false), + ("run.sh", "#!/bin/sh\n", true), + ("a/x", "1\n", false), + ], + ); + commit(&t, &[("a/x", "2\n")]); + let p = plan_of(&t); + let mut k = BTreeMap::new(); + k.insert("A".to_string(), known(Verdict::Pass, true)); + k.insert("ADV".to_string(), known(Verdict::Fail, true)); + let j = judge(&p, &k); + assert_eq!(j.verdict, Verdict::Pass); + assert_eq!(j.gates["ADV"].0, Verdict::Fail); + } + + #[test] + fn glob_and_covers() { + assert!(glob_match("*.md", "docs/a.md")); + assert!(glob_match("docs/", "docs/x/y")); + assert!(!glob_match("docs/", "docsx/y")); + assert!(glob_match("exact.txt", "exact.txt")); + assert!(!glob_match("exact.txt", "exact.txt2")); + assert!(glob_match("a*b*c", "aXXbYc")); + assert!(covers("a", "a/b")); + assert!(covers("a/", "a")); + assert!(!covers("a", "ab/c")); + assert!(covers("", "anything")); + } + + #[test] + fn remote_names_normalise() { + for u in [ + "git@github.com:aien-dev/x.git", + "https://github.com/aien-dev/x", + "https://github.com/aien-dev/x.git/", + "ssh://git@github.com/aien-dev/x.git", + ] { + assert_eq!( + normalise_remote(u).as_deref(), + Some("github.com/aien-dev/x"), + "{u}" + ); + } + assert_eq!(normalise_remote("/local/path"), None); + let t = repo(); + assert_eq!( + repository_name(t.path(), Some("github.com/a/b")), + "github.com/a/b" + ); + assert!(repository_name(t.path(), None).starts_with("github.com/aien-dev/")); + } + + #[test] + fn crate_dirs_follow_reverse_dependents() { + let meta = json!({ + "packages": [ + {"name": "core", "manifest_path": "/r/crates/core/Cargo.toml", "dependencies": []}, + {"name": "mid", "manifest_path": "/r/crates/mid/Cargo.toml", + "dependencies": [{"name": "core", "path": "/r/crates/core"}]}, + {"name": "top", "manifest_path": "/r/tools/top/Cargo.toml", + "dependencies": [{"name": "mid", "path": "/r/crates/mid"}, {"name": "serde", "path": null}]}, + {"name": "other", "manifest_path": "/r/crates/other/Cargo.toml", + "dependencies": [{"name": "core", "path": null}]} + ] + }); + let root = Path::new("/r"); + assert_eq!( + crate_dirs_from(&meta, root, "core").unwrap(), + ["crates/core", "crates/mid", "tools/top"] + ); + assert_eq!(crate_dirs_from(&meta, root, "top").unwrap(), ["tools/top"]); + assert!(crate_dirs_from(&meta, root, "nope").is_err()); + let t = repo(); + let g = graph::load(t.path()).unwrap(); + let picked = select_for_dirs(&g, &["b".to_string()]); + let names: Vec<&str> = picked.iter().map(|&i| g.node(i).id.as_str()).collect(); + assert_eq!(names, ["A", "B"]); + // A crate directory above an input also selects the gate. + let picked = select_for_dirs(&g, &[String::new()]); + assert_eq!(picked.len(), 4); + } + + #[test] + fn resolve_and_rows() { + let t = repo(); + let h = resolve(t.path(), "HEAD").unwrap(); + assert_eq!(h.len(), 40); + assert!(resolve(t.path(), "no-such-ref").is_err()); + assert_eq!(resolve_first(t.path(), &["nope", "HEAD"]).unwrap(), h); + let rows = tree_rows(t.path(), &h).unwrap(); + assert!(rows.contains_key("gates/a.gate")); + assert_eq!(rows["a/a.txt"].len(), 40); + assert_eq!(show(t.path(), &h, "a/a.txt").unwrap(), b"a\n"); + assert!(show(t.path(), &h, "missing").is_none()); + assert_eq!(always_set(t.path(), &h), ["S"]); + assert_eq!(unmapped_ok(t.path(), &h), ["*.md", "docs/"]); + } +} diff --git a/tools/aien-test/src/process.rs b/tools/aien-test/src/process.rs index 8984d5e1..efd49933 100644 --- a/tools/aien-test/src/process.rs +++ b/tools/aien-test/src/process.rs @@ -5,7 +5,7 @@ use std::io::{self, Read}; use std::os::unix::process::{CommandExt, ExitStatusExt}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitStatus, Output, Stdio}; use std::sync::{mpsc, Mutex, MutexGuard}; use std::thread; @@ -76,6 +76,55 @@ fn lost() -> io::Error { /// A genuinely held lock is still refused at once (ADR 0028 Decision 6). static SPAWN_GATE: Mutex<()> = Mutex::new(()); +/// Worktrees the operator's git may open although `aien-run` owns their +/// files. The worker adds one only after checking that it was made by INFRA's +/// `wt.sh`: its `.git` file is root-owned, not writable by anyone else, and +/// points into the operator's mirror, so every git setting and hook that git +/// reads there is the operator's, never the checked-out code's. +static TRUSTED_WORKTREES: Mutex> = Mutex::new(Vec::new()); + +/// Trust `dir` for git (git's `safe.directory`) until the guard is dropped. +pub fn trust_worktree(dir: &Path) -> TrustGuard { + let mut v = TRUSTED_WORKTREES.lock().unwrap_or_else(|p| p.into_inner()); + v.push(dir.to_path_buf()); + TrustGuard(dir.to_path_buf()) +} + +/// Removes its directory from the trusted list when dropped. +pub struct TrustGuard(PathBuf); + +impl Drop for TrustGuard { + fn drop(&mut self) { + let mut v = TRUSTED_WORKTREES.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(i) = v.iter().position(|d| d == &self.0) { + v.remove(i); + } + } +} + +/// Give `cmd` the trusted worktrees as `safe.directory` entries through +/// git's command-line configuration (`GIT_CONFIG_COUNT`), which git honours +/// for that setting. Children that run git themselves (crumb) inherit it. With +/// no trusted worktree the command is left exactly as it was. +pub fn apply_git_trust(cmd: &mut Command) { + let v = TRUSTED_WORKTREES.lock().unwrap_or_else(|p| p.into_inner()); + if v.is_empty() { + return; + } + cmd.env("GIT_CONFIG_COUNT", v.len().to_string()); + for (i, d) in v.iter().enumerate() { + cmd.env(format!("GIT_CONFIG_KEY_{i}"), "safe.directory"); + cmd.env(format!("GIT_CONFIG_VALUE_{i}"), d); + } +} + +/// `git` with the trusted worktrees applied (see [`apply_git_trust`]). +pub fn git_command() -> Command { + let mut cmd = Command::new("git"); + apply_git_trust(&mut cmd); + cmd +} + /// Take the spawn gate. It is a leaf lock: nothing else is taken while it is /// held, and a poisoned gate is still usable (it guards no data). pub(crate) fn spawn_gate() -> MutexGuard<'static, ()> { diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs index d06fcc08..edc644f3 100644 --- a/tools/aien-test/src/runner.rs +++ b/tools/aien-test/src/runner.rs @@ -29,6 +29,7 @@ use crate::process::{self, RunSpec}; use crate::resources::{ acquire_gpu, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools, }; +use crate::sandbox::{self, Sandbox}; use crate::verdict::{self, campaign_verdict, derive, parse_observations, DepFact, Facts, Verdict}; use serde_json::{json, Map, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -36,7 +37,6 @@ use std::fmt; use std::fs; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::{Component, Path, PathBuf}; -use std::process::Command; use std::sync::{Condvar, Mutex}; use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -54,6 +54,15 @@ pub struct Options { pub hardware: Hardware, /// Lock files and refusal checks for gb10 gates. pub gpu: GpuConfig, + /// `--sandbox none|user` (contract C8). `None` keeps every earlier + /// behaviour unchanged. + pub sandbox: Sandbox, + /// `CARGO_TARGET_DIR` as the runner itself was given it; passed through + /// the sandbox as the only environment pair. + pub cargo_target_dir: Option, + /// `--release`: qualification mode. No cache reuse and the tree must be + /// clean even with `--allow-dirty`. + pub release: bool, } impl Options { @@ -69,6 +78,9 @@ impl Options { pool_sizes: PoolSizes::detect(), hardware: Hardware::detect(), gpu: GpuConfig::detect(), + sandbox: Sandbox::None, + cargo_target_dir: None, + release: false, } } } @@ -112,10 +124,16 @@ pub enum CacheNote { Skipped(String), } +/// The exec helper refused the call: exit 2 and stderr starting with its +/// `aien-run-exec:` prefix (INFRA C8). Only under `Sandbox::User`. +pub fn sandbox_refused(sandbox: Sandbox, exit: Option, stderr: &[u8]) -> bool { + sandbox == Sandbox::User && exit == Some(2) && stderr.starts_with(b"aien-run-exec:") +} + fn git_out(root: &Path, args: &[&str]) -> Result { // Several jobs may ask for the status at once; the status command must // not take the index lock (and fail the other caller) to refresh it. - let mut cmd = Command::new("git"); + let mut cmd = process::git_command(); cmd.env("GIT_OPTIONAL_LOCKS", "0") .arg("-C") .arg(root) @@ -308,6 +326,46 @@ fn collect_files(root: &Path, rel: &str, out: &mut BTreeSet) { } } +/// Where `run.exec` is, for a run without the sandbox (the runner's PATH). +/// See [`exec_path_for`]. +pub fn exec_path(root: &Path, exec: &str) -> Option { + exec_path_in(root, exec, std::env::var_os("PATH")) +} + +/// Where `run.exec` is for a run under `sandbox`. A name with a slash is +/// repo-relative (the manifest already refuses absolute paths and `..`) and +/// must still be inside the repository after symlinks are followed. A bare +/// name is a program on the PATH, so a shared gate can say `exec: crumb`: +/// the runner's PATH without the sandbox, the exec helper's trusted PATH +/// ([`sandbox::TRUSTED_PATH`]) under `--sandbox user`, so the program hashed +/// into the receipt is the program that runs. None when it is not there. +pub fn exec_path_for(root: &Path, exec: &str, sandbox: Sandbox) -> Option { + match sandbox { + Sandbox::None => exec_path(root, exec), + Sandbox::User => exec_path_in(root, exec, Some(sandbox::TRUSTED_PATH.into())), + } +} + +fn exec_path_in(root: &Path, exec: &str, path: Option) -> Option { + if exec.contains('/') { + let p = root.join(exec); + if !p.is_file() { + return None; + } + // A symlink in the tree must not lead out of it. + let inside = match (p.canonicalize(), root.canonicalize()) { + (Ok(cp), Ok(cr)) => cp.starts_with(cr), + _ => false, + }; + return inside.then_some(p); + } + let path = path?; + std::env::split_paths(&path) + .filter(|d| !d.as_os_str().is_empty()) + .map(|d| d.join(exec)) + .find(|p| p.is_file()) +} + /// sha256 over the canonical list of (path, file sha256) for the explicit /// `inputs` plus the D3 convention-implied inputs of `tests//.gate`. /// A listed path that does not exist is recorded with a null digest. Compiler @@ -432,13 +490,11 @@ pub(crate) fn identity( manifest_path: &Path, m: &Manifest, hw: &Hardware, + sandbox: Sandbox, ) -> Result { - let exec_path = root.join(&m.exec); - let binary_sha = if exec_path.is_file() { - fs::read(&exec_path).ok().map(|b| sha256_hex(&b)) - } else { - None - }; + let binary_sha = exec_path_for(root, &m.exec, sandbox) + .and_then(|p| fs::read(p).ok()) + .map(|b| sha256_hex(&b)); let manifest_rel = manifest_path.strip_prefix(root).ok(); let machine = machine(hw); let machine_digest = canonical_digest(&machine)?; @@ -493,14 +549,17 @@ fn execute_gate(job: &Job<'_>, permit: Option>) -> Result = if evidence_inside { Some("evidence_inside".to_string()) - } else if !before.is_empty() && !opts.allow_dirty { + } else if !before.is_empty() && (!opts.allow_dirty || opts.release) { Some("dirty_tree".to_string()) } else { None }; - let exec_path = root.join(&m.exec); - let exec_exists = exec_path.is_file(); + // Resolved where it will run: a bare name under the user sandbox on the + // helper's trusted PATH. The full path is what runs and what is hashed. + let resolved = exec_path_for(root, &m.exec, opts.sandbox); + let exec_exists = resolved.is_some(); + let exec_path = resolved.unwrap_or_else(|| root.join(&m.exec)); let mut facts = Facts { refusal, exec_exists, @@ -512,11 +571,13 @@ fn execute_gate(job: &Job<'_>, permit: Option>) -> Result, permit: Option>) -> Result, permit: Option>) -> Result { facts.exit_status = o.exit_code.map(i64::from); + // Exit 2 with the helper's prefix is the helper refusing the + // call (nothing ran): never a program result, so it can never + // meet `expects.exit`, not even `exit: 2`. + if sandbox_refused(opts.sandbox, o.exit_code, &o.stderr) { + facts.exit_status = None; + } facts.timed_out = o.timed_out; timeout_exceeded = o.timeout_exceeded; stdout = o.stdout; @@ -1897,4 +1971,78 @@ mod tests { assert!(p.ends_with("workspace/evidence-out/my-repo"), "{p:?}"); } } + + /// A repo whose gate names a bare program (no slash), resolved on PATH. + fn bare_fixture(exec: &str) -> Fx { + let scratch = TempDir::new("scratch"); + let gate = gate_text(exec, &[], 0, &[], "20s", ""); + let repo = init_repo( + "repo", + &[ + ("tests/t.gate", gate.as_str(), false), + ("README", "hello\n", false), + ], + ); + Fx { + repo, + ev: TempDir::new("ev"), + scratch, + } + } + + #[test] + fn exec_path_rules() { + let fx = ok_fixture(); + let root = fx.repo.path(); + // A slash: repo-relative, present or not. + assert_eq!( + exec_path(root, "tools/run.sh"), + Some(root.join("tools/run.sh")) + ); + assert_eq!(exec_path(root, "tools/missing.sh"), None); + // No slash: the PATH, never the repository root. + write_file(root, "true", "#!/bin/sh\nexit 1\n", true); + let p = exec_path(root, "true").expect("true is on PATH"); + assert_ne!(p, root.join("true")); + assert!(p.is_absolute()); + assert_eq!(exec_path(root, "aien-test-no-such-program-x"), None); + } + + #[test] + fn bare_exec_runs_from_path() { + let fx = bare_fixture("true"); + let o = run(&fx, &fx.opts()); + assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["exit_status"], 0); + assert!( + r["core"]["binary_sha256"].is_string(), + "the PATH program is hashed" + ); + } + + #[test] + fn bare_exec_not_on_path_is_missing_implementation() { + let fx = bare_fixture("aien-test-no-such-program-x"); + let o = run(&fx, &fx.opts()); + assert_eq!( + o.verdict, + Verdict::MissingImplementation, + "reason {}", + o.reason + ); + } + + #[test] + fn escaping_exec_is_rejected_never_not_run() { + for bad in ["../../usr/bin/env", "/usr/bin/env", "tools/../../bin/true"] { + let fx = bare_fixture(bad); + match run_gate(fx.repo.path(), &fx.manifest(), &fx.opts()) { + Err(RunError::BadManifest(m)) => { + assert!(m.contains("run.exec"), "{bad}: {m}") + } + other => panic!("{bad} must be a manifest reject, got {other:?}"), + } + } + } } diff --git a/tools/aien-test/src/sandbox.rs b/tools/aien-test/src/sandbox.rs new file mode 100644 index 00000000..433da4da --- /dev/null +++ b/tools/aien-test/src/sandbox.rs @@ -0,0 +1,213 @@ +//! The sandbox seam (contract C8 of the local verification pipeline). +//! +//! `--sandbox none` (the default) runs a gate's program directly, exactly as +//! before. `--sandbox user` runs it through the privileged exec helper +//! `/usr/local/sbin/aien-run-exec`, which drops to the unprivileged +//! `aien-run` user and applies the pool's profile: +//! +//! ```text +//! sudo -n /usr/local/sbin/aien-run-exec --cwd CWD --timeout SECS \ +//! --profile host|qemu|gb10 [--env K=V]... -- PROGRAM ARGS... +//! ``` +//! +//! Only the environment pairs the gate needs are passed: the manifest grammar +//! has no `env` key today, so that set is empty, plus `CARGO_TARGET_DIR` when +//! the runner itself was given one. The helper is INFRA's; this module only +//! builds the command line and never checks that the helper exists (a +//! missing helper fails the spawn, which the receipt records as rc_nonzero +//! with the error on stderr, never as PASS). + +use crate::process::RunSpec; +use std::path::{Path, PathBuf}; + +pub const EXEC_HELPER: &str = "/usr/local/sbin/aien-run-exec"; +pub const SUDO: &str = "sudo"; +/// The PATH the exec helper sets for the `aien-run` user (`RUN_PATH` in +/// `aien-run-exec`). Bare `run.exec` names resolve here under `--sandbox user`. +pub const TRUSTED_PATH: &str = "/var/lib/aien-run/cargo/bin:/usr/local/bin:/usr/bin:/bin"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Sandbox { + /// Run the program directly (every earlier behaviour unchanged). + #[default] + None, + /// Run it as the `aien-run` user through the exec helper. + User, +} + +impl Sandbox { + pub fn parse(s: &str) -> Result { + match s { + "none" => Ok(Sandbox::None), + "user" => Ok(Sandbox::User), + other => Err(format!("--sandbox must be none or user, not {other:?}")), + } + } + + pub fn as_str(self) -> &'static str { + match self { + Sandbox::None => "none", + Sandbox::User => "user", + } + } +} + +/// The program and arguments to spawn for `program ARGS` under `sandbox`. +/// `profile` is the gate's pool name; `env` the `K=V` pairs to pass through. +pub fn command( + sandbox: Sandbox, + program: &Path, + args: &[String], + cwd: &Path, + timeout_secs: u64, + profile: &str, + env: &[(String, String)], +) -> (PathBuf, Vec) { + match sandbox { + Sandbox::None => (program.to_path_buf(), args.to_vec()), + Sandbox::User => { + let mut v: Vec = vec![ + "-n".to_string(), + EXEC_HELPER.to_string(), + "--cwd".to_string(), + cwd.display().to_string(), + "--timeout".to_string(), + timeout_secs.to_string(), + "--profile".to_string(), + profile.to_string(), + ]; + for (k, val) in env { + v.push("--env".to_string()); + v.push(format!("{k}={val}")); + } + v.push("--".to_string()); + v.push(program.display().to_string()); + v.extend(args.iter().cloned()); + (PathBuf::from(SUDO), v) + } + } +} + +/// Rewrite a direct `RunSpec` for the sandbox. `None` returns it unchanged, +/// byte for byte. The timeout policy (`enforce_timeout`) is not touched: a +/// gb10 job stays advisory and is never killed. +pub fn wrap(sandbox: Sandbox, spec: RunSpec, profile: &str, env: &[(String, String)]) -> RunSpec { + if sandbox == Sandbox::None { + return spec; + } + let secs = spec.timeout.as_secs().max(1); + let (program, args) = command( + sandbox, + &spec.program, + &spec.args, + &spec.cwd, + secs, + profile, + env, + ); + RunSpec { + program, + args, + ..spec + } +} + +/// The pairs the runner passes through: only `CARGO_TARGET_DIR` when set. +/// The manifest grammar has no `env` key, so nothing comes from the gate. +pub fn env_pairs(cargo_target_dir: Option<&Path>) -> Vec<(String, String)> { + let mut v = Vec::new(); + if let Some(d) = cargo_target_dir { + v.push(("CARGO_TARGET_DIR".to_string(), d.display().to_string())); + } + v +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn spec() -> RunSpec { + RunSpec { + program: PathBuf::from("/repo/tools/run.sh"), + args: vec!["--fast".into(), "x y".into()], + cwd: PathBuf::from("/repo"), + timeout: Duration::from_millis(90_500), + kill_grace: Duration::from_secs(10), + enforce_timeout: false, + } + } + + #[test] + fn none_is_the_identity() { + let s = spec(); + let w = wrap( + Sandbox::None, + spec(), + "gb10", + &[("CARGO_TARGET_DIR".into(), "/t".into())], + ); + assert_eq!(w.program, s.program); + assert_eq!(w.args, s.args); + assert_eq!(w.cwd, s.cwd); + assert_eq!(w.timeout, s.timeout); + assert!(!w.enforce_timeout); + let (p, a) = command(Sandbox::None, &s.program, &s.args, &s.cwd, 5, "host", &[]); + assert_eq!(p, s.program); + assert_eq!(a, s.args); + } + + #[test] + fn user_builds_the_c8_command_line() { + let env = vec![("CARGO_TARGET_DIR".to_string(), "/tmp/t".to_string())]; + let w = wrap(Sandbox::User, spec(), "qemu", &env); + assert_eq!(w.program, PathBuf::from("sudo")); + assert_eq!( + w.args, + [ + "-n", + EXEC_HELPER, + "--cwd", + "/repo", + "--timeout", + "90", + "--profile", + "qemu", + "--env", + "CARGO_TARGET_DIR=/tmp/t", + "--", + "/repo/tools/run.sh", + "--fast", + "x y", + ] + ); + // The timeout policy is untouched: gb10 stays advisory. + assert!(!w.enforce_timeout); + assert_eq!(w.timeout, Duration::from_millis(90_500)); + assert_eq!(w.cwd, PathBuf::from("/repo")); + } + + #[test] + fn no_env_means_no_env_flags_and_a_tiny_timeout_rounds_up_to_one() { + let mut s = spec(); + s.timeout = Duration::from_millis(10); + let w = wrap(Sandbox::User, s, "host", &[]); + assert!(!w.args.iter().any(|a| a == "--env")); + let pos = w.args.iter().position(|a| a == "--timeout").unwrap(); + assert_eq!(w.args[pos + 1], "1"); + assert_eq!(env_pairs(None), Vec::<(String, String)>::new()); + assert_eq!( + env_pairs(Some(Path::new("/x"))), + vec![("CARGO_TARGET_DIR".to_string(), "/x".to_string())] + ); + } + + #[test] + fn parse_and_names() { + assert_eq!(Sandbox::parse("none").unwrap(), Sandbox::None); + assert_eq!(Sandbox::parse("user").unwrap(), Sandbox::User); + assert!(Sandbox::parse("root").is_err()); + assert_eq!(Sandbox::default(), Sandbox::None); + assert_eq!(Sandbox::User.as_str(), "user"); + } +} diff --git a/tools/aien-test/src/status.rs b/tools/aien-test/src/status.rs new file mode 100644 index 00000000..41f761b9 --- /dev/null +++ b/tools/aien-test/src/status.rs @@ -0,0 +1,336 @@ +//! `aien-test status`: what the local pipeline is doing right now (ADR 0033 +//! Decision 10). Read-only: it never takes a lock or runs a gate. + +use crate::evidence::{utc_secs, utc_string}; +use crate::process; +use crate::resources::{GpuConfig, Hardware, PoolSizes}; +use crate::worker::{self, StateDir}; +use serde_json::Value; +use std::fs; +use std::os::unix::fs::MetadataExt; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// A lock file's state, read from `/proc/locks` by inode (never by probing +/// the lock, which could disturb a running gate). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LockState { + Absent, + Free, + Held(Vec), +} + +impl LockState { + pub fn text(&self) -> String { + match self { + LockState::Absent => "absent".to_string(), + LockState::Free => "free".to_string(), + LockState::Held(pids) => format!( + "held (pid {})", + pids.iter() + .map(|p| p.to_string()) + .collect::>() + .join(",") + ), + } + } +} + +/// Pids holding a FLOCK on `inode` according to `/proc/locks` text. +pub fn flock_holders(locks: &str, inode: u64) -> Vec { + let mut pids = Vec::new(); + for line in locks.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + // "N: FLOCK ADVISORY WRITE pid maj:min:inode start end" + if f.len() < 6 || f[1] != "FLOCK" { + continue; + } + let ino = f[5].rsplit(':').next().and_then(|s| s.parse::().ok()); + if ino == Some(inode) { + if let Ok(pid) = f[4].parse::() { + if !pids.contains(&pid) { + pids.push(pid); + } + } + } + } + pids +} + +pub fn lock_state(path: &Path, locks: &str) -> LockState { + match fs::metadata(path) { + Err(_) => LockState::Absent, + Ok(m) => { + let pids = flock_holders(locks, m.ino()); + if pids.is_empty() { + LockState::Free + } else { + LockState::Held(pids) + } + } + } +} + +fn proc_locks() -> String { + fs::read_to_string("/proc/locks").unwrap_or_default() +} + +/// The quiet flag: `quietlock check` exit code when the tool exists, else the +/// flag file. +pub fn quiet_flag(gpu: &GpuConfig) -> String { + let mut cmd = Command::new("quietlock"); + cmd.arg("check"); + match process::output_gated(&mut cmd) { + Ok(o) if o.status.success() => "clear (quietlock check rc 0)".to_string(), + Ok(o) => format!( + "RAISED (quietlock check rc {}): {}", + o.status.code().unwrap_or(-1), + String::from_utf8_lossy(&o.stdout) + .lines() + .next() + .unwrap_or("") + .trim() + ), + Err(_) => match &gpu.quiet_flag { + Some(p) if p.exists() => format!("RAISED (file {})", p.display()), + Some(p) => format!("clear (no file {})", p.display()), + None => "unknown (no quietlock, no HOME)".to_string(), + }, + } +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// The worker heartbeat line. +pub fn heartbeat_line(state: &StateDir, now: u64) -> String { + let p = state.heartbeat(); + let Ok(text) = fs::read_to_string(&p) else { + return "Worker: no heartbeat".to_string(); + }; + let Ok(v) = serde_json::from_str::(&text) else { + return "Worker: heartbeat unreadable".to_string(); + }; + let age = v["utc"] + .as_str() + .and_then(utc_secs) + .map(|t| now.saturating_sub(t)); + let alive = v["pid"] + .as_u64() + .map(|pid| Path::new(&format!("/proc/{pid}")).exists()); + format!( + "Worker: pid {} {} phase {} repo {} sha {} heartbeat {} ago", + v["pid"].as_u64().unwrap_or(0), + match alive { + Some(true) => "alive", + Some(false) => "GONE", + None => "?", + }, + v["phase"].as_str().unwrap_or("?"), + v["repo"].as_str().unwrap_or("-"), + v["sha"] + .as_str() + .map(|s| &s[..12.min(s.len())]) + .unwrap_or("-"), + match age { + Some(a) => format!("{a} s"), + None => "? s".to_string(), + } + ) +} + +/// Newest bundle per repository: (repo, sha, verdict, finished_utc). +pub fn newest_bundles(state: &StateDir) -> Vec<(String, String, String, String)> { + let mut out = Vec::new(); + let Ok(repos) = fs::read_dir(state.root.join("bundles")) else { + return out; + }; + let mut repos: Vec = repos.flatten().map(|e| e.path()).collect(); + repos.sort(); + for r in repos { + let Ok(shas) = fs::read_dir(&r) else { + continue; + }; + let mut best: Option<(String, String, String, String)> = None; + for s in shas.flatten() { + let p = s.path().join("bundle.json"); + let Ok(text) = fs::read(&p) else { + continue; + }; + let Ok(v) = serde_json::from_slice::(&text) else { + continue; + }; + let fin = v["finished_utc"].as_str().unwrap_or("").to_string(); + if best.as_ref().is_none_or(|b| fin > b.3) { + best = Some(( + r.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + v["commit"].as_str().unwrap_or("?").to_string(), + match v["plan"]["verdict"].as_str() { + Some(p) if p != v["verdict"].as_str().unwrap_or("") => { + format!("{} (plan {p})", v["verdict"].as_str().unwrap_or("?")) + } + _ => v["verdict"].as_str().unwrap_or("?").to_string(), + }, + fin, + )); + } + } + if let Some(b) = best { + out.push(b); + } + } + out +} + +/// The whole status block. +pub fn lines(state: &StateDir) -> Vec { + let now = now_secs(); + let mut out = vec![ + "AIEN STATUS".to_string(), + format!("Time: {}", utc_string(now)), + ]; + let pools = PoolSizes::detect(); + let hw = Hardware::detect(); + out.push(format!( + "Pools: host={} qemu={} gb10=1", + pools.host, pools.qemu + )); + out.push(format!( + "Hardware: gb10 {} qemu {}", + if hw.gb10_present { "present" } else { "absent" }, + if hw.qemu_available { + "available" + } else { + "absent" + } + )); + let gpu = GpuConfig::detect(); + let locks = proc_locks(); + out.push(format!( + "GPU lock {}: {}", + gpu.lock_path.display(), + lock_state(&gpu.lock_path, &locks).text() + )); + match &gpu.proof_lock_path { + Some(p) => { + let slots = p.parent().map(Path::to_path_buf).unwrap_or_default(); + let mut names: Vec = fs::read_dir(&slots) + .map(|rd| rd.flatten().map(|e| e.path()).collect()) + .unwrap_or_default(); + names.sort(); + names.retain(|n| n.extension().is_some_and(|e| e == "lock")); + if names.is_empty() { + out.push(format!("aien-proof slots {}: none", slots.display())); + } + for n in names { + out.push(format!( + "aien-proof slot {}: {}", + n.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + lock_state(&n, &locks).text() + )); + } + } + None => out.push("aien-proof slots: no board".to_string()), + } + out.push(format!("Quiet flag: {}", quiet_flag(&gpu))); + out.push(format!("State dir: {}", state.root.display())); + out.push(heartbeat_line(state, now)); + let triggers = worker::triggers(state); + out.push(format!( + "Triggers pending: {}{}", + triggers.len(), + if triggers.is_empty() { + String::new() + } else { + format!( + " ({})", + triggers + .iter() + .map(|(r, s, _)| format!("{r}@{}", &s[..12])) + .collect::>() + .join(" ") + ) + } + )); + let outbox = worker::outbox_files(state).len(); + out.push(format!("Outbox pending: {outbox}")); + let bundles = newest_bundles(state); + if bundles.is_empty() { + out.push("Newest bundles: none".to_string()); + } + for (repo, sha, verdict, fin) in bundles { + out.push(format!( + "Newest bundle {repo}: {} {verdict} {fin}", + &sha[..12.min(sha.len())] + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::TempDir; + + #[test] + fn proc_locks_parsing() { + let text = "1: POSIX ADVISORY READ 4076 103:02:10631027 1073741826 1073742335\n\ + 2: FLOCK ADVISORY WRITE 2379546 00:a9:8128022 0 EOF\n\ + 3: FLOCK ADVISORY WRITE 2502 103:02:8128022 0 EOF\n\ + 4: -> FLOCK ADVISORY WRITE 99 00:a9:8128022 0 EOF\n"; + assert_eq!(flock_holders(text, 8128022), vec![2379546, 2502]); + assert!(flock_holders(text, 10631027).is_empty()); + let t = TempDir::new("status-lock"); + let f = t.path().join("x.lock"); + assert_eq!(lock_state(&f, text), LockState::Absent); + fs::write(&f, "").unwrap(); + assert_eq!(lock_state(&f, text), LockState::Free); + let ino = fs::metadata(&f).unwrap().ino(); + let held = format!("5: FLOCK ADVISORY WRITE 777 00:01:{ino} 0 EOF\n"); + assert_eq!(lock_state(&f, &held), LockState::Held(vec![777])); + assert_eq!(LockState::Held(vec![1, 2]).text(), "held (pid 1,2)"); + } + + #[test] + fn heartbeat_and_bundles() { + let t = TempDir::new("status-state"); + let s = StateDir::new(t.path()); + assert_eq!(heartbeat_line(&s, 10), "Worker: no heartbeat"); + s.beat("r", &"c".repeat(40), "run"); + let l = heartbeat_line(&s, now_secs() + 5); + assert!(l.contains("alive") && l.contains("phase run"), "{l}"); + assert!(newest_bundles(&s).is_empty()); + for (sha, fin, v) in [ + ("a", "2026-10-11T01:00:00Z", "PASS"), + ("b", "2026-10-11T02:00:00Z", "FAIL"), + ] { + let d = s.root.join("bundles/r").join(sha.repeat(40)); + fs::create_dir_all(&d).unwrap(); + fs::write( + d.join("bundle.json"), + format!( + "{{\"commit\":\"{}\",\"verdict\":\"{v}\",\"finished_utc\":\"{fin}\"}}", + sha.repeat(40) + ), + ) + .unwrap(); + } + let n = newest_bundles(&s); + assert_eq!(n.len(), 1); + assert_eq!(n[0].2, "FAIL"); + let all = lines(&s); + assert_eq!(all[0], "AIEN STATUS"); + assert!(all + .iter() + .any(|l| l.starts_with("Newest bundle r: bbbbbbbbbbbb FAIL"))); + } +} diff --git a/tools/aien-test/src/verify.rs b/tools/aien-test/src/verify.rs new file mode 100644 index 00000000..745788b4 --- /dev/null +++ b/tools/aien-test/src/verify.rs @@ -0,0 +1,642 @@ +//! `aien-test verify COMMIT`: the independent check of a local verification +//! (ADR 0033 Decision 10, contracts C4 to C6, amendments A1 and A7). +//! +//! It reads the signed bundle the worker wrote, checks it against the public +//! keys the repository committed at BASE (`.aien/verify.pub`, one hex key per +//! line), recomputes the plan for BASE..COMMIT and compares the graph digest, +//! checks that every `run` entry has its receipt on disk, judges the verdict +//! with the planner's algebra, asks `crumb verify` about the tree at COMMIT, +//! and prints the fixed report block. Exit 0 only on MERGE ELIGIBILITY READY. + +use crate::bundle::{self, Expect}; +use crate::evidence::{self, utc_secs, Index, Store}; +use crate::manifest::CacheScope; +use crate::plan::{self, Known, Plan, Request, Section}; +use crate::process; +use crate::verdict::Verdict; +use crate::worker::StateDir; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +pub const KEYS_FILE: &str = ".aien/verify.pub"; + +/// What the verifier was asked to do. +#[derive(Debug, Clone)] +pub struct Ask { + pub state: StateDir, + pub commit: String, + pub base: String, + pub repository: Option, + pub release: bool, + pub operator: bool, + pub hardware_identity: String, + /// The crumb command; None skips the crumb check (status STALE). + pub crumb: Option, + /// Keys to trust instead of `.aien/verify.pub` at BASE (tests). + pub keys_override: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + pub lines: Vec, + pub ready: bool, +} + +/// Public keys from `.aien/verify.pub` at `commit`, one hex key per line, +/// `#` comments and blank lines ignored. +pub fn keys_at(root: &Path, commit: &str) -> Vec { + let Some(bytes) = plan::show(root, commit, KEYS_FILE) else { + return Vec::new(); + }; + parse_keys(&String::from_utf8_lossy(&bytes)) +} + +pub fn parse_keys(text: &str) -> Vec { + text.lines() + .map(|l| { + l.split('#') + .next() + .unwrap_or("") + .trim() + .to_ascii_lowercase() + }) + .filter(|l| l.len() == 64 && l.bytes().all(|b| b.is_ascii_hexdigit())) + .collect() +} + +/// A receipt the bundle points at, found in the commit's evidence directory. +struct Found { + index: Index, +} + +impl Found { + fn load(dir: &Path) -> Found { + Found { + index: Index::load(&Store::new(dir)), + } + } + fn get(&self, digest: &str) -> Option<&evidence::Stored> { + self.index.get(digest) + } +} + +fn sum_u64(index: &Index, digests: &[String], key: &str) -> Option { + let mut total = 0u64; + let mut any = false; + for d in digests { + if let Some(s) = index.get(d) { + if let Some(v) = s + .value + .get("volatile") + .and_then(|o| o.get(key)) + .and_then(Value::as_u64) + { + total += v; + any = true; + } + } + } + any.then_some(total) +} + +/// `crumb verify` over the tree at COMMIT, in a temporary detached worktree. +/// CURRENT only when crumb says OK; STALE otherwise, also when the command is +/// unavailable (the tree is then not proven current). +pub fn crumb_status(root: &Path, commit: &str, crumb: Option<&str>) -> (String, String) { + let Some(crumb) = crumb else { + return ("STALE".into(), "crumb check skipped".into()); + }; + let tmp = std::env::temp_dir().join(format!( + "aien-verify-{}-{}", + std::process::id(), + &commit[..12] + )); + let _ = fs::remove_dir_all(&tmp); + let mut add = Command::new("git"); + add.args(["worktree", "add", "--detach", "--quiet"]) + .arg(&tmp) + .arg(commit) + .current_dir(root) + .env("GIT_OPTIONAL_LOCKS", "0"); + let out = match process::output_gated(&mut add) { + Ok(o) if o.status.success() => o, + Ok(o) => { + return ( + "STALE".into(), + format!( + "cannot check out {commit}: {}", + String::from_utf8_lossy(&o.stderr).trim() + ), + ); + } + Err(e) => return ("STALE".into(), format!("cannot run git: {e}")), + }; + drop(out); + let result = if !tmp.join(".crumb").exists() { + ( + "STALE".to_string(), + "no .crumb at the repository root".to_string(), + ) + } else { + let mut cmd = Command::new(crumb); + cmd.args(["verify", "."]).current_dir(&tmp); + match process::output_gated(&mut cmd) { + Ok(o) if o.status.success() => ( + "CURRENT".to_string(), + String::from_utf8_lossy(&o.stdout) + .lines() + .next() + .unwrap_or("") + .trim() + .to_string(), + ), + Ok(o) => ( + "STALE".to_string(), + format!( + "{} {}", + String::from_utf8_lossy(&o.stdout) + .lines() + .last() + .unwrap_or("") + .trim(), + String::from_utf8_lossy(&o.stderr) + .lines() + .last() + .unwrap_or("") + .trim() + ) + .trim() + .to_string(), + ), + Err(e) => ("STALE".to_string(), format!("cannot run {crumb}: {e}")), + } + }; + let mut rm = Command::new("git"); + rm.args(["worktree", "remove", "--force"]) + .arg(&tmp) + .current_dir(root); + let _ = process::output_gated(&mut rm); + let _ = fs::remove_dir_all(&tmp); + let mut prune = Command::new("git"); + prune.args(["worktree", "prune"]).current_dir(root); + let _ = process::output_gated(&mut prune); + result +} + +fn verdict_line(v: &str) -> &str { + match v { + "PASS" | "FAIL" | "NOT_RUN" => v, + "BLOCKED_HARDWARE" | "BLOCKED_OPERATOR" => "BLOCKED", + _ => "NOT_RUN", + } +} + +/// Verify one commit's bundle against the repository at `root`. +pub fn run(root: &Path, ask: &Ask) -> Report { + let repository = plan::repository_name(root, ask.repository.as_deref()); + let repo = StateDir::repo_key(&repository); + let commit = ask.commit.to_ascii_lowercase(); + let mut lines: Vec = vec!["AIEN LOCAL VERIFICATION".to_string()]; + let mut problems: Vec = Vec::new(); + + // The commit and base must exist here. + let commit_ok = plan::resolve(root, &commit) + .map(|c| c == commit) + .unwrap_or(false); + // The worker's BASE rule: a commit already on the base line is checked + // against its first parent, any other against the base ref. + let base = if commit_ok { + plan::base_for(root, &ask.base, &commit).map(|(b, _)| b) + } else { + plan::resolve(root, &ask.base) + }; + lines.push(format!("Repository: {repository}")); + lines.push(format!("Commit: {commit}")); + if !commit_ok { + problems.push(format!("commit {commit} is not in this repository")); + } + let base = match base { + Ok(b) => Some(b), + Err(e) => { + problems.push(e); + None + } + }; + + // The plan, fresh. + let plan: Option = match (&base, commit_ok) { + (Some(b), true) => { + let mut req = Request::new(b, &commit); + req.operator = ask.operator; + req.hardware_identity = ask.hardware_identity.clone(); + match plan::compute(root, &req) { + Ok(p) => Some(p), + Err(e) => { + problems.push(format!("cannot plan: {e}")); + None + } + } + } + _ => None, + }; + + // The bundle. + let bundle_path = ask.state.bundle_path(&repo, &commit); + let bundle: Option = match fs::read(&bundle_path) { + Ok(b) => match serde_json::from_slice::(&b) { + Ok(v) => Some(v), + Err(e) => { + problems.push(format!("bundle is not JSON: {e}")); + None + } + }, + Err(_) => { + problems.push(format!("no bundle at {}", bundle_path.display())); + None + } + }; + + // Keys at BASE (A1, A7): pick the one the bundle names; otherwise UNKNOWN_KEY. + let keys = match (&ask.keys_override, &base) { + (Some(k), _) => k.clone(), + (None, Some(b)) => keys_at(root, b), + (None, None) => Vec::new(), + }; + let required: Vec = plan + .as_ref() + .map(|p| { + p.entries + .iter() + .filter(|e| e.required && e.section != Section::Blocked) + .map(|e| e.gate.clone()) + .collect() + }) + .unwrap_or_default(); + let mut evidence_status = "INVALID".to_string(); + let mut evidence_note = String::new(); + let mut verified: Option = None; + if let Some(b) = &bundle { + if keys.is_empty() { + evidence_note = format!("no trusted keys ({KEYS_FILE} at BASE is missing or empty)"); + } else { + let named = b["signature"]["pubkey"] + .as_str() + .unwrap_or("") + .to_ascii_lowercase(); + let key = keys + .iter() + .find(|k| **k == named) + .cloned() + .unwrap_or_else(|| keys[0].clone()); + let expect = Expect { + repository: repository.clone(), + commit: commit.clone(), + pubkey_hex: key, + required: required.clone(), + }; + match bundle::verify(b, &expect) { + Ok(v) => { + evidence_status = "VERIFIED".to_string(); + verified = Some(v); + } + Err(r) => evidence_note = r.to_string(), + } + } + } + + // Bundle against plan: graph digest, receipts, release rule. + let mut known: BTreeMap = BTreeMap::new(); + let mut executed: Vec = Vec::new(); + let mut cached: Vec = Vec::new(); + let mut failed: Vec = Vec::new(); + let mut blocked: Vec = Vec::new(); + let mut run_digests: Vec = Vec::new(); + let evidence_dir = ask.state.evidence(&repo, &commit); + let found = Found::load(&evidence_dir); + if let (Some(b), Some(p)) = (&bundle, &plan) { + if b["graph_digest"].as_str() != Some(p.graph_digest.as_str()) { + evidence_status = "INVALID".to_string(); + let note = format!( + "GRAPH_MISMATCH: bundle graph {} but the plan for {}..{} gives {}", + b["graph_digest"].as_str().unwrap_or("?"), + &p.base[..12.min(p.base.len())], + &commit[..12], + p.graph_digest + ); + if evidence_note.is_empty() { + evidence_note = note; + } else { + problems.push(note); + } + } + let by_gate: BTreeMap = + p.entries.iter().map(|e| (e.gate.clone(), e)).collect(); + for c in b["checks"].as_array().map(Vec::as_slice).unwrap_or(&[]) { + let gate = c["gate"].as_str().unwrap_or("").to_string(); + let status = c["status"].as_str().unwrap_or(""); + let v = Verdict::parse(c["verdict"].as_str().unwrap_or("")).unwrap_or(Verdict::NotRun); + let entry = by_gate.get(&gate); + let mut reason = String::new(); + let mut verdict = v; + // The entry must name the check the plan computes for this gate + // at COMMIT; an entry for another check id never counts. + if let Some(e) = entry { + if c["check_id"].as_str() != Some(e.check_id.as_str()) { + verdict = Verdict::NotRun; + reason = "CHECK_ID_MISMATCH".into(); + problems.push(format!( + "{gate}: CHECK_ID_MISMATCH bundle {} but the plan gives {}", + c["check_id"].as_str().unwrap_or("?"), + e.check_id + )); + } + } + // The manifest digest of this gate at COMMIT, for the receipt check. + let manifest_digest = p + .graph + .index_of(&gate) + .map(|i| p.graph.node(i).manifest.digest.clone()); + match status { + "run" => { + let d = c["receipt"].as_str().unwrap_or("").to_string(); + let receipt_manifest = |s: &evidence::Stored| { + s.value["core"]["manifest_digest"] + .as_str() + .map(str::to_string) + }; + match found.get(&d) { + Some(s) + if s.gate() == gate + && s.commit() == commit + && s.verdict() == Some(v) + && manifest_digest.is_some() + && receipt_manifest(s) == manifest_digest => + { + if reason.is_empty() { + executed.push(gate.clone()); + run_digests.push(d.clone()); + } + } + Some(s) if s.gate() == gate && receipt_manifest(s) != manifest_digest => { + verdict = Verdict::NotRun; + reason = "MANIFEST_MISMATCH".into(); + problems.push(format!( + "{gate}: MANIFEST_MISMATCH receipt {d} was made from another manifest than the one at {}", + &commit[..12] + )); + } + Some(_) => { + verdict = Verdict::NotRun; + reason = "RECEIPT_MISMATCH".into(); + problems.push(format!( + "{gate}: receipt {d} does not match the bundle entry" + )); + } + None => { + verdict = Verdict::NotRun; + reason = "RECEIPT_MISSING".into(); + problems.push(format!( + "{gate}: receipt {d} is not in {}", + evidence_dir.display() + )); + } + } + if v == Verdict::Fail { + failed.push(gate.clone()); + } + } + "cached" => { + let scope = entry.map(|e| e.cache_scope); + if ask.release && scope == Some(CacheScope::Hardware) { + verdict = Verdict::NotRun; + reason = "CACHE_SCOPE_HARDWARE_RELEASE".into(); + problems.push(format!( + "{gate}: a cached hardware-scoped result cannot satisfy --release" + )); + } else { + cached.push(gate.clone()); + } + if v == Verdict::Fail { + failed.push(gate.clone()); + } + } + "blocked" => { + blocked.push(gate.clone()); + if !matches!(v, Verdict::BlockedHardware | Verdict::BlockedOperator) { + verdict = Verdict::BlockedOperator; + } + reason = "BLOCKED".into(); + } + _ => { + if v == Verdict::Fail { + failed.push(gate.clone()); + } + reason = "NOT_RUN".into(); + } + } + if entry.is_none() { + problems.push(format!("{gate}: in the bundle but not in the plan")); + } + known.insert( + gate, + Known { + verdict, + reason, + receipt: c["receipt"] + .as_str() + .or_else(|| c["resolution"]["resolved_from"].as_str()) + .map(str::to_string), + }, + ); + } + } + let judged = plan.as_ref().map(|p| plan::judge(p, &known)); + + // The report body. + let changed = plan.as_ref().map(|p| p.changed.len()).unwrap_or(0); + let affected: Vec = plan + .as_ref() + .map(|p| p.entries.iter().map(|e| e.gate.clone()).collect()) + .unwrap_or_default(); + let unmapped = plan + .as_ref() + .map(|p| p.unmapped.clone()) + .unwrap_or_default(); + lines.push(format!("Changed files: {changed}")); + lines.push(format!("Affected gates: {}", list(&affected))); + lines.push(format!("Executed gates: {}", list(&executed))); + lines.push(format!("Cached gates: {}", list(&cached))); + lines.push(format!("Failed gates: {}", list(&failed))); + lines.push(format!("Blocked gates: {}", list(&blocked))); + let (crumb, crumb_note) = if commit_ok { + crumb_status(root, &commit, ask.crumb.as_deref()) + } else { + ("STALE".into(), "commit missing".into()) + }; + lines.push(format!("Crumb status: {crumb}")); + lines.push(format!("Evidence status: {evidence_status}")); + let hardware = match &plan { + Some(p) + if p.entries + .iter() + .any(|e| e.section == Section::NeedsGb10 || e.section == Section::NeedsSpark) => + { + let hw: Vec<&plan::Entry> = p + .entries + .iter() + .filter(|e| e.section == Section::NeedsGb10 || e.section == Section::NeedsSpark) + .collect(); + if hw.iter().all(|e| { + known + .get(&e.gate) + .map(|k| k.verdict == Verdict::Pass) + .unwrap_or(false) + }) { + "QUALIFIED" + } else { + "BLOCKED" + } + } + Some(_) => "NOT_REQUIRED", + None => "BLOCKED", + }; + lines.push(format!("Hardware status: {hardware}")); + let final_verdict = match (&judged, evidence_status.as_str()) { + (Some(j), "VERIFIED") => verdict_line(j.verdict.as_str()).to_string(), + (Some(j), _) if j.verdict == Verdict::Fail => "FAIL".to_string(), + (Some(j), _) + if matches!( + j.verdict, + Verdict::BlockedHardware | Verdict::BlockedOperator + ) => + { + "BLOCKED".to_string() + } + _ => "NOT_RUN".to_string(), + }; + lines.push(format!("Final verdict: {final_verdict}")); + let queue = sum_u64(&found.index, &run_digests, "pool_wait_ms"); + let test = sum_u64(&found.index, &run_digests, "duration_ms"); + let total = bundle.as_ref().and_then(|b| { + let s = utc_secs(b["started_utc"].as_str()?)?; + let f = utc_secs(b["finished_utc"].as_str()?)?; + Some(f.saturating_sub(s) * 1000) + }); + lines.push(format!("Queue time: {}", ms(queue))); + lines.push("Build time: n/a".to_string()); + lines.push(format!("Test time: {}", ms(test))); + lines.push(format!("Total time: {}", ms(total))); + let ready = evidence_status == "VERIFIED" + && final_verdict == "PASS" + && crumb == "CURRENT" + && unmapped.is_empty() + && blocked.is_empty() + && problems.is_empty() + && judged.as_ref().is_some_and(|j| j.verdict == Verdict::Pass) + && verified.as_ref().is_some_and(|v| v.verdict == "PASS"); + lines.push(format!( + "MERGE ELIGIBILITY: {}", + if ready { "READY" } else { "BLOCKED" } + )); + if !evidence_note.is_empty() { + lines.push(format!("Evidence note: {evidence_note}")); + } + if !crumb_note.is_empty() { + lines.push(format!("Crumb note: {crumb_note}")); + } + if let Some(j) = &judged { + if !j.reason.is_empty() { + lines.push(format!("Verdict reason: {}", j.reason)); + } + } + if !unmapped.is_empty() { + lines.push(format!("Unmapped: {}", unmapped.join(" "))); + } + for p in &problems { + lines.push(format!("Problem: {p}")); + } + lines.push(format!("Bundle: {}", bundle_path.display())); + Report { lines, ready } +} + +fn list(v: &[String]) -> String { + if v.is_empty() { + "none".to_string() + } else { + format!("{} ({})", v.len(), v.join(" ")) + } +} + +fn ms(v: Option) -> String { + match v { + Some(ms) => format!("{ms} ms"), + None => "n/a".to_string(), + } +} + +/// Where the trusted clone of `repository` is expected (`~/workspace/`). +pub fn default_clone(repository: &str) -> Option { + let home = std::env::var_os("HOME")?; + Some( + PathBuf::from(home) + .join("workspace") + .join(StateDir::repo_key(repository)), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_parse() { + let a = "a".repeat(64); + let text = format!( + "# keys\n{a}\n\n {} # second\nnot-a-key\n", + "B".repeat(64) + ); + let k = parse_keys(&text); + assert_eq!(k, vec![a, "b".repeat(64)]); + } + + #[test] + fn verdict_lines() { + assert_eq!(verdict_line("PASS"), "PASS"); + assert_eq!(verdict_line("BLOCKED_HARDWARE"), "BLOCKED"); + assert_eq!(verdict_line("MISSING_IMPLEMENTATION"), "NOT_RUN"); + assert_eq!(list(&[]), "none"); + assert_eq!(list(&["a".into(), "b".into()]), "2 (a b)"); + assert_eq!(ms(None), "n/a"); + assert_eq!(ms(Some(12)), "12 ms"); + } + + #[test] + fn missing_bundle_is_blocked_not_ready() { + let repo = crate::testutil::init_repo("verify-empty", &[("README", "x\n", false)]); + let head = plan::resolve(repo.path(), "HEAD").unwrap(); + let state = crate::testutil::TempDir::new("verify-state"); + let ask = Ask { + state: StateDir::new(state.path()), + commit: head.clone(), + base: "HEAD".into(), + repository: Some("github.com/t/r".into()), + release: false, + operator: false, + hardware_identity: String::new(), + crumb: None, + keys_override: None, + }; + let r = run(repo.path(), &ask); + assert!(!r.ready); + assert_eq!(r.lines[0], "AIEN LOCAL VERIFICATION"); + assert!(r.lines.iter().any(|l| l == "Evidence status: INVALID")); + assert!(r.lines.iter().any(|l| l == "MERGE ELIGIBILITY: BLOCKED")); + assert!(r + .lines + .iter() + .any(|l| l.starts_with("Problem: no bundle at "))); + } +} diff --git a/tools/aien-test/src/worker.rs b/tools/aien-test/src/worker.rs new file mode 100644 index 00000000..88a909b5 --- /dev/null +++ b/tools/aien-test/src/worker.rs @@ -0,0 +1,1231 @@ +//! The trusted worker (ADR 0033 Decision 9; local pipeline contracts C1 to +//! C7) and the state directory every local-CI command shares. +//! +//! State lives under `~/.local/state/aien-local-ci/`: +//! +//! ```text +//! evidence/// receipts and blobs of that commit's run +//! bundles///bundle.json the signed VerificationBundleV1 +//! trigger/. a file whose presence asks for a run +//! outbox/..json a GitHub status that could not be posted yet +//! journal.jsonl one line per finished head +//! worker.heartbeat what the worker is doing right now +//! ``` +//! +//! For one head: fetch into the trusted clone `/` (its checkout +//! is never touched), add a detached worktree `//`, +//! `crumb claim` it, plan, run the selected gates with the sandbox and the +//! pools, write receipts, build and sign the bundle with `~/.aien/verify.key`, +//! write it, journal it, `crumb close`, remove the worktree. With `--github` +//! the commit status `AIEN Verification (Spark)` is posted: success only on +//! PASS, failure on FAIL, error otherwise. When GitHub cannot be reached the +//! status goes to the outbox, the journal says `publication: pending`, and the +//! next successful contact flushes it. GitHub being down is never a local +//! failure. + +use crate::bundle; +use crate::evidence::{canonical, canonical_digest, sha256_hex, utc_string}; +use crate::graph; +use crate::plan::{self, Known, Section}; +use crate::process; +use crate::resources::Hardware; +use crate::runner::{self, CacheNote, Options}; +use crate::sandbox::Sandbox; +use crate::verdict::Verdict; +use crate::verify; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +pub const CONTEXT: &str = "AIEN Verification (Spark)"; +pub const EXECUTOR_CLASS: &str = "spark"; +/// Where INFRA keeps the per-repository cargo target dirs (A2). +pub const TARGET_ROOT: &str = "/var/lib/aien-run/target"; +/// Where INFRA's `wt.sh` keeps the bare mirrors its worktrees point into. +pub const MIRROR_ROOT: &str = "/var/lib/aien-run/mirror"; + +/// A repository directory key the worker accepts: letters, digits, `.`, `_` +/// and `-`, not starting with a dot (so never `.` or `..`). +pub fn valid_repo_key(repo: &str) -> bool { + !repo.is_empty() + && repo.len() <= 100 + && !repo.starts_with('.') + && repo + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-') +} + +/// A full lowercase 40-hex commit id. +pub fn valid_sha(sha: &str) -> bool { + sha.len() == 40 + && sha + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// The signing key must be a regular file only its owner can read or write +/// (mode 0600 or stricter): a key the `aien-run` user could read would let a +/// gate sign its own bundle. +pub fn check_key_private(path: &Path) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt; + let meta = fs::symlink_metadata(path) + .map_err(|e| format!("cannot stat signing key {}: {e}", path.display()))?; + if !meta.file_type().is_file() { + return Err(format!( + "signing key {} is not a regular file", + path.display() + )); + } + let mode = meta.permissions().mode() & 0o777; + if mode & 0o077 != 0 { + return Err(format!( + "signing key {} has mode {mode:o}; it must be 0600 (no group or other access)", + path.display() + )); + } + Ok(()) +} + +/// The local-CI state directory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StateDir { + pub root: PathBuf, +} + +impl StateDir { + pub fn new(root: &Path) -> StateDir { + StateDir { + root: root.to_path_buf(), + } + } + + /// `~/.local/state/aien-local-ci`; None without HOME. + pub fn default_dir() -> Option { + let home = std::env::var_os("HOME")?; + Some(StateDir::new( + &PathBuf::from(home).join(".local/state/aien-local-ci"), + )) + } + + /// The directory key of a repository name: its last path segment. + pub fn repo_key(repository: &str) -> String { + repository + .trim_end_matches('/') + .rsplit('/') + .next() + .unwrap_or(repository) + .to_string() + } + + pub fn evidence(&self, repo: &str, sha: &str) -> PathBuf { + self.root.join("evidence").join(repo).join(sha) + } + + pub fn bundle_path(&self, repo: &str, sha: &str) -> PathBuf { + self.root + .join("bundles") + .join(repo) + .join(sha) + .join("bundle.json") + } + + pub fn trigger_dir(&self) -> PathBuf { + self.root.join("trigger") + } + + pub fn outbox_dir(&self) -> PathBuf { + self.root.join("outbox") + } + + pub fn journal(&self) -> PathBuf { + self.root.join("journal.jsonl") + } + + pub fn heartbeat(&self) -> PathBuf { + self.root.join("worker.heartbeat") + } + + /// Append one JSON line to the journal. + pub fn journal_append(&self, entry: &Value) -> Result<(), String> { + fs::create_dir_all(&self.root).map_err(|e| format!("cannot create state dir: {e}"))?; + let mut f = fs::OpenOptions::new() + .append(true) + .create(true) + .open(self.journal()) + .map_err(|e| format!("cannot open journal: {e}"))?; + let mut line = serde_json::to_string(entry).map_err(|e| e.to_string())?; + line.push('\n'); + f.write_all(line.as_bytes()) + .map_err(|e| format!("cannot write journal: {e}")) + } + + /// Overwrite the heartbeat file (atomic rename). + pub fn beat(&self, repo: &str, sha: &str, phase: &str) { + let v = json!({ + "utc": utc_string(now_secs()), + "pid": std::process::id(), + "repo": repo, + "sha": sha, + "phase": phase, + }); + let _ = fs::create_dir_all(&self.root); + let tmp = self.root.join("worker.heartbeat.tmp"); + if fs::write(&tmp, serde_json::to_string(&v).unwrap_or_default()).is_ok() { + let _ = fs::rename(&tmp, self.heartbeat()); + } + } +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// How the worker is set up. +#[derive(Debug, Clone)] +pub struct Config { + pub state: StateDir, + pub key: PathBuf, + /// Where the trusted clones live: `/`. + pub clones: PathBuf, + pub wt_root: PathBuf, + pub sandbox: Sandbox, + pub github: bool, + pub poll: Duration, + pub repos: Vec, + /// The ref the plan is based on (`origin/main`); a head that *is* that + /// ref is planned against its first parent. + pub base_ref: String, + pub operator: bool, + /// The crumb command (`crumb`); None skips crumb claim/close. + pub crumb: Option, + /// The GitHub CLI (`gh`), looked up on PATH. + pub gh: String, + pub hardware_identity: String, + /// Allow `Sandbox::None` (development only: gates then run as the + /// worker user, who can read the signing key). Never with `github`. + pub allow_unsandboxed: bool, + /// Per-repository cargo target directories by trust class + /// (`//main|pr`), used under `Sandbox::User`. + pub target_root: PathBuf, + /// INFRA's worktree tool (`tools/aien-local-ci/wt.sh`). Under + /// `Sandbox::User` every checkout is made and removed with it; without it + /// the worker refuses to run. + pub wt_tool: Option, + /// The mirrors `wt_tool` keeps (`/.git`). + pub mirror_root: PathBuf, +} + +impl Config { + pub fn new(state: StateDir, key: &Path, clones: &Path, wt_root: &Path) -> Config { + Config { + state, + key: key.to_path_buf(), + clones: clones.to_path_buf(), + wt_root: wt_root.to_path_buf(), + sandbox: Sandbox::None, + github: false, + poll: Duration::from_secs(30), + repos: Vec::new(), + base_ref: "origin/main".to_string(), + operator: false, + crumb: Some("crumb".to_string()), + gh: "gh".to_string(), + hardware_identity: String::new(), + allow_unsandboxed: false, + target_root: PathBuf::from(TARGET_ROOT), + wt_tool: None, + mirror_root: PathBuf::from(MIRROR_ROOT), + } + } + + /// The sandbox rule: `Sandbox::User` always; `Sandbox::None` only when + /// `allow_unsandboxed` (development) and never when serving GitHub heads. + pub fn check_sandbox_policy_for(&self, github: bool) -> Result<(), String> { + if self.sandbox == Sandbox::User { + return Ok(()); + } + if github { + return Err("--sandbox none is refused with --github: pull request code must run as the aien-run user".to_string()); + } + if !self.allow_unsandboxed { + return Err("--sandbox none runs gates as the worker user, who can read the signing key; it needs --dev-unsandboxed (development only)".to_string()); + } + Ok(()) + } +} + +/// What one head produced. +#[derive(Debug, Clone)] +pub struct Summary { + pub repo: String, + pub sha: String, + pub repository: String, + pub verdict: Verdict, + pub reason: String, + pub bundle_verdict: String, + pub bundle_path: PathBuf, + pub bundle_digest: String, + pub gates: Vec<(String, String, Verdict)>, + pub publication: String, + /// What the independent check (`verify`) said about the bundle. + pub ready: bool, + pub notes: Vec, +} + +fn run_cmd(cwd: &Path, program: &str, args: &[&str]) -> Result { + let mut cmd = Command::new(program); + cmd.args(args).current_dir(cwd); + // git and crumb (which runs git) may open a trusted wt.sh worktree. + process::apply_git_trust(&mut cmd); + if program == "git" { + cmd.env("GIT_OPTIONAL_LOCKS", "0"); + } + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {program}: {e}"))?; + if !out.status.success() { + return Err(format!( + "{program} {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +fn git(cwd: &Path, args: &[&str]) -> Result { + run_cmd(cwd, "git", args) +} + +/// Under `Sandbox::User`: make the worktree with INFRA's `wt.sh` (`sync` the +/// mirror from the trusted clone, `add` the head), so `aien-run` can read its +/// git data and write its files while the `.git` link stays root-owned. An +/// older tree for the same head is removed first and never reused (a `main` +/// qualification must not inherit what a pull request run left behind). +fn checkout_for_sandbox( + cfg: &Config, + repo: &str, + sha: &str, + clone: &Path, +) -> Result { + let tool = cfg.wt_tool.as_ref().ok_or_else(|| { + "--sandbox user needs INFRA's worktree tool (--wt-tool, tools/aien-local-ci/wt.sh): \ + a checkout made from the private clone is unreadable to aien-run" + .to_string() + })?; + let tool = tool.display().to_string(); + let clone_s = clone.display().to_string(); + run_cmd(clone, &tool, &["sync", repo, &clone_s])?; + let mirror = cfg.mirror_root.join(format!("{repo}.git")); + let commit = format!("{sha}^{{commit}}"); + if git(&mirror, &["cat-file", "-e", &commit]).is_err() { + // A head no branch names (a pull request head, a trigger for a + // detached commit): fetch that one commit into the mirror. + git(&mirror, &["fetch", "--quiet", &clone_s, sha])?; + } + git(&mirror, &["cat-file", "-e", &commit]) + .map_err(|_| format!("commit {sha} is not in {}", mirror.display()))?; + let wt = cfg.wt_root.join(repo).join(sha); + if fs::symlink_metadata(&wt).is_ok() { + run_cmd(clone, &tool, &["remove", repo, sha])?; + } + let made = run_cmd(clone, &tool, &["add", repo, sha])?; + if Path::new(made.trim()) != wt { + return Err(format!( + "{tool} made {:?}, expected {}", + made.trim(), + wt.display() + )); + } + if let Err(e) = check_worktree_link(&wt, &mirror) { + let _ = run_cmd(clone, &tool, &["remove", repo, sha]); + return Err(e); + } + Ok(wt) +} + +/// The checks that make a `wt.sh` worktree safe to open with the operator's +/// git: the directory is no symlink, its `.git` is a regular root-owned file +/// nobody else can write, and it points into `/worktrees/`. +pub fn check_worktree_link(wt: &Path, mirror: &Path) -> Result<(), String> { + use std::os::unix::fs::MetadataExt; + let canon = fs::canonicalize(wt).map_err(|e| format!("{}: {e}", wt.display()))?; + if canon != wt { + return Err(format!("{} is not a plain directory path", wt.display())); + } + let link = wt.join(".git"); + let md = fs::symlink_metadata(&link).map_err(|e| format!("{}: {e}", link.display()))?; + if !md.file_type().is_file() || md.uid() != 0 || md.mode() & 0o022 != 0 { + return Err(format!( + "{} must be a root-owned file nobody else can write (uid {}, mode {:o})", + link.display(), + md.uid(), + md.mode() & 0o7777 + )); + } + let text = fs::read_to_string(&link).map_err(|e| format!("{}: {e}", link.display()))?; + let target = text + .trim_end_matches('\n') + .strip_prefix("gitdir: ") + .ok_or_else(|| format!("{} has no gitdir line", link.display()))?; + let target = Path::new(target); + let want = mirror.join("worktrees"); + if target.parent() != Some(want.as_path()) + || target + .components() + .any(|c| c == std::path::Component::ParentDir) + { + return Err(format!( + "{} points to {}, not into {}", + link.display(), + target.display(), + want.display() + )); + } + Ok(()) +} + +/// Fetch the clone and add a detached worktree for `sha`. The clone's own +/// checkout is never touched. +fn checkout( + cfg: &Config, + repo: &str, + sha: &str, + notes: &mut Vec, +) -> Result<(PathBuf, PathBuf), String> { + let clone = cfg.clones.join(repo); + if !clone.join(".git").exists() && !clone.join("HEAD").exists() { + return Err(format!("no trusted clone at {}", clone.display())); + } + let present = |c: &Path| git(c, &["cat-file", "-e", &format!("{sha}^{{commit}}")]).is_ok(); + if !present(&clone) { + if let Err(e) = git(&clone, &["fetch", "--quiet", "--all"]) { + notes.push(format!("fetch failed: {e}")); + } + } else if let Err(e) = git(&clone, &["fetch", "--quiet", "--all"]) { + notes.push(format!("fetch failed (commit already present): {e}")); + } + if !present(&clone) { + return Err(format!("commit {sha} is not in {}", clone.display())); + } + if cfg.sandbox == Sandbox::User { + let wt = checkout_for_sandbox(cfg, repo, sha, &clone)?; + return Ok((clone, wt)); + } + let wt = cfg.wt_root.join(repo).join(sha); + if wt.exists() { + let _ = git( + &clone, + &["worktree", "remove", "--force", &wt.display().to_string()], + ); + let _ = fs::remove_dir_all(&wt); + } + fs::create_dir_all(wt.parent().unwrap_or(&cfg.wt_root)) + .map_err(|e| format!("cannot create {}: {e}", cfg.wt_root.display()))?; + git( + &clone, + &[ + "worktree", + "add", + "--detach", + "--quiet", + &wt.display().to_string(), + sha, + ], + )?; + Ok((clone, wt)) +} + +fn remove_worktree(clone: &Path, wt: &Path) { + let _ = git( + clone, + &["worktree", "remove", "--force", &wt.display().to_string()], + ); + let _ = fs::remove_dir_all(wt); + let _ = git(clone, &["worktree", "prune"]); +} + +fn crumb(cfg: &Config, wt: &Path, args: &[&str], notes: &mut Vec) { + let Some(c) = &cfg.crumb else { + return; + }; + if !wt.join(".crumb").exists() { + notes.push(format!( + "crumb {}: no .crumb at the worktree root, skipped", + args[0] + )); + return; + } + match run_cmd(wt, c, args) { + Ok(_) => {} + Err(e) => notes.push(format!("crumb {}: {e}", args[0])), + } +} + +/// Verify one head end to end. Never panics on GitHub trouble. +pub fn run_once(cfg: &Config, repo: &str, sha: &str) -> Result { + // Refusals first: nothing is fetched, checked out or run before these. + if !valid_repo_key(repo) { + return Err(format!("refusing repository name {repo:?}")); + } + if !valid_sha(sha) { + return Err(format!( + "refusing commit {sha:?}: a lowercase 40-hex id is required" + )); + } + // Development mode needs the explicit opt-in; the CLI also refuses it + // with `--github` (tests post to a fake `gh` without the helper). + cfg.check_sandbox_policy_for(false)?; + check_key_private(&cfg.key)?; + if cfg.sandbox == Sandbox::User && cfg.wt_tool.is_none() { + return Err( + "--sandbox user needs INFRA's worktree tool (--wt-tool, tools/aien-local-ci/wt.sh)" + .to_string(), + ); + } + let mut notes: Vec = Vec::new(); + cfg.state.beat(repo, sha, "checkout"); + let (clone, wt) = checkout(cfg, repo, sha, &mut notes)?; + // A wt.sh worktree belongs to aien-run; the operator's git opens it only + // after `check_worktree_link` (see `process::trust_worktree`). + let trust = (cfg.sandbox == Sandbox::User).then(|| process::trust_worktree(&wt)); + let result = run_in_worktree(cfg, repo, sha, &clone, &wt, &mut notes); + crumb( + cfg, + &wt, + &[ + "close", + "aien-worker", + ".", + "worker", + "test", + "local verification finished", + ], + &mut notes, + ); + drop(trust); + if cfg.sandbox == Sandbox::User { + if let Some(tool) = &cfg.wt_tool { + let tool = tool.display().to_string(); + if let Err(e) = run_cmd(&clone, &tool, &["remove", repo, sha]) { + notes.push(format!("worktree not removed: {e}")); + } + } + } else { + remove_worktree(&clone, &wt); + } + cfg.state.beat(repo, sha, "idle"); + let mut summary = result?; + summary.notes.append(&mut notes); + Ok(summary) +} + +fn run_in_worktree( + cfg: &Config, + repo: &str, + sha: &str, + clone: &Path, + wt: &Path, + notes: &mut Vec, +) -> Result { + let started = now_secs(); + crumb( + cfg, + wt, + &[ + "claim", + "aien-worker", + ".", + "worker", + "local verification", + "7200", + ], + notes, + ); + let repository = plan::repository_name(clone, None); + + // Plan against the base ref; a head already on the base line is planned + // against its first parent so a push to main still verifies what it + // changed (the same rule `verify` uses). + cfg.state.beat(repo, sha, "plan"); + let (base, on_main) = plan::base_for(wt, &cfg.base_ref, sha)?; + let mut req = plan::Request::new(&base, sha); + req.operator = cfg.operator; + req.hardware_identity = cfg.hardware_identity.clone(); + let plan = plan::compute(wt, &req)?; + + // Run what the plan selects, through the sandbox and the pools. + cfg.state.beat(repo, sha, "run"); + let evidence_dir = cfg.state.evidence(repo, sha); + fs::create_dir_all(&evidence_dir).map_err(|e| format!("cannot create evidence dir: {e}"))?; + let mut opts = Options::new(evidence_dir.clone()); + opts.sandbox = cfg.sandbox; + opts.cargo_target_dir = target_dir_for(cfg, repo, on_main); + let mut known: BTreeMap = BTreeMap::new(); + let mut notes_cache: BTreeMap = BTreeMap::new(); + if plan.blocked.is_none() && !plan.entries.is_empty() { + let g = graph::load(wt).map_err(|e| e.to_string())?; + let mut sel = std::collections::BTreeSet::new(); + for e in plan + .entries + .iter() + .filter(|e| e.section != Section::Blocked) + { + match g.index_of(&e.gate) { + Some(i) => { + sel.insert(i); + } + None => notes.push(format!( + "gate {} is in the plan but not in the worktree graph", + e.gate + )), + } + } + let campaign = runner::run_graph(wt, &g, &sel, &opts).map_err(|e| e.to_string())?; + for (id, o) in campaign.results { + known.insert( + id.clone(), + Known { + verdict: o.verdict, + reason: o.reason.clone(), + receipt: o.receipt_digest.clone(), + }, + ); + notes_cache.insert(id, o.cache); + } + } + let judged = plan::judge(&plan, &known); + + // The bundle. + cfg.state.beat(repo, sha, "bundle"); + let key = bundle::load_signing_key(&cfg.key)?; + let vk = key.verifying_key(); + let machine = runner::machine(&Hardware::detect()); + let machine_digest = canonical_digest(&machine).map_err(|e| e.to_string())?; + let tree = git(wt, &["rev-parse", &format!("{sha}^{{tree}}")])?; + let mut checks: Vec = Vec::new(); + let mut entries: Vec<(bool, String, String)> = Vec::new(); + let mut gates: Vec<(String, String, Verdict)> = Vec::new(); + for e in &plan.entries { + let (eff, _) = judged + .gates + .get(&e.gate) + .cloned() + .unwrap_or((Verdict::NotRun, String::new())); + let k = known.get(&e.gate); + let (status, verdict, extra): (&str, String, Value) = + match (e.section, k, notes_cache.get(&e.gate)) { + (Section::Blocked, _, _) => ("blocked", bundle_verdict(eff), json!({})), + (_, Some(k), Some(CacheNote::Reused { from })) if k.receipt.is_some() => ( + "cached", + bundle_verdict(eff), + json!({ "resolution": { "resolved_from": from, "receipt": k.receipt } }), + ), + (_, Some(k), _) if k.receipt.is_some() => { + ("run", bundle_verdict(eff), json!({ "receipt": k.receipt })) + } + _ => ( + "not_run", + bundle_verdict(if eff == Verdict::Pass { + Verdict::NotRun + } else { + eff + }), + json!({}), + ), + }; + let mut entry = json!({ + "gate": e.gate, + "check_id": e.check_id, + "exactness": e.exactness.as_str(), + "required": e.required, + "status": status, + "verdict": verdict, + "backend": e.pool, + }); + if let (Some(dst), Some(src)) = (entry.as_object_mut(), extra.as_object()) { + for (k, v) in src { + dst.insert(k.clone(), v.clone()); + } + } + checks.push(entry); + entries.push((e.required, status.to_string(), verdict.clone())); + gates.push((e.gate.clone(), status.to_string(), eff)); + } + let bundle_verdict = bundle::compute_verdict(&entries).to_string(); + let unsigned = json!({ + "schema": bundle::SCHEMA, + "repository": repository, + "commit": sha, + "tree_digest": sha256_hex(tree.trim().as_bytes()), + "graph_digest": plan.graph_digest, + "receipt_id_scheme": "sha256-canonical-json", + "checks": checks, + "verdict": bundle_verdict, + "executor": { "id": bundle::fingerprint(&vk), "class": EXECUTOR_CLASS, "machine_digest": machine_digest }, + "started_utc": utc_string(started), + "finished_utc": utc_string(now_secs()), + // The planner's verdict beside the bundle algebra: a bundle with no + // required checks is PASS by the algebra (nothing required failed) + // while the plan may say NOT_RUN UNMAPPED_PATH or BLOCKED. Readers + // that gate on the plan read this; `verify` recomputes it anyway. + "plan": { + "verdict": judged.verdict.as_str(), + "reason": judged.reason, + "unmapped": plan.unmapped, + "removed": plan.removed, + "blocked": plan.blocked, + }, + }); + let signed = bundle::sign(&unsigned, &key).map_err(|r| format!("cannot sign bundle: {r}"))?; + let bytes = canonical(&signed).map_err(|e| e.to_string())?; + let bundle_digest = sha256_hex(&bytes); + let bundle_path = cfg.state.bundle_path(repo, sha); + fs::create_dir_all(bundle_path.parent().unwrap_or(&cfg.state.root)) + .map_err(|e| format!("cannot create bundle dir: {e}"))?; + fs::write(&bundle_path, &bytes).map_err(|e| format!("cannot write bundle: {e}"))?; + + // The independent check of what was just written, exactly as `verify` + // does it: keys at BASE, signature, graph digest, receipts, manifests, + // crumb. Nothing is published as success unless this says READY. + cfg.state.beat(repo, sha, "verify"); + let check = verify::run( + clone, + &verify::Ask { + state: cfg.state.clone(), + commit: sha.to_string(), + base: plan.base.clone(), + repository: Some(repository.clone()), + release: false, + operator: false, + hardware_identity: cfg.hardware_identity.clone(), + crumb: cfg.crumb.clone(), + keys_override: None, + }, + ); + let ready = check.ready; + let check_problems: Vec = check + .lines + .iter() + .filter(|l| { + l.starts_with("Problem: ") + || l.starts_with("Evidence note: ") + || l.starts_with("Crumb note: ") + }) + .cloned() + .collect(); + + // Publication, then the journal. + cfg.state.beat(repo, sha, "publish"); + let publication = if cfg.github { + let status = Status { + repository: repository.clone(), + sha: sha.to_string(), + state: publish_state(ready, &bundle_verdict, judged.verdict).to_string(), + description: format!( + "{} {} {}: bundle {}", + if ready { "READY" } else { "BLOCKED" }, + bundle_verdict, + judged.reason, + bundle_path.display() + ) + .chars() + .take(140) + .collect(), + }; + match post_status(&cfg.gh, &status) { + Ok(()) => "posted".to_string(), + Err(e) => { + notes.push(format!("GitHub unreachable, status queued: {e}")); + queue_status(&cfg.state, repo, &status)?; + "pending".to_string() + } + } + } else { + "local".to_string() + }; + let unmapped = plan.unmapped.clone(); + cfg.state.journal_append(&json!({ + "utc": utc_string(now_secs()), + "repo": repo, + "repository": repository, + "sha": sha, + "base": plan.base, + "verdict": judged.verdict.as_str(), + "reason": judged.reason, + "bundle_verdict": bundle_verdict, + "bundle": bundle_path.display().to_string(), + "bundle_digest": bundle_digest, + "graph_digest": plan.graph_digest, + "gates": gates.iter().map(|(g, s, v)| json!({ "gate": g, "status": s, "verdict": v.as_str() })).collect::>(), + "unmapped": unmapped, + "verify": if ready { "READY" } else { "BLOCKED" }, + "verify_notes": check_problems, + "publication": publication, + "notes": notes, + }))?; + Ok(Summary { + repo: repo.to_string(), + sha: sha.to_string(), + repository, + verdict: judged.verdict, + reason: judged.reason, + bundle_verdict, + bundle_path, + bundle_digest, + gates, + publication, + ready, + notes: Vec::new(), + }) +} + +/// `CARGO_TARGET_DIR` for the gates of one head. Under the user sandbox it is +/// the INFRA target dir of the head's trust class (A2): +/// `//main` for a head on the base line, `.../pr` +/// otherwise. The exec helper accepts only exactly those two paths under +/// `/var/lib/aien-run/target` and creates the class dir on demand. Never the +/// worker's own target dir, which `aien-run` cannot write. Without the +/// sandbox, the worker's own `CARGO_TARGET_DIR`. +fn target_dir_for(cfg: &Config, repo: &str, on_main: bool) -> Option { + match cfg.sandbox { + Sandbox::None => std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from), + Sandbox::User => { + let class = if on_main { "main" } else { "pr" }; + Some(cfg.target_root.join(repo).join(class)) + } + } +} + +/// The commit status for a head: `success` only when the independent check +/// of the bundle just written says READY; `failure` when the bundle or the +/// plan says FAIL; `error` otherwise. +pub fn publish_state(ready: bool, bundle_verdict: &str, judged: Verdict) -> &'static str { + match github_state(bundle_verdict, judged) { + "success" if !ready => "error", + s => s, + } +} + +fn bundle_verdict(v: Verdict) -> String { + v.as_str().to_string() +} + +/// success only on PASS, failure on FAIL, error on anything else. +pub fn github_state(bundle_verdict: &str, judged: Verdict) -> &'static str { + match (bundle_verdict, judged) { + ("PASS", Verdict::Pass) => "success", + ("FAIL", _) | (_, Verdict::Fail) => "failure", + _ => "error", + } +} + +/// A commit status to post. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Status { + pub repository: String, + pub sha: String, + pub state: String, + pub description: String, +} + +fn owner_repo(repository: &str) -> Option { + let parts: Vec<&str> = repository.split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() >= 3 { + Some(format!( + "{}/{}", + parts[parts.len() - 2], + parts[parts.len() - 1] + )) + } else if parts.len() == 2 { + Some(format!("{}/{}", parts[0], parts[1])) + } else { + None + } +} + +/// `gh api -X POST repos/O/R/statuses/SHA ...`. +pub fn post_status(gh: &str, s: &Status) -> Result<(), String> { + let or = owner_repo(&s.repository) + .ok_or_else(|| format!("cannot derive owner/repo from {}", s.repository))?; + let mut cmd = Command::new(gh); + cmd.args([ + "api", + "-X", + "POST", + &format!("repos/{or}/statuses/{}", s.sha), + "-f", + &format!("state={}", s.state), + "-f", + &format!("context={CONTEXT}"), + "-f", + &format!("description={}", s.description), + ]); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; + if out.status.success() { + Ok(()) + } else { + Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) + } +} + +/// Queue a status in the outbox. File names start with a strictly increasing +/// 20-digit sequence (nanoseconds since the epoch, bumped past the newest +/// queued file), so the outbox replays in the order statuses were queued. A +/// newer status for the same head replaces the older one and takes its place +/// at the end of the queue: the latest state is what GitHub must end with. +fn queue_status(state: &StateDir, repo: &str, s: &Status) -> Result<(), String> { + let dir = state.outbox_dir(); + fs::create_dir_all(&dir).map_err(|e| format!("cannot create outbox: {e}"))?; + let suffix = format!(".{repo}.{}.json", s.sha); + let mut newest: u128 = 0; + for f in outbox_files(state) { + let name = f + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + if let Some(seq) = name.split('.').next().and_then(|n| n.parse::().ok()) { + newest = newest.max(seq); + } + if name.ends_with(&suffix) || name == suffix.trim_start_matches('.') { + let _ = fs::remove_file(&f); + } + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let seq = now.max(newest + 1); + let v = json!({ "repository": s.repository, "sha": s.sha, "state": s.state, "description": s.description }); + let tmp = dir.join(format!(".tmp{suffix}")); + fs::write(&tmp, serde_json::to_string(&v).unwrap_or_default()) + .map_err(|e| format!("cannot write outbox: {e}"))?; + fs::rename(&tmp, dir.join(format!("{seq:020}{suffix}"))) + .map_err(|e| format!("cannot write outbox: {e}")) +} + +/// The queued status files, in queue order (`*.json`, by name). +pub fn outbox_files(state: &StateDir) -> Vec { + let Ok(rd) = fs::read_dir(state.outbox_dir()) else { + return Vec::new(); + }; + let mut files: Vec = rd + .flatten() + .map(|e| e.path()) + .filter(|p| { + let n = p + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + n.ends_with(".json") && !n.starts_with('.') + }) + .collect(); + files.sort(); + files +} + +/// Post the queued statuses in queue order; a success removes the file. The +/// first failure stops the replay so nothing overtakes an older status; the +/// rest stay queued for the next round. A file that is not a status is +/// renamed to `*.bad` (journaled) so it cannot block the queue. Returns +/// (posted, still pending). +pub fn flush_outbox(cfg: &Config) -> (usize, usize) { + let files = outbox_files(&cfg.state); + let mut posted = 0; + for (i, f) in files.iter().enumerate() { + let status = fs::read_to_string(f) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| { + let s = Status { + repository: v["repository"].as_str()?.to_string(), + sha: v["sha"].as_str()?.to_string(), + state: v["state"].as_str()?.to_string(), + description: v["description"].as_str().unwrap_or("").to_string(), + }; + (valid_sha(&s.sha) + && ["success", "failure", "error", "pending"].contains(&s.state.as_str())) + .then_some(s) + }); + let Some(s) = status else { + let _ = fs::rename(f, f.with_extension("bad")); + let _ = cfg.state.journal_append(&json!({ + "utc": utc_string(now_secs()), + "publication": "dropped", + "note": format!("outbox file {} is not a status; renamed to .bad", f.display()), + })); + continue; + }; + match post_status(&cfg.gh, &s) { + Ok(()) => { + let _ = fs::remove_file(f); + posted += 1; + let _ = cfg.state.journal_append(&json!({ + "utc": utc_string(now_secs()), + "sha": s.sha, + "repository": s.repository, + "state": s.state, + "publication": "posted", + "note": "flushed from outbox", + })); + } + Err(_) => return (posted, files.len() - i), + } + } + (posted, 0) +} + +/// Pending trigger files as (repo, sha), oldest first (modification time, +/// then name). Names that are not `.<40-hex sha>` with a safe repo +/// key are ignored. +pub fn triggers(state: &StateDir) -> Vec<(String, String, PathBuf)> { + let mut out = Vec::new(); + if let Ok(rd) = fs::read_dir(state.trigger_dir()) { + let mut files: Vec = rd.flatten().map(|e| e.path()).collect(); + // Oldest first: by modification time, then by name. + files.sort_by_key(|f| (fs::metadata(f).and_then(|m| m.modified()).ok(), f.clone())); + for f in files { + let name = f + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + if let Some((repo, sha)) = name.rsplit_once('.') { + let sha = sha.to_ascii_lowercase(); + if valid_sha(&sha) && valid_repo_key(repo) { + out.push((repo.to_string(), sha, f.clone())); + } + } + } + } + out +} + +/// Open PR heads and the main head of `repo` from GitHub (bounded: one call +/// per list). Errors are returned, never fatal to the loop. +pub fn github_heads(gh: &str, repository: &str) -> Result, String> { + let or = owner_repo(repository).ok_or("bad repository name")?; + let mut shas = Vec::new(); + for args in [ + vec![ + "api", + &format!("repos/{or}/pulls?state=open&per_page=50"), + "--jq", + ".[].head.sha", + ], + vec!["api", &format!("repos/{or}/commits/main"), "--jq", ".sha"], + ] { + let mut cmd = Command::new(gh); + cmd.args(&args); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; + if !out.status.success() { + return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); + } + for l in String::from_utf8_lossy(&out.stdout).lines() { + let l = l.trim().to_ascii_lowercase(); + if valid_sha(&l) { + shas.push(l); + } + } + } + shas.sort(); + shas.dedup(); + Ok(shas) +} + +/// The loop: flush the outbox, serve trigger files, poll GitHub when asked, +/// sleep. `iterations` bounds the rounds (None: forever). Returns the number +/// of heads served. +pub fn run_loop(cfg: &Config, iterations: Option) -> usize { + let mut served = 0; + let mut round = 0u64; + loop { + round += 1; + cfg.state.beat("-", "-", "poll"); + let (posted, pending) = flush_outbox(cfg); + if posted + pending > 0 { + println!("OUTBOX posted={posted} pending={pending}"); + } + let mut heads: Vec<(String, String, Option)> = triggers(&cfg.state) + .into_iter() + .map(|(r, s, f)| (r, s, Some(f))) + .collect(); + if cfg.github { + for repo in &cfg.repos { + let repository = plan::repository_name(&cfg.clones.join(repo), None); + match github_heads(&cfg.gh, &repository) { + Ok(shas) => { + for s in shas { + if !cfg.state.bundle_path(repo, &s).exists() { + heads.push((repo.clone(), s, None)); + } + } + } + Err(e) => println!("GITHUB unreachable for {repo}: {e} (will retry)"), + } + } + } + for (repo, sha, trigger) in heads { + match run_once(cfg, &repo, &sha) { + Ok(s) => { + println!( + "HEAD {repo} {sha} {} {} bundle {} publication {}", + s.verdict.as_str(), + s.reason, + s.bundle_path.display(), + s.publication + ); + served += 1; + } + Err(e) => { + println!("HEAD {repo} {sha} ERROR {e}"); + let _ = cfg.state.journal_append(&json!({ + "utc": utc_string(now_secs()), + "repo": repo, + "sha": sha, + "verdict": "NOT_RUN", + "reason": format!("WORKER_ERROR:{e}"), + "publication": "none", + })); + } + } + if let Some(f) = trigger { + let _ = fs::remove_file(f); + } + } + if iterations.is_some_and(|n| round >= n) { + break; + } + std::thread::sleep(cfg.poll); + } + served +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn state_layout() { + let s = StateDir::new(Path::new("/s")); + assert_eq!(s.evidence("r", "abc"), PathBuf::from("/s/evidence/r/abc")); + assert_eq!( + s.bundle_path("r", "abc"), + PathBuf::from("/s/bundles/r/abc/bundle.json") + ); + assert_eq!(s.trigger_dir(), PathBuf::from("/s/trigger")); + assert_eq!(s.journal(), PathBuf::from("/s/journal.jsonl")); + assert_eq!( + StateDir::repo_key("github.com/aien-dev/aien-sovereign-core"), + "aien-sovereign-core" + ); + assert_eq!(StateDir::repo_key("x"), "x"); + } + + #[test] + fn github_states() { + assert_eq!(github_state("PASS", Verdict::Pass), "success"); + assert_eq!(github_state("FAIL", Verdict::Fail), "failure"); + assert_eq!(github_state("NOT_RUN", Verdict::NotRun), "error"); + assert_eq!(github_state("NOT_RUN", Verdict::BlockedOperator), "error"); + // A PASS bundle whose plan-level verdict is not PASS is not success. + assert_eq!(github_state("PASS", Verdict::NotRun), "error"); + assert_eq!( + owner_repo("github.com/aien-dev/x").as_deref(), + Some("aien-dev/x") + ); + assert_eq!(owner_repo("aien-dev/x").as_deref(), Some("aien-dev/x")); + assert_eq!(owner_repo("x"), None); + // success needs the independent check too. + assert_eq!(publish_state(true, "PASS", Verdict::Pass), "success"); + assert_eq!(publish_state(false, "PASS", Verdict::Pass), "error"); + assert_eq!(publish_state(false, "FAIL", Verdict::Fail), "failure"); + assert_eq!(publish_state(true, "NOT_RUN", Verdict::NotRun), "error"); + } + + #[test] + fn names_and_sandbox_policy() { + assert!(valid_repo_key("aien-sovereign-core")); + assert!(valid_repo_key("a.b_c-1")); + for bad in ["", ".", "..", ".x", "a/b", "a b", "a\0b"] { + assert!(!valid_repo_key(bad), "{bad:?}"); + } + assert!(valid_sha(&"a".repeat(40))); + assert!(!valid_sha(&"A".repeat(40))); + assert!(!valid_sha(&"a".repeat(39))); + assert!(!valid_sha(&"g".repeat(40))); + let mut cfg = Config::new( + StateDir::new(Path::new("/s")), + Path::new("/k"), + Path::new("/c"), + Path::new("/w"), + ); + // The library default is the development sandbox, refused unless allowed. + assert_eq!(cfg.sandbox, Sandbox::None); + assert!(cfg.check_sandbox_policy_for(false).is_err()); + cfg.allow_unsandboxed = true; + assert!(cfg.check_sandbox_policy_for(false).is_ok()); + assert!(cfg.check_sandbox_policy_for(true).is_err()); + cfg.sandbox = Sandbox::User; + assert!(cfg.check_sandbox_policy_for(true).is_ok()); + } + + #[test] + fn triggers_and_outbox_files() { + let t = crate::testutil::TempDir::new("worker-state"); + let s = StateDir::new(t.path()); + fs::create_dir_all(s.trigger_dir()).unwrap(); + fs::write(s.trigger_dir().join(format!("repo.{}", "a".repeat(40))), "").unwrap(); + fs::write(s.trigger_dir().join("junk"), "").unwrap(); + fs::write(s.trigger_dir().join("repo.short"), "").unwrap(); + let t3 = triggers(&s); + assert_eq!(t3.len(), 1); + assert_eq!( + (t3[0].0.as_str(), t3[0].1.as_str()), + ("repo", "a".repeat(40).as_str()) + ); + let st = Status { + repository: "github.com/o/r".into(), + sha: "b".repeat(40), + state: "success".into(), + description: "d".into(), + }; + queue_status(&s, "r", &st).unwrap(); + let q = outbox_files(&s); + assert_eq!(q.len(), 1); + let name = q[0].file_name().unwrap().to_string_lossy().into_owned(); + assert!( + name.ends_with(&format!(".r.{}.json", "b".repeat(40))), + "{name}" + ); + assert_eq!(name.split('.').next().unwrap().len(), 20, "{name}"); + // Queue order: c after b; a newer status for b replaces the older one + // and moves to the end. + let c = Status { + sha: "c".repeat(40), + ..st.clone() + }; + queue_status(&s, "r", &c).unwrap(); + let b2 = Status { + state: "failure".into(), + ..st.clone() + }; + queue_status(&s, "r", &b2).unwrap(); + let q = outbox_files(&s); + assert_eq!(q.len(), 2); + assert!(q[0].to_string_lossy().contains(&"c".repeat(40))); + assert!(q[1].to_string_lossy().contains(&"b".repeat(40))); + assert!(fs::read_to_string(&q[1]).unwrap().contains("failure")); + s.journal_append(&json!({"a": 1})).unwrap(); + s.journal_append(&json!({"b": 2})).unwrap(); + let j = fs::read_to_string(s.journal()).unwrap(); + assert_eq!(j.lines().count(), 2); + s.beat("r", "sha", "plan"); + let hb: Value = serde_json::from_str(&fs::read_to_string(s.heartbeat()).unwrap()).unwrap(); + assert_eq!(hb["phase"], "plan"); + } +} diff --git a/tools/aien-test/tests/local_ci.rs b/tools/aien-test/tests/local_ci.rs new file mode 100644 index 00000000..8bc829ed --- /dev/null +++ b/tools/aien-test/tests/local_ci.rs @@ -0,0 +1,1080 @@ +//! The local pipeline end to end, and the negative cases the mission lists +//! (22 to 27): an altered receipt, a bad signature, a bundle from another +//! commit, a missing required check, a hardware-scoped cached result under +//! `--release`, and an executor whose key the repository does not trust. +//! Each must leave MERGE ELIGIBILITY at BLOCKED; none may print PASS. +//! +//! The worker runs with `--sandbox none` (development mode, +//! `allow_unsandboxed`) here because the exec helper is the INFRA lane's +//! file; the sandbox tests at the end run only when +//! `/usr/local/sbin/aien-run-exec` exists. + +use aien_test::bundle; +use aien_test::evidence::canonical; +use aien_test::plan::{self, Request}; +use aien_test::runner::{self, Options}; +use aien_test::sandbox::Sandbox; +use aien_test::verdict::Verdict; +use aien_test::verify::{self, Ask}; +use aien_test::worker::{self, Config, StateDir}; +use serde_json::{json, Value}; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +static COUNTER: AtomicU64 = AtomicU64::new(0); + +struct Tmp(PathBuf); + +impl Tmp { + fn new(tag: &str) -> Tmp { + let n = COUNTER.fetch_add(1, Ordering::SeqCst); + let p = + std::env::temp_dir().join(format!("aien-local-ci-{tag}-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&p); + fs::create_dir_all(&p).unwrap(); + Tmp(p) + } + /// A directory the exec helper accepts as `--cwd`: the sandbox shares no + /// `/tmp` with the caller, so sandboxed checks run in + /// `/var/lib/aien-run/wt/aien-test-selftest/<40 hex>`. + fn sandbox_wt() -> Tmp { + let n = COUNTER.fetch_add(1, Ordering::SeqCst); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let id = format!( + "{:0>40}", + format!("{:x}{:x}{n:x}", std::process::id(), nanos) + ); + let p = Path::new("/var/lib/aien-run/wt/aien-test-selftest").join(&id[id.len() - 40..]); + let _ = fs::remove_dir_all(&p); + fs::create_dir_all(&p).unwrap(); + Tmp(p) + } + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for Tmp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@t") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@t") + .output() + .expect("git"); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +fn write(dir: &Path, rel: &str, content: &str, exec: bool) { + let p = dir.join(rel); + fs::create_dir_all(p.parent().unwrap()).unwrap(); + fs::write(&p, content).unwrap(); + if exec { + fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap(); + } +} + +fn gate(id: &str, input: &str, exec: &str, extra: &str) -> String { + format!( + "gate: {id}\nmanifest_version: 2\nowner: t\nrequires:\n - host\ninputs:\n - {input}\nrun:\n exec: {exec}\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 10s\n{extra}" + ) +} + +/// Everything one scenario needs: an origin with `main` (base) and `topic` +/// (head, changes `a/a.txt`), a trusted clone, a state dir, a signing key +/// whose public half is committed in `.aien/verify.pub`, and a fake `crumb` +/// that always says OK. +struct World { + _root: Tmp, + origin: PathBuf, + clone: PathBuf, + state: StateDir, + key: PathBuf, + other_key: PathBuf, + crumb: PathBuf, + base: String, + head: String, + /// A second head that changes `h/h.txt` (gate H, cache_scope hardware). + head_h: String, + wt_root: PathBuf, +} + +const REPO: &str = "aien-test-selftest"; + +fn world() -> World { + let root = Tmp::new("world"); + let r = root.path(); + let key = r.join("verify.key"); + let pubkey = bundle::keygen(&key).unwrap(); + let other_key = r.join("other.key"); + bundle::keygen(&other_key).unwrap(); + let crumb = r.join("crumb"); + write( + r, + "crumb", + "#!/bin/sh\nif [ \"$1\" = close ]; then case \"$5\" in create|modify|delete|audit|test|build) ;; *) echo \"crumb: action must be create|modify|delete|audit|test|build\" >&2; exit 2;; esac; fi\necho \"crumb $1: OK\"\nexit 0\n", + true, + ); + + let origin = r.join("origin"); + fs::create_dir_all(&origin).unwrap(); + git(&origin, &["init", "-q", "-b", "main"]); + write(&origin, "tools/a.sh", "#!/bin/sh\necho PASS\n", true); + write(&origin, "tools/h.sh", "#!/bin/sh\necho PASS\n", true); + write( + &origin, + "tests/gates/A.gate", + &gate("A", "a/", "tools/a.sh", ""), + false, + ); + write( + &origin, + "tests/gates/H.gate", + &gate("H", "h/", "tools/h.sh", "cache_scope: hardware\n"), + false, + ); + write(&origin, "a/a.txt", "1\n", false); + write(&origin, "h/h.txt", "1\n", false); + write( + &origin, + ".aien/verify.pub", + &format!("# trusted executors\n{pubkey}\n"), + false, + ); + write(&origin, ".crumb", "crumb: 1\n", false); + git(&origin, &["add", "-A"]); + git(&origin, &["commit", "-q", "-m", "base"]); + let base = git(&origin, &["rev-parse", "HEAD"]); + git(&origin, &["checkout", "-q", "-b", "topic"]); + write(&origin, "a/a.txt", "2\n", false); + git(&origin, &["add", "-A"]); + git(&origin, &["commit", "-q", "-m", "change a"]); + let head = git(&origin, &["rev-parse", "HEAD"]); + git(&origin, &["checkout", "-q", "-b", "topic-h", "main"]); + write(&origin, "h/h.txt", "2\n", false); + git(&origin, &["add", "-A"]); + git(&origin, &["commit", "-q", "-m", "change h"]); + let head_h = git(&origin, &["rev-parse", "HEAD"]); + git(&origin, &["checkout", "-q", "main"]); + + let clones = r.join("clones"); + fs::create_dir_all(&clones).unwrap(); + let clone = clones.join(REPO); + git(&clones, &["clone", "-q", origin.to_str().unwrap(), REPO]); + git(&clone, &["fetch", "-q", "--all"]); + World { + state: StateDir::new(&r.join("state")), + wt_root: r.join("wt"), + _root: root, + origin, + clone, + key, + other_key, + crumb, + base, + head, + head_h, + } +} + +impl World { + fn config(&self) -> Config { + let mut cfg = Config::new( + self.state.clone(), + &self.key, + self.clone.parent().unwrap(), + &self.wt_root, + ); + cfg.crumb = Some(self.crumb.display().to_string()); + cfg.gh = self.crumb.display().to_string(); // never called unless github + // These scenarios run without the exec helper (development mode). + cfg.allow_unsandboxed = true; + cfg + } + + fn ask(&self, commit: &str) -> Ask { + Ask { + state: self.state.clone(), + commit: commit.to_string(), + base: "origin/main".to_string(), + repository: None, + release: false, + operator: false, + hardware_identity: String::new(), + crumb: Some(self.crumb.display().to_string()), + keys_override: None, + } + } + + fn verify(&self, ask: &Ask) -> verify::Report { + verify::run(&self.clone, ask) + } + + fn bundle_path(&self, sha: &str) -> PathBuf { + self.state.bundle_path(REPO, sha) + } + + fn read_bundle(&self, sha: &str) -> Value { + serde_json::from_slice(&fs::read(self.bundle_path(sha)).unwrap()).unwrap() + } + + fn write_bundle(&self, sha: &str, v: &Value) { + let p = self.bundle_path(sha); + fs::create_dir_all(p.parent().unwrap()).unwrap(); + fs::write(p, canonical(v).unwrap()).unwrap(); + } +} + +fn line<'a>(r: &'a verify::Report, prefix: &str) -> &'a str { + r.lines + .iter() + .find(|l| l.starts_with(prefix)) + .map(String::as_str) + .unwrap_or_else(|| panic!("no line {prefix:?} in {:#?}", r.lines)) +} + +fn assert_blocked(r: &verify::Report, why: &str) { + assert!(!r.ready, "{why}: {:#?}", r.lines); + assert_eq!( + line(r, "MERGE ELIGIBILITY:"), + "MERGE ELIGIBILITY: BLOCKED", + "{why}" + ); + assert_ne!(line(r, "Final verdict:"), "Final verdict: PASS", "{why}"); +} + +/// The happy path once, shared by the negative tests through `verified_world`. +fn verified_world() -> World { + let w = world(); + let s = worker::run_once(&w.config(), REPO, &w.head).expect("worker"); + assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); + assert_eq!(s.bundle_verdict, "PASS"); + // The fake crumb rejects actions the real tool rejects; no crumb note. + assert!( + !s.notes.iter().any(|n| n.starts_with("crumb ")), + "{:?}", + s.notes + ); + assert!(w.bundle_path(&w.head).exists()); + assert_eq!(s.publication, "local"); + w +} + +#[test] +fn worker_then_verify_is_ready() { + let w = verified_world(); + let r = w.verify(&w.ask(&w.head)); + assert_eq!(r.lines[0], "AIEN LOCAL VERIFICATION"); + assert_eq!(line(&r, "Evidence status:"), "Evidence status: VERIFIED"); + assert_eq!(line(&r, "Crumb status:"), "Crumb status: CURRENT"); + assert_eq!( + line(&r, "Hardware status:"), + "Hardware status: NOT_REQUIRED" + ); + assert_eq!(line(&r, "Final verdict:"), "Final verdict: PASS"); + assert_eq!(line(&r, "Executed gates:"), "Executed gates: 1 (A)"); + assert_eq!(line(&r, "Build time:"), "Build time: n/a"); + assert!(line(&r, "Test time:").ends_with(" ms")); + assert_eq!( + line(&r, "MERGE ELIGIBILITY:"), + "MERGE ELIGIBILITY: READY", + "{:#?}", + r.lines + ); + assert!(r.ready); + // The journal has the head, the worktree is gone, the clone's checkout is untouched. + let j = fs::read_to_string(w.state.journal()).unwrap(); + assert!(j.contains(&w.head) && j.contains("\"publication\":\"local\"")); + assert!(!w.wt_root.join(REPO).join(&w.head).exists()); + assert_eq!(git(&w.clone, &["rev-parse", "HEAD"]), w.base); + assert_eq!(git(&w.clone, &["status", "--porcelain"]), ""); + // Fresh crumb check leaves no worktree behind. + assert!(!git(&w.clone, &["worktree", "list"]).contains("aien-verify-")); + let _ = &w.origin; +} + +#[test] +fn altered_receipt_is_rejected() { + let w = verified_world(); + let b = w.read_bundle(&w.head); + let digest = b["checks"][0]["receipt"].as_str().unwrap().to_string(); + let p = w + .state + .evidence(REPO, &w.head) + .join(format!("{digest}.json")); + let text = fs::read_to_string(&p).unwrap(); + assert!(text.contains("\"derived_verdict\":\"PASS\"")); + fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); + fs::write( + &p, + text.replace( + "\"derived_verdict\":\"PASS\"", + "\"derived_verdict\":\"FAIL\"", + ), + ) + .unwrap(); + let r = w.verify(&w.ask(&w.head)); + assert_blocked(&r, "altered receipt"); + assert!( + r.lines.iter().any(|l| l.starts_with("Problem: A: receipt")), + "{:#?}", + r.lines + ); +} + +#[test] +fn invalid_signature_is_rejected() { + let w = verified_world(); + let mut b = w.read_bundle(&w.head); + let sig = b["signature"]["sig"].as_str().unwrap().to_string(); + let flipped = format!( + "{}{}", + if sig.starts_with('0') { "1" } else { "0" }, + &sig[1..] + ); + b["signature"]["sig"] = json!(flipped); + w.write_bundle(&w.head, &b); + let r = w.verify(&w.ask(&w.head)); + assert_blocked(&r, "bad signature"); + assert_eq!(line(&r, "Evidence status:"), "Evidence status: INVALID"); + assert!(line(&r, "Evidence note:").contains("BAD_SIGNATURE")); +} + +#[test] +fn bundle_from_another_commit_is_rejected() { + let w = verified_world(); + let b = w.read_bundle(&w.head); + // Present the head's bundle as the other branch head's. + w.write_bundle(&w.head_h, &b); + let r = w.verify(&w.ask(&w.head_h)); + assert_blocked(&r, "other commit"); + assert!( + line(&r, "Evidence note:").contains("COMMIT_MISMATCH"), + "{:#?}", + r.lines + ); +} + +#[test] +fn missing_required_check_never_passes() { + let w = verified_world(); + let mut b = w.read_bundle(&w.head); + b["checks"] = json!([]); + b.as_object_mut().unwrap().remove("signature"); + // Re-signed by the trusted key: the algebra, not the signature, must refuse it. + let key = bundle::load_signing_key(&w.key).unwrap(); + let signed = bundle::sign(&b, &key).unwrap(); + assert_eq!( + signed["verdict"], "PASS", + "an empty bundle declares PASS vacuously" + ); + w.write_bundle(&w.head, &signed); + let r = w.verify(&w.ask(&w.head)); + assert_blocked(&r, "missing required check"); + assert!( + line(&r, "Evidence note:").contains("MISSING_REQUIRED_CHECK: A"), + "{:#?}", + r.lines + ); +} + +#[test] +fn hardware_cached_result_cannot_satisfy_release() { + let w = world(); + // A hand-made bundle for the H head: H cached (PASS), signed by the trusted key. + let wt = w.wt_root.join("h-plan"); + git( + &w.clone, + &[ + "worktree", + "add", + "-q", + "--detach", + wt.to_str().unwrap(), + &w.head_h, + ], + ); + let p = plan::compute(&wt, &Request::new(&w.base, &w.head_h)).unwrap(); + git( + &w.clone, + &["worktree", "remove", "--force", wt.to_str().unwrap()], + ); + let h = p + .entries + .iter() + .find(|e| e.gate == "H") + .expect("H selected"); + let key = bundle::load_signing_key(&w.key).unwrap(); + let vk = key.verifying_key(); + let tree = git(&w.clone, &["rev-parse", &format!("{}^{{tree}}", w.head_h)]); + let unsigned = json!({ + "schema": bundle::SCHEMA, + "repository": plan::repository_name(&w.clone, None), + "commit": w.head_h, + "tree_digest": aien_test::evidence::sha256_hex(tree.as_bytes()), + "graph_digest": p.graph_digest, + "receipt_id_scheme": "sha256-canonical-json", + "checks": [{ + "gate": "H", "check_id": h.check_id, "exactness": "EXACT", "required": true, + "status": "cached", "verdict": "PASS", "backend": "host", + "resolution": { "resolved_from": "f".repeat(64) } + }], + "verdict": "PASS", + "executor": { "id": bundle::fingerprint(&vk), "class": "spark", "machine_digest": "0".repeat(64) }, + "started_utc": "2026-10-11T00:00:00Z", + "finished_utc": "2026-10-11T00:00:02Z", + }); + let signed = bundle::sign(&unsigned, &key).unwrap(); + w.write_bundle(&w.head_h, &signed); + let plain = w.verify(&w.ask(&w.head_h)); + assert_eq!( + line(&plain, "Evidence status:"), + "Evidence status: VERIFIED", + "{:#?}", + plain.lines + ); + assert_eq!(line(&plain, "Cached gates:"), "Cached gates: 1 (H)"); + assert_eq!(line(&plain, "Final verdict:"), "Final verdict: PASS"); + assert_eq!(line(&plain, "Total time:"), "Total time: 2000 ms"); + let mut release = w.ask(&w.head_h); + release.release = true; + let r = w.verify(&release); + assert_blocked(&r, "hardware cache under --release"); + assert_eq!(line(&r, "Cached gates:"), "Cached gates: none"); + assert!( + r.lines + .iter() + .any(|l| l.contains("cannot satisfy --release")), + "{:#?}", + r.lines + ); +} + +#[test] +fn executor_not_in_verify_pub_is_rejected() { + let w = verified_world(); + let mut b = w.read_bundle(&w.head); + b.as_object_mut().unwrap().remove("signature"); + let other = bundle::load_signing_key(&w.other_key).unwrap(); + b["executor"]["id"] = json!(bundle::fingerprint(&other.verifying_key())); + let signed = bundle::sign(&b, &other).unwrap(); + w.write_bundle(&w.head, &signed); + let r = w.verify(&w.ask(&w.head)); + assert_blocked(&r, "untrusted executor"); + assert!( + line(&r, "Evidence note:").contains("UNKNOWN_KEY"), + "{:#?}", + r.lines + ); + // And with no trusted keys at all the answer is the same. + let mut none = w.ask(&w.head); + none.keys_override = Some(Vec::new()); + let r = w.verify(&none); + assert_blocked(&r, "no keys"); +} + +#[test] +fn another_uid_cannot_read_the_key() { + let w = world(); + let probe = Command::new("sudo") + .args(["-n", "-u", "nobody", "true"]) + .output(); + match probe { + Ok(o) if o.status.success() => {} + _ => { + println!("SKIP: sudo -n -u nobody is not available here"); + return; + } + } + let mode = fs::metadata(&w.key).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let out = Command::new("sudo") + .args(["-n", "-u", "nobody", "cat", w.key.to_str().unwrap()]) + .output() + .unwrap(); + assert!( + !out.status.success(), + "nobody must not read the signing key" + ); + assert!(out.stdout.is_empty()); +} + +#[test] +fn github_down_queues_then_flushes() { + let w = world(); + let fake = w.state.root.join("fake-gh"); + let log = w.state.root.join("gh.log"); + let down = w.state.root.join("gh.down"); + fs::create_dir_all(&w.state.root).unwrap(); + fs::write( + &fake, + format!( + "#!/bin/sh\nif [ -e {} ]; then echo 'connect: network unreachable' >&2; exit 1; fi\necho \"$@\" >> {}\nexit 0\n", + down.display(), + log.display() + ), + ) + .unwrap(); + fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); + fs::write(&down, "").unwrap(); + let mut cfg = w.config(); + cfg.github = true; + cfg.gh = fake.display().to_string(); + let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); + assert_eq!(s.verdict, Verdict::Pass, "{}", s.reason); + assert_eq!(s.publication, "pending"); + assert!( + s.notes.iter().any(|n| n.starts_with("GitHub unreachable")), + "{:?}", + s.notes + ); + let queued: Vec<_> = fs::read_dir(w.state.outbox_dir()) + .unwrap() + .flatten() + .collect(); + assert_eq!(queued.len(), 1); + assert!(fs::read_to_string(w.state.journal()) + .unwrap() + .contains("\"publication\":\"pending\"")); + // Still down: nothing posted. + assert_eq!(worker::flush_outbox(&cfg), (0, 1)); + // Back: posted, outbox empty, the status names the bundle and is a success. + fs::remove_file(&down).unwrap(); + assert_eq!(worker::flush_outbox(&cfg), (1, 0)); + assert_eq!( + fs::read_dir(w.state.outbox_dir()) + .unwrap() + .flatten() + .count(), + 0 + ); + let l = fs::read_to_string(&log).unwrap(); + assert!(l.contains(&format!("statuses/{}", w.head)), "{l}"); + assert!( + l.contains("state=success") && l.contains("context=AIEN Verification (Spark)"), + "{l}" + ); + assert!(l.contains("bundle.json"), "{l}"); + assert!(fs::read_to_string(w.state.journal()) + .unwrap() + .contains("flushed from outbox")); +} + +#[test] +fn trigger_file_is_served_by_the_loop() { + let w = world(); + let cfg = w.config(); + fs::create_dir_all(w.state.trigger_dir()).unwrap(); + fs::write(w.state.trigger_dir().join(format!("{REPO}.{}", w.head)), "").unwrap(); + let served = worker::run_loop(&cfg, Some(1)); + assert_eq!(served, 1); + assert!(w.bundle_path(&w.head).exists()); + assert_eq!( + fs::read_dir(w.state.trigger_dir()) + .unwrap() + .flatten() + .count(), + 0 + ); +} + +#[test] +fn bare_exec_runs_and_escapes_are_refused() { + // `exec: true` (bare) runs from the PATH; `exec: ../x` is a manifest reject. + let t = Tmp::new("bare"); + let r = t.path(); + git(r, &["init", "-q", "-b", "main"]); + write(r, "tests/gates/T.gate", &gate("T", "a/", "true", ""), false); + write(r, "a/a.txt", "1\n", false); + git(r, &["add", "-A"]); + git(r, &["commit", "-q", "-m", "init"]); + let ev = Tmp::new("bare-ev"); + let opts = Options::new(ev.path().join("out")); + let o = runner::run_gate(r, &r.join("tests/gates/T.gate"), &opts).unwrap(); + assert_eq!(o.verdict, Verdict::Pass, "{}", o.reason); + for bad in ["../../usr/bin/env", "/usr/bin/env"] { + write(r, "tests/gates/T.gate", &gate("T", "a/", bad, ""), false); + git(r, &["commit", "-q", "-am", "bad exec"]); + match runner::run_gate(r, &r.join("tests/gates/T.gate"), &opts) { + Err(runner::RunError::BadManifest(m)) => assert!(m.contains("run.exec"), "{m}"), + other => panic!("{bad}: expected a manifest reject, got {other:?}"), + } + } +} + +#[test] +fn user_sandbox_when_the_helper_exists() { + if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() { + println!( + "SKIP: {} is not installed (INFRA lane)", + aien_test::sandbox::EXEC_HELPER + ); + return; + } + let t = Tmp::sandbox_wt(); + let r = t.path(); + git(r, &["init", "-q", "-b", "main"]); + write(r, "tools/a.sh", "#!/bin/sh\necho PASS\n", true); + write( + r, + "tests/gates/A.gate", + &gate("A", "a/", "tools/a.sh", ""), + false, + ); + write(r, "a/a.txt", "1\n", false); + git(r, &["add", "-A"]); + git(r, &["commit", "-q", "-m", "init"]); + let ev = Tmp::new("sandbox-ev"); + let mut opts = Options::new(ev.path().join("out")); + opts.sandbox = Sandbox::User; + let o = runner::run_gate(r, &r.join("tests/gates/A.gate"), &opts).unwrap(); + println!("sandbox user: {} {}", o.verdict.as_str(), o.reason); + assert_eq!(o.verdict, Verdict::Pass, "{}", o.reason); +} + +// ---------------------------------------------------------------- ENGINE-2 review fixes + +/// A fake `gh` that logs its arguments; `gh.down` makes every call fail and +/// `fail-` makes calls about that commit fail. +fn fake_gh(w: &World) -> (PathBuf, PathBuf, PathBuf) { + let fake = w.state.root.join("fake-gh"); + let log = w.state.root.join("gh.log"); + let down = w.state.root.join("gh.down"); + fs::create_dir_all(&w.state.root).unwrap(); + fs::write( + &fake, + format!( + "#!/bin/sh\nroot={}\nif [ -e \"$root/gh.down\" ]; then echo 'connect: network unreachable' >&2; exit 1; fi\nfor a in \"$@\"; do for f in \"$root\"/fail-*; do [ -e \"$f\" ] || continue; s=${{f##*/fail-}}; case \"$a\" in *\"$s\"*) echo 'refused' >&2; exit 1;; esac; done; done\necho \"$@\" >> {}\nexit 0\n", + w.state.root.display(), + log.display() + ), + ) + .unwrap(); + fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); + (fake, log, down) +} + +#[test] +fn worker_refuses_unsandboxed_runs_and_bad_names() { + let w = world(); + let mut cfg = w.config(); + cfg.allow_unsandboxed = false; + let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); + assert!(e.contains("--dev-unsandboxed"), "{e}"); + // Never with GitHub heads, even in development mode (the CLI applies it). + cfg.allow_unsandboxed = true; + let e = cfg.check_sandbox_policy_for(true).unwrap_err(); + assert!(e.contains("--github"), "{e}"); + let cfg = w.config(); + for (repo, sha) in [ + ("..", w.head.as_str()), + ("a/b", w.head.as_str()), + (".hidden", w.head.as_str()), + (REPO, "HEAD"), + (REPO, &w.head[..12]), + ] { + let e = worker::run_once(&cfg, repo, sha).unwrap_err(); + assert!(e.starts_with("refusing"), "{repo} {sha}: {e}"); + } + // Nothing was checked out, signed or journaled. + assert!(!w.wt_root.exists()); + assert!(!w.bundle_path(&w.head).exists()); + assert!(!w.state.journal().exists()); +} + +#[test] +fn worker_refuses_a_key_others_can_read() { + let w = world(); + fs::set_permissions(&w.key, fs::Permissions::from_mode(0o644)).unwrap(); + let e = worker::run_once(&w.config(), REPO, &w.head).unwrap_err(); + assert!(e.contains("mode 644"), "{e}"); + assert!(!w.wt_root.exists()); + assert!(!w.bundle_path(&w.head).exists()); +} + +#[test] +fn github_success_needs_a_ready_verify() { + let w = world(); + let (fake, log, _down) = fake_gh(&w); + let mut cfg = w.config(); + cfg.github = true; + cfg.gh = fake.display().to_string(); + // Signed by a key the repository does not list at BASE: the gates pass, + // the bundle algebra says PASS, and still no success is posted. + cfg.key = w.other_key.clone(); + let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); + assert_eq!(s.verdict, Verdict::Pass, "{}", s.reason); + assert_eq!(s.bundle_verdict, "PASS"); + assert!(!s.ready); + assert_eq!(s.publication, "posted"); + let l = fs::read_to_string(&log).unwrap(); + assert!(l.contains("state=error"), "{l}"); + assert!(!l.contains("state=success"), "{l}"); + let j = fs::read_to_string(w.state.journal()).unwrap(); + assert!(j.contains("\"verify\":\"BLOCKED\""), "{j}"); + assert!(j.contains("UNKNOWN_KEY"), "{j}"); + // With the trusted key the same head is READY and success is posted. + let mut cfg = cfg.clone(); + cfg.key = w.key.clone(); + let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); + assert!(s.ready, "{:?}", s.notes); + let l = fs::read_to_string(&log).unwrap(); + assert!(l.contains("state=success"), "{l}"); +} + +#[test] +fn outbox_replays_in_queue_order() { + let w = world(); + let (fake, log, down) = fake_gh(&w); + let mut cfg = w.config(); + cfg.github = true; + cfg.gh = fake.display().to_string(); + fs::write(&down, "").unwrap(); + // Queue the heads so that queue order differs from name order. + let (first, second) = if w.head > w.head_h { + (w.head.clone(), w.head_h.clone()) + } else { + (w.head_h.clone(), w.head.clone()) + }; + for sha in [&first, &second] { + let s = worker::run_once(&cfg, REPO, sha).expect("worker"); + assert_eq!(s.publication, "pending"); + } + let q = worker::outbox_files(&w.state); + assert_eq!(q.len(), 2); + assert!(q[0].to_string_lossy().contains(&first)); + // Still down: nothing posted, both pending. + assert_eq!(worker::flush_outbox(&cfg), (0, 2)); + // Up, but GitHub refuses the oldest: the replay stops there, the newer + // status does not overtake it. + fs::remove_file(&down).unwrap(); + let block = w.state.root.join(format!("fail-{first}")); + fs::write(&block, "").unwrap(); + assert_eq!(worker::flush_outbox(&cfg), (0, 2)); + assert!(!log.exists() || fs::read_to_string(&log).unwrap().is_empty()); + // Fully back: both posted, oldest first. + fs::remove_file(&block).unwrap(); + assert_eq!(worker::flush_outbox(&cfg), (2, 0)); + assert!(worker::outbox_files(&w.state).is_empty()); + let l = fs::read_to_string(&log).unwrap(); + let a = l.find(&format!("statuses/{first}")).expect("first posted"); + let b = l + .find(&format!("statuses/{second}")) + .expect("second posted"); + assert!(a < b, "{l}"); +} + +#[test] +fn verify_rejects_another_check_id_or_manifest() { + let w = verified_world(); + let key = bundle::load_signing_key(&w.key).unwrap(); + let original = w.read_bundle(&w.head); + + // A re-signed entry naming another check id. + let mut b = original.clone(); + b.as_object_mut().unwrap().remove("signature"); + b["checks"][0]["check_id"] = json!("0".repeat(64)); + w.write_bundle(&w.head, &bundle::sign(&b, &key).unwrap()); + let r = w.verify(&w.ask(&w.head)); + assert_blocked(&r, "check id"); + assert!( + r.lines.iter().any(|l| l.contains("CHECK_ID_MISMATCH")), + "{:#?}", + r.lines + ); + + // A receipt made from another manifest, stored under its own digest and + // named by a re-signed bundle. + let digest = original["checks"][0]["receipt"].as_str().unwrap(); + let dir = w.state.evidence(REPO, &w.head); + let mut receipt: Value = + serde_json::from_slice(&fs::read(dir.join(format!("{digest}.json"))).unwrap()).unwrap(); + receipt["core"]["manifest_digest"] = json!("1".repeat(64)); + let (forged, _) = aien_test::evidence::Store::new(&dir) + .put_receipt(&receipt) + .unwrap(); + let mut b = original.clone(); + b.as_object_mut().unwrap().remove("signature"); + b["checks"][0]["receipt"] = json!(forged); + w.write_bundle(&w.head, &bundle::sign(&b, &key).unwrap()); + let r = w.verify(&w.ask(&w.head)); + assert_blocked(&r, "manifest"); + assert!( + r.lines.iter().any(|l| l.contains("MANIFEST_MISMATCH")), + "{:#?}", + r.lines + ); + assert_eq!(line(&r, "Executed gates:"), "Executed gates: none"); +} + +#[test] +fn main_head_is_verified_against_its_first_parent() { + let w = world(); + // Land the topic on main: the head is now the tip of origin/main. + git(&w.origin, &["merge", "-q", "--ff-only", "topic"]); + git(&w.clone, &["fetch", "-q", "--all"]); + assert_eq!(git(&w.clone, &["rev-parse", "origin/main"]), w.head); + let s = worker::run_once(&w.config(), REPO, &w.head).expect("worker"); + assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); + assert!(s.ready, "{:?}", s.notes); + // `verify` with the default base reaches the same plan and is READY. + let r = w.verify(&w.ask(&w.head)); + assert_eq!( + line(&r, "MERGE ELIGIBILITY:"), + "MERGE ELIGIBILITY: READY", + "{:#?}", + r.lines + ); + assert_eq!(line(&r, "Executed gates:"), "Executed gates: 1 (A)"); +} + +#[test] +fn symlinked_exec_out_of_the_tree_never_runs() { + let t = Tmp::new("symlink"); + let r = t.path(); + git(r, &["init", "-q", "-b", "main"]); + fs::create_dir_all(r.join("tools")).unwrap(); + std::os::unix::fs::symlink("/bin/true", r.join("tools/run.sh")).unwrap(); + write( + r, + "tests/gates/T.gate", + &gate("T", "a/", "tools/run.sh", ""), + false, + ); + write(r, "a/a.txt", "1\n", false); + git(r, &["add", "-A"]); + git(r, &["commit", "-q", "-m", "init"]); + let ev = Tmp::new("symlink-ev"); + let opts = Options::new(ev.path().join("out")); + let o = runner::run_gate(r, &r.join("tests/gates/T.gate"), &opts).unwrap(); + assert_eq!(o.verdict, Verdict::MissingImplementation, "{}", o.reason); + assert_eq!(runner::exec_path(r, "tools/run.sh"), None); +} + +#[test] +fn worker_in_the_user_sandbox_is_ready() { + if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() { + println!( + "SKIP: {} is not installed (INFRA lane)", + aien_test::sandbox::EXEC_HELPER + ); + return; + } + let w = world(); + let mut cfg = w.config(); + cfg.allow_unsandboxed = false; + cfg.sandbox = Sandbox::User; + if !wt_tool().is_file() { + println!( + "SKIP: {} is not in this tree (INFRA lane)", + wt_tool().display() + ); + return; + } + cfg.wt_root = PathBuf::from("/var/lib/aien-run/wt"); + cfg.wt_tool = Some(wt_tool()); + let mirror = Path::new(worker::MIRROR_ROOT).join(format!("{REPO}.git")); + let _mirror = MirrorCleanup(mirror.clone()); + let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); + println!( + "worker --sandbox user: {} {} {:?}", + s.verdict.as_str(), + s.reason, + s.notes + ); + // The wt.sh worktree is gone again and no note says otherwise. + assert!( + !Path::new("/var/lib/aien-run/wt") + .join(REPO) + .join(&w.head) + .exists(), + "worktree left behind" + ); + assert!(mirror.join("HEAD").exists(), "wt.sh keeps its mirror"); + assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); + assert!(s.ready, "{:?}", s.notes); + let r = w.verify(&w.ask(&w.head)); + assert_eq!( + line(&r, "MERGE ELIGIBILITY:"), + "MERGE ELIGIBILITY: READY", + "{:#?}", + r.lines + ); +} + +#[test] +fn worker_cli_refuses_unsandboxed_github_and_unflagged_none() { + let bin = env!("CARGO_BIN_EXE_aien-test"); + let t = Tmp::new("cli"); + let state = t.path().join("state"); + let sha = "a".repeat(40); + let run = |extra: &[&str]| { + let mut args = vec![ + "worker", + "--once", + "repo", + sha.as_str(), + "--state-dir", + state.to_str().unwrap(), + "--clones", + t.path().to_str().unwrap(), + ]; + args.extend_from_slice(extra); + Command::new(bin).args(&args).output().unwrap() + }; + let o = run(&["--sandbox", "none"]); + assert_eq!(o.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&o.stderr).contains("--dev-unsandboxed")); + let o = run(&["--sandbox", "none", "--dev-unsandboxed", "--github"]); + assert_eq!(o.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&o.stderr).contains("--github")); + // Nothing ran: no state was written. + assert!(!state.exists()); +} + +// ---------------------------------------------------------------- INFRA-2 alignment + +/// INFRA's worktree tool, from this repository. +fn wt_tool() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../aien-local-ci/wt.sh") +} + +/// Removes a test mirror under `/var/lib/aien-run/mirror` when dropped. +struct MirrorCleanup(PathBuf); + +impl Drop for MirrorCleanup { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +#[test] +fn worker_refuses_the_user_sandbox_without_the_wt_tool() { + let w = world(); + let mut cfg = w.config(); + cfg.sandbox = Sandbox::User; + cfg.wt_tool = None; + let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); + assert!(e.contains("--wt-tool"), "{e}"); + // Nothing was checked out. + assert!(!w.wt_root.join(REPO).join(&w.head).exists()); +} + +#[test] +fn only_a_wt_sh_link_is_trusted() { + let t = Tmp::new("wt-link"); + let wt = t.path().join("wt"); + let mirror = t.path().join("m.git"); + fs::create_dir_all(&wt).unwrap(); + // Owned by the test user, not root: refused even with the right target. + fs::write( + wt.join(".git"), + format!("gitdir: {}/worktrees/x\n", mirror.display()), + ) + .unwrap(); + // Mode 0644 as wt.sh leaves it, so only the owner is wrong. + fs::set_permissions(wt.join(".git"), fs::Permissions::from_mode(0o644)).unwrap(); + let e = worker::check_worktree_link(&wt, &mirror).unwrap_err(); + assert!(e.contains("root-owned"), "{e}"); + // A real wt.sh worktree passes when one is present on this host. + let real = Path::new("/var/lib/aien-run/wt/aien-sovereign-core"); + let found = fs::read_dir(real).ok().and_then(|mut rd| { + rd.find_map(|e| { + e.ok() + .map(|e| e.path()) + .filter(|p| p.join(".git").is_file()) + }) + }); + if let Some(p) = found { + let m = Path::new(worker::MIRROR_ROOT).join("aien-sovereign-core.git"); + worker::check_worktree_link(&p, &m).expect("wt.sh worktree"); + let other = Path::new(worker::MIRROR_ROOT).join("elsewhere.git"); + assert!(worker::check_worktree_link(&p, &other).is_err()); + } else { + println!("SKIP real wt.sh worktree: none present"); + } +} + +#[test] +fn a_wrong_target_dir_is_refused_by_the_helper() { + if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() { + println!( + "SKIP: {} is not installed (INFRA lane)", + aien_test::sandbox::EXEC_HELPER + ); + return; + } + // The helper itself: exit 2, its prefix on stderr, nothing ran. + let t = Tmp::sandbox_wt(); + let r = t.path(); + let bad = "/var/lib/aien-run/target/aien-test-selftest/other"; + let (program, args) = aien_test::sandbox::command( + Sandbox::User, + Path::new("/bin/true"), + &[], + r, + 10, + "host", + &[("CARGO_TARGET_DIR".to_string(), bad.to_string())], + ); + let out = Command::new(program).args(&args).output().unwrap(); + assert_eq!(out.status.code(), Some(2), "{out:?}"); + assert!(out.stderr.starts_with(b"aien-run-exec:"), "{out:?}"); + assert!(runner::sandbox_refused( + Sandbox::User, + out.status.code(), + &out.stderr + )); + assert!(!runner::sandbox_refused( + Sandbox::None, + out.status.code(), + &out.stderr + )); + assert!(!runner::sandbox_refused( + Sandbox::User, + Some(2), + b"own error\n" + )); + + // Through the runner: a gate that expects exit 2 still never passes on + // a refusal, and its receipt has no exit status. + git(r, &["init", "-q", "-b", "main"]); + write( + r, + "tests/gates/R.gate", + &gate("R", "a/", "true", "").replace("exit: 0", "exit: 2"), + false, + ); + write(r, "a/a.txt", "1\n", false); + git(r, &["add", "-A"]); + git(r, &["commit", "-q", "-m", "init"]); + let ev = Tmp::new("refused-ev"); + let mut opts = Options::new(ev.path().join("out")); + opts.sandbox = Sandbox::User; + opts.cargo_target_dir = Some(PathBuf::from(bad)); + let o = runner::run_gate(r, &r.join("tests/gates/R.gate"), &opts).unwrap(); + assert_eq!(o.verdict, Verdict::Fail, "{}", o.reason); + let receipt: serde_json::Value = + serde_json::from_slice(&fs::read(o.receipt_path.unwrap()).unwrap()).unwrap(); + assert_eq!(receipt["core"]["exit_status"], serde_json::Value::Null); +} ```