oficina / equipo Public

headless: hosted checks scenarios for the dev drill

Task 34's prerequisite 4: hosted-pass, hosted-fail, hosted-new-module
and hosted-slow. Against staging only, and only when named, each adds
the scratch project (EQUIPO_STAGING_HOSTED_PROJECT, its default branch
the in-code hostedFixture), turns the hosted setting on through the
owners' route with the suite person's session, asks for one change,
waits for the first checks step to end, cancels the task, reads the
base checks SHA and the step's hosted jobs from staging's database copy,
and records witness/TestStaging/<name>.result in report.json and a
HOSTED-RESULT line. staging-thin.py passes the person's session file
and the read-only query command.

Offline: registration and selection, the gate, the result line, the
query on the real schema, the setting's route on a local instance, and
the scratch project's checks on each candidate.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2a88486048093c01dcbb206351c77e45f7796a32 parent abd527b
7 files changed, +829 −6
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +35 −0
  • internal/headless/hosted_fixture_test.go +295 −0
  • internal/headless/hosted_test.go +470 −0
  • internal/headless/scenarios_test.go +9 −1
  • scripts/staging-thin-test.py +9 −0
  • scripts/staging-thin.py +10 −4
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index d08eb6f8..1fe53609 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -75,7 +75,7 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only
perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
-size internal/headless - 13400 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files; restart wait; live site waits; card answer; scenario 7; Mac M9, mixed versions; 13400.
+size internal/headless - 14173 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files; restart wait; live site waits; card answer; scenario 7; Mac M9, mixed versions; 13400. Hosted slice 2: the dev drill's four hosted checks scenarios, their scratch project and its offline checks; 14173.
size internal/thintest - 42664 Protocol 31 to 38 contracts, Design end to end; hosted slice 2 Task 26: protocol 39 and 40 rows, older primaries' Research ends runner_update_needed; 42664.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 77020981..0b42af39 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -3529,3 +3529,38 @@ drifting computed value would be refused as an update); 7.2 uses `cert bundle ..
Green: `plan_check_test.py` (119), `make hosted-infra-check`, `go test ./cmd/equipo-hosted-certify`,
`-run '^TestPlanInvocationsParse$' ./internal/hostedops`, `-run TestPlan ./cmd/equipo-hosted-image`,
`make budget`, and `bash -n` on all 39 `sh` blocks.
+
+## Headless hosted scenarios (Task 34 prerequisite 4, 2026-12-02)
+
+`internal/headless` gains `hosted-pass`, `hosted-fail`, `hosted-new-module` and `hosted-slow`
+(`hosted_test.go`). Each, against staging only and only when named in `EQUIPO_STAGING_SCENARIOS`:
+adds the scratch project `EQUIPO_STAGING_HOSTED_PROJECT` (its default branch is `hostedFixture`, a
+dependency-free Go module whose base-pinned `.amadan/ci` runs `go test`), turns "Run checks on a
+hosted machine" on through `POST /settings/hosted` with the suite person's session at the revision
+the owners' page shows, asks for one change, waits up to 40 minutes for the first checks step to
+end, cancels the task (no fix round or review on a paid VM), reads the base checks SHA and the
+step's hosted jobs from staging's database copy, and records `witness/TestStaging/<name>` in
+`report.json` with `result`, plus a `HOSTED-RESULT <name> <result>` line. `result` is
+`state= checks= reason= shown= sandbox= certified= base_checks= jobs=`. The outcome is observed,
+not asserted. `scripts/staging-thin.py suite` passes `EQUIPO_STAGING_COOKIE_FILE` (this run's
+person's 0600 session file) and `EQUIPO_STAGING_DB_QUERY` (`carlos db query ... --sql`).
+`.rastrillo/budgets.txt` raises `internal/headless` to 14173.
+
+Green: `go test ./internal/headless -run '^(TestHosted.*|TestStaging)$'`, `-run
+'^TestHeadless$/^hosted'` (four skips), `go vet ./internal/headless`, `scripts/staging-thin-test.py`
+(17), `make budget`.
+
+Mutation checks, each restored:
+- **H1** `hostedGate` without `only == ""` (a whole staging run would launch VMs): `TestHostedGate`
+ FAILED `a whole staging run: skip "" fail ""`.
+- **H2** `certified` for any sandbox but `none`: `TestHostedResultLine` FAILED, `sandbox=hosted
+ certified=yes` and `sandbox=seatbelt certified=yes` against `certified=no` (it survived the first
+ table, which had no such sandbox; the two rows were added).
+- **H3** the step id guard as `^[^;]{1,80}$`: `TestHostedRecordQuery` FAILED `step id "s1' OR
+ '1'='1" put in the query`.
+- **H4** the contract without `scratch_test.go`: `TestHostedFixtureChecks` FAILED `the base does
+ not pin scratch_test.go`.
+- **H5** `staging-thin.py` passing the owner's cookie file: `test_fresh_runs_and_green_record`
+ FAILED its `AssertionError` on the file name.
+- **H6** the setting always saved at revision 0: `TestHostedSettingRoute` FAILED `saving the hosted
+ setting ...: 409 {}` on the second save.
diff --git a/internal/headless/hosted_fixture_test.go b/internal/headless/hosted_fixture_test.go
new file mode 100644
index 00000000..b780f774
--- /dev/null
+++ b/internal/headless/hosted_fixture_test.go
@@ -0,0 +1,295 @@
+package headless
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/checkrun"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/depsbundle"
+ "amadan.net/oficina/equipo/internal/testci"
+ "amadan.net/oficina/equipo/internal/thintest"
+)
+
+// The hosted scenarios offline: their names and selection, when they run,
+// the result line, the database read and the setting's route against a
+// local instance, and the scratch project's checks on each candidate.
+
+func TestHostedScenariosRegistered(t *testing.T) {
+ var names []string
+ for _, sc := range scenarios {
+ names = append(names, sc.name)
+ }
+ for _, c := range hostedCases {
+ if n := strings.Count(","+strings.Join(names, ",")+",", ","+c.name+","); n != 1 {
+ t.Fatalf("%s registered %d times", c.name, n)
+ }
+ }
+ pick := func(only string) []string {
+ var out []string
+ for _, n := range names {
+ if selected(only, n) {
+ out = append(out, n)
+ }
+ }
+ return out
+ }
+ if got := pick("hosted-pass,hosted-fail,hosted-new-module"); !slices.Equal(got, []string{"hosted-pass", "hosted-fail", "hosted-new-module"}) {
+ t.Fatalf("the drill's three checks select %v", got)
+ }
+ if got := pick("hosted-slow"); !slices.Equal(got, []string{"hosted-slow"}) {
+ t.Fatalf("the drills' scenario selects %v", got)
+ }
+ if got := pick(""); len(got) != len(names) {
+ t.Fatalf("a whole run selects %d of %d", len(got), len(names))
+ }
+}
+
+func TestHostedGate(t *testing.T) {
+ for _, c := range []struct {
+ live bool
+ only, repo, cookie string
+ skip, fail bool
+ why string
+ }{
+ {false, "hosted-pass", "oficina/scratch", "/c", true, false, "a local run"},
+ {true, "", "oficina/scratch", "/c", true, false, "a whole staging run"},
+ {true, "hosted-fail", "oficina/scratch", "/c", true, false, "another scenario named"},
+ {true, "hosted-pass", "", "/c", false, true, "no scratch project"},
+ {true, "hosted-pass", "oficina/scratch", "", false, true, "no session"},
+ {true, "2_project,hosted-pass", "oficina/scratch", "/c", false, false, "named, with both"},
+ } {
+ skip, fail := hostedGate(c.live, "hosted-pass", c.only, c.repo, c.cookie)
+ if (skip != "") != c.skip || (fail != "") != c.fail {
+ t.Errorf("%s: skip %q fail %q", c.why, skip, fail)
+ }
+ }
+}
+
+func TestHostedResultLine(t *testing.T) {
+ base := strings.Repeat("b", 40)
+ for _, c := range []struct {
+ o hostedOutcome
+ want string
+ }{
+ {hostedOutcome{State: "done", Checks: "passed", Sandbox: "bubblewrap", BaseSHA: base, Recorded: true, BaseChecksSHA: base, Jobs: 1},
+ "state=done checks=passed reason=- shown=- sandbox=bubblewrap certified=yes base_checks=trusted jobs=1"},
+ {hostedOutcome{State: "done", Checks: "failed", Sandbox: "bubblewrap", BaseSHA: base, Recorded: true, Jobs: 1},
+ "state=done checks=failed reason=- shown=- sandbox=bubblewrap certified=yes base_checks=none jobs=1"},
+ {hostedOutcome{State: "done", Checks: "cannot_run", Reason: "deps_new_module", Shown: "needs_network", BaseSHA: base, Recorded: true, Jobs: 1},
+ "state=done checks=cannot_run reason=deps_new_module shown=needs_network sandbox=none certified=no base_checks=none jobs=1"},
+ {hostedOutcome{State: "done", Checks: "cannot_run", Reason: "hosted_unavailable", Shown: "hosted_unavailable", BaseSHA: base, Recorded: true, BaseChecksSHA: strings.Repeat("c", 40), Jobs: 2},
+ "state=done checks=cannot_run reason=hosted_unavailable shown=hosted_unavailable sandbox=none certified=no base_checks=other jobs=2"},
+ {hostedOutcome{State: "done", Checks: "passed", Sandbox: "none", BaseSHA: base},
+ "state=done checks=passed reason=- shown=- sandbox=none certified=no base_checks=unknown jobs=unknown"},
+ // Only bubblewrap is a certified VM's: hosted CI's or a Mac's is not.
+ {hostedOutcome{State: "done", Checks: "passed", Sandbox: "hosted", BaseSHA: base, Recorded: true},
+ "state=done checks=passed reason=- shown=- sandbox=hosted certified=no base_checks=none jobs=0"},
+ {hostedOutcome{State: "done", Checks: "passed", Sandbox: "seatbelt", BaseSHA: base, Recorded: true, BaseChecksSHA: base, Jobs: 0},
+ "state=done checks=passed reason=- shown=- sandbox=seatbelt certified=no base_checks=trusted jobs=0"},
+ {hostedOutcome{}, "state=- checks=- reason=- shown=- sandbox=none certified=no base_checks=unknown jobs=unknown"},
+ } {
+ if got := c.o.Line(); got != c.want {
+ t.Errorf("%+v:\n got %s\nwant %s", c.o, got, c.want)
+ }
+ }
+}
+
+// TestHostedRecordQuery runs the database read on the instance's own
+// schema and parses its row as the query tool prints it.
+func TestHostedRecordQuery(t *testing.T) {
+ inst := thintest.StartInstance(t)
+ base := strings.Repeat("a", 40)
+ now := time.Now().UTC()
+ for _, q := range []struct {
+ sql string
+ args []any
+ }{
+ {"INSERT INTO chat_steps(id, task_id, idx, person, state, attempt, specialist, base_sha, candidate_sha, base_checks_sha, revision, created_at, updated_at) VALUES ('s1', 'tk1', 2, ?, 'done', 1, 'checks', ?, ?, ?, 1, ?, ?)",
+ []any{thintest.Owner, base, strings.Repeat("c", 40), base, now, now}},
+ {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, stop_reason, admitted_at, revision) VALUES ('j2', 's1', 1, 'tk1', 'ended', '', ?, 1)", []any{now}},
+ {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, stop_reason, admitted_at, revision) VALUES ('j1', 's1', 1, 'tk1', 'failed', 'uncertified', ?, 1)", []any{now.Add(-time.Minute)}},
+ {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, admitted_at, revision) VALUES ('j3', 'other', 1, 'tk2', 'enrolled', ?, 1)", []any{now}},
+ } {
+ if _, err := inst.DB.Writer().Exec(q.sql, q.args...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ q, ok := hostedQuery("s1")
+ if !ok {
+ t.Fatal("a plain step id refused")
+ }
+ var row string
+ if err := inst.DB.Writer().QueryRow(q).Scan(&row); err != nil {
+ t.Fatal(err)
+ }
+ state, o, ok := parseHostedRow("result\n" + row + "\n(1 row)\n")
+ if !ok || state != "done" || o.BaseChecksSHA != base || o.Jobs != 2 || o.JobEnds != "failed:uncertified,ended:" || !jobsSettled(o.JobEnds) {
+ t.Fatalf("row %q: %s %+v %v", row, state, o, ok)
+ }
+ if jobsSettled("ended:,enrolled:") {
+ t.Fatal("a live job counted as settled")
+ }
+ for _, bad := range []string{"", "s1' OR '1'='1", "s1;", strings.Repeat("s", 81)} {
+ if _, ok := hostedQuery(bad); ok {
+ t.Fatalf("step id %q put in the query", bad)
+ }
+ }
+}
+
+// TestHostedSettingRoute turns the setting on through the owners' route of
+// a local instance with hosted runners on, twice (the second at the
+// revision the first left), and is refused where the route is not served.
+func TestHostedSettingRoute(t *testing.T) {
+ inst := thintest.StartInstanceWith(t, func(i *thintest.Instance) { i.HostedRunners = true })
+ now := time.Now().UTC()
+ if _, err := inst.DB.Writer().Exec("INSERT INTO chat_projects(id, repo, state, revision, created_at, updated_at) VALUES ('p_scratch', 'amadan.net/oficina/scratch', 'active', 1, ?, ?)", now, now); err != nil {
+ t.Fatal(err)
+ }
+ ctx := t.Context()
+ for want := int64(1); want <= 2; want++ {
+ if err := enableHosted(ctx, inst.URL, inst.Cookie().String(), "p_scratch"); err != nil {
+ t.Fatal(err)
+ }
+ var on bool
+ var owner string
+ var revision int64
+ if err := inst.DB.Writer().QueryRow("SELECT hosted_checks, hosted_checks_owner, hosted_checks_revision FROM chat_projects WHERE id = 'p_scratch'").Scan(&on, &owner, &revision); err != nil {
+ t.Fatal(err)
+ }
+ if !on || owner != thintest.Owner || revision != want {
+ t.Fatalf("after save %d: on %v owner %q revision %d", want, on, owner, revision)
+ }
+ }
+ if err := enableHosted(ctx, inst.URL, inst.Cookie().String(), "p_missing"); err == nil || !strings.Contains(err.Error(), "not on the hosted settings page") {
+ t.Fatalf("an unknown project: %v", err)
+ }
+ off := thintest.StartInstance(t)
+ if err := enableHosted(ctx, off.URL, off.Cookie().String(), "p_scratch"); err == nil || !strings.Contains(err.Error(), "404") {
+ t.Fatalf("without hosted runners: %v", err)
+ }
+}
+
+// writeTree writes files into dir, the gate executable.
+func writeTree(t *testing.T, dir string, files ...map[string]string) {
+ t.Helper()
+ for _, set := range files {
+ for name, body := range set {
+ path := filepath.Join(dir, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ mode := os.FileMode(0o644)
+ if name == ".amadan/ci" {
+ mode = 0o755
+ }
+ if err := os.WriteFile(path, []byte(body), mode); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+}
+
+// TestHostedFixtureChecks runs the scratch project's own gate, as a hosted
+// VM finds it, on the base and on each scenario's candidate: the base and
+// hosted-pass pass, hosted-fail fails over budget, hosted-slow sleeps
+// (here for one second, not its 240), and hosted-new-module adds a
+// module the base does not pin, which a hosted VM never stages or runs.
+func TestHostedFixtureChecks(t *testing.T) {
+ testci.Tools(t, "git", "sh")
+ goBin, err := exec.LookPath("go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ baseDir := t.TempDir()
+ writeTree(t, baseDir, hostedFixture)
+ for _, args := range [][]string{{"init", "-q", "-b", "main"}, {"add", "-A"}, {"commit", "-q", "-m", "scratch"}} {
+ gitRun(t, baseDir, args...)
+ }
+ sha, err := exec.Command("git", "-C", baseDir, "rev-parse", "HEAD").Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ git, _ := exec.LookPath("git")
+ gates, err := checkrun.ReadBaseGates(context.Background(), checks.Repo{Git: git, GitDir: filepath.Join(baseDir, ".git")}, strings.TrimSpace(string(sha)))
+ if err != nil {
+ t.Fatalf("the base's gate contract: %v", err)
+ }
+ for _, name := range []string{".amadan/ci", "budgets.txt", "scratch_test.go"} {
+ if !gates.Covers(name) {
+ t.Fatalf("the base does not pin %s", name)
+ }
+ }
+ if g, ok := checkrun.FindGate(baseDir); !ok || g.Name != ".amadan/ci" {
+ t.Fatalf("gate %+v %v", g, ok)
+ }
+ gate := func(files ...map[string]string) (string, error) {
+ dir := t.TempDir()
+ writeTree(t, dir, files...)
+ cmd := exec.Command("./.amadan/ci")
+ cmd.Dir = dir
+ cmd.Env = append(os.Environ(), "PATH="+filepath.Dir(goBin)+":/usr/bin:/bin", "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off", "GOFLAGS=", "GOWORK=off", "CGO_ENABLED=0")
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+ }
+ if out, err := gate(hostedFixture); err != nil || !strings.Contains(out, "--- PASS: TestBudget") {
+ t.Fatalf("the base's checks: %v\n%s", err, out)
+ }
+ for _, c := range hostedCases {
+ for name := range c.change {
+ if !strings.Contains(c.ask, name) {
+ t.Errorf("%s's ask does not name %s", c.name, name)
+ }
+ }
+ switch c.name {
+ case "hosted-pass":
+ if out, err := gate(hostedFixture, c.change); err != nil || !strings.Contains(out, "ok") {
+ t.Errorf("%s: %v\n%s", c.name, err, out)
+ }
+ case "hosted-fail":
+ if out, err := gate(hostedFixture, c.change); err == nil || !strings.Contains(out, "over budget: size 2, budget 1") {
+ t.Errorf("%s passed or failed otherwise: %v\n%s", c.name, err, out)
+ }
+ case "hosted-slow":
+ if c.change["sleep.txt"] != "240\n" {
+ t.Errorf("%s sleeps %q", c.name, c.change["sleep.txt"])
+ }
+ start := time.Now()
+ out, err := gate(hostedFixture, map[string]string{"sleep.txt": "1\n"})
+ if err != nil || !strings.Contains(out, "sleeping 1 s") || time.Since(start) < time.Second {
+ t.Errorf("%s: %v after %v\n%s", c.name, err, time.Since(start), out)
+ }
+ case "hosted-new-module":
+ dir := t.TempDir()
+ writeTree(t, dir, hostedFixture, c.change)
+ fresh, err := depsbundle.NewModules(os.DirFS(baseDir), os.DirFS(dir))
+ if err != nil || len(fresh) != 1 || fresh[0] != (depsbundle.Module{Path: "example.com/n", Version: "v1.0.0"}) {
+ t.Errorf("%s: new modules %v %v", c.name, fresh, err)
+ }
+ if bad, err := depsbundle.Conflicts(os.DirFS(baseDir), os.DirFS(dir)); err != nil || len(bad) != 0 {
+ t.Errorf("%s: conflicts %v %v", c.name, bad, err)
+ }
+ if want, err := depsbundle.ModulesFor(os.DirFS(baseDir), os.DirFS(dir)); err != nil || !slices.Contains(want, depsbundle.Module{Path: "example.com/n", Version: "v1.0.0"}) {
+ t.Errorf("%s: modules %v %v", c.name, want, err)
+ }
+ default:
+ t.Errorf("%s has no offline check", c.name)
+ }
+ }
+}
+
+// TestHostedFixtureWrite writes the scratch project's default branch into
+// EQUIPO_HOSTED_FIXTURE_OUT, to seed the repository the drill names.
+func TestHostedFixtureWrite(t *testing.T) {
+ dir := os.Getenv("EQUIPO_HOSTED_FIXTURE_OUT")
+ if dir == "" {
+ t.Skip("set EQUIPO_HOSTED_FIXTURE_OUT to write the scratch project's files")
+ }
+ writeTree(t, dir, hostedFixture)
+}
diff --git a/internal/headless/hosted_test.go b/internal/headless/hosted_test.go
new file mode 100644
index 00000000..4f549ea7
--- /dev/null
+++ b/internal/headless/hosted_test.go
@@ -0,0 +1,470 @@
+package headless
+
+import (
+ "context"
+ "fmt"
+ "html"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "os/exec"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/thintest"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Hosted checks on staging (hosted runners slice 2; the Task 34 dev
+// drill's prerequisite 4). The suite's person adds the scratch project
+// (EQUIPO_STAGING_HOSTED_PROJECT, a repository whose default branch is
+// hostedFixture), turns on "Run checks on a hosted machine" for it through
+// the owners' setting, and asks for one change. Each scenario waits for
+// the task's first checks step to end, records what it saw (Witness, so
+// the suite's report.json has it) and prints one HOSTED-RESULT line, then
+// cancels the task so no fix round or review starts another paid VM.
+//
+// The outcome is an observation, not an assertion: the drill compares it
+// with what it expects (ops fact), and its drills expect a step that does
+// not pass. A scenario fails only when it cannot get to a result.
+
+// hostedRepoEnv names the scratch project's repository.
+const hostedRepoEnv = "EQUIPO_STAGING_HOSTED_PROJECT"
+
+// hostedFixture is the scratch project's default branch: a Go module with
+// no dependencies whose gate (.amadan/ci) is go test. TestBudget fails when
+// size.txt is over budgets.txt ("over budget"); TestSleep sleeps sleep.txt
+// seconds. The contract pins budgets.txt and the test file from the base,
+// so a candidate changes only what they read.
+var hostedFixture = map[string]string{
+ ".amadan/ci": "#!/bin/sh\nset -eu\nexec go test -count=1 -v ./...\n",
+ ".equipo/gates.json": `{"version":1,"files":["budgets.txt","scratch_test.go"]}` + "\n",
+ "go.mod": "module example.com/hostedscratch\n\ngo 1.26\n",
+ "scratch.go": "// Package scratch is the hosted checks scenarios' project.\npackage scratch\n",
+ "scratch_test.go": `package scratch
+
+import (
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+func number(t *testing.T, name string) int {
+ t.Helper()
+ raw, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ return n
+}
+
+func TestBudget(t *testing.T) {
+ if size, budget := number(t, "size.txt"), number(t, "budgets.txt"); size > budget {
+ t.Fatalf("over budget: size %d, budget %d", size, budget)
+ }
+}
+
+func TestSleep(t *testing.T) {
+ n := number(t, "sleep.txt")
+ t.Logf("sleeping %d s", n)
+ time.Sleep(time.Duration(n) * time.Second)
+}
+`,
+ "size.txt": "1\n",
+ "budgets.txt": "1\n",
+ "sleep.txt": "0\n",
+ "NEWS.md": "# News\n",
+}
+
+// hostedSum is the new module's go.sum lines (TestChainNewModule's).
+var hostedSum = "example.com/n v1.0.0 h1:" + strings.Repeat("A", 43) + "=\nexample.com/n v1.0.0/go.mod h1:" + strings.Repeat("B", 43) + "=\n"
+
+// hostedCase is one hosted scenario: what the person asks (%[1]s is the
+// scratch project) and the candidate that ask makes over hostedFixture,
+// which the offline test checks with the gate.
+type hostedCase struct {
+ name, ask string
+ change map[string]string
+}
+
+var hostedCases = []hostedCase{
+ {"hosted-pass", "Change in %[1]s: NEWS.md should say where its checks run. Add the line \"Checks run on a hosted machine.\" after the heading in NEWS.md, with one blank line between them. Change only NEWS.md and run no commands.",
+ map[string]string{"NEWS.md": "# News\n\nChecks run on a hosted machine.\n"}},
+ {"hosted-fail", "Change in %[1]s: the size grew to 2. Replace the contents of size.txt with the single line 2. Change only size.txt and run no commands. Its checks then fail on purpose: this task tests how a failing check is reported.",
+ map[string]string{"size.txt": "2\n"}},
+ {"hosted-new-module", "Change in %[1]s: it now depends on the module example.com/n v1.0.0. Add the line \"require example.com/n v1.0.0\" at the end of go.mod, and create go.sum with exactly these two lines:\n" + hostedSum + "Change only go.mod and go.sum and run no commands: there is no network, and these are test checksums.",
+ map[string]string{"go.mod": hostedFixture["go.mod"] + "require example.com/n v1.0.0\n", "go.sum": hostedSum}},
+ {"hosted-slow", "Change in %[1]s: the slow test should take four minutes. Replace the contents of sleep.txt with the single line 240. Change only sleep.txt and run no commands.",
+ map[string]string{"sleep.txt": "240\n"}},
+}
+
+// hostedScenario reports whether name is a hosted scenario.
+func hostedScenario(name string) bool {
+ _, ok := hostedCaseNamed(name)
+ return ok
+}
+
+func hostedCaseNamed(name string) (hostedCase, bool) {
+ for _, c := range hostedCases {
+ if c.name == name {
+ return c, true
+ }
+ }
+ return hostedCase{}, false
+}
+
+// selected reports whether scenario name runs under
+// EQUIPO_STAGING_SCENARIOS only (a comma list; empty runs all).
+func selected(only, name string) bool {
+ return only == "" || strings.Contains(","+only+",", ","+name+",")
+}
+
+// hostedGate says why a hosted scenario does not run here (skip) or
+// cannot (fail): only against staging, only when named (each launches
+// paid VMs, so a whole-suite run never starts one), and only with the
+// scratch project and the suite person's session.
+func hostedGate(live bool, name, only, repo, cookieFile string) (skip, fail string) {
+ switch {
+ case !live:
+ return "staging only: hosted checks need the controller and a hosted VM", ""
+ case only == "" || !selected(only, name):
+ return "runs only when named in EQUIPO_STAGING_SCENARIOS: it launches hosted VMs", ""
+ case repo == "":
+ return "", hostedRepoEnv + " is not set"
+ case cookieFile == "":
+ return "", "EQUIPO_STAGING_COOKIE_FILE is not set"
+ }
+ return "", ""
+}
+
+// hostedOutcome is what a hosted scenario saw of its checks step: the
+// step and the task's shown reason from the person API, and from the
+// instance's database copy (Recorded) the base checks SHA, the step's
+// hosted jobs and how each ended.
+type hostedOutcome struct {
+ State, Checks, Reason, Shown, Sandbox string
+ BaseSHA string
+ Recorded bool
+ BaseChecksSHA string
+ Jobs int
+ JobEnds string
+}
+
+// Line is the result the drill reads, one line of key=value pairs in a
+// fixed order, "-" for empty:
+//
+// state=<step state> checks=<checks> reason=<step reason> shown=<task checks_reason>
+// sandbox=<checks_sandbox|none> certified=<yes|no> base_checks=<trusted|none|other|unknown> jobs=<n|unknown>
+//
+// certified is yes only for sandbox bubblewrap, which the instance gives
+// only a certified hosted VM's result. base_checks is trusted when the
+// recorded base checks SHA is the step's base.
+func (o hostedOutcome) Line() string {
+ dash := func(s string) string {
+ if s == "" {
+ return "-"
+ }
+ return s
+ }
+ sandbox, certified := o.Sandbox, "no"
+ if sandbox == "" {
+ sandbox = "none"
+ }
+ if sandbox == wire.SandboxBubblewrap {
+ certified = "yes"
+ }
+ base, jobs := "unknown", "unknown"
+ if o.Recorded {
+ switch {
+ case o.BaseChecksSHA == "":
+ base = "none"
+ case len(o.BaseChecksSHA) == 40 && o.BaseChecksSHA == o.BaseSHA:
+ base = "trusted"
+ default:
+ base = "other"
+ }
+ jobs = strconv.Itoa(o.Jobs)
+ }
+ return fmt.Sprintf("state=%s checks=%s reason=%s shown=%s sandbox=%s certified=%s base_checks=%s jobs=%s",
+ dash(o.State), dash(o.Checks), dash(o.Reason), dash(o.Shown), sandbox, certified, base, jobs)
+}
+
+var hostedStepID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,80}$`)
+
+// hostedQuery is the database copy's one row for step: its state, base
+// checks SHA, hosted job count and each job's state:stop_reason in
+// admission order. Only a plain step id is ever put in it.
+func hostedQuery(step string) (string, bool) {
+ if !hostedStepID.MatchString(step) {
+ return "", false
+ }
+ q := "'" + step + "'"
+ return "SELECT 'state=' || state || ' base_checks_sha=' || coalesce(base_checks_sha, '') || ' jobs=' || (SELECT count(*) FROM hosted_jobs WHERE step_id = " + q + ") || ' ended=' || coalesce((SELECT group_concat(state || ':' || coalesce(stop_reason, ''), ',') FROM (SELECT state, stop_reason FROM hosted_jobs WHERE step_id = " + q + " ORDER BY admitted_at, rowid)), '') FROM chat_steps WHERE id = " + q, true
+}
+
+var hostedRow = regexp.MustCompile(`(?m)^state=([a-z_]+) base_checks_sha=([0-9a-f]*) jobs=([0-9]+) ended=(\S*)\s*$`)
+
+// parseHostedRow reads hostedQuery's row from the query tool's output.
+func parseHostedRow(out string) (state string, o hostedOutcome, ok bool) {
+ m := hostedRow.FindStringSubmatch(out)
+ if m == nil {
+ return "", o, false
+ }
+ n, err := strconv.Atoi(m[3])
+ if err != nil {
+ return "", o, false
+ }
+ return m[1], hostedOutcome{Recorded: true, BaseChecksSHA: m[2], Jobs: n, JobEnds: m[4]}, true
+}
+
+// jobsSettled reports whether every job in ends (state:reason,...) has
+// ended or failed.
+func jobsSettled(ends string) bool {
+ if ends == "" {
+ return true
+ }
+ for _, e := range strings.Split(ends, ",") {
+ if st, _, _ := strings.Cut(e, ":"); st != chat.HostedJobEnded && st != chat.HostedJobFailed {
+ return false
+ }
+ }
+ return true
+}
+
+// hostedRecord reads the step's row from staging's database copy with
+// EQUIPO_STAGING_DB_QUERY (a command the SQL is appended to), waiting for
+// the copy to show the step's state and its jobs ended. Unknown when the
+// command is unset or the copy never caught up.
+func hostedRecord(t *testing.T, step, state string) hostedOutcome {
+ t.Helper()
+ command := os.Getenv("EQUIPO_STAGING_DB_QUERY")
+ q, ok := hostedQuery(step)
+ if command == "" || !ok {
+ t.Logf("hosted record: not read (query command set %v, step id plain %v)", command != "", ok)
+ return hostedOutcome{}
+ }
+ var last hostedOutcome
+ deadline := time.Now().Add(5 * time.Minute)
+ for {
+ out, err := exec.Command("/bin/sh", "-c", command+` "$1"`, "sh", q).CombinedOutput()
+ got, o, ok := parseHostedRow(string(out))
+ if err == nil && ok && got == state {
+ last = o
+ if jobsSettled(o.JobEnds) {
+ return o
+ }
+ }
+ if time.Now().After(deadline) {
+ t.Logf("hosted record: the database copy shows step %s as %q (want %s), jobs %q: %v %s", step, got, state, last.JobEnds, err, clipText(string(out), 300))
+ return last
+ }
+ time.Sleep(15 * time.Second)
+ }
+}
+
+// hostedRevision is the revision the owners' hosted settings page shows
+// for project, and whether its setting shows on.
+func hostedRevision(page, project string) (revision int64, on, found bool) {
+ p := regexp.QuoteMeta(html.EscapeString(project))
+ m := regexp.MustCompile(`<input type="hidden" name="project" value="` + p + `"><input type="hidden" name="revision" value="([0-9]+)">`).FindStringSubmatch(page)
+ if m == nil {
+ return 0, false, false
+ }
+ revision, err := strconv.ParseInt(m[1], 10, 64)
+ if err != nil {
+ return 0, false, false
+ }
+ on = regexp.MustCompile(`id="hosted-checks-` + p + `"[^>]*name="hosted_checks" checked>`).MatchString(page)
+ return revision, on, true
+}
+
+// enableHosted turns "Run checks on a hosted machine" on for project as
+// the person whose session cookie is, at the revision the owners' page
+// shows now, through the setting's own route (owners only, served only
+// with EQUIPO_HOSTED_RUNNERS=1), and reads the page again to see it on.
+func enableHosted(ctx context.Context, origin, cookie, project string) error {
+ client := &http.Client{Timeout: 60 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ page := func() (string, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+"/conversation/settings/hosted", nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Cookie", cookie)
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("the hosted settings page: %d (is EQUIPO_HOSTED_RUNNERS=1 there, and the person an owner?)", resp.StatusCode)
+ }
+ return string(body), nil
+ }
+ before, err := page()
+ if err != nil {
+ return err
+ }
+ revision, _, found := hostedRevision(before, project)
+ if !found {
+ return fmt.Errorf("project %s is not on the hosted settings page", project)
+ }
+ form := url.Values{"project": {project}, "hosted_checks": {"on"}, "revision": {strconv.FormatInt(revision, 10)}}
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+"/settings/hosted", strings.NewReader(form.Encode()))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Origin", origin)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ req.Header.Set("Cookie", cookie)
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("saving the hosted setting at revision %d: %d %s", revision, resp.StatusCode, clipText(string(body), 200))
+ }
+ after, err := page()
+ if err != nil {
+ return err
+ }
+ if _, on, _ := hostedRevision(after, project); !on {
+ return fmt.Errorf("the hosted setting for %s does not show on after saving", project)
+ }
+ return nil
+}
+
+// firstChecks is the task's first checks step at its newest revision.
+func firstChecks(c *thintest.Conversation, task string) (wire.Step, bool) {
+ for _, st := range c.Tasks[task].Steps {
+ if st.Specialist != wire.SpecialistChecks {
+ continue
+ }
+ if seen, ok := c.Steps[st.ID]; ok && seen.Revision >= st.Revision {
+ st = seen
+ }
+ return st, true
+ }
+ return wire.Step{}, false
+}
+
+// engineeringStopped reports whether the task's newest Engineering step
+// ended without a candidate to check and the task waits for its person:
+// nothing moves on by itself.
+func engineeringStopped(c *thintest.Conversation, task string) bool {
+ if c.Tasks[task].NeedsYou == "" {
+ return false
+ }
+ var last *wire.Step
+ for i := range c.Tasks[task].Steps {
+ if c.Tasks[task].Steps[i].Specialist == wire.SpecialistEngineering {
+ last = &c.Tasks[task].Steps[i]
+ }
+ }
+ if last == nil {
+ return false
+ }
+ st := *last
+ if seen, ok := c.Steps[st.ID]; ok && seen.Revision >= st.Revision {
+ st = seen
+ }
+ return wire.StepTerminal(st.State) && st.State != wire.StepDone
+}
+
+// scenarioHosted is the hosted scenario name (hostedCases).
+func scenarioHosted(name string) func(*testing.T, *Env) {
+ return func(t *testing.T, env *Env) {
+ c, _ := hostedCaseNamed(name)
+ repo, cookieFile := os.Getenv(hostedRepoEnv), os.Getenv("EQUIPO_STAGING_COOKIE_FILE")
+ skip, fail := hostedGate(env.Live, name, os.Getenv("EQUIPO_STAGING_SCENARIOS"), repo, cookieFile)
+ if skip != "" {
+ t.Skip(skip)
+ }
+ if fail != "" {
+ t.Fatal(fail)
+ }
+ raw, err := os.ReadFile(cookieFile)
+ if err != nil {
+ t.Fatalf("the suite person's session: %v", err)
+ }
+ s := open(t, env)
+ s.keep()
+ s.wait(t, "runner online", time.Minute, func(c *thintest.Conversation) bool { return c.Runner.Online })
+ p, err := env.Client.AddProject(s.ctx, repo)
+ if err != nil {
+ t.Fatalf("adding %s: %v", repo, err)
+ }
+ if err := enableHosted(s.ctx, os.Getenv("EQUIPO_STAGING_ORIGIN"), strings.TrimSpace(string(raw)), p.ID); err != nil {
+ t.Fatal(err)
+ }
+ start := time.Now()
+ sent := s.send(t, fmt.Sprintf(c.ask, repo))
+ id := s.taskOf(t, sent.Turn.ID)
+ hostedAt := -1.0
+ var checks wire.Step
+ // Engineering, enrolment within 2 minutes, a 240 s test, and in the
+ // drills a retry or a 10-minute launch window, inside the session.
+ // A step still running then is recorded as it stands, then fails.
+ s.conv.Wait(40*time.Minute, func(c *thintest.Conversation) bool {
+ st, ok := firstChecks(c, id)
+ if !ok {
+ return wire.FinalStage(c.Tasks[id].Stage) || engineeringStopped(c, id)
+ }
+ if st.Placement == wire.PlacementHosted && hostedAt < 0 {
+ hostedAt = time.Since(start).Seconds()
+ }
+ checks = st
+ return wire.StepTerminal(st.State) || wire.FinalStage(c.Tasks[id].Stage)
+ })
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ k, err := env.Client.Task(ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, st := range k.Steps {
+ if st.ID == checks.ID {
+ checks = st
+ }
+ }
+ // Nothing more runs on paid VMs: no fix round, no review.
+ if !wire.FinalStage(k.Stage) {
+ if _, err := env.Client.CancelTask(ctx, id); err != nil {
+ t.Logf("cancelling %s: %v", id, err)
+ }
+ }
+ o := hostedOutcome{}
+ if checks.ID != "" && wire.StepTerminal(checks.State) {
+ o = hostedRecord(t, checks.ID, checks.State)
+ }
+ o.State, o.Checks, o.Reason, o.Shown, o.Sandbox, o.BaseSHA = checks.State, checks.Checks, checks.Reason, k.ChecksReason, checks.ChecksSandbox, checks.BaseSHA
+ line := o.Line()
+ w := map[string]any{"result": line, "task": id, "stage": k.Stage, "step": checks.ID, "state": checks.State, "checks": checks.Checks, "reason": checks.Reason,
+ "checks_reason": k.ChecksReason, "checks_sandbox": checks.ChecksSandbox, "base_sha": checks.BaseSHA, "candidate_sha": checks.CandidateSHA,
+ "base_checks": checks.BaseChecks, "seconds": time.Since(start).Seconds(), "waiting_hosted_s": hostedAt}
+ if o.Recorded {
+ w["base_checks_sha"], w["jobs"], w["job_ends"] = o.BaseChecksSHA, o.Jobs, o.JobEnds
+ }
+ Witness[t.Name()] = w
+ fmt.Printf("HOSTED-RESULT %s %s\n", name, line)
+ t.Logf("task %s (%s): %s", id, k.Stage, line)
+ if checks.ID == "" || !wire.StepTerminal(checks.State) {
+ t.Fatalf("no checks step ended: task %s %s", id, k.Stage)
+ }
+ }
+}
diff --git a/internal/headless/scenarios_test.go b/internal/headless/scenarios_test.go
index 2f773a9d..7e961027 100644
--- a/internal/headless/scenarios_test.go
+++ b/internal/headless/scenarios_test.go
@@ -592,6 +592,11 @@ var scenarios = []struct {
{"4c_witness", scenarioMergeWitness},
{"conn1_witness", scenarioConnWitness},
{"assistant_attachments", scenarioAssistantAttachments},
+ // Hosted checks (hosted_test.go): staging only, and only when named.
+ {"hosted-pass", scenarioHosted("hosted-pass")},
+ {"hosted-fail", scenarioHosted("hosted-fail")},
+ {"hosted-new-module", scenarioHosted("hosted-new-module")},
+ {"hosted-slow", scenarioHosted("hosted-slow")},
}
// TestHeadless runs every scenario against a fresh local instance and
@@ -599,6 +604,9 @@ var scenarios = []struct {
func TestHeadless(t *testing.T) {
for _, sc := range scenarios {
t.Run(sc.name, func(t *testing.T) {
+ if hostedScenario(sc.name) {
+ t.Skip("staging only: hosted checks need the controller and a hosted VM")
+ }
env, _, r := localEnv(t)
r.subprocess = sc.name == "runner_crash" || sc.name == "4_step_crash"
// Moving in is on for its own scenarios; those that reset the
@@ -647,7 +655,7 @@ func TestStaging(t *testing.T) {
env := stagingEnv(t)
only := os.Getenv("EQUIPO_STAGING_SCENARIOS")
for _, sc := range scenarios {
- if only != "" && !strings.Contains(","+only+",", ","+sc.name+",") {
+ if !selected(only, sc.name) {
continue
}
if !t.Run(sc.name, func(t *testing.T) {
diff --git a/scripts/staging-thin-test.py b/scripts/staging-thin-test.py
index 04eb9d84..eecd28f4 100644
--- a/scripts/staging-thin-test.py
+++ b/scripts/staging-thin-test.py
@@ -2,6 +2,7 @@ import importlib.util
import json
import os
from pathlib import Path
+import shlex
import tempfile
import sys
import unittest
@@ -56,6 +57,14 @@ class SuiteTest(unittest.TestCase):
self.assertIn(env['EQUIPO_STAGING_RUN_ID'], kwargs['log'].name)
self.assertEqual(env['EQUIPO_STAGING_TOKEN'], 'fresh-token')
self.assertGreaterEqual(int(env['EQUIPO_STAGING_TURN_LIMIT']), 25)
+ # The hosted scenarios get this run's person's session,
+ # a 0600 file, and the read-only database query.
+ cookie = Path(env['EQUIPO_STAGING_COOKIE_FILE'])
+ self.assertEqual(cookie.read_text(), 'cookie')
+ self.assertEqual(cookie.stat().st_mode & 0o777, 0o600)
+ self.assertTrue(cookie.name == 'cookie' and cookie.parent.name.startswith('equipo-suite-'))
+ self.assertEqual(shlex.split(env['EQUIPO_STAGING_DB_QUERY']),
+ ['carlos', 'db', 'query', '--app', 'equipo-staging', '--account', 'bds', '--console', 'https://console.carloku.com', '--sql'])
running = staging.read_env(service)
self.assertTrue(all(b['person_id'] == addresses[-1] for b in json.loads(Path(running['EQUIPO_ACCOUNT_BINDINGS_PATH']).read_text())))
state = Path(running['EQUIPO_RUNNER_STATE_DIR'])
diff --git a/scripts/staging-thin.py b/scripts/staging-thin.py
index c5b8f061..3a3a93ad 100755
--- a/scripts/staging-thin.py
+++ b/scripts/staging-thin.py
@@ -670,7 +670,7 @@ def fresh_suite():
private(service, ''.join(f'{k}={json.dumps(v)}\n' for k, v in sorted(env.items())))
run(['systemctl', '--user', 'start', SUITE_UNIT])
print('suite run ' + run_id + ' as ' + person, flush=True)
- yield run_id, token
+ yield run_id, token, root / 'cookie'
finally:
try:
cleanup_suite(token, person)
@@ -685,13 +685,19 @@ def fresh_suite():
def suite(only=''):
- with fresh_suite() as (run_id, token):
- suite_run(only, run_id, token)
+ with fresh_suite() as (run_id, token, cookie):
+ suite_run(only, run_id, token, cookie)
-def suite_run(only, run_id, token):
+def suite_run(only, run_id, token, cookie):
restart = f'carlos restart --app {APP} --account {ACCOUNT} --console {CONSOLE}'
env = dict(os.environ, CGO_ENABLED='0', EQUIPO_STAGING_ORIGIN=ORIGIN, EQUIPO_STAGING_TOKEN=token,
+ # The hosted scenarios: the suite person's session (a 0600
+ # file) for the owners' hosted setting, and the read-only
+ # query of staging's database copy the SQL is appended to.
+ # The scratch project is EQUIPO_STAGING_HOSTED_PROJECT.
+ EQUIPO_STAGING_COOKIE_FILE=str(cookie),
+ EQUIPO_STAGING_DB_QUERY=shlex.join(['carlos', 'db', 'query', '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, '--sql']),
EQUIPO_STAGING_RUNNER_START=f'systemctl --user start {SUITE_UNIT}',
EQUIPO_STAGING_RUNNER_STOP=f'systemctl --user stop {SUITE_UNIT}',
EQUIPO_STAGING_RUNNER_RESTART=f'systemctl --user restart {SUITE_UNIT}',