| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/taskplan" |
| 5 | "errors" |
| 6 | "net/http/httptest" |
| 7 | "net/url" |
| 8 | "reflect" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo" |
| 13 | "amadan.net/oficina/equipo/internal/equipo/library" |
| 14 | ) |
| 15 | |
| 16 | func specialistInput(name string) equipo.SpecialistInput { |
| 17 | return equipo.SpecialistInput{Name: name, Icon: "check-circle", Instructions: "Check the supplied evidence.", MaxConcurrent: 1} |
| 18 | } |
| 19 | func TestSpecialistLibraryCopies(t *testing.T) { |
| 20 | f := newFixture(t) |
| 21 | ref := equipo.TemplateRef{ID: "qa", Version: 1} |
| 22 | a, err := f.Store.InstallSpecialistTemplate(ctx, owner, ref, equipo.Mutation{RequestID: "a"}) |
| 23 | must(t, err) |
| 24 | b, err := f.Store.InstallSpecialistTemplate(ctx, owner, ref, equipo.Mutation{RequestID: "b"}) |
| 25 | must(t, err) |
| 26 | if a.Key == b.Key || a.TemplateID != "qa" || a.TemplateVersion != 1 || a.Creator != owner.Address { |
| 27 | t.Fatal("copies lack independent identity or provenance") |
| 28 | } |
| 29 | retry, err := f.Store.InstallSpecialistTemplate(ctx, owner, ref, equipo.Mutation{RequestID: "a"}) |
| 30 | must(t, err) |
| 31 | if retry.Key != a.Key { |
| 32 | t.Fatal("retry duplicated copy") |
| 33 | } |
| 34 | in := library.Input(a) |
| 35 | in.Name = "Our QA" |
| 36 | in.Instructions = "Our own instructions." |
| 37 | a, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: a.Revision}) |
| 38 | must(t, err) |
| 39 | b2, err := f.Store.Specialist(ctx, owner, b.Key) |
| 40 | must(t, err) |
| 41 | if !reflect.DeepEqual(b, b2) { |
| 42 | t.Fatal("editing one copy changed another") |
| 43 | } |
| 44 | diff, err := f.Store.SpecialistTemplateDiff(ctx, owner, a.Key, ref) |
| 45 | must(t, err) |
| 46 | if string(diff.Current["name"]) != `"Our QA"` || string(diff.Old["name"]) == string(diff.Current["name"]) || diff.CurrentRevision != a.Revision { |
| 47 | t.Fatal("diff lost old/current values", diff) |
| 48 | } |
| 49 | a, err = f.Store.ApplySpecialistTemplate(ctx, owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "apply", Revision: a.Revision}) |
| 50 | must(t, err) |
| 51 | if a.Name != b.Name || a.StandingInstructions != "Our own instructions." { |
| 52 | t.Fatal("selected fields not respected") |
| 53 | } |
| 54 | _, err = f.Store.ApplySpecialistTemplate(ctx, owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "stale", Revision: diff.CurrentRevision}) |
| 55 | if !errors.Is(err, equipo.ErrConflict) { |
| 56 | t.Fatal("stale diff accepted", err) |
| 57 | } |
| 58 | diff, err = f.Store.SpecialistTemplateDiff(ctx, owner, a.Key, ref) |
| 59 | must(t, err) |
| 60 | diff.Suggested["name"] = []byte(`"forged"`) |
| 61 | _, err = f.Store.ApplySpecialistTemplate(ctx, owner, a.Key, diff, []string{"name"}, equipo.Mutation{RequestID: "forged", Revision: a.Revision}) |
| 62 | if !errors.Is(err, equipo.ErrConflict) { |
| 63 | t.Fatal("forged diff accepted", err) |
| 64 | } |
| 65 | } |
| 66 | func TestSpecialistRequiredDefaults(t *testing.T) { |
| 67 | f := newFixture(t) |
| 68 | for _, key := range []string{"engineering", "review"} { |
| 69 | row, err := f.Store.Specialist(ctx, owner, key) |
| 70 | must(t, err) |
| 71 | if !row.Required || row.Role != key { |
| 72 | t.Fatal("required default lost role", row) |
| 73 | } |
| 74 | err = f.Store.DeleteSpecialist(ctx, owner, key, equipo.Mutation{RequestID: key, Revision: row.Revision}) |
| 75 | if !errors.Is(err, equipo.ErrForbidden) { |
| 76 | t.Fatal("required default archived", err) |
| 77 | } |
| 78 | in := library.Input(row) |
| 79 | in.Name = "Different role" |
| 80 | _, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "convert-" + key, Revision: row.Revision}) |
| 81 | if !errors.Is(err, equipo.ErrForbidden) { |
| 82 | t.Fatal("required role converted", err) |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | func TestSpecialistToolPolicy(t *testing.T) { |
| 87 | f := newFixture(t) |
| 88 | for _, tools := range [][]string{{"sh -c deploy"}, {"Bash"}, {"submit_candidate"}, {"submit_answer", "ask_person"}} { |
| 89 | in := specialistInput("Unsafe") |
| 90 | in.Tools = tools |
| 91 | if _, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: strings.Join(tools, ",")}); err == nil { |
| 92 | t.Fatal("uncertified or arbitrary tools accepted", tools) |
| 93 | } |
| 94 | } |
| 95 | row, err := f.Store.CreateSpecialist(ctx, owner, specialistInput("Safe"), equipo.Mutation{RequestID: "safe"}) |
| 96 | must(t, err) |
| 97 | if _, err = f.Store.SelectConnection(ctx, owner.Address, 1, row.Key, ""); err == nil { |
| 98 | t.Fatal("unavailable tool profile dispatched") |
| 99 | } |
| 100 | } |
| 101 | func TestSpecialistScopeAndPermissions(t *testing.T) { |
| 102 | f := newFixture(t) |
| 103 | f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| 104 | row, err := f.Store.CreateSpecialist(ctx, peer, specialistInput("Team QA"), equipo.Mutation{RequestID: "create"}) |
| 105 | must(t, err) |
| 106 | in := library.Input(row) |
| 107 | in.Instructions = "Changed" |
| 108 | row, err = f.Store.UpdateSpecialist(ctx, peer, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision}) |
| 109 | must(t, err) |
| 110 | outsider := equipo.Actor{Address: "outsider@example.com"} |
| 111 | must(t, f.Store.SetMember(ctx, owner, outsider.Address, equipo.RoleMember, true, 0)) |
| 112 | in = library.Input(row) |
| 113 | if _, err = f.Store.UpdateSpecialist(ctx, outsider, in, equipo.Mutation{RequestID: "steal", Revision: row.Revision}); !errors.Is(err, equipo.ErrForbidden) { |
| 114 | t.Fatal("other member edited specialist", err) |
| 115 | } |
| 116 | if err = f.Store.DeleteSpecialist(ctx, outsider, row.Key, equipo.Mutation{RequestID: "steal-delete", Revision: row.Revision}); !errors.Is(err, equipo.ErrForbidden) { |
| 117 | t.Fatal("other member deleted specialist", err) |
| 118 | } |
| 119 | in.ProjectIDs = []int64{99999} |
| 120 | if _, err = f.Store.UpdateSpecialist(ctx, peer, in, equipo.Mutation{RequestID: "foreign-project", Revision: row.Revision}); err == nil { |
| 121 | t.Fatal("foreign project accepted") |
| 122 | } |
| 123 | f.exec(t, "UPDATE specialists SET team_id='other-team' WHERE key=?", row.Key) |
| 124 | if _, err = f.Store.Specialist(ctx, owner, row.Key); !errors.Is(err, equipo.ErrNotFound) { |
| 125 | t.Fatal("foreign specialist visible", err) |
| 126 | } |
| 127 | f.exec(t, "UPDATE specialists SET team_id=? WHERE key=?", f.TeamID, row.Key) |
| 128 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", peer.Address) |
| 129 | if _, err = f.Store.CreateSpecialist(ctx, peer, specialistInput("Team QA"), equipo.Mutation{RequestID: "create"}); !errors.Is(err, equipo.ErrForbidden) { |
| 130 | t.Fatal("removed creator replayed write", err) |
| 131 | } |
| 132 | must(t, f.Store.DeleteSpecialist(ctx, owner, row.Key, equipo.Mutation{RequestID: "archive", Revision: row.Revision})) |
| 133 | archived, err := f.Store.Specialist(ctx, owner, row.Key) |
| 134 | must(t, err) |
| 135 | if !archived.Archived { |
| 136 | t.Fatal("history deleted instead of archived") |
| 137 | } |
| 138 | } |
| 139 | func TestSpecialistTemplateGroups(t *testing.T) { |
| 140 | f := newFixture(t) |
| 141 | rows, err := f.Store.SpecialistTemplates(ctx, owner) |
| 142 | must(t, err) |
| 143 | expected := map[string]string{"qa": "quality", "accessibility": "quality", "performance": "quality", "security": "safety", "privacy": "safety", "ops": "running", "data": "running", "support": "running", "docs": "words", "localisation": "words", "seo": "words", "blank": ""} |
| 144 | if len(rows) != len(expected) { |
| 145 | t.Fatal("catalog missing templates", len(rows)) |
| 146 | } |
| 147 | for _, row := range rows { |
| 148 | group, ok := expected[row.Ref.ID] |
| 149 | if !ok || row.Group != group || row.NameKey == "" || row.Icon == "" || row.InstructionsKey == "" { |
| 150 | t.Fatal("missing group/name/icon/instructions", row) |
| 151 | } |
| 152 | } |
| 153 | w := f.get(t, owner, "/templates") |
| 154 | if w.Code != 200 || !strings.Contains(w.Body.String(), "QA and testing") || !strings.Contains(w.Body.String(), "<svg") { |
| 155 | t.Fatal("template display", w.Code, w.Body.String()) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | func TestSpecialistScopeArchiveReferences(t *testing.T) { |
| 160 | f := newFixture(t) |
| 161 | base := f.createTask(t) |
| 162 | row, err := f.Store.CreateSpecialist(ctx, owner, specialistInput("My specialist"), equipo.Mutation{RequestID: "create"}) |
| 163 | must(t, err) |
| 164 | p := taskplan.BugPlan("", base.ProjectID) |
| 165 | p.Revision = 0 |
| 166 | p.Steps[0].Specialist = row.Key |
| 167 | p, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| 168 | must(t, err) |
| 169 | if err = f.Store.DeleteSpecialist(ctx, owner, row.Key, equipo.Mutation{RequestID: "archive", Revision: row.Revision}); !errors.Is(err, equipo.ErrConflict) { |
| 170 | t.Fatal("unstarted plan lost specialist", err) |
| 171 | } |
| 172 | snapshot := `{"StandingInstructions":"Check the supplied evidence.","step":{"SpecialistKey":"` + row.Key + `","SpecialistRevision":1}}` |
| 173 | f.exec(t, "INSERT INTO runner_assignments(id,task_id,step_key,claim_request,brief) VALUES(?,?,?,?,?)", "saved-step", p.TaskID, "reproduce", "claimed", snapshot) |
| 174 | in := library.Input(row) |
| 175 | in.Instructions = "Future work instructions." |
| 176 | row, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision}) |
| 177 | must(t, err) |
| 178 | var got string |
| 179 | must(t, f.DB.Writer().QueryRow("SELECT brief FROM runner_assignments WHERE id='saved-step'").Scan(&got)) |
| 180 | if got != snapshot { |
| 181 | t.Fatal("started snapshot rewritten") |
| 182 | } |
| 183 | must(t, f.Store.DeleteSpecialist(ctx, owner, row.Key, equipo.Mutation{RequestID: "archive", Revision: row.Revision})) |
| 184 | must(t, f.DB.Writer().QueryRow("SELECT brief FROM runner_assignments WHERE id='saved-step'").Scan(&got)) |
| 185 | if got != snapshot { |
| 186 | t.Fatal("archiving changed started snapshot") |
| 187 | } |
| 188 | next := taskplan.BugPlan("", base.ProjectID) |
| 189 | next.Revision = 0 |
| 190 | next.Steps[0].Specialist = row.Key |
| 191 | if _, err = f.Store.ProposePlan(ctx, owner, next, equipo.Mutation{RequestID: "archived-plan"}); err == nil { |
| 192 | t.Fatal("archived specialist offered to new plan") |
| 193 | } |
| 194 | } |
| 195 | func TestSpecialistLibraryRevisionAndAudit(t *testing.T) { |
| 196 | f := newFixture(t) |
| 197 | in := specialistInput("Original") |
| 198 | row, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "create"}) |
| 199 | must(t, err) |
| 200 | in.Name = "Changed" |
| 201 | if _, err = f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "create"}); !errors.Is(err, equipo.ErrConflict) { |
| 202 | t.Fatal("changed request accepted", err) |
| 203 | } |
| 204 | in = library.Input(row) |
| 205 | in.Name = "New" |
| 206 | edited, err := f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision}) |
| 207 | must(t, err) |
| 208 | replay, err := f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "edit", Revision: row.Revision}) |
| 209 | must(t, err) |
| 210 | if edited.Revision != replay.Revision { |
| 211 | t.Fatal("retry advanced revision") |
| 212 | } |
| 213 | if _, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "stale", Revision: row.Revision}); !errors.Is(err, equipo.ErrConflict) { |
| 214 | t.Fatal("stale update accepted", err) |
| 215 | } |
| 216 | f.exec(t, `CREATE TRIGGER reject_library_audit BEFORE INSERT ON audit_events WHEN NEW.kind='specialist.update' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END`) |
| 217 | in.Name = "Must roll back" |
| 218 | if _, err = f.Store.UpdateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "rollback", Revision: edited.Revision}); err == nil { |
| 219 | t.Fatal("audit failure accepted") |
| 220 | } |
| 221 | got, err := f.Store.Specialist(ctx, owner, row.Key) |
| 222 | must(t, err) |
| 223 | if got.Name != edited.Name || got.Revision != edited.Revision { |
| 224 | t.Fatal("audit failure did not roll back") |
| 225 | } |
| 226 | } |
| 227 | func TestSpecialistTemplateForms(t *testing.T) { |
| 228 | f := newFixture(t) |
| 229 | f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| 230 | post := func(actor equipo.Actor, path string, values url.Values) *httptest.ResponseRecorder { |
| 231 | r := httptest.NewRequest("POST", path, strings.NewReader(values.Encode())) |
| 232 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 233 | r.Header.Set("Origin", origin) |
| 234 | r.AddCookie(f.Cookies[actor.Address]) |
| 235 | w := httptest.NewRecorder() |
| 236 | f.Handler.ServeHTTP(w, r) |
| 237 | return w |
| 238 | } |
| 239 | values := url.Values{"request_id": {"web-create"}, "revision": {"0"}, "name": {"Web QA"}, "icon": {"check-circle"}, "instructions": {"Check evidence."}, "max_concurrent": {"1"}} |
| 240 | w := post(peer, "/specialists", values) |
| 241 | if w.Code != 303 { |
| 242 | t.Fatal("active member could not create", w.Code, w.Body.String()) |
| 243 | } |
| 244 | key := strings.TrimPrefix(w.Header().Get("Location"), "/specialists/") |
| 245 | // Custom specialists are an old-engine page; the thin sidebar (slice |
| 246 | // 4) does not list them, so /work no longer names them. |
| 247 | for _, path := range []string{"/specialists/" + key, "/specialists/" + key + "/edit"} { |
| 248 | w = f.get(t, peer, path) |
| 249 | if w.Code != 200 || !strings.Contains(w.Body.String(), "Web QA") { |
| 250 | t.Fatal("custom specialist missing from page", path, w.Code) |
| 251 | } |
| 252 | } |
| 253 | values.Set("actor", owner.Address) |
| 254 | values.Set("request_id", "forged") |
| 255 | if w = post(peer, "/specialists", values); w.Code != 422 { |
| 256 | t.Fatal("submitted actor accepted", w.Code) |
| 257 | } |
| 258 | values.Del("actor") |
| 259 | values["name"] = []string{"one", "two"} |
| 260 | if w = post(peer, "/specialists", values); w.Code != 422 { |
| 261 | t.Fatal("duplicate field accepted", w.Code) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | func TestSpecialistScopeProjectAndModels(t *testing.T) { |
| 266 | f := newFixture(t) |
| 267 | base := f.createTask(t) |
| 268 | other := equipo.Project{Name: "Other", Repository: "amadan.net/test/other", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| 269 | must(t, f.DB.G.Create(&other).Error) |
| 270 | must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: other.ID, Decision: "merge", Address: owner.Address}).Error) |
| 271 | in := specialistInput("Project QA") |
| 272 | in.ProjectIDs = []int64{base.ProjectID} |
| 273 | in.AllowedModels = []equipo.ModelRef{{Provider: "codex", Family: "gpt", Model: "fixture-model"}} |
| 274 | row, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "project-qa"}) |
| 275 | must(t, err) |
| 276 | if library.ModelAllowed(row, "codex", "gpt", "another-model") || !library.ModelAllowed(row, "codex", "gpt", "fixture-model") { |
| 277 | t.Fatal("allowed model set ignored") |
| 278 | } |
| 279 | p := taskplan.BugPlan("", other.ID) |
| 280 | p.Revision = 0 |
| 281 | p.Steps[0].Specialist = row.Key |
| 282 | if _, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "other-project"}); !errors.Is(err, equipo.ErrForbidden) { |
| 283 | t.Fatal("specialist project set ignored", err) |
| 284 | } |
| 285 | p.ProjectID = base.ProjectID |
| 286 | p, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "allowed-project"}) |
| 287 | must(t, err) |
| 288 | counts, err := f.Store.SpecialistCounts(ctx, owner) |
| 289 | must(t, err) |
| 290 | if counts[row.Key].Queued != 1 || !counts[row.Key].CountsKnown || counts[row.Key].UsageKnown { |
| 291 | t.Fatal("custom counts lost unknown usage", counts[row.Key]) |
| 292 | } |
| 293 | view, err := f.Store.TaskView(ctx, owner, p.TaskID) |
| 294 | must(t, err) |
| 295 | if view.Steps[0].CategoryName != row.Name || view.Steps[0].CategoryIcon != row.Icon { |
| 296 | t.Fatal("custom category lost icon/name") |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | func TestSpecialistScopeLookupFailure(t *testing.T) { |
| 301 | f := newFixture(t) |
| 302 | f.exec(t, "DROP TABLE projects") |
| 303 | in := specialistInput("Must not save") |
| 304 | in.ProjectIDs = []int64{1} |
| 305 | if _, err := f.Store.CreateSpecialist(ctx, owner, in, equipo.Mutation{RequestID: "lookup"}); !errors.Is(err, equipo.ErrUnavailable) { |
| 306 | t.Fatal("project query failure lost unavailable state", err) |
| 307 | } |
| 308 | if f.count(t, "SELECT count(*) FROM specialists WHERE creator<>''") != 0 { |
| 309 | t.Fatal("lookup failure saved record") |
| 310 | } |
| 311 | } |
| 312 | |