diff --git a/.crumb b/.crumb index f1d77dbe..6ecd026c 100644 --- a/.crumb +++ b/.crumb @@ -65,68 +65,68 @@ "children": [ { "digest": "4e7f370019e67f6c71565d1544530851eb1b3b1bed61c2712f4ac7d9614a89bf", - "last_commit": "6bbe2ec2", + "last_commit": "6bbe2ec", "name": "crates/aien-allen", "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). " }, { "digest": "40a231c50dba92af7de2527ab33879c5d1eaaa6e7ea5d6a5ebaa9d60c7542075", - "last_commit": "b9b52f9c", + "last_commit": "b9b52f9", "name": "crates/aien-allen-memory", "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for" }, { "digest": "44dc482b8c9db8919a68ec69b019cd77967232a6ec8b1910c0dfe3cd4d71f141", - "last_commit": "b9b52f9c", + "last_commit": "b9b52f9", "name": "crates/aien-allen-profile", "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; " }, { "digest": "f5571bcc0bb95b44dd8bf8f0b47ded3bcb1e1ee76c81b4ff5edb87ac237d66d8", - "last_commit": "f8eea420", + "last_commit": "f8eea42", "name": "crates/aien-cli", "purpose": "" }, { "digest": "25fd9f8afbea19702750f8ddba2ef4aeafc5bc4515aa695340a5af6931989c03", - "last_commit": "8cca8020", + "last_commit": "8cca802", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { "digest": "a0a981f6168d15e43a6b036c3aa82d44547aadfc3b6c62139a5a3afab0644514", - "last_commit": "8cca8020", + "last_commit": "8cca802", "name": "crates/spark-cockpit-rs", "purpose": "" }, { "digest": "f38ccede5d794040581cf48d409424c923d705a2fc206140b52691ef7fb186ef", - "last_commit": "deff6f7a", + "last_commit": "deff6f7", "name": "scripts", "purpose": "" }, { "digest": "75e439cb2ae120e1807af894b70b6454971028f5527f56451f9d6558f503c88b", - "last_commit": "fa73e778", + "last_commit": "fa73e77", "name": "skills", "purpose": "" }, { - "digest": "b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", - "last_commit": "247e0927", + "digest": "425d20f6938609687a0502311efe537dd8f66e48ae8a2fc6dbb838904cdeef49", + "last_commit": "7d3c26e", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], - "children_root": "sha256:7d8cf5937a13dd896fe511aee80a0873f4917a0a5eb07cbe0fe3690c0c878cbb", - "compiled_at": "2026-10-16T15:26:31Z", + "children_root": "sha256:f14e75d979378caa5a5df3643f334384d33ed54710f81ef6301faaadef6132e1", + "compiled_at": "2026-10-16T18:42:59Z", "compiler": "crumb-compile/1", - "digest": "sha256:5c3262fb97f4051b7780f820f039da497a16ac9d1cf8d077e593d3b2e786ba89", + "digest": "sha256:6a2cd729ba4b8080c865333fed0cbc796c09c4a1e5da4ad06ba7a51b8117fd6d", "evidence_files": 1578, "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160", - "files": 5889, - "generated_at_commit": "228809d2f65ded6e8bbc011bc817209d82255bb5", - "source_tree": "sha256:7bdcd0cf99ffd24054c17de9287bf4506d8059c855d566eab42a2280024ec2a2" + "files": 5891, + "generated_at_commit": "7d3c26e48e33684276e5e6667ada8ec712fcd2e0", + "source_tree": "sha256:ac510575d95d65b5cab4c45f97cf8b7ba8500d064aafb643029bff5e89573ff6" } }, "history": [], diff --git a/tools/aien-local-ci/.crumb b/tools/aien-local-ci/.crumb index 602ce99d..299fe774 100644 --- a/tools/aien-local-ci/.crumb +++ b/tools/aien-local-ci/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T05:31:46Z", + "compiled_at": "2026-10-16T09:08:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", + "digest": "sha256:425d20f6938609687a0502311efe537dd8f66e48ae8a2fc6dbb838904cdeef49", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 12, - "generated_at_commit": "db857500b1867559a663d4aa1c78b8200655d6b5", - "source_tree": "sha256:f5eb6931b7a33500be48cede1b99e7448b5369a48a401e3dc2ef56aba3915525" + "files": 14, + "generated_at_commit": "7c292a2d12e3741c9a1c52a6a2c6cbce892c4cce", + "source_tree": "sha256:f85574a652f572cf27c708712320f5a80a1d6bd3c7c7fb75ba1f882b28fb1453" } }, "layer": "infra", diff --git a/tools/aien-local-ci/README.md b/tools/aien-local-ci/README.md index af8d9224..a9cbef88 100644 --- a/tools/aien-local-ci/README.md +++ b/tools/aien-local-ci/README.md @@ -18,6 +18,8 @@ AIENOS. | `tests/run.sh` | proofs of the contract on this host (33 checks with two wt.sh worktrees present) | | `pipeline.sh` | ADR 0033 phase 3: publish verified bundles to aien-receipts, rerun the GitHub thin gate, merge `ready-to-merge` PRs behind guards | | `tests/pipeline_test.sh` | offline proofs of `pipeline.sh` with fake `gh`, fake `aien-test` and throwaway git repositories (56 checks) | +| `train.sh` | the merge train: batches `ready-to-merge` PRs every measured T, verifies stacked prefixes on the Spark, names the culprit, lands the tested stack by merging its train PR (not installed; review first) | +| `tests/train_test.sh` | offline proofs of `train.sh` with fake `gh`, worker, quietlock and crumb tool, the real `pipeline.sh` for publishing (70 checks) | ## C8 exec contract @@ -191,6 +193,68 @@ or configuration error. Overrides: `AIEN_STATE`, `AIEN_CLONES`, `AIEN_RECEIPTS`, is queued or in progress. Then `gh pr merge N -R --merge --match-head-commit `. Never `--admin`. A base branch without required status checks (or whose protection cannot be read) is refused, not merged. +## Merge train (train.sh, Drake 2026-10-16; NOT installed, pipeline owner reviews first) + +``` +tools/aien-local-ci/train.sh cadence [--repos a,b] # measured T per repository, from real bundles +tools/aien-local-ci/train.sh cycle [--repos a,b] [--dry-run] # one cycle; dry-run prints the plan, pushes nothing +tools/aien-local-ci/train.sh loop [--repos a,b] [--every SECS] # a cycle per repository every T (measured) or --every +bash tools/aien-local-ci/tests/train_test.sh # offline proofs, a few seconds +``` + +Idea: the gates have a known duration T, so instead of one PR per worker run, every T the train takes every open PR +labeled exactly `ready-to-merge` (base main, not draft, oldest number first) and tests them as **stacked prefixes**: +stack k = `origin/main` + PR1..PRk merged in order (merge commits, the same shape `gh pr merge --merge` leaves) plus +one crumb recompile commit made with the repository's pinned crumb tool (see guard 5 for how the pin is found; built +from the aien-architecture source into `$STATE/train-crumb//`). That +recompile commit is part of the tested sha. Stack 0 is main itself. + +Capacity (measured, not assumed): the worker serves heads one at a time (`run_loop` in `tools/aien-test/src/worker.rs`); +the pools `host=`, `qemu=min(4, cpus/2)`, `gb10=1` parallelise gates inside one head, and two heads would share +`target//pr` and the one GB10. So the train runs stack N first and, on FAIL, bisects (log2 N more runs) for the +longest passing prefix p and the first failing prefix p+1. PR p+1 is the culprit: a comment with the receipt link +(`aien-receipts///bundle.json`), the label removed, never closed; the next cycle runs without it. When stack 1 +fails, main itself is tested before PR 1 is blamed. + +T per repository is read from `$STATE/bundles//*/bundle.json` (`started_utc` to `finished_utc` of PASS/FAIL +runs with `plan.blocked` null; the longest one is T). Measured 2026-10-16 on the Spark: aienos 2292 s (three full runs, +2188 to 2292 s), aien-sovereign-core 274 s (seven runs, 154 to 274 s), omega 475 s (one run), spark-rsi 119 s, physics +17 s, the rest under 10 s. `loop` schedules each repository every T; a repository with no real run is not scheduled. + +Guards (every one journaled in `$STATE/train.jsonl`, `action: train`): +1. **Receipt binding**: the stack bundle is published by `pipeline.sh publish` and its sha256 is read back from + receipts `origin/main` before any push to main; `pipeline.sh publish` takes the pipeline lock with `flock -n` and + exits 0 silently when busy, so the train waits for the lock first and refuses with "lock busy" instead of mistaking + silence for publication. +2. **Branch protection untouched, no direct push to main** (pipeline owner's decision, 2026-10-16): the stack sha is + pushed as branch `train/` with one train PR whose head is the EXACT tested sha, so the hosted required check + runs on it (Sovereign CI triggers only on `push: main` and `pull_request`). The merge waits until every required + context of main is `success` on that sha, re-checked under the lock. It then runs + `gh pr merge --merge --match-head-commit ` (a merge commit), and only if, under the lock: + the PR is open, into main, with head == tested sha; `origin/main` still equals the base the stack was built on + (otherwise the cycle is journaled `aborted` and the next cycle restacks); the base is an ancestor of the tested sha. + Main being an ancestor of the head, the merge commit adds no content: merged tree == tested tree, the same binding + `pipeline.sh merge` uses (the receipt binds the PR head). After landing, the train re-reads main and journals + `failed` loudly if the tree differs (main moved in the last instant). The stacked PRs show as merged because + their heads are in main. +3. **BLOCKED_OPERATOR**: a PR touching `crumb.lock`, `.aien/`, `tests/gates/`, `.github/workflows/`, `.forgejo/` or + `tools/aien-test/` (any changed or renamed path, from `pulls/N/files`) never enters a stack; label kept. +4. **Freshness at merge time**: under the lock, every PR of the prefix must still be open, labeled, not draft, head + unchanged since stacking; the first stale one ends the prefix before it and the train falls back to the longest + tested passing prefix inside it (re-tested when bisection skipped it). `origin/main` must equal the stacking base. +5. **Crumb recompile** in the tested sha with the pinned tool, then `verify` with the same tool. The pin is the target repository's own, read from the BASE (`origin/main`), never from the stack: `crumb.lock` where it has one, else the `pinned crumb tool` ref of its own `.github/workflows/aien-verification.yml`; a PR touching `crumb.lock` is BLOCKED_OPERATOR (left out of the stack); neither (or a malformed one) fails closed, no default pin. The recompile may only change `.crumb` files, and a stack whose recompile would change a `.crumb` inside `.aien/`, `tests/gates/`, `.github/workflows/`, `.forgejo/` or `tools/aien-test/` is skipped (journaled `refused`), so the train never writes into the trust surface. +6. **One merger per repository**: `flock` on `$STATE/pipeline.lock`, the file `pipeline.sh merge` uses (`-w AIEN_LOCK_WAIT`, default 900 s); and one train cycle per repository: a non-blocking `flock` on `$STATE/train..lock`, held on fd 8 which every child (worker, publish, crumb, gh) gets closed (a second loop skips, journaled `skipped`, instead of force-pushing the same `train/`). The train also refuses to start without a git committer identity (user.name and user.email), because every merge it makes needs one. +7. **Spark etiquette**: `quietlock check` must pass before every worker run (`AIEN_QUIET_WAIT`, default 2 h, then + refuse); the worker is `aien-local-ci once `, never a chip run of the train's own. +8. No Python; pure bash, git, jq, gh, cc for the pinned crumb tool. + +Also excluded (journaled, label kept): head not equal to `refs/pull/N/head`, merge conflict with main or an earlier +stacked PR, queue beyond `AIEN_MAX_STACK` (20). Unlabeled PRs are skipped silently, as in `pipeline.sh`. The train +never reads `~/.aien/verify.key`, never signs, never changes protection. Overrides beyond pipeline.sh's: `AIEN_PIPELINE`, +`AIEN_LOCAL_CI`, `QUIETLOCK`, `AIEN_TRAIN_CLONES` (its own scratch clones, default `$STATE/train-clones`; the trusted +clone is only read), `AIEN_ARCH_URL`, `AIEN_CRUMB_PIN`, `AIEN_CRUMB_TOOL`, `AIEN_MAX_STACK`, `AIEN_LOCK_WAIT`, +`AIEN_CHECK_WAIT`, `AIEN_QUIET_WAIT`, `AIEN_TRAIN_POLL`. + ## Operate ``` diff --git a/tools/aien-local-ci/tests/train_test.sh b/tools/aien-local-ci/tests/train_test.sh new file mode 100755 index 00000000..a38fcad6 --- /dev/null +++ b/tools/aien-local-ci/tests/train_test.sh @@ -0,0 +1,412 @@ +#!/usr/bin/env bash +# train_test.sh: offline proofs for tools/aien-local-ci/train.sh (no network, no real gh, worker, key or crumb). +# Fakes: gh (JSON files + the real --jq filter; writes are logged), aien-test (verify-bundle by the bundle's "fake" +# member, as in pipeline_test.sh), aien-local-ci once (writes a bundle: FAIL when the tested tree holds BAD or MAINBAD, +# no bundle when the sha was never pushed to origin), quietlock (held while $T/quiet exists), crumb (compile writes a +# deterministic .crumb from the tracked files; verify compares), git (logs every push so order can be checked). +# The real pipeline.sh does the publishing. Throwaway bare repositories stand in for GitHub and aien-receipts. +# bash tools/aien-local-ci/tests/train_test.sh +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +TRAIN=$HERE/../train.sh +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +pass=0 fail=0 +ok() { pass=$((pass + 1)); echo "ok $*"; } +bad() { fail=$((fail + 1)); echo "FAIL $*"; } +check() { local name=$1; shift; if "$@"; then ok "$name"; else bad "$name"; fi; } + +export GIT_CONFIG_GLOBAL=$T/gitconfig GIT_CONFIG_NOSYSTEM=1 +: > "$GIT_CONFIG_GLOBAL" +export GIT_AUTHOR_NAME=test GIT_AUTHOR_EMAIL=test@example.invalid GIT_COMMITTER_NAME=test GIT_COMMITTER_EMAIL=test@example.invalid +export FAKE_LOG=$T/calls.log FAKE_GH=$T/gh ORIGIN=$T/origin-demo.git +export AIEN_STATE=$T/state AIEN_CLONES=$T/clones AIEN_RECEIPTS=$T/receipts AIEN_TEST_BIN=$T/bin/aien-test +export GH=$T/bin/gh GIT=$T/bin/git AIEN_REPOS=demo AIEN_LOCAL_CI=$T/bin/aien-local-ci QUIETLOCK=$T/bin/quietlock +export AIEN_CRUMB_TOOL=$T/bin/crumb AIEN_LOCK_WAIT=1 AIEN_RETRY_SLEEP=0 AIEN_QUIET_WAIT=0 AIEN_TRAIN_POLL=0 AIEN_CHECK_WAIT=0 +mkdir -p "$T/bin" "$FAKE_GH" "$AIEN_STATE" "$AIEN_CLONES" +: > "$FAKE_LOG" +S=aien-spark/demo +CTX1="Workspace Verification & Invariant Audit" +L=ready-to-merge + +cat > "$T/bin/gh" <<'EOF' +#!/usr/bin/env bash +echo "gh $*" >> "$FAKE_LOG" +if [[ $1 == pr && $2 == merge ]]; then + shift 2; num=$1; match="" + while [[ $# -gt 0 ]]; do case $1 in --match-head-commit) match=$2; shift 2 ;; -R|--subject) shift 2 ;; *) shift ;; esac; done + [[ $num == 900 ]] || exit 1 + [[ -z ${FAKE_PUT_FAIL:-} ]] || { echo "HTTP 409 Head branch was modified" >&2; exit 1; } + head=$(git --git-dir="$ORIGIN" rev-parse -q --verify refs/heads/train/demo) || { echo "HTTP 404" >&2; exit 1; } + [[ $match == "$head" ]] || { echo "head branch was modified" >&2; exit 1; } + m=$(git --git-dir="$ORIGIN" rev-parse main) + c=$(git --git-dir="$ORIGIN" commit-tree "$head^{tree}" -p "$m" -p "$head" -m "Merge pull request #900") + git --git-dir="$ORIGIN" update-ref refs/heads/main "$c" + exit 0 +fi +[[ $1 == api ]] || exit 9 +shift +method=GET expr="" path="" sha="" +while [[ $# -gt 0 ]]; do + case $1 in -X) method=$2; shift 2 ;; --jq) expr=$2; shift 2 ;; -f|-F) case $2 in sha=*) sha=${2#sha=} ;; esac; shift 2 ;; --paginate) shift ;; *) path=$1; shift ;; esac +done +if [[ $method != GET ]]; then + if [[ $method == POST && $path == */pulls ]]; then echo '{"number":900}' | { [[ -n $expr ]] && jq -r "$expr" || cat; }; fi + exit 0 +fi +if [[ $path == */pulls/900 ]]; then + h=${FAKE_TRAIN_HEAD:-$(git --git-dir="$ORIGIN" rev-parse -q --verify refs/heads/train/demo || echo none)} + j="{\"number\":900,\"state\":\"open\",\"base\":{\"ref\":\"main\"},\"head\":{\"sha\":\"$h\"}}" + if [[ -n $expr ]]; then jq -r "$expr" <<< "$j"; else echo "$j"; fi; exit 0 +fi +f=$FAKE_GH/$(printf '%s' "$path" | tr -c 'A-Za-z0-9._-' '_').json +if [[ ! -f $f ]]; then + case $path in + */commits/*/check-runs*) sha=${path#*/commits/}; sha=${sha%%/*} + if grep -qx "$sha" "$FAKE_GH/redcheck" 2>/dev/null; then c=failure; else c=success; fi + printf '{"check_runs":[{"name":"%s","status":"completed","conclusion":"%s"}]}' "Workspace Verification & Invariant Audit" "$c" > "$f" ;; + */commits/*/status*) echo '{"statuses":[]}' > "$f" ;; + */pulls?state=open\&head=*) echo '[]' > "$f" ;; + *) echo "gh: HTTP 404 $path" >&2; exit 1 ;; + esac +fi +if [[ -n $expr ]]; then jq -r "$expr" "$f"; else cat "$f"; fi +EOF +cat > "$T/bin/aien-test" <<'EOF' +#!/usr/bin/env bash +echo "aien-test $*" >> "$FAKE_LOG" +[[ $1 == verify-bundle ]] || exit 9 +file=$2; shift 2 +while [[ $# -gt 0 ]]; do + case $1 in --repo) repo=$2 ;; --commit) commit=$2 ;; --pubkey) key=$2 ;; --require) ;; *) exit 2 ;; esac; shift 2 +done +[[ $(jq -r .repository "$file") == "$repo" && $(jq -r .commit "$file") == "$commit" ]] || exit 3 +[[ $(jq -r .fake.key "$file") == "$key" ]] || exit 3 +exit "$(jq -r .fake.rc "$file")" +EOF +cat > "$T/bin/aien-local-ci" <<'EOF' +#!/usr/bin/env bash +# fake worker: once REPO SHA -> bundle; FAIL when BAD or MAINBAD is in the tree; nothing when the sha is not at origin +echo "once $2 $3" >> "$FAKE_LOG" +[ -e "/proc/$$/fd/8" ] && echo "worker-fd8 open" >> "$FAKE_LOG" || echo "worker-fd8 closed" >> "$FAKE_LOG" +[[ $1 == once ]] || exit 9 +repo=$2 sha=$3 +git --git-dir="$ORIGIN" cat-file -e "$sha^{commit}" 2>/dev/null || { echo "fake worker: $sha not at origin"; exit 1; } +rc=0 +git --git-dir="$ORIGIN" cat-file -e "$sha:BAD" 2>/dev/null && rc=1 +git --git-dir="$ORIGIN" cat-file -e "$sha:MAINBAD" 2>/dev/null && rc=1 +d=$AIEN_STATE/bundles/$repo/$sha; mkdir -p "$d" +K2=$(printf '2%.0s' {1..64}) +jq -n --arg repo "github.com/aien-dev/$repo" --arg c "$sha" --arg k "$K2" --argjson rc "$rc" \ + --arg s "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + '{repository:$repo, commit:$c, started_utc:$s, finished_utc:$s, verdict:(if $rc==0 then "PASS" else "FAIL" end), + plan:{blocked:null}, signature:{pubkey:$k}, fake:{key:$k, rc:$rc}}' > "$d/bundle.json" +EOF +cat > "$T/bin/quietlock" <<'EOF' +#!/usr/bin/env bash +echo "quietlock $*" >> "$FAKE_LOG" +[[ $1 == check ]] || exit 9 +[[ -e $T_QUIET ]] && { echo "QUIETLOCK_REFUSED held"; exit 75; } +exit 0 +EOF +cat > "$T/bin/crumb" <<'EOF' +#!/usr/bin/env bash +# fake pinned crumb tool: .crumb at the root = one line derived from the tracked files (not the crumbs themselves) +echo "crumb $*" >> "$FAKE_LOG" +want="crumb-fake files=$(git ls-files | grep -v -E '(^|/)\.crumb$' | sort | sha256sum | cut -c1-16)" +case $1 in + compile) printf '%s\n' "$want" > .crumb + [[ -z ${FAKE_CRUMB_TRUST:-} ]] || { mkdir -p .aien; echo x > .aien/.crumb; } + [[ -z ${FAKE_CRUMB_JUNK:-} ]] || echo junk > stray.txt ;; + verify) [[ -f .crumb && $(cat .crumb) == "$want" ]] ;; + *) exit 9 ;; +esac +EOF +cat > "$T/bin/git" <<'EOF' +#!/usr/bin/env bash +# logs pushes (with the directory) so the order of receipts publication and the merge of the train PR can be checked; +# races one commit onto main right before the train pushes its train/ branch when $T_RACE names a seed clone +if [[ " $* " == *" push "* ]]; then + echo "push $*" >> "$FAKE_LOG" + if [[ -n ${T_RACE:-} && " $* " == *":refs/heads/train/"* && ! -e $T_RACE/.raced ]]; then + touch "$T_RACE/.raced" + /usr/bin/git -C "$T_RACE" pull -q --rebase origin main && echo raced >> "$T_RACE/RACED" && /usr/bin/git -C "$T_RACE" add -A \ + && /usr/bin/git -C "$T_RACE" commit -q -m raced && /usr/bin/git -C "$T_RACE" push -q origin main + fi +fi +exec /usr/bin/git "$@" +EOF +chmod +x "$T/bin/"* +export T T_QUIET=$T/quiet + +ghset() { printf '%s\n' "$2" > "$FAKE_GH/$(printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_').json"; } +K1=$(printf '1%.0s' {1..64}) K2=$(printf '2%.0s' {1..64}) +jl() { jq -c "select($1)" "$AIEN_STATE/train.jsonl" | wc -l; } +origin_main() { /usr/bin/git --git-dir="$ORIGIN" rev-parse main; } +origin_has() { /usr/bin/git --git-dir="$ORIGIN" cat-file -e "$1:$2" 2>/dev/null; } +remote_has() { /usr/bin/git --git-dir="$T/receipts.git" cat-file -e "main:demo/$1/bundle.json" 2>/dev/null; } +export -f origin_has remote_has + +# origin "demo" with main (crumbs compiled by the fake tool), the trusted clone, receipts remote + clone. +/usr/bin/git init -q --bare -b main "$ORIGIN" +/usr/bin/git clone -q "$ORIGIN" "$T/seed" 2>/dev/null +SEED=$T/seed +mkdir -p "$SEED/.aien" +printf '# keys\n%s\n%s\n' "$K1" "$K2" > "$SEED/.aien/verify.pub" +printf 'g1\ng2\n' > "$SEED/.aien/always" +echo base > "$SEED/README" +(cd "$SEED" && /usr/bin/git add -A && "$T/bin/crumb" compile . && /usr/bin/git add -A && /usr/bin/git commit -q -m init && /usr/bin/git push -q origin main) +/usr/bin/git clone -q "$ORIGIN" "$AIEN_CLONES/demo" 2>/dev/null +/usr/bin/git init -q --bare -b main "$T/receipts.git" +/usr/bin/git clone -q "$T/receipts.git" "$T/rseed" 2>/dev/null +echo shelf > "$T/rseed/README.md" && /usr/bin/git -C "$T/rseed" add -A && /usr/bin/git -C "$T/rseed" commit -q -m shelf && /usr/bin/git -C "$T/rseed" push -q origin main +/usr/bin/git clone -q "$T/receipts.git" "$AIEN_RECEIPTS" + +# pr NUM FILE CONTENT [README_LINE]: a pull request head off main, as refs/pull/NUM/head at origin. Prints its sha. +pr() { + local num=$1 file=$2 content=$3 readme=${4:-} + (cd "$SEED" && /usr/bin/git checkout -q --detach main >/dev/null 2>&1 + mkdir -p "$(dirname "$file")"; printf '%s\n' "$content" > "$file" + [[ -z $readme ]] || printf '%s\n' "$readme" > README + /usr/bin/git add -A && /usr/bin/git commit -q -m "pr $num: $file" && /usr/bin/git push -q origin "HEAD:refs/pull/$num/head" && /usr/bin/git rev-parse HEAD) +} +declare -A PR +PR[11]=$(pr 11 a.txt a one) # good; also edits README (conflicts with 15) +PR[12]=$(pr 12 BAD bad) # the culprit +PR[13]=$(pr 13 c.txt c) # good +PR[14]=$(pr 14 .github/workflows/x.yml "on: push") # BLOCKED_OPERATOR +PR[15]=$(pr 15 e.txt e five) # conflicts with 11 on README +PR[16]=$(pr 16 f.txt f) # draft +PR[17]=$(pr 17 g.txt g) # not labeled +PR[18]=$(pr 18 h.txt h) # listing says another head (moved) +# pulls "NUM:SHA:DRAFT:LABEL:FILE" ...: the open PR listing, the single-PR views (same facts) and the file lists. +pulls() { + local out="[" sep="" n s d l f spec + for spec in "$@"; do + IFS=: read -r n s d l f <<< "$spec" + out+="$sep{\"number\":$n,\"draft\":$d,\"state\":\"open\",\"title\":\"PR $n\",\"head\":{\"sha\":\"$s\"},\"base\":{\"ref\":\"main\"},\"labels\":[{\"name\":\"other\"}${l:+,{\"name\":\"$l\"\}}]}" + sep=, + ghset "repos/$S/pulls/$n" "{\"number\":$n,\"draft\":$d,\"state\":\"open\",\"head\":{\"sha\":\"$s\"},\"labels\":[${l:+{\"name\":\"$l\"\}}]}" + ghset "repos/$S/pulls/$n/files?per_page=100" "[{\"filename\":\"$f\"},{\"filename\":\"README\"}]" + done + ghset "repos/$S/pulls?state=open&per_page=100" "$out]" +} +ghset "repos/aien-dev/demo" '{"full_name":"aien-spark/demo"}' +ghset "repos/$S/branches/main/protection/required_status_checks" "{\"contexts\":[\"$CTX1\"]}" +ghset "repos/$S/branches/main/protection" '{"required_pull_request_reviews":null,"enforce_admins":{"enabled":true}}' +pulls "11:${PR[11]}:false:$L:a.txt" "12:${PR[12]}:false:$L:BAD" "13:${PR[13]}:false:$L:c.txt" \ + "14:${PR[14]}:false:$L:.github/workflows/x.yml" "15:${PR[15]}:false:$L:e.txt" "16:${PR[16]}:true:$L:f.txt" \ + "17:${PR[17]}:false::g.txt" "18:$(printf '%040x' 999):false:$L:h.txt" +MAIN0=$(origin_main) + +echo "== usage and configuration" +rc=0; bash "$TRAIN" bogus >/dev/null 2>&1 || rc=$?; check "unknown command exits 2" [ "$rc" = 2 ] +rc=0; bash "$TRAIN" cycle --repos 'bad/name' >/dev/null 2>&1 || rc=$?; check "bad --repos exits 2" [ "$rc" = 2 ] +rc=0; bash "$TRAIN" loop --every x >/dev/null 2>&1 || rc=$?; check "bad --every exits 2" [ "$rc" = 2 ] + +echo "== cadence (measured from bundles, never assumed)" +mkbundle() { mkdir -p "$AIEN_STATE/bundles/demo/$1"; jq -n --arg s "$2" --arg e "$3" --arg v "$4" --argjson b "${5:-null}" \ + '{started_utc:$s, finished_utc:$e, verdict:$v, plan:{blocked:$b}}' > "$AIEN_STATE/bundles/demo/$1/bundle.json"; } +mkbundle "$(printf '%040x' 1)" 2026-10-16T00:00:00Z 2026-10-16T00:05:00Z PASS +mkbundle "$(printf '%040x' 2)" 2026-10-16T01:00:00Z 2026-10-16T01:02:00Z FAIL +mkbundle "$(printf '%040x' 3)" 2026-10-16T02:00:00Z 2026-10-16T03:00:00Z NOT_RUN +mkbundle "$(printf '%040x' 4)" 2026-10-16T02:00:00Z 2026-10-16T03:00:00Z PASS '"gpu"' +out=$(bash "$TRAIN" cadence) +check "cadence: T is the longest PASS/FAIL unblocked run (300s), 2 runs counted" grep -qE '^demo +2 +300s +120s +120s +300s' <<< "$out" +check "cadence: a repository without bundles is unknown, not guessed" grep -qE '^none +0 .*unknown' <<< "$(AIEN_REPOS=none bash "$TRAIN" cadence)" +rm -rf "$AIEN_STATE/bundles/demo" + +echo "== dry run" +bash "$TRAIN" cycle --dry-run > "$T/dry" 2>&1 +check "dry run prints the plan with stack 3" grep -q 'stack 3 = [0-9a-f]\{40\}' "$T/dry" +check "dry run ran no worker, pushed nothing, wrote nothing to GitHub" bash -c "! grep -qE '^(once|push) |^gh api -X' '$FAKE_LOG'" +check "dry run left main alone" [ "$(origin_main)" = "$MAIN0" ] +check "journal: dry-run line" [ "$(jl '.result=="dry-run" and .stack=="3"')" = 1 ] +: > "$AIEN_STATE/train.jsonl" + +echo "== cycle 1: three stacked, the middle one is the culprit" +bash "$TRAIN" cycle > "$T/c1" 2>&1 +check "BLOCKED_OPERATOR PR excluded, label kept" bash -c "[ \"$(jl '.pr=="14" and .result=="excluded" and (.reason|test("BLOCKED_OPERATOR.*workflows"))')\" = 1 ] && ! grep -q 'issues/14/labels' '$FAKE_LOG'" +check "conflicting PR excluded" [ "$(jl '.pr=="15" and .result=="excluded" and (.reason|test("conflict"))')" = 1 ] +check "draft excluded" [ "$(jl '.pr=="16" and .result=="excluded" and .reason=="draft"')" = 1 ] +check "unlabeled PR skipped silently" [ "$(jl '.pr=="17"')" = 0 ] +check "head not matching refs/pull/N/head excluded" [ "$(jl '.pr=="18" and .result=="excluded" and (.reason|test("head moved"))')" = 1 ] +check "queue is 11, 12, 13 in order" [ "$(jq -r 'select(.result=="queued") | .pr' "$AIEN_STATE/train.jsonl" | paste -sd,)" = "11,12,13" ] +runs=$(grep -c '^once demo ' "$FAKE_LOG" || true) +check "worker ran exactly three stacks (3, then bisect 1 and 2), never main" [ "$runs" = 3 ] +S3=$(jq -r 'select(.result=="running" and .stack=="3") | .sha' "$AIEN_STATE/train.jsonl") +S1=$(jq -r 'select(.result=="running" and .stack=="1") | .sha' "$AIEN_STATE/train.jsonl") +S2=$(jq -r 'select(.result=="running" and .stack=="2") | .sha' "$AIEN_STATE/train.jsonl") +check "stack shas were pushed before the worker fetched them" bash -c "grep -n '^push .*$S3:refs/heads/train/demo' '$FAKE_LOG' | head -1 | cut -d: -f1 | xargs -I{} test {} -lt \$(grep -n '^once demo $S3' '$FAKE_LOG' | cut -d: -f1)" +check "stack 3 FAIL, stack 1 PASS, stack 2 FAIL" [ "$(jq -r 'select(.result=="verdict") | "\(.stack)=\(.verdict)"' "$AIEN_STATE/train.jsonl" | paste -sd,)" = "3=FAIL,1=PASS,2=FAIL" ] +check "culprit: PR 12 commented with the receipt link of stack 2" grep -q "issues/12/comments -f body=Merge train: stack 2 .*tested sha $S2) FAILED.*stack 1 ($S1) passed.*aien-receipts/blob/main/demo/$S2/bundle.json" "$FAKE_LOG" +check "culprit: label removed, PR not closed" bash -c "grep -q '^gh api -X DELETE repos/$S/issues/12/labels/ready-to-merge' '$FAKE_LOG' && ! grep -q 'pulls/12 -f state' '$FAKE_LOG'" +check "journal: culprit line" [ "$(jl '.result=="culprit" and .pr=="12" and .stack=="2"')" = 1 ] +check "main landed by a merge commit whose second parent is the exact tested stack 1 sha" [ "$(/usr/bin/git --git-dir="$ORIGIN" rev-parse main^2)" = "$S1" ] +check "merged tree equals the tested tree" [ "$(/usr/bin/git --git-dir="$ORIGIN" rev-parse "main^{tree}")" = "$(/usr/bin/git --git-dir="$ORIGIN" rev-parse "$S1^{tree}")" ] +check "tested sha ends with the crumb recompile commit" [ "$(/usr/bin/git --git-dir="$ORIGIN" log -1 --format=%s main^2)" = "train: crumb recompile (crumb tool override:$T/bin/crumb)" ] +check "below it, the merge of PR 11" [ "$(/usr/bin/git --git-dir="$ORIGIN" log -1 --format=%s main^2^)" = "Merge pull request #11: PR 11" ] +check "stack 1 contains PR 11 and nothing else" bash -c "origin_has main a.txt && ! origin_has main BAD && ! origin_has main c.txt && ! origin_has main .github/workflows/x.yml" +/usr/bin/git clone -q "$ORIGIN" "$T/chk" 2>/dev/null && check "crumbs in the merged sha verify with the pinned tool" bash -c "cd '$T/chk' && '$T/bin/crumb' verify ." +rm -rf "$T/chk" +check "stack 1 bundle published to receipts (digest of the local bundle)" [ "$(/usr/bin/git --git-dir="$T/receipts.git" show "main:demo/$S1/bundle.json" | sha256sum | cut -d' ' -f1)" = "$(sha256sum "$AIEN_STATE/bundles/demo/$S1/bundle.json" | cut -d' ' -f1)" ] +check "stack 2 FAIL bundle published too (the receipt the culprit comment links)" remote_has "$S2" +rpush=$(grep -n "^push -C $AIEN_RECEIPTS " "$FAKE_LOG" | head -1 | cut -d: -f1); mpush=$(grep -n "^gh pr merge 900 -R $S" "$FAKE_LOG" | head -1 | cut -d: -f1) +check "receipts were pushed before the train PR was merged" [ -n "$rpush" ] && [ -n "$mpush" ] && [ "$rpush" -lt "$mpush" ] +check "no push to main at all; the merge call pins the tested head (--match-head-commit)" bash -c "! grep -q '^push .*refs/heads/main' '$FAKE_LOG' && grep -q \"^gh pr merge 900 -R $S --merge --match-head-commit $S1 \" '$FAKE_LOG'" +check "train pull request opened for the hosted check and merged by the train" bash -c "grep -q 'gh api -X POST repos/$S/pulls -f title=train: demo stack' '$FAKE_LOG'" +check "train branch removed after the merge" bash -c "! /usr/bin/git --git-dir='$ORIGIN' rev-parse -q --verify refs/heads/train/demo >/dev/null" +check "journal: merged line names the PRs and the published digest" [ "$(jl '.result=="merged" and .prs=="11" and .stack=="1" and (.digest|length)==64')" = 1 ] +check "quiet flag was checked before every worker run" [ "$(grep -c '^quietlock check' "$FAKE_LOG")" -ge 3 ] + +echo "== cycle 2: freshness at merge time (label removed after stacking)" +: > "$FAKE_LOG" +PR[19]=$(pr 19 d.txt d) +pulls "13:${PR[13]}:false:$L:c.txt" "19:${PR[19]}:false:$L:d.txt" +ghset "repos/$S/pulls/19" "{\"number\":19,\"draft\":false,\"state\":\"open\",\"head\":{\"sha\":\"${PR[19]}\"},\"labels\":[]}" +bash "$TRAIN" cycle > "$T/c2" 2>&1 +check "stack 2 passed, then PR 19 found stale under the lock" [ "$(jl '.result=="stale" and .pr=="19" and (.reason|test("label"))')" = 1 ] +check "prefix shortened to stack 1 and that stack was tested before merging" bash -c "[ \"$(jl '.result=="shortened" and .stack=="2"')\" = 1 ] && [ \"$(jq -r 'select(.result=="verdict") | .stack' "$AIEN_STATE/train.jsonl" | tail -n 2 | paste -sd,)\" = '2,1' ]" +check "main now holds PR 13 and not PR 19" bash -c "origin_has main c.txt && ! origin_has main d.txt" +check "stale PR kept its label (no removal, no comment)" bash -c "! grep -q 'issues/19' '$FAKE_LOG'" + +echo "== cycle 3: lock contention with pipeline.sh merge" +: > "$FAKE_LOG" +pulls "19:${PR[19]}:false:$L:d.txt" +before=$(origin_main) +exec 8>>"$AIEN_STATE/pipeline.lock"; flock 8 +bash "$TRAIN" cycle > "$T/c3" 2>&1 +flock -u 8; exec 8>&- +check "lock held: refused, nothing pushed to main" bash -c "[ \"$(jl '.result=="refused" and (.reason|test("pipeline lock busy"))')\" = 1 ] && [ \"$(origin_main)\" = '$before' ]" +check "lock held: the stack was still tested, nothing published (publish needs the same lock)" bash -c "grep -q '^once demo ' '$FAKE_LOG' && ! remote_has \$(jq -r 'select(.result==\"running\") | .sha' '$AIEN_STATE/train.jsonl' | tail -n 1)" +bash "$TRAIN" cycle > "$T/c3b" 2>&1 +check "lock released: merged" bash -c "[ \"$(jl '.result=="merged" and .prs=="19"')\" = 1 ] && origin_has main d.txt" + +echo "== cycle 4: main itself fails, so nobody is blamed" +: > "$FAKE_LOG" +(cd "$SEED" && /usr/bin/git checkout -q main && /usr/bin/git pull -q origin main && echo x > MAINBAD && /usr/bin/git add -A && /usr/bin/git commit -q -m mainbad && /usr/bin/git push -q origin main) +PR[20]=$(pr 20 i.txt i) +pulls "20:${PR[20]}:false:$L:i.txt" +before=$(origin_main) +bash "$TRAIN" cycle > "$T/c4" 2>&1 +check "stack 1 FAIL, then main tested and FAIL" [ "$(jq -r 'select(.result=="verdict") | "\(.stack)=\(.verdict)"' "$AIEN_STATE/train.jsonl" | tail -n 2 | paste -sd,)" = "1=FAIL,0=FAIL" ] +check "no culprit, label kept, main untouched" bash -c "[ \"$(jl '.result=="refused" and (.reason|test("main itself fails"))')\" = 1 ] && ! grep -q 'issues/20' '$FAKE_LOG' && [ \"$(origin_main)\" = '$before' ]" + +echo "== cycle 5: quiet flag held" +: > "$FAKE_LOG"; touch "$T_QUIET" +bash "$TRAIN" cycle > "$T/c5" 2>&1 +check "quiet flag held: no worker run, refusal journaled" bash -c "! grep -q '^once ' '$FAKE_LOG' && [ \"$(jl '.result=="refused" and (.reason|test("quiet flag held"))')\" = 1 ]" +rm -f "$T_QUIET" + +echo "== cycle 6: main moves after the stack was built: abort, no merge, next cycle restacks" +: > "$FAKE_LOG" +(cd "$SEED" && /usr/bin/git checkout -q main && /usr/bin/git rm -q MAINBAD && /usr/bin/git commit -q -m fixmain && /usr/bin/git push -q origin main) +T_RACE=$SEED bash "$TRAIN" cycle > "$T/c6" 2>&1 +check "main moved: cycle aborted, restack named" [ "$(jl '.result=="aborted" and (.reason|test("main moved.*restacks"))')" = 1 ] +check "aborted cycle never called the merge API and never pushed to main" bash -c "! grep -q '^gh pr merge 900' '$FAKE_LOG' && ! grep -q '^push .*refs/heads/main' '$FAKE_LOG'" +check "main is the racer's commit, untouched by the train" bash -c "origin_has main RACED && ! origin_has main i.txt" +check "the aborted stack's bundle was still published (receipt binding before any merge)" bash -c "s=\$(jq -r 'select(.result==\"aborted\") | .sha' '$AIEN_STATE/train.jsonl' | tail -n 1); remote_has \"\$s\"" +: > "$FAKE_LOG" +bash "$TRAIN" cycle > "$T/c6b" 2>&1 +check "next cycle restacked on the new main and landed PR 20 by merge commit" bash -c "[ \"$(jl '.result=="merged" and .prs=="20"')\" = 1 ] && origin_has main i.txt && origin_has main RACED && grep -q '^gh pr merge 900' '$FAKE_LOG'" +check "restacked merge: second parent is the new tested sha, trees equal" bash -c "g=/usr/bin/git; o='$ORIGIN'; [ \"\$(\$g --git-dir=\$o rev-parse 'main^{tree}')\" = \"\$(\$g --git-dir=\$o rev-parse 'main^2^{tree}')\" ] && [ \"\$(\$g --git-dir=\$o rev-parse main^1)\" != \"\$(\$g --git-dir=\$o rev-parse main^2)\" ]" + +echo "== cycle 7: train PR head is not the tested sha: refuse" +: > "$FAKE_LOG" +(cd "$SEED" && /usr/bin/git checkout -q main && /usr/bin/git pull -q origin main) +PR[21]=$(pr 21 j.txt j) +pulls "21:${PR[21]}:false:$L:j.txt" +before=$(origin_main) +FAKE_TRAIN_HEAD=$(printf '%040x' 777) bash "$TRAIN" cycle > "$T/c7" 2>&1 +check "head differs from tested sha: refused, merge API never called, main untouched" bash -c "[ \"$(jl '.result=="refused" and (.reason|test("not the tested sha"))')\" = 1 ] && ! grep -q '^gh pr merge 900' '$FAKE_LOG' && [ \"$(origin_main)\" = '$before' ]" +: > "$FAKE_LOG" +bash "$TRAIN" cycle > "$T/c7b" 2>&1 +check "same queue with a matching head lands" bash -c "[ \"$(jl '.result=="merged" and .prs=="21"')\" = 1 ] && origin_has main j.txt" +: > "$FAKE_LOG" +(cd "$SEED" && /usr/bin/git checkout -q main && /usr/bin/git pull -q origin main) +PR[22]=$(pr 22 k.txt k) +pulls "22:${PR[22]}:false:$L:k.txt" +before=$(origin_main) +FAKE_PUT_FAIL=1 bash "$TRAIN" cycle > "$T/c7c" 2>&1 +check "GitHub refusing the merge (moved head via sha=) is journaled failed, main untouched" bash -c "[ \"$(jl '.result=="failed" and (.reason|test("merge of train pull request refused"))')\" = 1 ] && [ \"$(origin_main)\" = '$before' ]" + +echo "== listing is paginated" +check "open-PR listing uses --paginate" grep -q 'pulls?state=open&per_page=100 --paginate' "$FAKE_LOG" + +echo "== committer identity is checked at startup" +rc=0; env -u GIT_COMMITTER_NAME -u GIT_COMMITTER_EMAIL -u GIT_AUTHOR_NAME -u GIT_AUTHOR_EMAIL -u EMAIL bash "$TRAIN" cycle --dry-run > "$T/id.out" 2> "$T/id.err" || rc=$? +check "no git identity: exit 2 with a plain message, no cycle started" bash -c "[ $rc = 2 ] && grep -q 'no committer identity' '$T/id.err' && [ ! -s '$T/id.out' ]" + +echo "== one train per repository" +: > "$FAKE_LOG" +exec 6>>"$AIEN_STATE/train.demo.lock"; flock 6 +bash "$TRAIN" cycle > "$T/lock.out" 2>&1 +flock -u 6; exec 6>&- +check "second cycle on the same repository skips: journaled, no worker, no push, no GitHub write" bash -c "[ \"$(jl '.result=="skipped" and (.reason|test("another train cycle"))')\" = 1 ] && ! grep -qE '^(once|push) |^gh (api -X|pr merge)' '$FAKE_LOG'" + +echo "== crumb recompile never writes into a trust-surface directory" +: > "$FAKE_LOG" +before=$(origin_main) +FAKE_CRUMB_TRUST=1 bash "$TRAIN" cycle > "$T/trust.out" 2>&1 +check "recompile touching .aien/.crumb: stack skipped, journaled, no worker, main untouched" bash -c "[ \"$(jl '.result=="refused" and (.reason|test("trust-surface directory"))')\" = 1 ] && ! grep -q '^once ' '$FAKE_LOG' && [ \"$(origin_main)\" = '$before' ]" +FAKE_CRUMB_JUNK=1 bash "$TRAIN" cycle > "$T/junk.out" 2>&1 +check "compile changing a non-.crumb file: stack skipped" [ "$(jl '.result=="refused" and (.reason|test("something other than .crumb"))')" -ge 1 ] + +echo "== crumb pin comes from the target repository, fail closed" +cat > "$T/crumb-min.c" <<'EOC' +#include +#include +int main(int c, char **v) { + char b[16] = {0}; + FILE *f; + if (c < 2) return 9; + if (!strcmp(v[1], "compile")) { f = fopen(".crumb", "w"); if (!f) return 1; fputs("c-tool\n", f); fclose(f); return 0; } + if (!strcmp(v[1], "verify")) { f = fopen(".crumb", "r"); if (!f) return 1; if (!fgets(b, 16, f)) return 1; fclose(f); return strcmp(b, "c-tool\n") ? 1 : 0; } + return 9; +} +EOC +/usr/bin/git init -q -b main "$T/archseed" +mkdir -p "$T/archseed/tools/crumb"; cp "$T/crumb-min.c" "$T/archseed/tools/crumb/crumb.c" +(cd "$T/archseed" && /usr/bin/git add -A && /usr/bin/git commit -q -m A && echo "/* b */" >> tools/crumb/crumb.c && /usr/bin/git commit -q -am B) +PIN_A=$(/usr/bin/git -C "$T/archseed" rev-parse HEAD~1); PIN_B=$(/usr/bin/git -C "$T/archseed" rev-parse HEAD) +/usr/bin/git clone -q --bare "$T/archseed" "$T/arch.git" +(cd "$SEED" && /usr/bin/git checkout -q main && /usr/bin/git pull -q origin main && mkdir -p .github/workflows \ + && printf 'steps:\n - name: Checkout the pinned crumb tool source (aien-architecture @ %s)\n uses: actions/checkout@v4\n with:\n repository: x/aien-architecture\n ref: %s\n' "$PIN_A" "$PIN_A" > .github/workflows/aien-verification.yml \ + && /usr/bin/git add -A && /usr/bin/git commit -q -m workflow && /usr/bin/git push -q origin main) +nopin() { env -u AIEN_CRUMB_TOOL AIEN_ARCH_URL="$T/arch.git" bash "$TRAIN" cycle --dry-run 2>&1; } +check "pin read from the repository's own aien-verification.yml" grep -q "crumb tool $PIN_A)" <<< "$(nopin)" +(cd "$SEED" && printf '%s\n' "$PIN_B" > crumb.lock && /usr/bin/git add -A && /usr/bin/git commit -q -m lock && /usr/bin/git push -q origin main) +check "crumb.lock wins where it exists" grep -q "crumb tool $PIN_B)" <<< "$(nopin)" +(cd "$SEED" && printf 'nothex\n' > crumb.lock && /usr/bin/git commit -q -am badlock && /usr/bin/git push -q origin main) +check "malformed crumb.lock fails closed" grep -q "crumb.lock does not hold a 40-hex commit" <<< "$(nopin)" +(cd "$SEED" && /usr/bin/git rm -q crumb.lock .github/workflows/aien-verification.yml && /usr/bin/git commit -q -m nopin && /usr/bin/git push -q origin main) +out=$(nopin) +check "neither crumb.lock nor workflow: fail closed, no default pin" bash -c "grep -q 'no crumb pin' <<< \"\$1\" && ! grep -q 'dry-run' <<< \"\$1\"" _ "$out" +check "train.sh carries no default pin of any repository" bash -c "! grep -q '94fffbcf' '$TRAIN'" + +echo "== a PR cannot choose the crumb tool" +(cd "$SEED" && /usr/bin/git checkout -q main && /usr/bin/git pull -q origin main && mkdir -p .github/workflows \ + && printf 'steps:\n - name: Checkout the pinned crumb tool source (aien-architecture @ %s)\n with:\n ref: %s\n' "$PIN_A" "$PIN_A" > .github/workflows/aien-verification.yml \ + && /usr/bin/git add -A && /usr/bin/git commit -q -m basepin && /usr/bin/git push -q origin main) +PR[23]=$(pr 23 crumb.lock "$PIN_B") +PR[24]=$(pr 24 m.txt m) +pulls "23:${PR[23]}:false:$L:crumb.lock" "24:${PR[24]}:false:$L:m.txt" +: > "$FAKE_LOG"; before=$(origin_main) +out=$(env -u AIEN_CRUMB_TOOL AIEN_ARCH_URL="$T/arch.git" bash "$TRAIN" cycle --dry-run 2>&1) +check "PR changing crumb.lock is BLOCKED_OPERATOR and left out of the stack" bash -c "[ \"$(jl '.pr=="23" and .result=="excluded" and (.reason|test("BLOCKED_OPERATOR: touches crumb.lock"))')\" = 1 ] && [ \"$(jl '.pr=="23" and .result=="queued"')\" = 0 ]" +check "the stack is built with the base pin (A), not the PR's pin (B)" bash -c "grep -q 'crumb tool $PIN_A)' <<< \"\$1\" && ! grep -q 'crumb tool $PIN_B' <<< \"\$1\"" _ "$out" +check "pin is read from the base ref, never from the stack" bash -c "grep -q 'show \"\\\$MAIN:crumb.lock\"' '$TRAIN' && grep -q 'show \"\\\$MAIN:.github/workflows/aien-verification.yml\"' '$TRAIN' && ! grep -q 'HEAD:crumb.lock' '$TRAIN'" + +echo "== the per-repository lock is not inherited by children" +: > "$FAKE_LOG" +pulls "24:${PR[24]}:false:$L:m.txt" +bash "$TRAIN" cycle > "$T/fd.out" 2>&1 +check "the worker ran with fd 8 closed" bash -c "grep -q '^worker-fd8 closed' '$FAKE_LOG' && ! grep -q '^worker-fd8 open' '$FAKE_LOG'" + +echo "== secrets and protection" +check "train.sh never names the signing key file" bash -c "! grep -q 'verify\\.key' '$TRAIN'" +check "train.sh never touches branch protection or uses --admin" bash -c "! grep -qE 'PUT .*protection|DELETE .*protection|--admin' '$TRAIN'" + +echo +echo "train_test: $pass passed, $fail failed" +[[ $fail == 0 ]] diff --git a/tools/aien-local-ci/train.sh b/tools/aien-local-ci/train.sh new file mode 100755 index 00000000..e902feca --- /dev/null +++ b/tools/aien-local-ci/train.sh @@ -0,0 +1,605 @@ +#!/usr/bin/env bash +# train.sh: the Spark merge train (Drake, 2026-10-16). Tests have a known duration T, so pull requests are batched +# on a timed rhythm and verified as stacked prefixes instead of one at a time. +# +# train.sh cadence [--repos a,b] measured full-gate duration T per repository, from real bundles +# train.sh cycle [--repos a,b] [--dry-run] one train cycle per repository (dry-run: print the plan, push nothing) +# train.sh loop [--repos a,b] [--every SECS] cycles forever, one per repository every T (measured, or --every) +# +# One cycle for a repository: +# 1. queue = open pull requests labeled exactly ready-to-merge, base main, not draft, oldest number first. +# Excluded (label kept, one journal line each): BLOCKED_OPERATOR paths (.aien/, tests/gates/, +# .github/workflows/, .forgejo/, tools/aien-test/), head not equal to refs/pull/N/head, merge conflict with the +# stack so far, queue longer than AIEN_MAX_STACK. +# 2. stack k = origin/main + PR1..PRk merged in order (merge commits, as `gh pr merge --merge` makes them), then one +# crumb recompile commit made with the repository's pinned crumb tool (crumb.lock in its tree, else the +# "pinned crumb tool" ref of its own aien-verification.yml, else fail closed). Stack 0 is main itself, untouched. +# 3. The worker (aien-local-ci once) verifies stack shas one at a time (the worker serves heads sequentially; the +# gate pools are per head): first stack N; on FAIL a bisection finds the longest passing prefix p and the first +# failing prefix p+1, whose last pull request is the culprit: a comment with the receipt link, label removed, not +# closed. When stack 1 fails, main itself is tested before blaming PR1. +# 4. Merge of stack p (p >= 1): its bundle is published to aien-receipts (pipeline.sh publish, checked by digest at +# origin), the required checks of main are green on that exact sha (the stack is pushed as branch train/ +# with one open train pull request so the hosted check runs), then under the pipeline lock: every PR in the prefix +# still open, labeled, not draft, head unchanged; origin/main still the stack base (else the cycle aborts and +# the next one restacks); the train PR head must equal the tested sha; then the train PR is merged with a merge +# commit (`--match-head-commit`), so the merged tree equals the tested tree and is checked after landing. No direct push +# to main. If a PR went stale the prefix ends +# before it and the longest tested passing prefix inside it is taken (re-tested when it was never run). +# +# It never reads the signing key, never signs, never changes branch protection, never pushes to main, never closes a stacked pull request. +# Every action and refusal is one JSON line in $STATE/train.jsonl. Exit 0 when the cycle ran (refusals included), +# 2 on usage or configuration error. Spark etiquette: `quietlock check` must pass before every worker run. +set -euo pipefail + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +STATE=${AIEN_STATE:-$HOME/.local/state/aien-local-ci} +CLONES=${AIEN_CLONES:-$HOME/workspace/pipeline/clones} +RECEIPTS=${AIEN_RECEIPTS:-$HOME/workspace/pipeline/aien-receipts} +RECEIPTS_BRANCH=${AIEN_RECEIPTS_BRANCH:-main} +BIN=${AIEN_TEST_BIN:-$HOME/workspace/pipeline/target-sc/release/aien-test} +OWNER=${AIEN_GH_OWNER:-aien-dev} +REPOS=${AIEN_REPOS:-aien-sovereign-core,omega,aienos,physics,aien-protocols,aegis-runtime,spark-rsi,aien-architecture,benchmarks} +GH=${GH:-gh} +GIT=${GIT:-git} +PIPELINE=${AIEN_PIPELINE:-$HERE/pipeline.sh} +LOCAL_CI=${AIEN_LOCAL_CI:-$HOME/.local/bin/aien-local-ci} +QUIETLOCK=${QUIETLOCK:-quietlock} +TRAIN=${AIEN_TRAIN_CLONES:-$STATE/train-clones} +ARCH_URL=${AIEN_ARCH_URL:-https://github.com/aien-spark/aien-architecture} +CRUMB_TOOL=${AIEN_CRUMB_TOOL:-} # set: use this crumb binary for every repository (tests); unset: build the pin +MAX_STACK=${AIEN_MAX_STACK:-20} +CRUMB_PIN=unresolved CRUMB_BIN="" # set by crumb_tool for the stack being built +LOCK_WAIT=${AIEN_LOCK_WAIT:-900} # seconds to wait for the pipeline lock at merge time +CHECK_WAIT=${AIEN_CHECK_WAIT:-3600} # seconds to wait for the required hosted checks on the stack sha +QUIET_WAIT=${AIEN_QUIET_WAIT:-7200} # seconds to wait for the quiet flag before a worker run +POLL=${AIEN_TRAIN_POLL:-30} # seconds between polls (quiet flag, hosted checks) +RETRY_SLEEP=${AIEN_RETRY_SLEEP:-5} +MERGE_LABEL="ready-to-merge" +BLOCKED_OPERATOR_PREFIXES=("crumb.lock" ".aien/" "tests/gates/" ".github/workflows/" ".forgejo/" "tools/aien-test/") + +usage() { echo "usage: train.sh cadence|cycle|loop [--repos a,b] [--dry-run] [--every SECS]" >&2; exit 2; } +die() { echo "train.sh: $*" >&2; exit 2; } + +[[ $# -ge 1 ]] || usage +cmd=$1; shift +case "$cmd" in cadence|cycle|loop) ;; *) usage ;; esac +DRY=0 EVERY="" +while [[ $# -gt 0 ]]; do + case "$1" in + --repos) [[ $# -ge 2 ]] || usage; REPOS=$2; shift 2 ;; + --dry-run) DRY=1; shift ;; + --every) [[ $# -ge 2 && $2 =~ ^[0-9]+$ ]] || usage; EVERY=$2; shift 2 ;; + *) usage ;; + esac +done +IFS=, read -r -a repo_list <<< "$REPOS" +[[ ${#repo_list[@]} -gt 0 ]] || die "no repositories named" +for r in "${repo_list[@]}"; do + [[ $r =~ ^[A-Za-z0-9._-]+$ && $r != . && $r != .. ]] || die "bad repository name '$r'" +done +command -v jq >/dev/null || die "jq not found" +command -v "$GIT" >/dev/null || die "git ($GIT) not found" +if [[ $cmd != cadence ]]; then + # every merge the train makes needs a committer; without one git fails and it would be misread as a merge conflict + "$GIT" -c user.useConfigOnly=true var GIT_COMMITTER_IDENT >/dev/null 2>&1 \ + || die "git has no committer identity: set user.name and user.email (the train makes merge commits and would misreport every merge as a conflict)" +fi +mkdir -p "$STATE" +JOURNAL=$STATE/train.jsonl +if [[ $cmd != cadence ]]; then + command -v flock >/dev/null || die "flock not found" + command -v sha256sum >/dev/null || die "sha256sum not found" + command -v "$GH" >/dev/null || die "gh ($GH) not found" + [[ -d $CLONES ]] || die "clones directory $CLONES missing" + [[ -f $PIPELINE ]] || die "pipeline.sh not found at $PIPELINE" + if [[ $DRY == 0 ]]; then + [[ -x $BIN ]] || die "aien-test binary $BIN missing or not executable" + [[ -d $RECEIPTS/.git ]] || die "receipts clone $RECEIPTS is not a git clone" + [[ -x $LOCAL_CI ]] || die "aien-local-ci ($LOCAL_CI) missing or not executable" + command -v "$QUIETLOCK" >/dev/null || die "quietlock ($QUIETLOCK) not found" + fi + mkdir -p "$TRAIN" "$STATE/train-logs" +fi +WORK=$(mktemp -d "$STATE/.train.XXXXXX") +trap 'rm -rf "$WORK"' EXIT + +# journal key=value ...: one JSON line (built by jq), a short line on stdout. +journal() { + local args=(--arg utc "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg action train) kv + for kv in "$@"; do args+=(--arg "${kv%%=*}" "${kv#*=}"); done + jq -nc "${args[@]}" '$ARGS.named' >> "$JOURNAL" + echo "$*" +} +say() { echo "train: $*"; } +digest() { sha256sum "$1" | cut -d' ' -f1; } + +# ---------------------------------------------------------------- cadence: T per repository from real bundles +# A qualifying run: plan.blocked null, verdict PASS or FAIL, both timestamps present. T = the longest such run. +cadence_of() { # REPO -> "runs max median last" in seconds, or "0 0 0 0" + local f durs=() s e + for f in "$STATE/bundles/$1"/*/bundle.json; do + [[ -f $f ]] || continue + s="" e="" + read -r s e < <(jq -r 'select(.plan.blocked == null and (.verdict == "PASS" or .verdict == "FAIL")) + | "\(.started_utc // "") \(.finished_utc // "")"' "$f" 2>/dev/null) || true + [[ -n ${s:-} && -n ${e:-} ]] || continue + s=$(date -u -d "$s" +%s 2>/dev/null) || continue + e=$(date -u -d "$e" +%s 2>/dev/null) || continue + [[ $e -ge $s ]] && durs+=("$s $((e - s))") + done + [[ ${#durs[@]} -gt 0 ]] || { echo "0 0 0 0"; return 0; } + local n last mx med sorted + n=${#durs[@]} + last=$(printf '%s\n' "${durs[@]}" | sort -n | tail -n 1 | cut -d" " -f2) + sorted=$(printf '%s\n' "${durs[@]}" | cut -d" " -f2 | sort -n) + mx=$(tail -n 1 <<< "$sorted") + med=$(sed -n "$(( (n + 1) / 2 ))p" <<< "$sorted") + echo "$n $mx $med $last" +} +do_cadence() { + local repo n mx med last + printf '%-22s %5s %8s %8s %8s %8s\n' repository runs max median last T + for repo in "${repo_list[@]}"; do + read -r n mx med last < <(cadence_of "$repo") + if [[ $n == 0 ]]; then printf '%-22s %5s %8s %8s %8s %8s\n' "$repo" 0 - - - "unknown"; continue; fi + printf '%-22s %5s %7ss %7ss %7ss %7ss\n' "$repo" "$n" "$mx" "$med" "$last" "$mx" + done +} + +# ---------------------------------------------------------------- GitHub helpers +declare -A SLUGS=() +slug() { + local s + if [[ -z ${SLUGS[$1]:-} ]]; then + s=$("$GH" api "repos/$OWNER/$1" --jq .full_name 2>/dev/null) || return 1 + [[ $s =~ ^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$ ]] || return 1 + SLUGS[$1]=$s + fi + echo "${SLUGS[$1]}" +} +keys() { + "$GIT" -C "$1" show "$2:.aien/verify.pub" 2>/dev/null | sed 's/#.*//' | tr -d ' \t\r' | tr 'A-F' 'a-f' \ + | grep -E '^[0-9a-f]{64}$' || true +} +verify() { # FILE REPO SHA KEYS [REQUIRE] -> "best codes" + local file=$1 repo=$2 sha=$3 keylist=$4 require=${5:-} key rc codes="" best="" extra=() + [[ -n $require ]] && extra=(--require "$require") + while IFS= read -r key; do + [[ -n $key ]] || continue + rc=0 + "$BIN" verify-bundle "$file" --repo "github.com/$OWNER/$repo" --commit "$sha" --pubkey "$key" "${extra[@]}" \ + >/dev/null 2>&1 || rc=$? + codes+="${codes:+,}$rc" + done <<< "$keylist" + for rc in 0 1 2 3; do [[ ,$codes, == *",$rc,"* ]] && { best=$rc; break; }; done + echo "${best:-${codes%%,*}} ${codes:-none}" +} +verdict_name() { case "$1" in 0) echo PASS ;; 1) echo FAIL ;; 2) echo NOT_RUN ;; 3) echo REJECTED ;; *) echo "EXIT_$1" ;; esac; } +published() { # REPO SHA -> digest at receipts origin, or empty (caller fetched) + local tmp=$WORK/published + if "$GIT" -C "$RECEIPTS" show "origin/$RECEIPTS_BRANCH:$1/$2/bundle.json" > "$tmp" 2>/dev/null; then digest "$tmp"; else echo ""; fi +} +receipt_url() { echo "https://github.com/$OWNER/aien-receipts/blob/$RECEIPTS_BRANCH/$1/$2/bundle.json"; } + +# checks_state SLUG SHA: 0 every required context of main is success on SHA, 1 some are missing or pending, +# 2 some failed, 3 cannot tell (API or no required checks). Mirrors pipeline.sh merge_one. +checks_state() { + local s=$1 sha=$2 ctxs checks statuses ctx found bad + ctxs=$("$GH" api "repos/$s/branches/main/protection/required_status_checks" --jq '.contexts[]' 2>/dev/null) || { CHECK_NOTE="cannot read required status checks of main"; return 3; } + [[ -n $ctxs ]] || { CHECK_NOTE="main has no required status checks"; return 3; } + checks=$("$GH" api "repos/$s/commits/$sha/check-runs?per_page=100" --jq '.check_runs[] | [.name, (.conclusion // .status)] | @tsv' 2>/dev/null) || { CHECK_NOTE="cannot read check runs"; return 3; } + statuses=$("$GH" api "repos/$s/commits/$sha/status?per_page=100" --jq '.statuses[] | [.context, .state] | @tsv' 2>/dev/null) || { CHECK_NOTE="cannot read commit statuses"; return 3; } + local pending=0 + while IFS= read -r ctx; do + [[ -n $ctx ]] || continue + found=$(printf '%s\n%s\n' "$checks" "$statuses" | C="$ctx" awk -F'\t' '$1 == ENVIRON["C"] {print $2}') + if [[ -z $found ]]; then CHECK_NOTE="required context '$ctx' missing"; pending=1; continue; fi + bad=$(grep -vx success <<< "$found" | head -n 1 || true) + [[ -z $bad ]] && continue + case $bad in + queued|in_progress|pending|waiting|requested|null) CHECK_NOTE="required context '$ctx' is $bad"; pending=1 ;; + *) CHECK_NOTE="required context '$ctx' is $bad"; return 2 ;; + esac + done <<< "$ctxs" + [[ $pending == 0 ]] || return 1 + CHECK_NOTE="required checks green"; return 0 +} + +# ---------------------------------------------------------------- crumb tool for the stack (pinned per repository) +# crumb_pin_of_tree: sets TREE_PIN to the pinned crumb tool commit as the BASE ($MAIN) has it, never the stack's: a PR must not choose the tool the Spark builds and runs. crumb.lock where the repository has one, +# else the "pinned crumb tool source" ref of its own .github/workflows/aien-verification.yml. Neither: fail closed. +crumb_pin_of_tree() { + local pin wf + if "$GIT" -C "$TC" cat-file -e "$MAIN:crumb.lock" 2>/dev/null; then + pin=$("$GIT" -C "$TC" show "$MAIN:crumb.lock" | tr -d " \t\r\n") + [[ $pin =~ ^[0-9a-f]{40}$ ]] || { RECOMPILE_NOTE="crumb.lock does not hold a 40-hex commit"; return 1; } + TREE_PIN=$pin; return 0 + fi + wf=$("$GIT" -C "$TC" show "$MAIN:.github/workflows/aien-verification.yml" 2>/dev/null) || { RECOMPILE_NOTE="no crumb pin: no crumb.lock and no .github/workflows/aien-verification.yml"; return 1; } + pin=$(awk 'f>0{f--} /pinned crumb tool/{f=8} f>0 && $1=="ref:" && $2 ~ /^[0-9a-f]{40}$/ {print $2; exit}' <<< "$wf") + [[ -n $pin ]] || { RECOMPILE_NOTE="no crumb pin: no pinned crumb tool ref in aien-verification.yml"; return 1; } + TREE_PIN=$pin +} + +crumb_tool() { # sets CRUMB_BIN (the crumb binary for the tree at HEAD of $TC) and CRUMB_PIN + local pin built src + if [[ -n $CRUMB_TOOL ]]; then CRUMB_PIN="override:$CRUMB_TOOL"; CRUMB_BIN=$CRUMB_TOOL; return 0; fi + crumb_pin_of_tree || { CRUMB_PIN=none; return 1; } + pin=$TREE_PIN + CRUMB_PIN=$pin + built=$STATE/train-crumb/$pin/crumb + if [[ ! -x $built ]]; then + src=$TRAIN/aien-architecture.git + [[ -d $src ]] || "$GIT" clone -q --bare --filter=blob:none "$ARCH_URL" "$src" || return 1 + "$GIT" --git-dir="$src" cat-file -e "$pin^{commit}" 2>/dev/null || "$GIT" --git-dir="$src" fetch -q origin "$pin" || return 1 + mkdir -p "$(dirname "$built")" + "$GIT" --git-dir="$src" show "$pin:tools/crumb/crumb.c" > "$WORK/crumb.c" || return 1 + cc -std=c11 -O2 -Wall -Wextra -Werror -o "$WORK/crumb" "$WORK/crumb.c" || return 1 + mv "$WORK/crumb" "$built" + fi + CRUMB_BIN=$built +} + +# ---------------------------------------------------------------- stacks +# Globals per repository cycle: TC (train clone), MAIN, QN[] QS[] QT[] (queue: number, head sha, title), N, +# STACK[k] (sha of stack k, built lazily), RESULT[sha] (PASS|FAIL|). +declare -a QN QS QT STACK +declare -A RESULT +train_clone() { # REPO -> sets TC, MAIN; the train's own scratch clone of the trusted clone's origin + local repo=$1 url + TC=$TRAIN/$repo + url=$("$GIT" -C "$CLONES/$repo" remote get-url origin) || return 1 + if [[ ! -d $TC/.git ]]; then "$GIT" clone -q --no-checkout "$url" "$TC" || return 1; fi + "$GIT" -C "$TC" remote set-url origin "$url" + "$GIT" -C "$TC" fetch -q --prune origin || return 1 + MAIN=$("$GIT" -C "$TC" rev-parse --verify -q origin/main) || return 1 +} +reset_to() { "$GIT" -C "$TC" checkout -q --detach "$1" && "$GIT" -C "$TC" reset -q --hard && "$GIT" -C "$TC" clean -fdxq; } +merge_pr() { # i: merge queue entry i onto HEAD of $TC; 1 on conflict (aborted) + if ! "$GIT" -C "$TC" merge -q --no-ff --no-edit -m "Merge pull request #${QN[$1]}: ${QT[$1]}" "${QS[$1]}" >/dev/null 2>&1; then + "$GIT" -C "$TC" merge --abort >/dev/null 2>&1 || true; return 1 + fi +} +recompile() { # crumb recompile commit on HEAD of $TC with the pinned tool, then verify with the same tool + local changed + RECOMPILE_NOTE="" + crumb_tool || { RECOMPILE_NOTE=${RECOMPILE_NOTE:-cannot build the pinned crumb tool}; return 1; } + (cd "$TC" && "$CRUMB_BIN" compile . 8>&-) >/dev/null 2>&1 || { RECOMPILE_NOTE="crumb compile failed (tool $CRUMB_PIN)"; return 1; } + changed=$("$GIT" -C "$TC" ls-files -m -o --exclude-standard | grep -E '(^|/)\.crumb$' || true) + local other path pfx + other=$("$GIT" -C "$TC" status --porcelain | grep -vE '\.crumb$' || true) + [[ -z $other ]] || { RECOMPILE_NOTE="crumb compile changed something other than .crumb files: $(head -n 1 <<< "$other")"; return 1; } + while IFS= read -r path; do + [[ -n $path ]] || continue + for pfx in "${BLOCKED_OPERATOR_PREFIXES[@]}"; do + [[ $path == "$pfx"* ]] && { RECOMPILE_NOTE="crumb recompile would change $path inside a trust-surface directory ($pfx); stack skipped"; return 1; } + done + done <<< "$changed" + if [[ -n $changed ]]; then + printf '%s\n' "$changed" | "$GIT" -C "$TC" add --pathspec-from-file=- + "$GIT" -C "$TC" commit -q -m "train: crumb recompile (crumb tool $CRUMB_PIN)" + fi + (cd "$TC" && "$CRUMB_BIN" verify . 8>&-) >/dev/null 2>&1 || { RECOMPILE_NOTE="crumb verify failed after compile (tool $CRUMB_PIN)"; return 1; } +} +build_stack() { # k -> sets BUILT to the sha of stack k (0 = main), builds and caches it in STACK[k] + local k=$1 i + if [[ $k == 0 ]]; then BUILT=$MAIN; return 0; fi + if [[ -n ${STACK[$k]:-} ]]; then BUILT=${STACK[$k]}; return 0; fi + reset_to "$MAIN" || return 1 + for ((i = 1; i <= k; i++)); do merge_pr "$i" || { RECOMPILE_NOTE="PR #${QN[$i]} no longer merges"; return 1; }; done + recompile || return 1 + STACK[$k]=$("$GIT" -C "$TC" rev-parse HEAD) + BUILT=${STACK[$k]} +} + +# admit REPO SLUG: fill the queue from GitHub, excluding what may not ride. Sets N. +admit() { + local repo=$1 s=$2 prs num sha base draft labeled title files p hit fetched i + QN=() QS=() QT=() STACK=() RESULT=(); N=0 + prs=$("$GH" api "repos/$s/pulls?state=open&per_page=100" --paginate --jq \ + ".[] | [.number, .head.sha, .base.ref, .draft, ([.labels[].name] | index(\"$MERGE_LABEL\") != null), (.title | gsub(\"[\\t\\n\\r]\"; \" \"))] | @tsv" \ + | sort -n) || { journal repo="$repo" result=refused reason="cannot list pull requests"; return 1; } + reset_to "$MAIN" || return 1 + i=0 + while IFS=$'\t' read -r num sha base draft labeled title; do + [[ -n $num ]] || continue + [[ $labeled == true ]] || continue # not the train's: skipped silently, like pipeline.sh + [[ $sha =~ ^[0-9a-f]{40}$ ]] || { journal repo="$repo" pr="$num" result=excluded reason="bad head sha"; continue; } + [[ $base == main ]] || { journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="base is $base, not main"; continue; } + [[ $draft == false ]] || { journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="draft"; continue; } + if [[ $N -ge $MAX_STACK ]]; then journal repo="$repo" pr="$num" sha="$sha" result=deferred reason="stack full ($MAX_STACK)"; continue; fi + files=$("$GH" api "repos/$s/pulls/$num/files?per_page=100" --paginate --jq '.[] | .filename, (.previous_filename // empty)') \ + || { journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="cannot list changed files"; continue; } + hit="" + for p in "${BLOCKED_OPERATOR_PREFIXES[@]}"; do + hit=$(grep -m1 -E "^$(printf '%s' "$p" | sed 's/[.[\*^$]/\\&/g')" <<< "$files" || true) + [[ -z $hit ]] || break + done + if [[ -n $hit ]]; then journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="BLOCKED_OPERATOR: touches $hit"; continue; fi + if ! "$GIT" -C "$TC" fetch -q origin "refs/pull/$num/head" 2>/dev/null; then + journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="cannot fetch refs/pull/$num/head"; continue + fi + fetched=$("$GIT" -C "$TC" rev-parse FETCH_HEAD) + [[ $fetched == "$sha" ]] || { journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="head moved to $fetched"; continue; } + i=$((N + 1)); QN[$i]=$num; QS[$i]=$sha; QT[$i]=$title + if ! merge_pr "$i"; then + unset "QN[$i]" "QS[$i]" "QT[$i]" + journal repo="$repo" pr="$num" sha="$sha" result=excluded reason="merge conflict with main or an earlier stacked PR"; continue + fi + N=$i + journal repo="$repo" pr="$num" sha="$sha" result=queued reason="position $N" + done <<< "$prs" + return 0 +} + +# ---------------------------------------------------------------- running a stack on the Spark +wait_quiet() { + local waited=0 + while ! "$QUIETLOCK" check >/dev/null 2>&1; do + [[ $waited -lt $QUIET_WAIT ]] || return 1 + sleep "$POLL"; waited=$((waited + POLL)) + done +} +push_train_branch() { "$GIT" -C "$TC" push -q -f origin "$2:refs/heads/train/$1" >/dev/null 2>&1; } +run_stack() { # REPO k SHA -> sets RESULT[sha] to PASS|FAIL|; 0 when PASS or FAIL (a verdict), 1 otherwise + local repo=$1 k=$2 sha=$3 lfile v best keylist require + if [[ -n ${RESULT[$sha]:-} ]]; then [[ ${RESULT[$sha]} == PASS || ${RESULT[$sha]} == FAIL ]]; return; fi + if [[ $k != 0 ]] && ! push_train_branch "$repo" "$sha"; then + RESULT[$sha]=NOT_PUSHED; journal repo="$repo" stack="$k" sha="$sha" result=refused reason="cannot push train/$repo"; return 1 + fi + if ! wait_quiet; then + RESULT[$sha]=QUIET; journal repo="$repo" stack="$k" sha="$sha" result=refused reason="quiet flag held for ${QUIET_WAIT}s"; return 1 + fi + journal repo="$repo" stack="$k" sha="$sha" result=running reason="worker once" + "$LOCAL_CI" once "$repo" "$sha" 8>&- > "$STATE/train-logs/$repo.$sha.log" 2>&1 || true + lfile=$STATE/bundles/$repo/$sha/bundle.json + if [[ ! -f $lfile ]]; then + RESULT[$sha]=NO_BUNDLE; journal repo="$repo" stack="$k" sha="$sha" result=refused reason="worker left no bundle"; return 1 + fi + keylist=$(keys "$CLONES/$repo" origin/main) + [[ -n $keylist ]] || { RESULT[$sha]=NO_KEY; journal repo="$repo" stack="$k" sha="$sha" result=refused reason="no key in origin/main:.aien/verify.pub"; return 1; } + require=$("$GIT" -C "$CLONES/$repo" show "origin/main:.aien/always" 2>/dev/null | grep -v '^#' | grep -v '^$' | paste -sd, - || true) + v=$(verify "$lfile" "$repo" "$sha" "$keylist" "$require"); best=${v%% *} + RESULT[$sha]=$(verdict_name "$best") + journal repo="$repo" stack="$k" sha="$sha" result=verdict verdict="${RESULT[$sha]}" reason="verify-bundle exit codes per key: ${v#* }" + [[ $best == 0 || $best == 1 ]] +} +# test_stack REPO k -> 0 PASS, 1 FAIL, 2 cannot tell (journaled). Builds the stack when needed. +test_stack() { + local repo=$1 k=$2 sha + build_stack "$k" || { journal repo="$repo" stack="$k" result=refused reason="cannot build stack: ${RECOMPILE_NOTE:-unknown}"; return 2; } + sha=$BUILT + run_stack "$repo" "$k" "$sha" || return 2 + [[ ${RESULT[$sha]} == PASS ]] && return 0 + return 1 +} + +# ---------------------------------------------------------------- culprit and merge +blame() { # REPO SLUG k: PR k is the culprit (stack k failed, stack k-1 passed) + local repo=$1 s=$2 k=$3 num=${QN[$3]} sha=${STACK[$3]} prev body url pdig + build_stack $((k - 1)); prev=$BUILT + bash "$PIPELINE" publish --repos "$repo" 8>&- 9>&- >/dev/null 2>&1 || true + "$GIT" -C "$RECEIPTS" fetch -q origin 2>/dev/null || true + pdig=$(published "$repo" "$sha") + url=$(receipt_url "$repo" "$sha") + [[ -n $pdig ]] || url="$url (not published yet; local bundle $STATE/bundles/$repo/$sha/bundle.json)" + body="Merge train: stack $k (main + ${k} pull request(s) in queue order, tested sha $sha) FAILED on the Spark while stack $((k - 1)) ($prev) passed, so this pull request is the one that breaks the gates. Receipt: $url. The \`$MERGE_LABEL\` label was removed; fix, then add it back to ride the next train. Nothing was closed." + if "$GH" api -X POST "repos/$s/issues/$num/comments" -f body="$body" >/dev/null 2>&1 \ + && "$GH" api -X DELETE "repos/$s/issues/$num/labels/$MERGE_LABEL" >/dev/null 2>&1; then + journal repo="$repo" pr="$num" sha="${QS[$k]}" stack="$k" tested="$sha" result=culprit reason="stack $k FAIL, stack $((k - 1)) PASS; label removed" + else + journal repo="$repo" pr="$num" sha="${QS[$k]}" stack="$k" tested="$sha" result=failed reason="culprit comment or label removal failed" + fi +} +ensure_train_pr() { # REPO SLUG SHA: one open PR from train/ to main; its head is the tested SHA, it runs the hosted check and is what gets merged + local repo=$1 s=$2 sha=$3 num body + num=$("$GH" api "repos/$s/pulls?state=open&head=${s%%/*}:train/$repo&per_page=5" --jq '.[0].number // empty' 2>/dev/null || true) + if [[ -z $num ]]; then + body="Merge train stack for \`$repo\` (tools/aien-local-ci/train.sh). Its head is the exact tested stack sha. The train merges it with a merge commit only while main is still the stack base, so the merged tree equals the tested tree. Do not merge it by hand." + num=$("$GH" api -X POST "repos/$s/pulls" -f title="train: $repo stack (do not merge by hand)" -f head="train/$repo" -f base=main -f body="$body" --jq .number 2>/dev/null) || return 1 + fi + TRAIN_PR=$num +} +wait_checks() { # SLUG SHA -> 0 green, 1 otherwise (CHECK_NOTE says why) + local waited=0 rc + while :; do + rc=0; checks_state "$1" "$2" || rc=$? + case $rc in 0) return 0 ;; 1) ;; *) return 1 ;; esac + [[ $waited -lt $CHECK_WAIT ]] || { CHECK_NOTE="$CHECK_NOTE after ${CHECK_WAIT}s"; return 1; } + sleep "$POLL"; waited=$((waited + POLL)) + done +} +publish_stack() { # REPO SHA -> 0 when the local bundle's digest is at receipts origin + local repo=$1 sha=$2 ldig pdig attempt + ldig=$(digest "$STATE/bundles/$repo/$sha/bundle.json") + for attempt in 1 2 3; do + bash "$PIPELINE" publish --repos "$repo" 8>&- 9>&- >/dev/null 2>&1 || true + "$GIT" -C "$RECEIPTS" fetch -q origin 2>/dev/null || true + pdig=$(published "$repo" "$sha") + [[ $pdig == "$ldig" ]] && { PUB_DIGEST=$ldig; return 0; } + sleep "$RETRY_SLEEP" + done + PUB_NOTE="local sha256:$ldig, published ${pdig:+sha256:}${pdig:-nothing}" + return 1 +} +# fresh REPO SLUG p: every PR 1..p still open, labeled, not draft, head unchanged. Prints the first stale index or 0. +fresh() { + local repo=$1 s=$2 p=$3 i num pr state draft head labeled + for ((i = 1; i <= p; i++)); do + num=${QN[$i]} + if ! pr=$("$GH" api "repos/$s/pulls/$num" --jq "[.state, .draft, .head.sha, ([.labels[].name] | index(\"$MERGE_LABEL\") != null)] | @tsv" 2>/dev/null); then + journal repo="$repo" pr="$num" result=stale reason="cannot read pull request" >&2; echo "$i"; return 0 + fi + IFS=$'\t' read -r state draft head labeled <<< "$pr" + if [[ $state != open ]]; then journal repo="$repo" pr="$num" result=stale reason="state $state" >&2; echo "$i"; return 0; fi + if [[ $draft != false ]]; then journal repo="$repo" pr="$num" result=stale reason="draft" >&2; echo "$i"; return 0; fi + if [[ $labeled != true ]]; then journal repo="$repo" pr="$num" result=stale reason="label $MERGE_LABEL removed" >&2; echo "$i"; return 0; fi + if [[ $head != "${QS[$i]}" ]]; then journal repo="$repo" pr="$num" result=stale reason="head moved to $head" >&2; echo "$i"; return 0; fi + done + echo 0 +} +# merge_stack REPO SLUG p: publish, hosted checks, lock, freshness, main unchanged, merge the train PR. 0 merged. +merge_stack() { + local repo=$1 s=$2 p=$3 sha stale i rc now + while [[ $p -ge 1 ]]; do + build_stack "$p" || { journal repo="$repo" stack="$p" result=refused reason="cannot build stack $p: ${RECOMPILE_NOTE:-unknown}"; return 1; } + sha=$BUILT + if [[ ${RESULT[$sha]:-} != PASS ]]; then + # a prefix never run (bisection skipped it, or a shorter prefix after a stale drop-out): test it now + rc=0; test_stack "$repo" "$p" || rc=$? + [[ $rc == 0 ]] || { journal repo="$repo" stack="$p" sha="$sha" result=refused reason="stack $p is ${RESULT[$sha]:-untested}, nothing to merge"; return 1; } + fi + # pipeline.sh publish takes the same lock with flock -n and exits 0 silently when it is busy: wait for it first. + exec 9>>"$STATE/pipeline.lock" + if ! flock -w "$LOCK_WAIT" 9; then + exec 9>&-; journal repo="$repo" stack="$p" sha="$sha" result=refused reason="pipeline lock busy for ${LOCK_WAIT}s (pipeline.sh round or another train); publication and merge deferred"; return 1 + fi + flock -u 9; exec 9>&- + if ! publish_stack "$repo" "$sha"; then + journal repo="$repo" stack="$p" sha="$sha" result=refused reason="bundle not published to receipts: $PUB_NOTE"; return 1 + fi + push_train_branch "$repo" "$sha" || { journal repo="$repo" stack="$p" sha="$sha" result=refused reason="cannot push train/$repo"; return 1; } + ensure_train_pr "$repo" "$s" "$sha" || { journal repo="$repo" stack="$p" sha="$sha" result=refused reason="cannot open the train pull request"; return 1; } + if ! wait_checks "$s" "$sha"; then + journal repo="$repo" stack="$p" sha="$sha" result=refused reason="$CHECK_NOTE"; return 1 + fi + exec 9>>"$STATE/pipeline.lock" + if ! flock -w "$LOCK_WAIT" 9; then + exec 9>&-; journal repo="$repo" stack="$p" sha="$sha" result=refused reason="pipeline lock busy for ${LOCK_WAIT}s (pipeline.sh merge or another train)"; return 1 + fi + stale=$(fresh "$repo" "$s" "$p") + if [[ $stale != 0 ]]; then + flock -u 9; exec 9>&- + journal repo="$repo" stack="$p" sha="$sha" result=shortened reason="PR #${QN[$stale]} stale; prefix ends before it" + p=$((stale - 1)); continue + fi + "$GIT" -C "$TC" fetch -q origin main 2>/dev/null || true + now=$("$GIT" -C "$TC" rev-parse --verify -q origin/main || echo "") + if [[ $now != "$MAIN" ]]; then + flock -u 9; exec 9>&-; journal repo="$repo" stack="$p" sha="$sha" result=aborted reason="main moved to $now since the stack was built on $MAIN; cycle aborted, the next cycle restacks"; return 1 + fi + if ! checks_state "$s" "$sha"; then + flock -u 9; exec 9>&-; journal repo="$repo" stack="$p" sha="$sha" result=refused reason="$CHECK_NOTE (re-checked under lock)"; return 1 + fi + # Landing (pipeline owner, 2026-10-16): the train PR, whose head must be the EXACT tested sha, is merged with a + # merge commit, and only while main is still the base the stack was built on. Then the merged tree is the tested + # tree (main is an ancestor of the head, so a merge commit adds no content). No direct push to main, no protection + # change; the stacked PRs show as merged because their heads are in main. `--match-head-commit` makes GitHub refuse the merge when + # the head moved after we looked. + local tinfo tstate tbase thead resp landed + if ! tinfo=$("$GH" api "repos/$s/pulls/$TRAIN_PR" --jq '[.state, .base.ref, .head.sha] | @tsv' 2>/dev/null); then + flock -u 9; exec 9>&-; journal repo="$repo" stack="$p" sha="$sha" result=refused reason="cannot read train pull request #$TRAIN_PR"; return 1 + fi + IFS=$'\t' read -r tstate tbase thead <<< "$tinfo" + if [[ $tstate != open || $tbase != main || $thead != "$sha" ]]; then + flock -u 9; exec 9>&- + journal repo="$repo" stack="$p" sha="$sha" result=refused reason="train pull request #$TRAIN_PR is $tstate into $tbase with head ${thead:-none}, not the tested sha; not merged"; return 1 + fi + if ! "$GIT" -C "$TC" merge-base --is-ancestor "$MAIN" "$sha" 2>/dev/null; then + flock -u 9; exec 9>&-; journal repo="$repo" stack="$p" sha="$sha" result=refused reason="tested sha does not contain the base main $MAIN; not merged"; return 1 + fi + resp=$("$GH" pr merge "$TRAIN_PR" -R "$s" 8>&- 9>&- --merge --match-head-commit "$sha" \ + --subject "Merge train stack for $repo (PRs ${QN[1]}..${QN[$p]}) at tested sha $sha" 2>&1) && rc=0 || rc=$? + flock -u 9; exec 9>&- + if [[ $rc != 0 ]]; then + journal repo="$repo" stack="$p" sha="$sha" result=failed reason="merge of train pull request refused: $(tr '\n' ' ' <<< "$resp" | cut -c1-300)"; return 1 + fi + landed=$("$GIT" -C "$TC" fetch -q origin main 2>/dev/null && "$GIT" -C "$TC" rev-parse origin/main || echo "") + if [[ -z $landed || $("$GIT" -C "$TC" rev-parse "$landed^{tree}") != "$("$GIT" -C "$TC" rev-parse "$sha^{tree}")" ]]; then + journal repo="$repo" stack="$p" sha="$sha" landed="$landed" result=failed reason="merged tree differs from the tested tree (main moved in the last instant); stop and look at main"; return 1 + fi + local nums="" ; for ((i = 1; i <= p; i++)); do nums+="${nums:+,}${QN[$i]}"; done + journal repo="$repo" stack="$p" sha="$sha" landed="$landed" digest="$PUB_DIGEST" prs="$nums" result=merged reason="train pull request merged with a merge commit; merged tree equals tested tree" + "$GIT" -C "$TC" push -q origin --delete "train/$repo" >/dev/null 2>&1 || true + return 0 + done + journal repo="$repo" result=refused reason="no fresh tested prefix left to merge"; return 1 +} + +# ---------------------------------------------------------------- one cycle +# One train per repository: a second loop would force-push the same train/ branch. Lock fd 8, never waited for. +cycle_repo() { + local lockf=$STATE/train.$1.lock + exec 8>>"$lockf" + if ! flock -n 8; then + exec 8>&-; journal repo="$1" result=skipped reason="another train cycle holds $lockf"; return 0 + fi + cycle_repo_locked "$1" + exec 8>&- +} +cycle_repo_locked() { + local repo=$1 s rc lo hi mid p sha k + [[ -d $CLONES/$repo ]] || { say "$repo: no trusted clone, skipped"; return 0; } + if ! s=$(slug "$repo"); then journal repo="$repo" result=refused reason="cannot resolve GitHub slug"; return 0; fi + if ! train_clone "$repo"; then journal repo="$repo" result=refused reason="cannot prepare the train clone"; return 0; fi + admit "$repo" "$s" || return 0 + if [[ $N == 0 ]]; then say "$repo: nothing queued at $MAIN"; return 0; fi + if [[ $DRY == 1 ]]; then + build_stack "$N" || { journal repo="$repo" result=refused reason="cannot build stack $N: ${RECOMPILE_NOTE:-unknown}"; return 0; } + sha=$BUILT + say "$repo DRY RUN: main $MAIN, queue of $N:" + for ((k = 1; k <= N; k++)); do say " $k. #${QN[$k]} ${QS[$k]} ${QT[$k]}"; done + crumb_tool || true + say " stack $N = $sha (top: $("$GIT" -C "$TC" log -1 --format=%s "$sha"), crumb tool $CRUMB_PIN)" + say " would: push train/$repo, quietlock check, aien-local-ci once $repo $sha, bisect on FAIL, publish, merge the train PR (head = tested sha) while main is unchanged" + journal repo="$repo" stack="$N" sha="$sha" result=dry-run reason="plan printed, nothing pushed" + return 0 + fi + journal repo="$repo" result=cycle reason="main $MAIN, $N queued" + rc=0; test_stack "$repo" "$N" || rc=$? + case $rc in + 0) merge_stack "$repo" "$s" "$N" || true; return 0 ;; + 2) return 0 ;; + esac + lo=0; hi=$N + while [[ $((hi - lo)) -gt 1 ]]; do + mid=$(((lo + hi) / 2)) + rc=0; test_stack "$repo" "$mid" || rc=$? + case $rc in 0) lo=$mid ;; 1) hi=$mid ;; *) return 0 ;; esac + done + if [[ $lo == 0 ]]; then + # Stack 1 failed: main itself must pass before PR 1 is blamed. + rc=0; test_stack "$repo" 0 || rc=$? + case $rc in + 1) journal repo="$repo" sha="$MAIN" result=refused reason="main itself fails the gates; no culprit named"; return 0 ;; + 2) return 0 ;; + esac + fi + blame "$repo" "$s" "$hi" + [[ $lo -ge 1 ]] && { merge_stack "$repo" "$s" "$lo" || true; } + return 0 +} +do_cycle() { local repo; for repo in "${repo_list[@]}"; do cycle_repo "$repo"; done; } + +do_loop() { + local repo n mx med last t + declare -A PERIOD DUE + for repo in "${repo_list[@]}"; do + if [[ -n $EVERY ]]; then PERIOD[$repo]=$EVERY + else + read -r n mx med last < <(cadence_of "$repo") + if [[ $n == 0 ]]; then say "$repo: no measured T (no real bundle yet), not scheduled; pass --every SECS"; continue; fi + PERIOD[$repo]=$mx + fi + DUE[$repo]=$(date +%s) + say "$repo: one cycle every ${PERIOD[$repo]}s" + done + [[ ${#PERIOD[@]} -gt 0 ]] || die "nothing to schedule" + while :; do + t=$(date +%s) + for repo in "${!PERIOD[@]}"; do + [[ $t -ge ${DUE[$repo]} ]] || continue + cycle_repo "$repo" + DUE[$repo]=$(( $(date +%s) + PERIOD[$repo] )) + done + sleep "$POLL" + done +} + +case "$cmd" in + cadence) do_cadence ;; + cycle) do_cycle ;; + loop) do_loop ;; +esac +exit 0