package equipotest import ( "context" "crypto/sha256" "fmt" "io" "log/slog" "os" "os/exec" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/release" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" ) func TestDirectEligibilityRequiresCertifiedTuple(t *testing.T) { for _, provider := range []string{"claude", "codex"} { for _, change := range []string{"certified", "unlisted", "stale", "legacy", "trial"} { t.Run(provider+"/"+change, func(t *testing.T) { f := connectionStore(t) tuples := []team.IsolationTuple{} for i := range f.reports { r := &f.reports[i] r.PaseoVersion = "" r.LauncherVersion = "direct-v2" r.BwrapVersion = "0.11.0" r.PolicyVersion = "policy-v2" tuples = append(tuples, team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, LauncherVersion: r.LauncherVersion, BwrapVersion: r.BwrapVersion, PolicyVersion: r.PolicyVersion, IsolationConfigHash: r.IsolationConfigHash}) } f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples(tuples)) for i := range f.reports { r := &f.reports[i] if r.Provider != provider { continue } switch change { case "unlisted": r.IsolationConfigHash = strings.Repeat("c", 64) case "stale": r.LauncherVersion = "old" case "legacy": r.LauncherVersion = "" r.PaseoVersion = "0.14.0" case "trial": r.TrialReady = true } } err := f.s.ReportConnections(connectionContext, f.principal, f.reports) if change == "certified" { executionMust(t, err) } f.choice(t, "") if change == "certified" { f.selectOK(t, "engineering", "") return } // A forged report or persisted consent cannot grant new authority. _, err = f.d.Writer().Exec(`INSERT INTO isolation_acknowledgements(id,connection_id,owner,owner_revision,provider,provider_version,paseo_version,isolation_config_hash,connection_revision,acknowledged_at) VALUES('forged',?,?,1,?,'0.165.0','0.14.0',?,1,CURRENT_TIMESTAMP)`, f.ids[provider], ownerAddress, provider, strings.Repeat("a", 64)) executionMust(t, err) f.denied(t, "engineering", "") }) } } } func TestDirectCutoverPreservesHistory(t *testing.T) { for _, brokenAudit := range []bool{false, true} { t.Run(map[bool]string{false: "upgrade", true: "audit_atomicity"}[brokenAudit], func(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "upgrade.db") d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) defer d.Close() before := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if m.ID != "equipo/0019_direct_reconcile" && m.ID != "equipo/0018_direct_launch" { before.Add(m) } } _, err = migrate.Apply(ctx, d, before) executionMust(t, err) for _, table := range []string{"supervised_trials", "isolation_acknowledgements"} { _, err = d.Writer().Exec("INSERT INTO " + table + "(id,revoked_at) VALUES('open',NULL),('closed','2026-11-01 01:02:03')") executionMust(t, err) } cutoverRow(t, d, "jobs", map[string]any{"id": 1, "account": "team", "state": "running"}) cutoverRow(t, d, "steps", map[string]any{"id": 1, "job_id": 1, "fence": 7, "holder": 1, "state": "running"}) cutoverRow(t, d, "attempts", map[string]any{"id": 1, "job_id": 1, "step_id": 1, "fence": 7, "state": "active", "containment": "pending"}) cutoverRow(t, d, "artifacts", map[string]any{"id": 1, "job_id": 1, "payload": []byte(`{"history":"unchanged"}`), "provenance": `{"trial":{"label":"supervised trial"}}`}) cutoverRow(t, d, "reservations", map[string]any{"id": 1, "job_id": 1, "r_calls": 3, "r_input": 1234, "state": "open", "settled_by": "unknown"}) cutoverRow(t, d, "tasks", map[string]any{"id": "old", "job_id": 1, "state": "queued", "request_id": "old"}) cutoverRow(t, d, "tasks", map[string]any{"id": "finished", "state": "merged", "request_id": "finished"}) cutoverRow(t, d, "task_outboxes", map[string]any{"task_id": "old", "state": "done"}) cutoverRow(t, d, "runner_assignments", map[string]any{"id": "old", "task_id": "old", "state": "claimed", "revision": 3, "attempt_id": 1, "job_id": 1, "fence": 7}) if brokenAudit { _, err = d.Writer().Exec(`CREATE TRIGGER cutover_audit_failure BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'audit unavailable'); END`) executionMust(t, err) } result, err := migrate.Apply(ctx, d, equipo.BootSchema) if brokenAudit { if err == nil { t.Fatal("migration ignored audit failure") } var open int executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM supervised_trials WHERE revoked_at IS NULL`).Scan(&open)) if open != 1 { t.Fatal("partial revocation") } return } executionMust(t, err) if len(result.Applied) != 2 || result.Applied[0] != "equipo/0018_direct_launch" { t.Fatalf("missing cutover: %v", result.Applied) } for _, table := range []string{"supervised_trials", "isolation_acknowledgements"} { var open, total int var old string executionMust(t, d.Writer().QueryRow("SELECT count(*),sum(revoked_at IS NULL) FROM "+table).Scan(&total, &open)) if total != 2 || open != 0 { t.Fatalf("history/revocation %s: %d/%d", table, total, open) } executionMust(t, d.Writer().QueryRow("SELECT CAST(revoked_at AS TEXT) FROM "+table+" WHERE id='closed'").Scan(&old)) if old != "2026-11-01 01:02:03" { t.Fatal("rewrote historical timestamp", old) } } var state, wait, contained, payload, provenance string var fence, calls, input int executionMust(t, d.Writer().QueryRow("SELECT state,wait FROM jobs WHERE id=1").Scan(&state, &wait)) if state != "waiting" || wait != "uncertain_external_outcome" { t.Fatal("legacy job not waiting", state, wait) } executionMust(t, d.Writer().QueryRow("SELECT containment FROM attempts WHERE id=1").Scan(&contained)) if contained != "pending" { t.Fatal("fabricated containment") } executionMust(t, d.Writer().QueryRow("SELECT fence FROM steps WHERE id=1").Scan(&fence)) if fence != 8 { t.Fatal("legacy handle not fenced") } executionMust(t, d.Writer().QueryRow("SELECT state FROM runner_assignments WHERE id='old'").Scan(&state)) var protocol int executionMust(t, d.Writer().QueryRow("SELECT protocol_version FROM runner_assignments WHERE id='old'").Scan(&protocol)) if protocol != 1 { t.Fatal("old assignment relabelled direct") } if state != "fenced" { t.Fatal("legacy assignment can resume") } executionMust(t, d.Writer().QueryRow("SELECT payload,provenance FROM artifacts WHERE id=1").Scan(&payload, &provenance)) if payload != `{"history":"unchanged"}` || provenance != `{"trial":{"label":"supervised trial"}}` { t.Fatal("lost historical evidence") } executionMust(t, d.Writer().QueryRow("SELECT r_calls,r_input,settled_by FROM reservations WHERE id=1").Scan(&calls, &input, &state)) if calls != 3 || input != 1234 || state != "unknown" { t.Fatal("lost historical charge") } executionMust(t, d.Writer().QueryRow("SELECT state FROM task_outboxes WHERE task_id='old'").Scan(&state)) if state != "reconcile" { t.Fatal("old selection was not invalidated") } executionMust(t, d.Writer().QueryRow("SELECT state FROM tasks WHERE id='finished'").Scan(&state)) if state != "merged" { t.Fatal("completed history reopened") } var n int executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM audit_events WHERE kind='system.migration.direct_launch' AND actor='system'`).Scan(&n)) if n != 1 { t.Fatal("missing cutover audit") } executionMust(t, d.Close()) d, err = db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) defer d.Close() result, err = migrate.Apply(ctx, d, equipo.BootSchema) executionMust(t, err) if len(result.Applied) != 0 { t.Fatal("reapplied cutover") } }) } } func TestDirectReleaseContract(t *testing.T) { m := release.BuildManifest() if m.Schema != 3 || m.LauncherVersion == "" || m.BwrapVersion != "0.11.0" || m.PolicyVersion == "" { t.Fatalf("not a direct manifest: %+v", m) } // The four pinned programs; the tool proxy is recorded by a release build. if len(m.Binaries) != 4 || m.ToolProxySHA256() != "" || m.Installable() { t.Fatal("the source manifest pins a tool proxy or installs without one") } for _, name := range []string{"../../Makefile", "../../packaging/equipo-runner.service", "../runner/config.go"} { raw, err := os.ReadFile(name) executionMust(t, err) for _, dead := range []string{"EQUIPO_NODE_PATH", "EQUIPO_PASEO_", "npm ci", "node --version", "User=equipo-runner"} { if strings.Contains(string(raw), dead) { t.Fatalf("%s still requires %s", name, dead) } } } } func TestDirectDeadReferencesRepository(t *testing.T) { // The scan reads every file git lists. testci.RepoFiles(t) script, err := filepath.Abs("../../scripts/runner-dead-references.py") executionMust(t, err) testci.Files(t, script) if out, err := exec.Command("python3", script).CombinedOutput(); err != nil { t.Fatalf("repository reference inventory: %v\n%s", err, out) } } func TestDirectDeadReferences(t *testing.T) { script, err := filepath.Abs("../../scripts/runner-dead-references.py") executionMust(t, err) testci.Files(t, script) for _, name := range []string{"active.go", "active_test.go", "Makefile", "docs/current.md", "scripts/build.sh", "ui.html", "config.json", ".hidden", "odd.extension"} { t.Run(name, func(t *testing.T) { root := t.TempDir() cmd := exec.Command("git", "init", "-q", root) executionMust(t, cmd.Run()) executionMust(t, os.MkdirAll(filepath.Dir(filepath.Join(root, name)), 0700)) executionMust(t, os.WriteFile(filepath.Join(root, name), []byte("obsolete paseo dependency\n"), 0600)) cmd = exec.Command("git", "-C", root, "add", ".") executionMust(t, cmd.Run()) cmd = exec.Command("python3", script, "--root", root) out, err := cmd.CombinedOutput() if err == nil || !strings.Contains(string(out), name) { t.Fatalf("scanner missed tracked %s: %v %s", name, err, out) } }) } } func TestDirectLegacyWorkCannotResume(t *testing.T) { f := runnerFixtureNew(t, false) _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "legacy-v1"}) if err == nil { t.Fatal("legacy protocol claimed new work") } } func cutoverRow(t *testing.T, d *db.DB, table string, values map[string]any) { t.Helper() rows, err := d.Writer().Query("PRAGMA table_info(" + table + ")") executionMust(t, err) var names, marks []string var args []any for rows.Next() { var id, required, key int var name, kind string var defaultValue any executionMust(t, rows.Scan(&id, &name, &kind, &required, &defaultValue, &key)) value, ok := values[name] if !ok { if defaultValue != nil || required == 0 && key == 0 { continue } if strings.Contains(strings.ToUpper(kind), "INT") { value = 0 } else { value = "" } } names = append(names, name) marks = append(marks, "?") args = append(args, value) } executionMust(t, rows.Err()) executionMust(t, rows.Close()) _, err = d.Writer().Exec("INSERT INTO "+table+"("+strings.Join(names, ",")+") VALUES("+strings.Join(marks, ",")+")", args...) executionMust(t, err) } func TestDirectDeadReferencesExactAllowances(t *testing.T) { script, err := filepath.Abs("../../scripts/runner-dead-references.py") executionMust(t, err) testci.Files(t, script) root := t.TempDir() executionMust(t, exec.Command("git", "init", "-q", root).Run()) file := filepath.Join(root, "active.go") line := "// equipo-runner executable" executionMust(t, os.WriteFile(file, []byte(line+"\n"), 0600)) executionMust(t, exec.Command("git", "-C", root, "add", ".").Run()) executionMust(t, os.Mkdir(filepath.Join(root, "scripts"), 0700)) entry := map[string]any{"path": "active.go", "line_sha256": fmt.Sprintf("%x", sha256.Sum256([]byte(line))), "match": "equipo-runner", "count": 1, "reason": "Retained executable name only."} write := func(v any) { executionMust(t, os.WriteFile(filepath.Join(root, "scripts/runner-reference-allowlist.json"), flowJSON(v), 0600)) } run := func(pass bool) { t.Helper() cmd := exec.Command("python3", script, "--root", root) out, err := cmd.CombinedOutput() if (err == nil) != pass { t.Fatalf("classification pass=%v: %v %s", pass, err, out) } } write([]any{entry}) run(true) executionMust(t, os.WriteFile(file, []byte(line+" and obsolete paseo\n"), 0600)) run(false) executionMust(t, os.WriteFile(file, []byte("// no references\n"), 0600)) run(false) executionMust(t, os.WriteFile(file, []byte(line+"\n"), 0600)) entry["line_sha256"] = "*" write([]any{entry}) run(false) entry["line_sha256"] = fmt.Sprintf("%x", sha256.Sum256([]byte(line))) entry["file_exemption"] = true write([]any{entry}) run(false) } func TestDirectPreparationEventScope(t *testing.T) { for _, kind := range []string{"namespace.owner", "namespace.launch", "timeline", "turn.completed"} { e := runnerproto.Event{Version: 2, ID: "id", TaskID: "task", AssignmentID: "assignment", Scope: team.Scope{Account: "team"}, Handle: team.Handle{Fence: 1, Runner: "runner"}, ServerID: "direct", AgentID: "agent", SessionID: "session", Kind: kind, Payload: []byte(`{}`), SourceTime: time.Now().UTC()} want := strings.HasPrefix(kind, "namespace.") if (e.Validate() == nil) != want { t.Fatal("incorrect preparation event scope", kind) } e.Scope.Job = -1 if e.Validate() == nil { t.Fatal("negative job accepted") } } } func TestDirectCutoverPendingSelectionStaysFenced(t *testing.T) { f := bugFixture(t) task := bugTask(t, f) mustSQL(t, f.d, "UPDATE task_outboxes SET state='reconcile' WHERE task_id=?", task.ID) mustSQL(t, f.d, "UPDATE tasks SET state='waiting',wait_code='task.wait.reconcile' WHERE id=?", task.ID) x := attachBugExecution(t, f) executionMust(t, x.Sync(connectionContext)) if scalar(t, f.d, "SELECT count(*) FROM runner_assignments") != 0 { t.Fatal("cutover silently selected new work") } saved, err := f.s.Task(connectionContext, ownerActor, task.ID) executionMust(t, err) if saved.WaitCode != "task.wait.reconcile" { t.Fatal("cutover person wait was relabelled", saved.WaitCode) } } func TestDirectLegacyProofCannotCertifyContainment(t *testing.T) { f := runnerFixtureNew(t, true, true) mustSQL(t, f.d, "UPDATE runner_assignments SET protocol_version=1 WHERE id=?", f.a.ID) q := f.request() if _, err := f.x.Mutate(connectionContext, f.principal, "validate", q); err == nil { t.Fatal("legacy assignment gained current authority") } claim := equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"} if _, err := f.x.RecoverClaim(connectionContext, f.principal, claim); err == nil { t.Fatal("legacy claim was recovered") } q.Proof = flowJSON(runnerproto.ContainmentProof{Version: 2, Scope: q.Scope, Handle: q.Handle, CheckedAt: time.Now().UTC()}) if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil { t.Fatal("legacy process was certified by an empty direct proof") } if scalar(t, f.d, "SELECT count(*) FROM attempts WHERE containment='pending'") != 1 { t.Fatal("legacy capacity released") } } func TestDirectLegacyEvidenceNotReconciled(t *testing.T) { f := runnerFixtureNew(t, true) seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID) mustSQL(t, f.d, "UPDATE runner_assignments SET protocol_version=1,state='fenced' WHERE id=?", f.a.ID) mustSQL(t, f.d, "UPDATE tasks SET state='waiting',wait_code='task.wait.reconcile' WHERE id=?", f.a.TaskID) mustSQL(t, f.d, "UPDATE connections SET reports_json='[]'") var before, after string executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", f.a.ID).Scan(&before)) executionMust(t, f.x.Sync(connectionContext)) executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", f.a.ID).Scan(&after)) if before != after { t.Fatal("legacy evidence was automatically reconciled") } } func TestDirectDeadReferencesTrackedOnly(t *testing.T) { script, err := filepath.Abs("../../scripts/runner-dead-references.py") executionMust(t, err) testci.Files(t, script) root := t.TempDir() executionMust(t, exec.Command("git", "init", "-q", root).Run()) executionMust(t, os.WriteFile(filepath.Join(root, "untracked.txt"), []byte("obsolete paseo dependency\n"), 0600)) executionMust(t, os.WriteFile(filepath.Join(root, ".gitignore"), []byte("ignored.txt\n"), 0600)) executionMust(t, os.WriteFile(filepath.Join(root, "ignored.txt"), []byte("obsolete node dependency\n"), 0600)) if out, err := exec.Command("python3", script, "--root", root).CombinedOutput(); err != nil { t.Fatalf("untracked content scanned: %v %s", err, out) } executionMust(t, exec.Command("git", "-C", root, "add", "untracked.txt").Run()) if out, err := exec.Command("python3", script, "--root", root).CombinedOutput(); err == nil || !strings.Contains(string(out), "untracked.txt") { t.Fatalf("tracked content missed: %v %s", err, out) } }