oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "context"
5 "crypto/sha256"
6 "fmt"
7 "io"
8 "log/slog"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/runnerproto"
17 "amadan.net/oficina/equipo/internal/testci"
18
19 "amadan.net/oficina/equipo/internal/equipo"
20 "amadan.net/oficina/equipo/internal/equipo/team"
21 "amadan.net/oficina/equipo/internal/release"
22 "amadan.net/rastrillo/rastrillo/db"
23 "amadan.net/rastrillo/rastrillo/migrate"
24)
25
26func TestDirectEligibilityRequiresCertifiedTuple(t *testing.T) {
27 for _, provider := range []string{"claude", "codex"} {
28 for _, change := range []string{"certified", "unlisted", "stale", "legacy", "trial"} {
29 t.Run(provider+"/"+change, func(t *testing.T) {
30 f := connectionStore(t)
31 tuples := []team.IsolationTuple{}
32 for i := range f.reports {
33 r := &f.reports[i]
34 r.PaseoVersion = ""
35 r.LauncherVersion = "direct-v2"
36 r.BwrapVersion = "0.11.0"
37 r.PolicyVersion = "policy-v2"
38 tuples = append(tuples, team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, LauncherVersion: r.LauncherVersion, BwrapVersion: r.BwrapVersion, PolicyVersion: r.PolicyVersion, IsolationConfigHash: r.IsolationConfigHash})
39 }
40 f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples(tuples))
41 for i := range f.reports {
42 r := &f.reports[i]
43 if r.Provider != provider {
44 continue
45 }
46 switch change {
47 case "unlisted":
48 r.IsolationConfigHash = strings.Repeat("c", 64)
49 case "stale":
50 r.LauncherVersion = "old"
51 case "legacy":
52 r.LauncherVersion = ""
53 r.PaseoVersion = "0.14.0"
54 case "trial":
55 r.TrialReady = true
56 }
57 }
58 err := f.s.ReportConnections(connectionContext, f.principal, f.reports)
59 if change == "certified" {
60 executionMust(t, err)
61 }
62 f.choice(t, "")
63 if change == "certified" {
64 f.selectOK(t, "engineering", "")
65 return
66 }
67 // A forged report or persisted consent cannot grant new authority.
68 _, 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))
69 executionMust(t, err)
70 f.denied(t, "engineering", "")
71 })
72 }
73 }
74}
75
76func TestDirectCutoverPreservesHistory(t *testing.T) {
77 for _, brokenAudit := range []bool{false, true} {
78 t.Run(map[bool]string{false: "upgrade", true: "audit_atomicity"}[brokenAudit], func(t *testing.T) {
79 ctx := context.Background()
80 path := filepath.Join(t.TempDir(), "upgrade.db")
81 d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
82 executionMust(t, err)
83 defer d.Close()
84 before := &migrate.Set{}
85 for _, m := range equipo.BootSchema.All() {
86 if m.ID != "equipo/0019_direct_reconcile" && m.ID != "equipo/0018_direct_launch" {
87 before.Add(m)
88 }
89 }
90 _, err = migrate.Apply(ctx, d, before)
91 executionMust(t, err)
92 for _, table := range []string{"supervised_trials", "isolation_acknowledgements"} {
93 _, err = d.Writer().Exec("INSERT INTO " + table + "(id,revoked_at) VALUES('open',NULL),('closed','2026-11-01 01:02:03')")
94 executionMust(t, err)
95 }
96 cutoverRow(t, d, "jobs", map[string]any{"id": 1, "account": "team", "state": "running"})
97 cutoverRow(t, d, "steps", map[string]any{"id": 1, "job_id": 1, "fence": 7, "holder": 1, "state": "running"})
98 cutoverRow(t, d, "attempts", map[string]any{"id": 1, "job_id": 1, "step_id": 1, "fence": 7, "state": "active", "containment": "pending"})
99 cutoverRow(t, d, "artifacts", map[string]any{"id": 1, "job_id": 1, "payload": []byte(`{"history":"unchanged"}`), "provenance": `{"trial":{"label":"supervised trial"}}`})
100 cutoverRow(t, d, "reservations", map[string]any{"id": 1, "job_id": 1, "r_calls": 3, "r_input": 1234, "state": "open", "settled_by": "unknown"})
101 cutoverRow(t, d, "tasks", map[string]any{"id": "old", "job_id": 1, "state": "queued", "request_id": "old"})
102 cutoverRow(t, d, "tasks", map[string]any{"id": "finished", "state": "merged", "request_id": "finished"})
103 cutoverRow(t, d, "task_outboxes", map[string]any{"task_id": "old", "state": "done"})
104 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})
105 if brokenAudit {
106 _, err = d.Writer().Exec(`CREATE TRIGGER cutover_audit_failure BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'audit unavailable'); END`)
107 executionMust(t, err)
108 }
109 result, err := migrate.Apply(ctx, d, equipo.BootSchema)
110 if brokenAudit {
111 if err == nil {
112 t.Fatal("migration ignored audit failure")
113 }
114 var open int
115 executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM supervised_trials WHERE revoked_at IS NULL`).Scan(&open))
116 if open != 1 {
117 t.Fatal("partial revocation")
118 }
119 return
120 }
121 executionMust(t, err)
122 if len(result.Applied) != 2 || result.Applied[0] != "equipo/0018_direct_launch" {
123 t.Fatalf("missing cutover: %v", result.Applied)
124 }
125 for _, table := range []string{"supervised_trials", "isolation_acknowledgements"} {
126 var open, total int
127 var old string
128 executionMust(t, d.Writer().QueryRow("SELECT count(*),sum(revoked_at IS NULL) FROM "+table).Scan(&total, &open))
129 if total != 2 || open != 0 {
130 t.Fatalf("history/revocation %s: %d/%d", table, total, open)
131 }
132 executionMust(t, d.Writer().QueryRow("SELECT CAST(revoked_at AS TEXT) FROM "+table+" WHERE id='closed'").Scan(&old))
133 if old != "2026-11-01 01:02:03" {
134 t.Fatal("rewrote historical timestamp", old)
135 }
136 }
137 var state, wait, contained, payload, provenance string
138 var fence, calls, input int
139 executionMust(t, d.Writer().QueryRow("SELECT state,wait FROM jobs WHERE id=1").Scan(&state, &wait))
140 if state != "waiting" || wait != "uncertain_external_outcome" {
141 t.Fatal("legacy job not waiting", state, wait)
142 }
143 executionMust(t, d.Writer().QueryRow("SELECT containment FROM attempts WHERE id=1").Scan(&contained))
144 if contained != "pending" {
145 t.Fatal("fabricated containment")
146 }
147 executionMust(t, d.Writer().QueryRow("SELECT fence FROM steps WHERE id=1").Scan(&fence))
148 if fence != 8 {
149 t.Fatal("legacy handle not fenced")
150 }
151 executionMust(t, d.Writer().QueryRow("SELECT state FROM runner_assignments WHERE id='old'").Scan(&state))
152 var protocol int
153 executionMust(t, d.Writer().QueryRow("SELECT protocol_version FROM runner_assignments WHERE id='old'").Scan(&protocol))
154 if protocol != 1 {
155 t.Fatal("old assignment relabelled direct")
156 }
157 if state != "fenced" {
158 t.Fatal("legacy assignment can resume")
159 }
160 executionMust(t, d.Writer().QueryRow("SELECT payload,provenance FROM artifacts WHERE id=1").Scan(&payload, &provenance))
161 if payload != `{"history":"unchanged"}` || provenance != `{"trial":{"label":"supervised trial"}}` {
162 t.Fatal("lost historical evidence")
163 }
164 executionMust(t, d.Writer().QueryRow("SELECT r_calls,r_input,settled_by FROM reservations WHERE id=1").Scan(&calls, &input, &state))
165 if calls != 3 || input != 1234 || state != "unknown" {
166 t.Fatal("lost historical charge")
167 }
168 executionMust(t, d.Writer().QueryRow("SELECT state FROM task_outboxes WHERE task_id='old'").Scan(&state))
169 if state != "reconcile" {
170 t.Fatal("old selection was not invalidated")
171 }
172 executionMust(t, d.Writer().QueryRow("SELECT state FROM tasks WHERE id='finished'").Scan(&state))
173 if state != "merged" {
174 t.Fatal("completed history reopened")
175 }
176 var n int
177 executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM audit_events WHERE kind='system.migration.direct_launch' AND actor='system'`).Scan(&n))
178 if n != 1 {
179 t.Fatal("missing cutover audit")
180 }
181 executionMust(t, d.Close())
182 d, err = db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
183 executionMust(t, err)
184 defer d.Close()
185 result, err = migrate.Apply(ctx, d, equipo.BootSchema)
186 executionMust(t, err)
187 if len(result.Applied) != 0 {
188 t.Fatal("reapplied cutover")
189 }
190 })
191 }
192}
193
194func TestDirectReleaseContract(t *testing.T) {
195 m := release.BuildManifest()
196 if m.Schema != 3 || m.LauncherVersion == "" || m.BwrapVersion != "0.11.0" || m.PolicyVersion == "" {
197 t.Fatalf("not a direct manifest: %+v", m)
198 }
199 // The four pinned programs; the tool proxy is recorded by a release build.
200 if len(m.Binaries) != 4 || m.ToolProxySHA256() != "" || m.Installable() {
201 t.Fatal("the source manifest pins a tool proxy or installs without one")
202 }
203 for _, name := range []string{"../../Makefile", "../../packaging/equipo-runner.service", "../runner/config.go"} {
204 raw, err := os.ReadFile(name)
205 executionMust(t, err)
206 for _, dead := range []string{"EQUIPO_NODE_PATH", "EQUIPO_PASEO_", "npm ci", "node --version", "User=equipo-runner"} {
207 if strings.Contains(string(raw), dead) {
208 t.Fatalf("%s still requires %s", name, dead)
209 }
210 }
211 }
212}
213
214func TestDirectDeadReferencesRepository(t *testing.T) {
215 // The scan reads every file git lists.
216 testci.RepoFiles(t)
217 script, err := filepath.Abs("../../scripts/runner-dead-references.py")
218 executionMust(t, err)
219 testci.Files(t, script)
220 if out, err := exec.Command("python3", script).CombinedOutput(); err != nil {
221 t.Fatalf("repository reference inventory: %v\n%s", err, out)
222 }
223}
224
225func TestDirectDeadReferences(t *testing.T) {
226 script, err := filepath.Abs("../../scripts/runner-dead-references.py")
227 executionMust(t, err)
228 testci.Files(t, script)
229 for _, name := range []string{"active.go", "active_test.go", "Makefile", "docs/current.md", "scripts/build.sh", "ui.html", "config.json", ".hidden", "odd.extension"} {
230 t.Run(name, func(t *testing.T) {
231 root := t.TempDir()
232 cmd := exec.Command("git", "init", "-q", root)
233 executionMust(t, cmd.Run())
234 executionMust(t, os.MkdirAll(filepath.Dir(filepath.Join(root, name)), 0700))
235 executionMust(t, os.WriteFile(filepath.Join(root, name), []byte("obsolete paseo dependency\n"), 0600))
236 cmd = exec.Command("git", "-C", root, "add", ".")
237 executionMust(t, cmd.Run())
238 cmd = exec.Command("python3", script, "--root", root)
239 out, err := cmd.CombinedOutput()
240 if err == nil || !strings.Contains(string(out), name) {
241 t.Fatalf("scanner missed tracked %s: %v %s", name, err, out)
242 }
243 })
244 }
245}
246
247func TestDirectLegacyWorkCannotResume(t *testing.T) {
248 f := runnerFixtureNew(t, false)
249 _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "legacy-v1"})
250 if err == nil {
251 t.Fatal("legacy protocol claimed new work")
252 }
253}
254
255func cutoverRow(t *testing.T, d *db.DB, table string, values map[string]any) {
256 t.Helper()
257 rows, err := d.Writer().Query("PRAGMA table_info(" + table + ")")
258 executionMust(t, err)
259 var names, marks []string
260 var args []any
261 for rows.Next() {
262 var id, required, key int
263 var name, kind string
264 var defaultValue any
265 executionMust(t, rows.Scan(&id, &name, &kind, &required, &defaultValue, &key))
266 value, ok := values[name]
267 if !ok {
268 if defaultValue != nil || required == 0 && key == 0 {
269 continue
270 }
271 if strings.Contains(strings.ToUpper(kind), "INT") {
272 value = 0
273 } else {
274 value = ""
275 }
276 }
277 names = append(names, name)
278 marks = append(marks, "?")
279 args = append(args, value)
280 }
281 executionMust(t, rows.Err())
282 executionMust(t, rows.Close())
283 _, err = d.Writer().Exec("INSERT INTO "+table+"("+strings.Join(names, ",")+") VALUES("+strings.Join(marks, ",")+")", args...)
284 executionMust(t, err)
285}
286
287func TestDirectDeadReferencesExactAllowances(t *testing.T) {
288 script, err := filepath.Abs("../../scripts/runner-dead-references.py")
289 executionMust(t, err)
290 testci.Files(t, script)
291 root := t.TempDir()
292 executionMust(t, exec.Command("git", "init", "-q", root).Run())
293 file := filepath.Join(root, "active.go")
294 line := "// equipo-runner executable"
295 executionMust(t, os.WriteFile(file, []byte(line+"\n"), 0600))
296 executionMust(t, exec.Command("git", "-C", root, "add", ".").Run())
297 executionMust(t, os.Mkdir(filepath.Join(root, "scripts"), 0700))
298 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."}
299 write := func(v any) {
300 executionMust(t, os.WriteFile(filepath.Join(root, "scripts/runner-reference-allowlist.json"), flowJSON(v), 0600))
301 }
302 run := func(pass bool) {
303 t.Helper()
304 cmd := exec.Command("python3", script, "--root", root)
305 out, err := cmd.CombinedOutput()
306 if (err == nil) != pass {
307 t.Fatalf("classification pass=%v: %v %s", pass, err, out)
308 }
309 }
310 write([]any{entry})
311 run(true)
312 executionMust(t, os.WriteFile(file, []byte(line+" and obsolete paseo\n"), 0600))
313 run(false)
314 executionMust(t, os.WriteFile(file, []byte("// no references\n"), 0600))
315 run(false)
316 executionMust(t, os.WriteFile(file, []byte(line+"\n"), 0600))
317 entry["line_sha256"] = "*"
318 write([]any{entry})
319 run(false)
320 entry["line_sha256"] = fmt.Sprintf("%x", sha256.Sum256([]byte(line)))
321 entry["file_exemption"] = true
322 write([]any{entry})
323 run(false)
324}
325
326func TestDirectPreparationEventScope(t *testing.T) {
327 for _, kind := range []string{"namespace.owner", "namespace.launch", "timeline", "turn.completed"} {
328 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()}
329 want := strings.HasPrefix(kind, "namespace.")
330 if (e.Validate() == nil) != want {
331 t.Fatal("incorrect preparation event scope", kind)
332 }
333 e.Scope.Job = -1
334 if e.Validate() == nil {
335 t.Fatal("negative job accepted")
336 }
337 }
338}
339
340func TestDirectCutoverPendingSelectionStaysFenced(t *testing.T) {
341 f := bugFixture(t)
342 task := bugTask(t, f)
343 mustSQL(t, f.d, "UPDATE task_outboxes SET state='reconcile' WHERE task_id=?", task.ID)
344 mustSQL(t, f.d, "UPDATE tasks SET state='waiting',wait_code='task.wait.reconcile' WHERE id=?", task.ID)
345 x := attachBugExecution(t, f)
346 executionMust(t, x.Sync(connectionContext))
347 if scalar(t, f.d, "SELECT count(*) FROM runner_assignments") != 0 {
348 t.Fatal("cutover silently selected new work")
349 }
350 saved, err := f.s.Task(connectionContext, ownerActor, task.ID)
351 executionMust(t, err)
352 if saved.WaitCode != "task.wait.reconcile" {
353 t.Fatal("cutover person wait was relabelled", saved.WaitCode)
354 }
355}
356
357func TestDirectLegacyProofCannotCertifyContainment(t *testing.T) {
358 f := runnerFixtureNew(t, true, true)
359 mustSQL(t, f.d, "UPDATE runner_assignments SET protocol_version=1 WHERE id=?", f.a.ID)
360 q := f.request()
361 if _, err := f.x.Mutate(connectionContext, f.principal, "validate", q); err == nil {
362 t.Fatal("legacy assignment gained current authority")
363 }
364 claim := equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
365 if _, err := f.x.RecoverClaim(connectionContext, f.principal, claim); err == nil {
366 t.Fatal("legacy claim was recovered")
367 }
368 q.Proof = flowJSON(runnerproto.ContainmentProof{Version: 2, Scope: q.Scope, Handle: q.Handle, CheckedAt: time.Now().UTC()})
369 if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
370 t.Fatal("legacy process was certified by an empty direct proof")
371 }
372 if scalar(t, f.d, "SELECT count(*) FROM attempts WHERE containment='pending'") != 1 {
373 t.Fatal("legacy capacity released")
374 }
375}
376
377func TestDirectLegacyEvidenceNotReconciled(t *testing.T) {
378 f := runnerFixtureNew(t, true)
379 seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID)
380 mustSQL(t, f.d, "UPDATE runner_assignments SET protocol_version=1,state='fenced' WHERE id=?", f.a.ID)
381 mustSQL(t, f.d, "UPDATE tasks SET state='waiting',wait_code='task.wait.reconcile' WHERE id=?", f.a.TaskID)
382 mustSQL(t, f.d, "UPDATE connections SET reports_json='[]'")
383 var before, after string
384 executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", f.a.ID).Scan(&before))
385 executionMust(t, f.x.Sync(connectionContext))
386 executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", f.a.ID).Scan(&after))
387 if before != after {
388 t.Fatal("legacy evidence was automatically reconciled")
389 }
390}
391
392func TestDirectDeadReferencesTrackedOnly(t *testing.T) {
393 script, err := filepath.Abs("../../scripts/runner-dead-references.py")
394 executionMust(t, err)
395 testci.Files(t, script)
396 root := t.TempDir()
397 executionMust(t, exec.Command("git", "init", "-q", root).Run())
398 executionMust(t, os.WriteFile(filepath.Join(root, "untracked.txt"), []byte("obsolete paseo dependency\n"), 0600))
399 executionMust(t, os.WriteFile(filepath.Join(root, ".gitignore"), []byte("ignored.txt\n"), 0600))
400 executionMust(t, os.WriteFile(filepath.Join(root, "ignored.txt"), []byte("obsolete node dependency\n"), 0600))
401 if out, err := exec.Command("python3", script, "--root", root).CombinedOutput(); err != nil {
402 t.Fatalf("untracked content scanned: %v %s", err, out)
403 }
404 executionMust(t, exec.Command("git", "-C", root, "add", "untracked.txt").Run())
405 if out, err := exec.Command("python3", script, "--root", root).CombinedOutput(); err == nil || !strings.Contains(string(out), "untracked.txt") {
406 t.Fatalf("tracked content missed: %v %s", err, out)
407 }
408}
409