package equipotest import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" "context" "fmt" "io" "log/slog" "path/filepath" "strings" "testing" "time" ) func migratedExitFixture(t *testing.T, claimed, cancelled bool) (*equipo.Store, *equipo.Execution, *db.DB, string) { t.Helper() ctx := context.Background() path := filepath.Join(t.TempDir(), "old.db") d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) t.Cleanup(func() { d.Close() }) before := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if schemaBefore(m.ID, "0017") { before.Add(m) } } _, err = migrate.Apply(ctx, d, before) executionMust(t, err) s := equipo.NewStore(d) cutoverRow(t, d, "teams", map[string]any{"id": "team", "name": "Existing team", "roster_epoch": 1}) cutoverRow(t, d, "members", map[string]any{"address": ownerAddress, "role": "owner", "active": 1, "revision": 1}) cutoverRow(t, d, "members", map[string]any{"address": "member@example.com", "role": "member", "active": 1, "revision": 1}) options := executionOptions() options.Authority.(*team.FakeAuthority).Issue("old-grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpJobContinue: true, team.OpAttemptContinue: true}}) core, err := team.Open(ctx, path, options) executionMust(t, err) x := &equipo.Execution{Core: core} _, err = x.Core.Resume(ctx) executionMust(t, err) job, err := x.Core.CreateJob(ctx, team.JobSpec{Account: "team", Requester: ownerAddress, GrantRef: "old-grant", Target: team.TargetBinding{Kind: team.TargetRepository, Repository: "example/shop", Ref: "team/old", DefaultRef: "main", BaseRevision: fmt.Sprintf("%064x", 1)}, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, Policy: team.DefaultPolicy(5000000, team.Rates{Version: 1}), Steps: team.SoftwareSteps(false)}) executionMust(t, err) var instance equipo.Team executionMust(t, d.G.First(&instance).Error) // The job's authority account matches the migrated task's team. _, err = d.Writer().Exec("UPDATE jobs SET account=? WHERE id=?", instance.ID, job.ID) executionMust(t, err) state := "queued" if cancelled { state = "cancel_requested" } cutoverRow(t, d, "tasks", map[string]any{"id": "old", "team_id": instance.ID, "job_id": job.ID, "state": state, "request_id": "old", "requester": ownerAddress, "revision": 1}) cutoverRow(t, d, "task_outboxes", map[string]any{"task_id": "old", "state": "done", "engineering": "{}", "review": "{}"}) if cancelled { cutoverRow(t, d, "audit_events", map[string]any{"actor": ownerAddress, "kind": "task.cancel", "record_id": "old", "at": time.Now().UTC()}) } if claimed { stamp := "2026-11-02T11:59:00Z" cutoverRow(t, d, "attempts", map[string]any{"id": 1, "job_id": job.ID, "step_id": 1, "number": 1, "state": "active", "containment": "pending", "fence": 7, "created_at": stamp, "updated_at": stamp, "lease_deadline": "2026-11-02T12:01:00Z"}) _, err = d.Writer().Exec("UPDATE steps SET holder=1,state='running',fence=7 WHERE id=1") executionMust(t, err) cutoverRow(t, d, "time_reservations", map[string]any{"attempt_id": 1, "job_id": job.ID, "state": "open", "reserved_seconds": 120, "started_at": stamp}) cutoverRow(t, d, "runner_assignments", map[string]any{"id": "v1", "task_id": "old", "team_id": instance.ID, "state": "claimed", "claim_request": "old-claim", "attempt_id": 1, "job_id": job.ID, "fence": 7}) } executionMust(t, core.Close()) _, err = migrate.Apply(ctx, d, equipo.BootSchema) executionMust(t, err) x, err = s.AttachExecution(ctx, path, options) executionMust(t, err) t.Cleanup(func() { x.Core.Close() }) return s, x, d, "old" } func TestMigratedTaskWaitExit(t *testing.T) { for _, kind := range []string{"unclaimed", "unclaimed-cancel", "claimed", "claimed-cancel", "member", "removed-owner", "audit-failure"} { t.Run(kind, func(t *testing.T) { claimed := !strings.HasPrefix(kind, "unclaimed") cancelled := strings.HasSuffix(kind, "cancel") s, _, d, id := migratedExitFixture(t, claimed, cancelled) var state, wait string executionMust(t, d.Writer().QueryRow("SELECT state,wait_code FROM tasks WHERE id=?", id).Scan(&state, &wait)) if !claimed { if wait == "task.wait.reconcile" { t.Fatal("unclaimed task trapped") } if cancelled && state != "cancelled" { t.Fatal("cancel request lost", state) } return } actor := ownerActor if kind == "member" { actor = equipo.Actor{Address: "member@example.com"} } if kind == "removed-owner" { _, err := d.Writer().Exec("UPDATE members SET active=0 WHERE address=?", ownerAddress) executionMust(t, err) } if kind == "audit-failure" { _, err := d.Writer().Exec("CREATE TRIGGER stop_audit_failure BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'audit unavailable'); END") executionMust(t, err) } err := s.OldRunnerStopped(context.Background(), actor, id) if kind == "member" || kind == "removed-owner" || kind == "audit-failure" { if err == nil { t.Fatal("unauthorized or unaudited containment") } if scalar(t, d, "SELECT count(*) FROM attempts WHERE containment='pending'") != 1 { t.Fatal("failed transaction changed containment") } return } executionMust(t, err) executionMust(t, d.Writer().QueryRow("SELECT state,wait_code FROM tasks WHERE id=?", id).Scan(&state, &wait)) if wait == "task.wait.reconcile" || cancelled && state != "cancelled" { t.Fatal("task still trapped", state, wait) } if scalar(t, d, "SELECT count(*) FROM runner_assignments WHERE state='contained'") != 1 || scalar(t, d, "SELECT count(*) FROM attempts WHERE containment='contained'") != 1 { t.Fatal("v1 work not contained") } if scalar(t, d, "SELECT count(*) FROM audit_events WHERE kind='task.old_runner_stopped'") != 1 { t.Fatal("missing audit") } if !cancelled { var jobState string executionMust(t, d.Writer().QueryRow("SELECT state FROM jobs LIMIT 1").Scan(&jobState)) if jobState != "running" { t.Fatal("job not resumed", jobState) } } }) } }