oficina / equipo Public

CI: run in a box on hosted CI; arm64 pins; lint and test shards

amadan's hosted CI gives each job a fresh arm64 machine with Docker and
no bubblewrap, and CI no longer runs on docs-t1. Most of the suite starts
real containment that needs bubblewrap 0.11.0 exactly, the pinned Codex
program and a delegated cgroup.

- scripts/ci-box.py runs every step in one privileged container (the
  official Go 1.26.10 image on Debian 13, pinned by digest) as an
  ordinary user, with the pinned bubblewrap, codex and claude fetched by
  SHA-256 for the machine's architecture and mounted where a runner host
  has them. On a runner host it runs the command directly.
- arm64 pins sit beside the certified amd64 ones, which are unchanged and
  still the only pins a launcher or release trusts. The replay tests
  pick the pin for runtime.GOARCH; a missing pinned program fails on CI.
- File times are set from git content and paths in the box are fixed, so
  Go's build and test caches hold from one fresh machine to the next.
- Steps: prepare, lint@4, test@9 (seven lanes, quarantine, runner-host),
  perf, cache. Steps run one after another on hosted; shards run side by
  side.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev dfc58307c88aff9057692766064721d514e31a72 parent c6319a5
36 files changed, +1,016 −57
  • .amadan/ci +5 −1
  • .amadan/ci.d/00-prepare +5 −0
  • .amadan/ci.d/05-build +0 −2
  • .amadan/ci.d/10-lint@4 +5 −0
  • .amadan/ci.d/10-vet +0 −2
  • .amadan/ci.d/15-budget +0 −2
  • .amadan/ci.d/20-fmt +0 −2
  • .amadan/ci.d/25-staticcheck +0 −2
  • .amadan/ci.d/26-govulncheck +0 −2
  • .amadan/ci.d/27-gitleaks +0 −2
  • .amadan/ci.d/30-test@7 +0 −4
  • .amadan/ci.d/30-test@9 +8 −0
  • .amadan/ci.d/31-test-quarantine +0 −4
  • .amadan/ci.d/34-runner-dead-references +0 −3
  • .amadan/ci.d/35-runner-adapter-test +0 −2
  • .amadan/ci.d/36-runner-namespaces +0 −2
  • .amadan/ci.d/40-migration-check +0 −2
  • .amadan/ci.d/50-perf +2 −1
  • .amadan/ci.d/90-cache +3 −0
  • Makefile +25 −4
  • docs/superpowers/plans/HOSTED-CI-PROGRESS.md +92 −0
  • internal/equipotest/foundation_test.go +42 −7
  • internal/runner/provider/claude/pins.go +23 −0
  • internal/runner/provider/claude/pins_test.go +19 −0
  • internal/runner/provider/claude/runtime_replay_test.go +9 −2
  • internal/runner/provider/codex/pins.go +26 −0
  • internal/runner/provider/codex/pins_test.go +34 −0
  • internal/runner/provider/codex/runtime_replay_test.go +9 −2
  • internal/testci/absent_test.go +37 −0
  • internal/testci/box_test.go +57 −0
  • internal/testci/testci.go +16 −0
  • scripts/ci-box-enter.sh +52 −0
  • scripts/ci-box.json +68 −0
  • scripts/ci-box.py +453 −0
  • scripts/ci-test.py +18 −7
  • scripts/runner-prerequisites.py +8 −2
diff --git a/.amadan/ci b/.amadan/ci
index 8c547eee..beeef7ea 100755
--- a/.amadan/ci
+++ b/.amadan/ci
@@ -2,5 +2,9 @@
# amadan CI entry (single-script fallback for runners without step
# support). The steps in ci.d/ are the same targets, reported one by
# one. Must stay executable: a non-executable script resolves "skipped".
+#
+# "$(dirname "$0")/../scripts/ci-box.py" puts the command in the CI box on a hosted CI machine
+# and runs it directly on a runner host.
set -e
-exec make ci
+"$(dirname "$0")/../scripts/ci-box.py" prepare
+exec "$(dirname "$0")/../scripts/ci-box.py" run make ci
diff --git a/.amadan/ci.d/00-prepare b/.amadan/ci.d/00-prepare
new file mode 100755
index 00000000..c5e9b09c
--- /dev/null
+++ b/.amadan/ci.d/00-prepare
@@ -0,0 +1,5 @@
+#!/bin/sh
+# Get the CI box ready on a hosted CI machine: the pinned bubblewrap,
+# Codex and Claude programs, the image, the full clone and file times
+# that let cached test results hold. Nothing to do on a runner host.
+exec "$(dirname "$0")/../../scripts/ci-box.py" prepare
diff --git a/.amadan/ci.d/05-build b/.amadan/ci.d/05-build
deleted file mode 100755
index 9fc4060b..00000000
--- a/.amadan/ci.d/05-build
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make build
diff --git a/.amadan/ci.d/10-lint@4 b/.amadan/ci.d/10-lint@4
new file mode 100755
index 00000000..876f037f
--- /dev/null
+++ b/.amadan/ci.d/10-lint@4
@@ -0,0 +1,5 @@
+#!/bin/sh
+# The static checks, four shards side by side (Makefile LINT_SHARD_0 to
+# LINT_SHARD_3): build, vet, format, budgets and the migration check;
+# staticcheck; govulncheck; gitleaks. AMADAN_SHARD picks one.
+exec "$(dirname "$0")/../../scripts/ci-box.py" run make lint-shard
diff --git a/.amadan/ci.d/10-vet b/.amadan/ci.d/10-vet
deleted file mode 100755
index 139a2a25..00000000
--- a/.amadan/ci.d/10-vet
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make vet
diff --git a/.amadan/ci.d/15-budget b/.amadan/ci.d/15-budget
deleted file mode 100755
index b9dabd50..00000000
--- a/.amadan/ci.d/15-budget
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make budget
diff --git a/.amadan/ci.d/20-fmt b/.amadan/ci.d/20-fmt
deleted file mode 100755
index 5884a7b5..00000000
--- a/.amadan/ci.d/20-fmt
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make fmt-check
diff --git a/.amadan/ci.d/25-staticcheck b/.amadan/ci.d/25-staticcheck
deleted file mode 100755
index 751a4e61..00000000
--- a/.amadan/ci.d/25-staticcheck
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make staticcheck
diff --git a/.amadan/ci.d/26-govulncheck b/.amadan/ci.d/26-govulncheck
deleted file mode 100755
index 6873a71b..00000000
--- a/.amadan/ci.d/26-govulncheck
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make govulncheck
diff --git a/.amadan/ci.d/27-gitleaks b/.amadan/ci.d/27-gitleaks
deleted file mode 100755
index faeccf6e..00000000
--- a/.amadan/ci.d/27-gitleaks
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make gitleaks
diff --git a/.amadan/ci.d/30-test@7 b/.amadan/ci.d/30-test@7
deleted file mode 100755
index ecb26e42..00000000
--- a/.amadan/ci.d/30-test@7
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-# Seven shards, one per test lane (scripts/ci-test.py LANES), run side by
-# side: AMADAN_SHARD picks the lane.
-exec make test-shard
diff --git a/.amadan/ci.d/30-test@9 b/.amadan/ci.d/30-test@9
new file mode 100755
index 00000000..53cf1833
--- /dev/null
+++ b/.amadan/ci.d/30-test@9
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Nine shards run side by side; AMADAN_SHARD picks one. The first seven
+# are the test lanes (scripts/ci-test.py LANES). Then the quarantine:
+# known flaky tests (scripts/ci-quarantine.txt), each retried once on
+# failure, a pass on the retry reported as a flake. Last, runner-host:
+# the exact bubblewrap build, the pinned programs, real namespaces and
+# the cgroup move, uncached.
+exec "$(dirname "$0")/../../scripts/ci-box.py" run make test-shard
diff --git a/.amadan/ci.d/31-test-quarantine b/.amadan/ci.d/31-test-quarantine
deleted file mode 100755
index dcfd05ca..00000000
--- a/.amadan/ci.d/31-test-quarantine
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-# Known flaky tests (scripts/ci-quarantine.txt), each retried once on
-# failure; a pass on the retry is reported as a flake.
-exec make test-quarantine
diff --git a/.amadan/ci.d/34-runner-dead-references b/.amadan/ci.d/34-runner-dead-references
deleted file mode 100755
index fb3d202a..00000000
--- a/.amadan/ci.d/34-runner-dead-references
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/sh
-set -eu
-exec make runner-dead-references
diff --git a/.amadan/ci.d/35-runner-adapter-test b/.amadan/ci.d/35-runner-adapter-test
deleted file mode 100755
index 7bef3886..00000000
--- a/.amadan/ci.d/35-runner-adapter-test
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make runner-adapter-test
diff --git a/.amadan/ci.d/36-runner-namespaces b/.amadan/ci.d/36-runner-namespaces
deleted file mode 100755
index 88d7bf45..00000000
--- a/.amadan/ci.d/36-runner-namespaces
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make runner-namespace-test
diff --git a/.amadan/ci.d/40-migration-check b/.amadan/ci.d/40-migration-check
deleted file mode 100755
index 81db0932..00000000
--- a/.amadan/ci.d/40-migration-check
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make migration-check
diff --git a/.amadan/ci.d/50-perf b/.amadan/ci.d/50-perf
index 0c6a01a7..93ad2cd1 100755
--- a/.amadan/ci.d/50-perf
+++ b/.amadan/ci.d/50-perf
@@ -1,2 +1,3 @@
#!/bin/sh
-exec make perf
+# Alone, after everything else: it measures time.
+exec "$(dirname "$0")/../../scripts/ci-box.py" run make perf
diff --git a/.amadan/ci.d/90-cache b/.amadan/ci.d/90-cache
new file mode 100755
index 00000000..130445b0
--- /dev/null
+++ b/.amadan/ci.d/90-cache
@@ -0,0 +1,3 @@
+#!/bin/sh
+# Report the Go caches and keep them under what hosted CI will save.
+exec "$(dirname "$0")/../../scripts/ci-box.py" cache
diff --git a/Makefile b/Makefile
index b86a9f84..5ce970ad 100644
--- a/Makefile
+++ b/Makefile
@@ -27,7 +27,7 @@ RUNNER_RELEASE_DIR = releases/equipo-runner-linux-amd64-$(RELEASE_VERSION)
# and a suite running beside it would be measured too.
.NOTPARALLEL:
-.PHONY: build release test test-lane test-shard test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-dead-references ci
+.PHONY: build release test test-lane test-shard test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references lint-shard ci
RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo
@@ -83,8 +83,9 @@ budget:
# lists the packages that must run every time (UNCACHED).
#
# test runs every package at once. CI runs the same packages as lanes,
-# the shards of .amadan/ci.d/30-test@7: the slow packages each in a lane
-# of their own, side by side (make test-lane LANE=headless runs one).
+# shards of .amadan/ci.d/30-test@9: the slow packages each in a lane of
+# their own, side by side (make test-lane LANE=headless runs one), with
+# test-quarantine and runner-host as the last two shards.
# Known flaky tests are quarantined (scripts/ci-quarantine.txt): skipped
# here, run by test-quarantine with one retry, and reported as flakes.
test:
@@ -189,6 +190,26 @@ runner-adapter-test: runner-prerequisites
runner-dead-references:
python3 scripts/runner-dead-references.py
+# runner-host checks the machine the tests run on, not only the code: the
+# exact bubblewrap build, the pinned Codex program, real namespaces, and a
+# process moved between two delegated cgroups. Uncached, every time. On
+# hosted CI the machine is the CI box (scripts/ci-box.py), which is made
+# to pass for a runner host.
+runner-host: runner-adapter-test runner-namespace-test
+
+# The static checks as CI runs them: the four shards of
+# .amadan/ci.d/10-lint@4, side by side. AMADAN_SHARD picks one. Each
+# stays a target of its own for a person to run.
+LINT_SHARD_0 := runner-dead-references build vet fmt-check budget migration-check
+LINT_SHARD_1 := staticcheck
+LINT_SHARD_2 := govulncheck
+LINT_SHARD_3 := gitleaks
+lint-shard:
+ @test "$(AMADAN_SHARD_COUNT)" = 4 && test -n "$(LINT_SHARD_$(AMADAN_SHARD))" || \
+ { echo "lint-shard: shard $(AMADAN_SHARD) of $(AMADAN_SHARD_COUNT), but there are 4 lint shards; name the step 10-lint@4"; exit 1; }
+ @echo "lint shard $(AMADAN_SHARD): $(LINT_SHARD_$(AMADAN_SHARD))"
+ @$(MAKE) --no-print-directory $(LINT_SHARD_$(AMADAN_SHARD))
+
# ci is the one gate: what a runner executes and what you run before
# pushing are the same definition. amadan's runner falls back to this
# target when .amadan/ci is absent; ci.d/ carries the same targets,
@@ -196,7 +217,7 @@ runner-dead-references:
# fails the build the moment models.go and migrations/ disagree,
# instead of at boot on whatever machine notices next. If the app
# declares manifest resources, also add: rastrillo generate --check
-ci: runner-dead-references build vet fmt-check staticcheck govulncheck gitleaks budget test test-quarantine runner-adapter-test runner-namespace-test migration-check perf
+ci: runner-dead-references build vet fmt-check staticcheck govulncheck gitleaks budget test test-quarantine runner-host migration-check perf
.PHONY: copy-release-check direct-release-check release-runner runner-prerequisites
copy-release-check:
diff --git a/docs/superpowers/plans/HOSTED-CI-PROGRESS.md b/docs/superpowers/plans/HOSTED-CI-PROGRESS.md
new file mode 100644
index 00000000..9bd87f6e
--- /dev/null
+++ b/docs/superpowers/plans/HOSTED-CI-PROGRESS.md
@@ -0,0 +1,92 @@
+# Hosted CI (branch hosted-ci)
+
+Goal: Equipo's CI on amadan's hosted CI, fast, with nothing on docs-t1.
+Paul's ruling (2026-11-10): no CI on docs-t1 at all, not even a small
+host step. Locally, run only targeted tests.
+
+## What hosted CI is
+
+Each job gets its own single-use arm64 machine (Amazon Linux 2023, up to
+32 vCPU), with Go, Docker, git, make and python3 3.9. No bubblewrap, no
+systemd user session, no isolation around steps. The clone is one commit
+deep. GOCACHE and GOMODCACHE are restored from S3 before the job and
+saved after a passing one (limits: 2 GiB compressed, 6 GiB unpacked;
+over either, the save is dropped whole). Steps run one after another; a
+step's `@N` shards run side by side on the one machine. Only the `ci`
+pipeline gives the commit its verdict.
+
+## What Equipo needs that the machine lacks
+
+Most of the suite, not only the old steps 35 and 36, starts real
+containment through production code that requires `bubblewrap 0.11.0`
+exactly, runs the pinned Codex program, and one test moves a process
+between two delegated cgroups. So:
+
+- **The CI box** (`scripts/ci-box.py`, `scripts/ci-box-enter.sh`,
+ `scripts/ci-box.json`). Every step runs in one privileged container,
+ the official Go 1.26.10 image on Debian 13 (the runner host's own
+ system, pinned by digest, pulled, never built), as an ordinary user.
+ The pinned programs are fetched by URL and checked by SHA-256 for the
+ machine's architecture, then mounted where a runner host has them:
+ Debian's bubblewrap 0.11.0-2+deb13u1 at `/usr/bin/bwrap`, codex
+ 0.165.0 on PATH, and codex, its code mode host and claude 2.1.312 in
+ `~/.local/share/equipo/try/bin`. The entry script gives `/etc` its own
+ filesystem (containment overlays `/etc`, and the kernel refuses an
+ overlay over the container's overlay root) and makes a cgroup v2
+ subtree the user may write, at the path a systemd user session has.
+- **On a runner host the box is skipped.** `ci-box.py run` runs the
+ command directly where `/usr/bin/bwrap` is already 0.11.0 and codex is
+ on PATH. `EQUIPO_CI_BOX=on|off` forces it.
+- **arm64 pins beside the certified ones** (`codex/pins.go`,
+ `claude/pins.go`). The certified amd64 constants are untouched and are
+ still the only pins a launcher or a release trusts. The replay tests
+ pick the pin for `runtime.GOARCH`. Digests come from the official
+ releases:
+
+ | program | arm64 SHA-256 | source |
+ |---|---|---|
+ | codex 0.165.0 | b32ece31...c543f | openai/codex rust-v0.165.0, aarch64-unknown-linux-musl |
+ | codex code mode host | fd7a4a1f...aa14 | same release |
+ | claude 2.1.312 | dc4af289...61f5 | the release manifest at downloads.claude.ai |
+ | bubblewrap 0.11.0 | ef2316fc...3b59 | Debian 0.11.0-2+deb13u1 arm64, snapshot.debian.org |
+
+ The same sources reproduce the amd64 pins already in the tree (codex
+ c06a67fd, host 522935d4, claude 4f4178ce, bwrap 0dfa36b9), which is the
+ check that they are the right sources.
+- **A missing pinned program fails on CI** instead of skipping
+ (`testci.Absent`, `EQUIPO_TEST_TOOLS_REQUIRED=1` set by the box).
+
+## Caches across fresh machines
+
+- Fixed paths in the box (`/work/equipo`, `/cache/go-build`,
+ `/cache/go-mod`): Go keys a compiled package on its directory.
+- `ci-box.py prepare` sets every tracked file's modification time from
+ its git blob and every directory's to one fixed time, so go test's
+ cached results (keyed on size and time of each file a test opened)
+ hold on the next machine. A changed file gets a new time.
+- `ci-box.py cache` (last step) reports the cache sizes and, past 4 GiB,
+ drops build cache entries the job did not read. A restore stamps every
+ entry "now", so Go's own trim never fires on hosted.
+
+## Steps
+
+| step | what |
+|---|---|
+| `00-prepare` | fetch and verify the pinned programs, pull the image, deepen the clone, set file times |
+| `10-lint@4` | build, vet, format, budgets, references, migration check; staticcheck; govulncheck; gitleaks |
+| `30-test@9` | the seven test lanes, the quarantine, and `runner-host` (bubblewrap build, pinned codex, namespaces, cgroup move, uncached) |
+| `50-perf` | alone, it measures time |
+| `90-cache` | report and trim the caches |
+
+## Before (docs-t1)
+
+Main c6319a5 on docs-t1 (load 26 to 44): failed after 512 s; the
+headless lane ran 470 s and failed, thintest failed at 102 s. Best warm
+docs-t1 run (ci-speed 5258905, nothing changed): 217 s.
+
+## Runs on hosted
+
+Proved first in the scratch repository `oficina/equipo-hostedci` (hosted
+is per repository, and main's old steps cannot pass there).
+
+(filled in below as runs come back)
diff --git a/internal/equipotest/foundation_test.go b/internal/equipotest/foundation_test.go
index a3f7f0a2..80f9afbd 100644
--- a/internal/equipotest/foundation_test.go
+++ b/internal/equipotest/foundation_test.go
@@ -11,7 +11,9 @@ import (
"os/exec"
"path/filepath"
"reflect"
+ "regexp"
"sort"
+ "strconv"
"strings"
"testing"
@@ -167,26 +169,45 @@ func TestFoundationMigratesTwice(t *testing.T) {
// Mutation check: remove build from ci and a wrapper, one at a time;
// each must fail. Executing with a fake make also checks shell behavior.
+//
+// The steps run through scripts/ci-box.py, which on a hosted CI machine
+// puts the command in the CI box. EQUIPO_CI_BOX=off runs it directly, as
+// on a runner host, so the fake make sees what each step asks for.
func TestCIGateSteps(t *testing.T) {
root := filepath.Join("..", "..")
- want := []string{"build", "vet", "fmt-check", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "test-quarantine", "runner-adapter-test", "runner-namespace-test", "runner-dead-references", "migration-check", "perf"}
+ want := []string{"build", "vet", "fmt-check", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "test-quarantine", "runner-host", "runner-dead-references", "migration-check", "perf"}
sort.Strings(want)
// The step scripts run outside this process; their bytes are inputs.
- testci.Files(t, filepath.Join(root, ".amadan"), filepath.Join(root, "scripts", "ci-test.py"))
+ testci.Files(t, filepath.Join(root, ".amadan"), filepath.Join(root, "scripts", "ci-test.py"), filepath.Join(root, "scripts", "ci-box.py"))
contents, err := os.ReadFile(filepath.Join(root, "Makefile"))
if err != nil {
t.Fatal(err)
}
var targets []string
+ lint := map[string][]string{}
for _, line := range strings.Split(string(contents), "\n") {
if strings.HasPrefix(line, "ci:") {
targets = append(targets, strings.Fields(strings.TrimPrefix(line, "ci:"))...)
}
+ if name, list, ok := strings.Cut(line, " := "); ok && strings.HasPrefix(name, "LINT_SHARD_") {
+ lint[name] = strings.Fields(list)
+ }
}
sort.Strings(targets)
if !reflect.DeepEqual(targets, want) {
t.Errorf("make ci targets = %v, want %v", targets, want)
}
+ // The shards of the test step after the lanes, as ci-test.py lists them.
+ script, err := os.ReadFile(filepath.Join(root, "scripts", "ci-test.py"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ extra := regexp.MustCompile(`(?m)^EXTRA_SHARDS = \[(.*)\]$`).FindSubmatch(script)
+ if extra == nil {
+ t.Fatal("scripts/ci-test.py has no EXTRA_SHARDS list")
+ }
+ extraShards := strings.Fields(strings.NewReplacer(`"`, "", ",", " ").Replace(string(extra[1])))
+ lanes := strings.Count(string(script), "\n (\"")
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "make"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0755); err != nil {
t.Fatal(err)
@@ -201,7 +222,7 @@ func TestCIGateSteps(t *testing.T) {
t.Errorf("%s is not executable", path)
}
cmd := exec.Command(path)
- cmd.Env = append(os.Environ(), "PATH="+bin+":"+os.Getenv("PATH"))
+ cmd.Env = append(os.Environ(), "PATH="+bin+":"+os.Getenv("PATH"), "EQUIPO_CI_BOX=off")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%s: %v: %s", path, err, out)
@@ -217,12 +238,26 @@ func TestCIGateSteps(t *testing.T) {
}
var steps []string
for _, path := range paths {
+ _, shards, _ := strings.Cut(filepath.Base(path), "@")
for _, target := range run(path) {
- // CI runs make test as its lanes, the shards of one step.
- if target == "test-shard" {
- target = "test"
+ switch target {
+ case "test-shard":
+ // CI runs make test as its lanes, then the extra shards.
+ if want := strconv.Itoa(lanes + len(extraShards)); shards != want {
+ t.Errorf("%s: %d lanes and %d extra shards need @%s", path, lanes, len(extraShards), want)
+ }
+ steps = append(steps, "test")
+ steps = append(steps, extraShards...)
+ case "lint-shard":
+ if want := strconv.Itoa(len(lint)); shards != want {
+ t.Errorf("%s: %d lint shards need @%s", path, len(lint), want)
+ }
+ for _, list := range lint {
+ steps = append(steps, list...)
+ }
+ default:
+ steps = append(steps, target)
}
- steps = append(steps, target)
}
}
sort.Strings(steps)
diff --git a/internal/runner/provider/claude/pins.go b/internal/runner/provider/claude/pins.go
new file mode 100644
index 00000000..a2db6154
--- /dev/null
+++ b/internal/runner/provider/claude/pins.go
@@ -0,0 +1,23 @@
+package claude
+
+// The arm64 build of the pinned release, for tests only. The certified
+// runner target is linux/amd64: ExecutableSHA256 is the only pin a
+// launcher or a release trusts, and no release ships with the one below.
+// It is the official 2.1.312 linux-arm64 binary, as its release manifest
+// lists it, so a test that runs the real program can run on an arm64 CI
+// machine.
+const ExecutableSHA256Arm64 = "dc4af28917455e009d26704b82a438353a06149e825b6cdf782908b2d28661f5"
+
+// ReleasePin returns the digest of the official 2.1.312 binary built for
+// goarch: the certified pin on amd64, the arm64 build's on arm64. A test
+// hands it runtime.GOARCH to check the binary on the machine it runs on.
+// ok is false where there is no pinned build.
+func ReleasePin(goarch string) (pin string, ok bool) {
+ switch goarch {
+ case "amd64":
+ return ExecutableSHA256, true
+ case "arm64":
+ return ExecutableSHA256Arm64, true
+ }
+ return "", false
+}
diff --git a/internal/runner/provider/claude/pins_test.go b/internal/runner/provider/claude/pins_test.go
new file mode 100644
index 00000000..94eb21a3
--- /dev/null
+++ b/internal/runner/provider/claude/pins_test.go
@@ -0,0 +1,19 @@
+package claude
+
+import "testing"
+
+// The amd64 pin is the certified one and must not move with the arm64 one
+// beside it. The arm64 digest is the official 2.1.312 linux-arm64 binary.
+func TestReleasePinByArchitecture(t *testing.T) {
+ pin, ok := ReleasePin("amd64")
+ if !ok || pin != ExecutableSHA256 {
+ t.Fatalf("amd64 must be the certified pin, got %q %v", pin, ok)
+ }
+ pin, ok = ReleasePin("arm64")
+ if !ok || pin != "dc4af28917455e009d26704b82a438353a06149e825b6cdf782908b2d28661f5" {
+ t.Fatalf("arm64 pin changed: %q %v", pin, ok)
+ }
+ if pin, ok = ReleasePin("riscv64"); ok || pin != "" {
+ t.Fatal("an architecture with no pinned build has a pin")
+ }
+}
diff --git a/internal/runner/provider/claude/runtime_replay_test.go b/internal/runner/provider/claude/runtime_replay_test.go
index 6c9d17f9..d2c32eca 100644
--- a/internal/runner/provider/claude/runtime_replay_test.go
+++ b/internal/runner/provider/claude/runtime_replay_test.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"testing"
"time"
@@ -125,7 +126,7 @@ func TestClaudeEmptyHomeReplay(t *testing.T) {
binary := filepath.Join(home, ".local/share/equipo/try/bin/claude")
file, err := os.Open(binary)
if os.IsNotExist(err) {
- t.Skip("pinned Claude 2.1.312 binary absent; empty-home replay requires the local pinned installation")
+ testci.Absent(t, "pinned Claude 2.1.312 binary absent; empty-home replay requires the local pinned installation")
}
if err != nil {
t.Fatal(err)
@@ -133,7 +134,12 @@ func TestClaudeEmptyHomeReplay(t *testing.T) {
sum := sha256.New()
_, err = io.Copy(sum, file)
file.Close()
- if err != nil || hex.EncodeToString(sum.Sum(nil)) != ExecutableSHA256 {
+ // The official build for this machine: the certified pin on amd64.
+ pin, ok := ReleasePin(runtime.GOARCH)
+ if !ok {
+ t.Fatalf("no pinned Claude 2.1.312 build for %s", runtime.GOARCH)
+ }
+ if err != nil || hex.EncodeToString(sum.Sum(nil)) != pin {
t.Fatal("pinned Claude digest differs")
}
for _, role := range []string{"Engineering", "Coordinator"} {
@@ -181,6 +187,7 @@ func TestClaudeEmptyHomeReplay(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ launcher.digest = pin
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
_, err = launcher.Open(ctx, f.launch)
diff --git a/internal/runner/provider/codex/pins.go b/internal/runner/provider/codex/pins.go
new file mode 100644
index 00000000..75bc33d8
--- /dev/null
+++ b/internal/runner/provider/codex/pins.go
@@ -0,0 +1,26 @@
+package codex
+
+// The arm64 builds of the pinned release, for tests only. The certified
+// runner target is linux/amd64: ExecutableSHA256 and CodeModeHostSHA256
+// are the only pins a launcher or a release trusts, and no release ships
+// with the ones below. These are the same official release's
+// aarch64-unknown-linux-musl binaries (rust-v0.165.0), so a test that
+// runs the real program can run on an arm64 CI machine.
+const (
+ ExecutableSHA256Arm64 = "b32ece31af06440da980b733fb8fefdd1f193439595fda84096f1caaceec543f"
+ CodeModeHostSHA256Arm64 = "fd7a4a1f29871fb0015c19ad2f885ef6a878244643260703e17663418695aa14"
+)
+
+// ReleasePins returns the digests of the official 0.165.0 binaries built
+// for goarch: the certified pins on amd64, the arm64 build's on arm64. A
+// test hands it runtime.GOARCH to check the binaries on the machine it
+// runs on. ok is false where there is no pinned build.
+func ReleasePins(goarch string) (executable, codeModeHost string, ok bool) {
+ switch goarch {
+ case "amd64":
+ return ExecutableSHA256, CodeModeHostSHA256, true
+ case "arm64":
+ return ExecutableSHA256Arm64, CodeModeHostSHA256Arm64, true
+ }
+ return "", "", false
+}
diff --git a/internal/runner/provider/codex/pins_test.go b/internal/runner/provider/codex/pins_test.go
new file mode 100644
index 00000000..6d9ad081
--- /dev/null
+++ b/internal/runner/provider/codex/pins_test.go
@@ -0,0 +1,34 @@
+package codex
+
+import "testing"
+
+// The amd64 pins are the certified ones and must not move with the arm64
+// ones beside them. The arm64 digests are the official rust-v0.165.0
+// aarch64-unknown-linux-musl binaries.
+func TestReleasePinsByArchitecture(t *testing.T) {
+ executable, host, ok := ReleasePins("amd64")
+ if !ok || executable != ExecutableSHA256 || host != CodeModeHostSHA256 {
+ t.Fatalf("amd64 must be the certified pins, got %q %q %v", executable, host, ok)
+ }
+ executable, host, ok = ReleasePins("arm64")
+ if !ok || executable != "b32ece31af06440da980b733fb8fefdd1f193439595fda84096f1caaceec543f" || host != "fd7a4a1f29871fb0015c19ad2f885ef6a878244643260703e17663418695aa14" {
+ t.Fatalf("arm64 pins changed: %q %q %v", executable, host, ok)
+ }
+ if executable == ExecutableSHA256 || host == CodeModeHostSHA256 {
+ t.Fatal("arm64 pins equal the certified amd64 pins")
+ }
+ if executable, host, ok = ReleasePins("riscv64"); ok || executable != "" || host != "" {
+ t.Fatal("an architecture with no official build has pins")
+ }
+}
+
+// A launcher trusts only the certified pins, whatever machine builds it.
+func TestLauncherKeepsCertifiedPins(t *testing.T) {
+ l, err := New(offlineCodexHost{t}, fakeCapture{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if l.digest != ExecutableSHA256 || l.hostDigest != CodeModeHostSHA256 {
+ t.Fatal("launcher pins are not the certified ones")
+ }
+}
diff --git a/internal/runner/provider/codex/runtime_replay_test.go b/internal/runner/provider/codex/runtime_replay_test.go
index b23c2f48..ea29e1fe 100644
--- a/internal/runner/provider/codex/runtime_replay_test.go
+++ b/internal/runner/provider/codex/runtime_replay_test.go
@@ -10,6 +10,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"testing"
"time"
@@ -78,10 +79,15 @@ func TestCodexEmptyHomeReplay(t *testing.T) {
t.Fatal(err)
}
bin := filepath.Join(home, ".local/share/equipo/try/bin")
- for name, want := range map[string]string{"codex": ExecutableSHA256, "codex-code-mode-host": CodeModeHostSHA256} {
+ // The official build for this machine: the certified pins on amd64.
+ executable, codeModeHost, ok := ReleasePins(runtime.GOARCH)
+ if !ok {
+ t.Fatalf("no pinned Codex 0.165.0 build for %s", runtime.GOARCH)
+ }
+ for name, want := range map[string]string{"codex": executable, "codex-code-mode-host": codeModeHost} {
f, err := os.Open(filepath.Join(bin, name))
if os.IsNotExist(err) {
- t.Skip("pinned Codex 0.165.0 binaries absent; empty-home replay requires the local pinned installation")
+ testci.Absent(t, "pinned Codex 0.165.0 binaries absent; empty-home replay requires the local pinned installation")
}
if err != nil {
t.Fatal(err)
@@ -126,6 +132,7 @@ func TestCodexEmptyHomeReplay(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ f.l.digest, f.l.hostDigest = executable, codeModeHost
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err = f.l.Open(ctx, f.launch)
diff --git a/internal/testci/absent_test.go b/internal/testci/absent_test.go
new file mode 100644
index 00000000..65de61b4
--- /dev/null
+++ b/internal/testci/absent_test.go
@@ -0,0 +1,37 @@
+package testci
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+)
+
+// recorder stands in for a test, so Absent's verdict can be read.
+type recorder struct {
+ testing.TB
+ skipped, failed string
+}
+
+func (r *recorder) Helper() {}
+func (r *recorder) Skip(args ...any) { r.skipped = fmt.Sprint(args...) }
+func (r *recorder) Fatalf(f string, a ...any) { r.failed = fmt.Sprintf(f, a...) }
+
+func TestAbsentSkipsOnADeveloperMachine(t *testing.T) {
+ t.Setenv(ToolsRequired, "")
+ r := &recorder{TB: t}
+ Absent(r, "pinned program absent")
+ if r.skipped != "pinned program absent" || r.failed != "" {
+ t.Fatalf("want a skip, got skip %q fail %q", r.skipped, r.failed)
+ }
+}
+
+// Where CI installs the pinned programs, a missing one is a failure: a
+// skip there would be a green run that tested nothing.
+func TestAbsentFailsWhereToolsAreRequired(t *testing.T) {
+ t.Setenv(ToolsRequired, "1")
+ r := &recorder{TB: t}
+ Absent(r, "pinned program absent")
+ if r.skipped != "" || !strings.Contains(r.failed, "pinned program absent") || !strings.Contains(r.failed, ToolsRequired) {
+ t.Fatalf("want a failure naming the program and the variable, got skip %q fail %q", r.skipped, r.failed)
+ }
+}
diff --git a/internal/testci/box_test.go b/internal/testci/box_test.go
new file mode 100644
index 00000000..b1d1c38e
--- /dev/null
+++ b/internal/testci/box_test.go
@@ -0,0 +1,57 @@
+package testci_test
+
+import (
+ "encoding/json"
+ "os"
+ "regexp"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+)
+
+// The CI box fetches the pinned programs by the digests in
+// scripts/ci-box.json. They must be the ones the tests check: the
+// certified pins on amd64 and the arm64 pins beside them.
+func TestBoxPinsMatchTheCode(t *testing.T) {
+ raw, err := os.ReadFile("../../scripts/ci-box.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var box struct {
+ Image string
+ Tools map[string]map[string]json.RawMessage
+ }
+ if err = json.Unmarshal(raw, &box); err != nil {
+ t.Fatal(err)
+ }
+ if !regexp.MustCompile(`@sha256:[a-f0-9]{64}$`).MatchString(box.Image) {
+ t.Errorf("the box image %q is not pinned by digest", box.Image)
+ }
+ digest := regexp.MustCompile(`^[a-f0-9]{64}$`)
+ for _, arch := range []string{"amd64", "arm64"} {
+ executable, host, ok := codex.ReleasePins(arch)
+ pin, okClaude := claude.ReleasePin(arch)
+ if !ok || !okClaude {
+ t.Fatalf("no pins for %s", arch)
+ }
+ want := map[string]string{"codex": executable, "codex-code-mode-host": host, "claude": pin, "bwrap": ""}
+ for name, sum := range want {
+ var entry struct{ URL, SHA256 string }
+ if err = json.Unmarshal(box.Tools[name][arch], &entry); err != nil {
+ t.Errorf("%s %s: %v", name, arch, err)
+ continue
+ }
+ if !strings.HasPrefix(entry.URL, "https://") || !digest.MatchString(entry.SHA256) {
+ t.Errorf("%s %s: want an https URL and a SHA-256, got %q %q", name, arch, entry.URL, entry.SHA256)
+ }
+ if sum != "" && entry.SHA256 != sum {
+ t.Errorf("%s %s: the box fetches %s, the code pins %s", name, arch, entry.SHA256, sum)
+ }
+ }
+ }
+ if len(box.Tools) != 4 {
+ t.Errorf("the box fetches %d programs; this test knows 4", len(box.Tools))
+ }
+}
diff --git a/internal/testci/testci.go b/internal/testci/testci.go
index 568a785a..2485149e 100644
--- a/internal/testci/testci.go
+++ b/internal/testci/testci.go
@@ -283,3 +283,19 @@ func quarantineListed(test string) (bool, error) {
}
return false, s.Err()
}
+
+// ToolsRequired is the environment variable CI sets to 1 on a machine it
+// has given every pinned program the tests run (make ci-box does).
+const ToolsRequired = "EQUIPO_TEST_TOOLS_REQUIRED"
+
+// Absent reports that a pinned program the test runs is not installed.
+// On a developer's machine that skips the test. Where ToolsRequired is 1
+// it fails it: a skip there would be a green run that tested nothing.
+func Absent(t testing.TB, what string) {
+ t.Helper()
+ if os.Getenv(ToolsRequired) == "1" {
+ t.Fatalf("%s, and %s=1 says this machine has it", what, ToolsRequired)
+ return
+ }
+ t.Skip(what)
+}
diff --git a/scripts/ci-box-enter.sh b/scripts/ci-box-enter.sh
new file mode 100755
index 00000000..de40ce48
--- /dev/null
+++ b/scripts/ci-box-enter.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# The first program in Equipo's CI box (scripts/ci-box.py run). It starts
+# as root, makes the box look like a runner host, and runs the command as
+# the job's own user:
+#
+# - /etc on a filesystem of its own. Containment lays an overlay over
+# /etc, and the kernel refuses one whose lower layer is the
+# container's own overlay root;
+# - a home directory, with the pinned programs where tests look for them;
+# - a cgroup v2 subtree the user may write, at the path systemd gives a
+# user session. The cgroup move test moves a contained process between
+# two cgroups there, as a person on a runner host can.
+#
+# Tests never run as root: bubblewrap and file permissions behave
+# differently for root, and no runner runs as root. The one exception is a
+# rootless engine on a developer's machine, whose root is the caller.
+set -eu
+
+uid=${EQUIPO_BOX_UID:-0}
+gid=${EQUIPO_BOX_GID:-0}
+home=/home/ci
+
+if [ "$(id -u)" != 0 ]; then
+ exec "$@"
+fi
+
+mkdir -p /run/equipo-etc
+mount -t tmpfs -o mode=0755 tmpfs /run/equipo-etc
+cp -a /etc/. /run/equipo-etc/
+mount --bind /run/equipo-etc /etc
+
+grep -q '^ci:' /etc/passwd || [ "$uid" = 0 ] || echo "ci:x:$uid:$gid:Equipo CI:$home:/bin/sh" >>/etc/passwd
+grep -q '^ci:' /etc/group || [ "$gid" = 0 ] || echo "ci:x:$gid:" >>/etc/group
+mkdir -p "$home/.local/share/equipo/try"
+chown "$uid:$gid" "$home" "$home/.local" "$home/.local/share" "$home/.local/share/equipo" "$home/.local/share/equipo/try"
+
+base=/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service
+if mkdir -p "$base/ci.scope" 2>/dev/null && echo $$ >"$base/ci.scope/cgroup.procs" 2>/dev/null; then
+ for file in "$base" "$base/cgroup.procs" "$base/cgroup.threads" "$base/cgroup.subtree_control" \
+ "$base/ci.scope" "$base/ci.scope/cgroup.procs" "$base/ci.scope/cgroup.threads" "$base/ci.scope/cgroup.subtree_control"; do
+ chown "$uid:$gid" "$file"
+ done
+else
+ echo "ci-box: no writable cgroup v2 tree here; the cgroup move test will fail" >&2
+fi
+
+export HOME="$home"
+if [ "$uid" = 0 ]; then
+ exec "$@"
+fi
+export USER=ci LOGNAME=ci
+exec setpriv --reuid "$uid" --regid "$gid" --clear-groups -- "$@"
diff --git a/scripts/ci-box.json b/scripts/ci-box.json
new file mode 100644
index 00000000..6125e6a9
--- /dev/null
+++ b/scripts/ci-box.json
@@ -0,0 +1,68 @@
+{
+ "image": "public.ecr.aws/docker/library/golang:1.26.10-trixie@sha256:fd9a91f0ece5664556f4851d06dce5e5b505a71166dffd385a03ba9d200b6983",
+ "tools": {
+ "bwrap": {
+ "version": "bubblewrap 0.11.0",
+ "amd64": {
+ "url": "https://snapshot.debian.org/file/817a2e6186906394f63696c2b289f0f19e45b8d3",
+ "archive_sha256": "7a541ad9d12b23db7082ed3bf1f6d5253f23439cdfa7c28b4e022d0a602a19d6",
+ "format": "deb",
+ "member": "./usr/bin/bwrap",
+ "sha256": "0dfa36b98ada69568aaaa741fe210d2150a1441433bd13c428137d6a972a959c"
+ },
+ "arm64": {
+ "url": "https://snapshot.debian.org/file/ef2d83d8c40c740e00a7dde0ffffff41e5f855ee",
+ "archive_sha256": "c838daebddb7fe169ebb461612e90b1fcb981de838f81bfbecf26d45ab5a71ee",
+ "format": "deb",
+ "member": "./usr/bin/bwrap",
+ "sha256": "ef2316fc741885e6d7b422661ea60c20cbe07ec7eb592a4c2370cbcb90843b59"
+ }
+ },
+ "codex": {
+ "version": "codex-cli 0.165.0",
+ "amd64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-x86_64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "be635d3486a5bd060d0fff582ae6d30160280c31344dd85719707fa920e187f0",
+ "format": "tar.gz",
+ "member": "codex-x86_64-unknown-linux-musl",
+ "sha256": "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5"
+ },
+ "arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-aarch64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "6522e056d0be7f531da915c9a81ae05bc70811b782542499cc0a9776d3abf5d3",
+ "format": "tar.gz",
+ "member": "codex-aarch64-unknown-linux-musl",
+ "sha256": "b32ece31af06440da980b733fb8fefdd1f193439595fda84096f1caaceec543f"
+ }
+ },
+ "codex-code-mode-host": {
+ "amd64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-code-mode-host-x86_64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "9577b09b2a546eeb3da8a09807de6d58fbaa207755256390113772ea4f05235e",
+ "format": "tar.gz",
+ "member": "codex-code-mode-host-x86_64-unknown-linux-musl",
+ "sha256": "522935d4392ec9674fab60b239b5495992c6a93e4deb65113a216b6f5451ccd4"
+ },
+ "arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-code-mode-host-aarch64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "400956c325a2118768029f235958b7d2fd2ea4e59c5466d336fb4fb7f0e94b61",
+ "format": "tar.gz",
+ "member": "codex-code-mode-host-aarch64-unknown-linux-musl",
+ "sha256": "fd7a4a1f29871fb0015c19ad2f885ef6a878244643260703e17663418695aa14"
+ }
+ },
+ "claude": {
+ "version": "2.1.312 (Claude Code)",
+ "amd64": {
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.312/linux-x64/claude",
+ "format": "raw",
+ "sha256": "4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d"
+ },
+ "arm64": {
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.312/linux-arm64/claude",
+ "format": "raw",
+ "sha256": "dc4af28917455e009d26704b82a438353a06149e825b6cdf782908b2d28661f5"
+ }
+ }
+ }
+}
diff --git a/scripts/ci-box.py b/scripts/ci-box.py
new file mode 100755
index 00000000..5f96fd6d
--- /dev/null
+++ b/scripts/ci-box.py
@@ -0,0 +1,453 @@
+#!/usr/bin/env python3
+"""Run Equipo's CI in its box: one container that looks like a runner host.
+
+ scripts/ci-box.py prepare fetch the pinned tools and the image; on CI
+ also deepen the clone and set file times
+ scripts/ci-box.py run CMD... run CMD in the box, from the repository root
+ scripts/ci-box.py cache report the Go caches and trim them to fit
+ scripts/ci-box.py facts print what this machine is
+
+amadan's hosted CI gives each job a fresh arm64 machine with Docker and no
+bubblewrap. Equipo's tests start real containment: they need bubblewrap
+0.11.0 exactly, the pinned Codex and Claude programs, user namespaces and
+a delegated cgroup. The box supplies those. It is the official Go image
+on Debian 13 (the runner host's own system), run privileged, with the
+pinned programs mounted where a runner host has them:
+
+ /usr/bin/bwrap Debian's 0.11.0-2+deb13u1 build
+ /usr/local/bin/codex codex 0.165.0
+ ~/.local/share/equipo/try/bin codex, its code mode host, claude
+
+Every pinned program is fetched by URL and checked against the SHA-256 in
+scripts/ci-box.json, for this machine's architecture. The job's checkout
+and Go caches are mounted at fixed paths, so Go's build and test caches
+hold from one fresh machine to the next. Inside, the command runs as an
+ordinary user (scripts/ci-box-enter.sh), never as root.
+
+This file also runs on the CI machine itself, outside the box, where
+python3 is 3.9: keep it to that.
+"""
+import hashlib
+import io
+import json
+import lzma
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.request
+from concurrent.futures import ThreadPoolExecutor
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+PINS = os.path.join(ROOT, "scripts", "ci-box.json")
+
+# Where things sit inside the box. Fixed, whatever the job's own paths
+# are: Go keys a compiled package on its source directory, so a checkout
+# that moved would recompile everything.
+WORK = "/work/equipo"
+GOCACHE = "/cache/go-build"
+GOMODCACHE = "/cache/go-mod"
+HOME = "/home/ci"
+TRY_BIN = HOME + "/.local/share/equipo/try/bin"
+
+# Fetched programs get this modification time (2026-01-01), and tracked
+# files get one made from their content: make test fingerprints programs
+# by size and time, and go test keys a cached result on the size and time
+# of each file the test opened. A fresh clone would stamp everything
+# "now" and no result would ever be reused.
+TOOL_TIME = 1767225600
+FILE_TIME_BASE = 1577836800 # 2020-01-01
+FILE_TIME_SPAN = 5 * 365 * 86400
+
+# The hosted cache holds 6 GiB unpacked and 2 GiB compressed, and a save
+# over either is dropped whole. Trim well under it.
+CACHE_LIMIT = 4 * 1024 ** 3
+
+# Environment a step may see inside the box, besides what run() sets.
+PASS_PREFIXES = ("AMADAN_", "EQUIPO_")
+PASS_NAMES = ("CI", "GOFLAGS", "GOPROXY", "GOPRIVATE", "GONOSUMDB", "GONOPROXY", "GOSUMDB", "GOAUTH", "TERM")
+
+
+def say(text):
+ print("ci-box: " + text, flush=True)
+
+
+def arch():
+ machine = platform.machine().lower()
+ name = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(machine)
+ if name is None:
+ sys.exit("ci-box: no pinned tools for a %s machine" % machine)
+ return name
+
+
+def pins():
+ with open(PINS) as f:
+ return json.load(f)
+
+
+def box_dir():
+ path = os.environ.get("EQUIPO_CI_BOX_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "equipo-ci-box")
+ os.makedirs(path, exist_ok=True)
+ return path
+
+
+def tools_dir():
+ return os.path.join(box_dir(), "tools", arch(), "bin")
+
+
+def boxed():
+ """Whether commands go in the box. EQUIPO_CI_BOX=on or off decides;
+ unset, a machine that already has what the box supplies (the pinned
+ bubblewrap and a codex) is a runner host, and commands run directly."""
+ mode = os.environ.get("EQUIPO_CI_BOX", "")
+ if mode in ("on", "off"):
+ return mode == "on"
+ if mode:
+ sys.exit("ci-box: EQUIPO_CI_BOX is %r; use on or off" % mode)
+ try:
+ version = subprocess.check_output(["/usr/bin/bwrap", "--version"], stderr=subprocess.DEVNULL, text=True).strip()
+ except (OSError, subprocess.CalledProcessError):
+ version = ""
+ return version != pins()["tools"]["bwrap"]["version"] or shutil.which("codex") is None
+
+
+# Pinned tools.
+
+def sha256_file(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+
+def download(url, dest):
+ """Fetch url into dest and return its SHA-256; three attempts."""
+ last = None
+ for attempt in range(3):
+ try:
+ h = hashlib.sha256()
+ request = urllib.request.Request(url, headers={"User-Agent": "equipo-ci-box"})
+ with urllib.request.urlopen(request, timeout=120) as response, open(dest, "wb") as out:
+ for block in iter(lambda: response.read(1 << 20), b""):
+ h.update(block)
+ out.write(block)
+ return h.hexdigest()
+ except Exception as e: # a CDN's bad minute is not this change's failure
+ last = e
+ time.sleep(2 * (attempt + 1))
+ raise RuntimeError("fetch %s: %s" % (url, last))
+
+
+def deb_data(path):
+ """The data archive of a .deb: an ar file whose data.tar.* member holds the files."""
+ with open(path, "rb") as f:
+ if f.read(8) != b"!<arch>\n":
+ raise RuntimeError("not a .deb: " + path)
+ while True:
+ header = f.read(60)
+ if len(header) < 60:
+ raise RuntimeError("no data archive in " + path)
+ name = header[:16].decode().strip().rstrip("/")
+ size = int(header[48:58].decode().strip())
+ body = f.read(size + (size & 1))[:size]
+ if name.startswith("data.tar"):
+ if name.endswith(".xz"):
+ body = lzma.decompress(body)
+ elif name != "data.tar":
+ raise RuntimeError("unsupported .deb compression: " + name)
+ return body
+
+
+def extract(archive, fmt, member, dest):
+ if fmt == "raw":
+ shutil.copyfile(archive, dest)
+ return
+ if fmt == "deb":
+ tar = tarfile.open(fileobj=io.BytesIO(deb_data(archive)))
+ elif fmt == "tar.gz":
+ tar = tarfile.open(archive, "r:gz")
+ else:
+ raise RuntimeError("unknown archive format " + fmt)
+ with tar:
+ source = tar.extractfile(member)
+ if source is None:
+ raise RuntimeError("%s is not a file in the archive" % member)
+ with source, open(dest, "wb") as out:
+ shutil.copyfileobj(source, out)
+
+
+def fetch_tool(name, pin, directory):
+ target = os.path.join(directory, name)
+ if os.path.isfile(target) and sha256_file(target) == pin["sha256"]:
+ return "%s: present" % name
+ started = time.time()
+ with tempfile.TemporaryDirectory(dir=directory) as scratch:
+ archive = os.path.join(scratch, "archive")
+ got = download(pin["url"], archive)
+ want = pin.get("archive_sha256", pin["sha256"])
+ if got != want:
+ raise RuntimeError("%s: %s has SHA-256 %s, pinned %s" % (name, pin["url"], got, want))
+ out = os.path.join(scratch, name)
+ extract(archive, pin["format"], pin.get("member"), out)
+ if sha256_file(out) != pin["sha256"]:
+ raise RuntimeError("%s: the program in %s is not the pinned one" % (name, pin["url"]))
+ os.chmod(out, 0o755)
+ os.utime(out, (TOOL_TIME, TOOL_TIME))
+ os.replace(out, target)
+ return "%s: fetched and verified in %.1fs" % (name, time.time() - started)
+
+
+def fetch_tools():
+ directory = tools_dir()
+ os.makedirs(directory, exist_ok=True)
+ machine = arch()
+ jobs = []
+ for name, tool in sorted(pins()["tools"].items()):
+ if machine not in tool:
+ sys.exit("ci-box: %s has no pin for %s" % (name, machine))
+ jobs.append((name, tool[machine]))
+ with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
+ for line in pool.map(lambda job: fetch_tool(job[0], job[1], directory), jobs):
+ say(line)
+ return directory
+
+
+# The container engine and the image.
+
+def engine():
+ name = os.environ.get("EQUIPO_CI_ENGINE")
+ if name:
+ return name
+ for name in ("docker", "podman"):
+ if shutil.which(name):
+ return name
+ sys.exit("ci-box: neither docker nor podman is installed")
+
+
+def pull_image():
+ image = pins()["image"]
+ if subprocess.call([engine(), "image", "inspect", image], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
+ say("image present")
+ return
+ started = time.time()
+ for attempt in range(3):
+ if subprocess.call([engine(), "pull", "-q", image], stdout=subprocess.DEVNULL) == 0:
+ say("image pulled in %.1fs" % (time.time() - started))
+ return
+ time.sleep(3 * (attempt + 1))
+ sys.exit("ci-box: could not pull " + image)
+
+
+# The checkout.
+
+def git(*args):
+ return subprocess.run(["git", "-C", ROOT] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+
+def deepen():
+ """A hosted job clones one commit. gitleaks reads history, and the
+ mixed-version test builds an older release, so fetch the rest."""
+ if git("rev-parse", "--is-shallow-repository").stdout.strip() != b"true":
+ return
+ started = time.time()
+ result = git("fetch", "--quiet", "--unshallow", "origin")
+ if result.returncode != 0:
+ say("WARNING: the clone is one commit deep and could not be deepened: " +
+ result.stderr.decode(errors="replace").strip()[-400:])
+ return
+ say("clone deepened in %.1fs" % (time.time() - started))
+
+
+def set_file_times():
+ """Give every tracked file a modification time made from its content,
+ and every directory one fixed time. See TOOL_TIME."""
+ listed = git("ls-files", "-s", "-z")
+ if listed.returncode != 0:
+ sys.exit("ci-box: git ls-files: " + listed.stderr.decode(errors="replace"))
+ directories = {ROOT}
+ count = 0
+ for entry in listed.stdout.split(b"\0"):
+ if not entry:
+ continue
+ meta, name = entry.split(b"\t", 1)
+ mode, blob = meta.split()[:2]
+ if mode == b"160000":
+ continue
+ path = os.path.join(ROOT, os.fsdecode(name))
+ stamp = FILE_TIME_BASE + int(blob[:8], 16) % FILE_TIME_SPAN
+ try:
+ os.utime(path, (stamp, stamp), follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ count += 1
+ parent = os.path.dirname(path)
+ while parent not in directories:
+ directories.add(parent)
+ parent = os.path.dirname(parent)
+ for directory in directories:
+ os.utime(directory, (FILE_TIME_BASE, FILE_TIME_BASE))
+ git("update-index", "-q", "--refresh")
+ say("file times set from content: %d files, %d directories" % (count, len(directories)))
+
+
+# Running a command in the box.
+
+def go_env(name):
+ value = os.environ.get(name)
+ if value:
+ return value
+ return subprocess.check_output(["go", "env", name], text=True).strip()
+
+
+def run(command):
+ if not command:
+ sys.exit("ci-box: run what?")
+ if not boxed():
+ os.chdir(ROOT)
+ os.execvp(command[0], command)
+ tools = tools_dir()
+ missing = [name for name in pins()["tools"] if not os.path.isfile(os.path.join(tools, name))]
+ if missing:
+ sys.exit("ci-box: %s not fetched; run scripts/ci-box.py prepare first" % ", ".join(sorted(missing)))
+ gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE")
+ for path in (gocache, gomodcache):
+ os.makedirs(path, exist_ok=True)
+ tool = engine()
+ args = [tool, "run", "--rm", "--privileged", "--cgroupns=private",
+ "--tmpfs", "/tmp:exec,mode=1777",
+ "-v", ROOT + ":" + WORK, "-w", WORK,
+ "-v", gocache + ":" + GOCACHE, "-v", gomodcache + ":" + GOMODCACHE,
+ "-v", os.path.join(tools, "bwrap") + ":/usr/bin/bwrap:ro",
+ "-v", os.path.join(tools, "codex") + ":/usr/local/bin/codex:ro",
+ "-v", tools + ":" + TRY_BIN + ":ro"]
+ if tool == "docker":
+ args.append("--init") # reaps the orphans the containment tests leave on purpose
+ for mount in filter(None, os.environ.get("EQUIPO_CI_BOX_MOUNTS", "").split(os.pathsep)):
+ args += ["-v", mount]
+ env = {
+ "GOCACHE": GOCACHE, "GOMODCACHE": GOMODCACHE,
+ "EQUIPO_TEST_TOOLS_REQUIRED": "1",
+ "EQUIPO_BOX_UID": str(os.getuid()), "EQUIPO_BOX_GID": str(os.getgid()),
+ }
+ if tool == "podman" and os.getuid() != 0:
+ # Rootless podman, a developer's machine: its root is the caller, and
+ # any other user inside could not write the checkout. Tests then run
+ # as that root, which is good for a first look and not for a verdict.
+ env["EQUIPO_BOX_UID"] = env["EQUIPO_BOX_GID"] = "0"
+ for name, value in os.environ.items():
+ if name in PASS_NAMES or name.startswith(PASS_PREFIXES):
+ env.setdefault(name, value)
+ for name in sorted(env):
+ args += ["-e", name + "=" + env[name]]
+ args += [pins()["image"], WORK + "/scripts/ci-box-enter.sh"] + command
+ os.execvp(args[0], args)
+
+
+# The Go caches.
+
+def tree_size(path):
+ total = files = 0
+ for directory, _, names in os.walk(path):
+ for name in names:
+ try:
+ total += os.lstat(os.path.join(directory, name)).st_size
+ files += 1
+ except OSError:
+ pass
+ return total, files
+
+
+def cache():
+ """Report the caches and, past CACHE_LIMIT, drop what this job did not
+ read. A restore stamps every entry "now", so Go's own five-day trim
+ never fires on a hosted machine and the cache would grow until its
+ save is refused."""
+ if not boxed():
+ return # a runner host's cache is its own to trim
+ gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE")
+ for name, path in (("build cache", gocache), ("module cache", gomodcache)):
+ size, files = tree_size(path)
+ say("%s %s: %.2f GiB in %d files" % (name, path, size / 1024 ** 3, files))
+ size, _ = tree_size(gocache)
+ marker = os.path.join(box_dir(), "prepared")
+ if size <= CACHE_LIMIT or not os.path.exists(marker):
+ return
+ since = os.stat(marker).st_mtime
+ dropped = kept = 0
+ for directory, _, names in os.walk(gocache):
+ for name in names:
+ path = os.path.join(directory, name)
+ try:
+ st = os.lstat(path)
+ if max(st.st_atime, st.st_mtime) < since:
+ os.unlink(path)
+ dropped += st.st_size
+ else:
+ kept += st.st_size
+ except OSError:
+ pass
+ say("build cache over %.1f GiB: dropped %.2f GiB this job did not read, kept %.2f GiB" %
+ (CACHE_LIMIT / 1024 ** 3, dropped / 1024 ** 3, kept / 1024 ** 3))
+
+
+def facts():
+ def out(*command):
+ try:
+ return subprocess.check_output(list(command), stderr=subprocess.STDOUT, text=True).strip()
+ except Exception as e:
+ return "unavailable (%s)" % e
+
+ memory = "unknown"
+ try:
+ with open("/proc/meminfo") as f:
+ memory = "%.0f GiB" % (int(f.readline().split()[1]) / 1024 ** 2)
+ except OSError:
+ pass
+ say("machine: %s, %s CPUs, %s memory, kernel %s" % (platform.machine(), os.cpu_count(), memory, platform.release()))
+ say("python %s; %s" % (platform.python_version(), out(engine(), "--version")))
+ say("user namespaces allowed: " + out("cat", "/proc/sys/user/max_user_namespaces"))
+ say("cgroup: " + out("stat", "-fc", "%T", "/sys/fs/cgroup"))
+ for path in ("/tmp", ROOT, box_dir()):
+ say("disk %s: %s" % (path, out("df", "-h", "--output=fstype,size,avail", path).replace("\n", " | ")))
+
+
+def prepare():
+ if not boxed():
+ return # a runner host: nothing to fetch
+ started = time.time()
+ facts()
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ image = pool.submit(pull_image)
+ fetch_tools()
+ image.result()
+ if os.environ.get("AMADAN_CI") == "1":
+ deepen()
+ set_file_times()
+ with open(os.path.join(box_dir(), "prepared"), "w") as f:
+ f.write("%d\n" % time.time())
+ say("ready in %.1fs" % (time.time() - started))
+
+
+def main(argv):
+ if argv == ["prepare"]:
+ return prepare()
+ if argv[:1] == ["run"]:
+ return run(argv[1:])
+ if argv == ["cache"]:
+ return cache()
+ if argv == ["facts"]:
+ return facts()
+ if argv == ["tools"]:
+ print(fetch_tools())
+ return 0
+ print(__doc__, file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/ci-test.py b/scripts/ci-test.py
index a47bd215..8242be13 100755
--- a/scripts/ci-test.py
+++ b/scripts/ci-test.py
@@ -11,7 +11,8 @@ The slow packages each have a lane of their own and "rest" holds every
other package. CI runs the lanes side by side as the shards of one step,
.amadan/ci.d/30-test@N: amadan runs separate steps one after another, and
a step's @N shards are how it runs work in parallel. A lane's packages
-pass or fail in that shard's own log.
+pass or fail in that shard's own log. The quarantine and the runner host
+checks (make runner-host) are the last two shards of the same step.
Results are cached: go test replays a pass for a package whose test
binary, declared files and environment are unchanged (internal/testci
@@ -35,8 +36,9 @@ MODULE = "amadan.net/oficina/equipo"
TAGS = "testbuild"
TIMEOUT = "15m"
-# Lane order is the shard index: shard 0 runs the first lane. Keep the
-# count in .amadan/ci.d/30-test@N equal to the number of lanes.
+# Lane order is the shard index: shard 0 runs the first lane. After the
+# lanes come EXTRA_SHARDS. Keep the count in .amadan/ci.d/30-test@N equal
+# to the number of lanes plus the extra shards.
LANES = [
("headless", ["./internal/headless"]),
("thintest", ["./internal/thintest"]),
@@ -47,6 +49,10 @@ LANES = [
("rest", None), # every package no other lane names
]
+# Shards after the lanes: work that is not a lane of packages but runs
+# beside them, each a make target.
+EXTRA_SHARDS = ["test-quarantine", "runner-host"]
+
# Packages whose results must never come from the cache, with the reason.
# They run with -count=1 inside their lane.
UNCACHED = {}
@@ -197,10 +203,15 @@ def run_all():
def run_shard():
index = int(os.environ.get("AMADAN_SHARD", "-1"))
count = int(os.environ.get("AMADAN_SHARD_COUNT", "0"))
- if count != len(LANES) or not 0 <= index < count:
- sys.exit(f"ci-test: shard {index} of {count}, but there are {len(LANES)} lanes; "
- f"name the step 30-test@{len(LANES)}")
- return run_lane(LANES[index][0])
+ shards = len(LANES) + len(EXTRA_SHARDS)
+ if count != shards or not 0 <= index < count:
+ sys.exit(f"ci-test: shard {index} of {count}, but there are {len(LANES)} lanes and "
+ f"{len(EXTRA_SHARDS)} extra shards; name the step 30-test@{shards}")
+ if index < len(LANES):
+ return run_lane(LANES[index][0])
+ target = EXTRA_SHARDS[index - len(LANES)]
+ print(f"test shard {index}: make {target}", flush=True)
+ return subprocess.call(["make", "--no-print-directory", target])
# The quarantine.
diff --git a/scripts/runner-prerequisites.py b/scripts/runner-prerequisites.py
index 54abe80f..15e62e3c 100644
--- a/scripts/runner-prerequisites.py
+++ b/scripts/runner-prerequisites.py
@@ -3,13 +3,19 @@
import hashlib
import os
from pathlib import Path
+import platform
import re
import shutil
import sys
root = Path(__file__).resolve().parent.parent
-source = (root / "internal/runner/provider/codex/launcher.go").read_text()
-pin = re.search(r'const ExecutableSHA256 = "([a-f0-9]{64})"', source)
+codex = root / "internal/runner/provider/codex"
+# The certified pin on x86-64; the same release's arm64 build on an arm64
+# CI machine (pins.go), where no certified release runs.
+if platform.machine().lower() in ("aarch64", "arm64"):
+ pin = re.search(r'ExecutableSHA256Arm64\s+= "([a-f0-9]{64})"', (codex / "pins.go").read_text())
+else:
+ pin = re.search(r'const ExecutableSHA256 = "([a-f0-9]{64})"', (codex / "launcher.go").read_text())
path = os.environ.get("EQUIPO_CODEX_PATH") or shutil.which("codex")
try:
if not pin or not path or not os.access(path, os.X_OK):