package plan3test import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "encoding/json" "fmt" "net/url" "os" "strings" "testing" ) func TestPersonAPISharedOperations(t *testing.T) { f := newFixture(t) body := `{"name":"Parity QA","icon":"check-circle","instructions":"Check the supplied evidence.","max_concurrent":1}` form := url.Values{"name": {"Parity QA"}, "icon": {"check-circle"}, "instructions": {"Check the supplied evidence."}, "max_concurrent": {"1"}, "request_id": {"shared-specialist"}} expectHTTP(t, formPost(t, f, owner, "/specialists", form), 303) w := apiRequest(t, f, owner, "POST", "/api/v1/specialists", body, "shared-specialist", "") expectHTTP(t, w, 200) sp := apiValue[personapi.Specialist](t, w) if sp.ID == "" || sp.Revision != 1 { t.Fatal("missing shared specialist result", sp) } if f.count(t, "SELECT count(*) FROM specialists WHERE name='Parity QA'") != 1 { t.Fatal("HTML/API duplicated specialist") } expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/specialists/"+sp.ID, body, "edit", `"1"`), 200) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/specialists/"+sp.ID, body, "stale", `"1"`), 409) expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/specialists/engineering", `{}`, "required", `"1"`), 403) w = apiRequest(t, f, owner, "POST", "/api/v1/templates/qa/install", `{"version":1}`, "install", "") expectHTTP(t, w, 200) installed := apiValue[personapi.Specialist](t, w) diff := apiRequest(t, f, owner, "GET", "/api/v1/specialists/"+installed.ID+"/template-diff", "", "", "") expectHTTP(t, diff, 200) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/specialists/"+installed.ID+"/template-update", jsonBody(t, personapi.TemplateUpdateInput{Diff: apiValue[personapi.TemplateDiff](t, diff), Fields: []string{"name"}}), "apply", `"1"`), 200) w = apiRequest(t, f, owner, "POST", "/api/v1/templates/playbook_bug/install", `{"version":1}`, "playbook", "") expectHTTP(t, w, 200) pb := apiValue[personapi.Playbook](t, w) pb.Name = "Shared bug" expectHTTP(t, formPost(t, f, owner, "/playbook-templates/playbook_bug/install", url.Values{"request_id": {"playbook"}, "version": {"1"}}), 303) w = apiRequest(t, f, owner, "PATCH", "/api/v1/playbooks/"+pb.ID, jsonBody(t, pb.PlaybookInput), "playbook-edit", `"1"`) expectHTTP(t, w, 200) if apiValue[personapi.Playbook](t, w).Revision != 2 { t.Fatal("playbook parity failed") } account := apiRequest(t, f, owner, "POST", "/api/v1/accounts", `{"label":"Manual account"}`, "account", "") expectHTTP(t, account, 200) again := apiRequest(t, f, owner, "POST", "/api/v1/accounts", `{"label":"Manual account"}`, "account", "") expectHTTP(t, again, 200) if account.Body.String() != again.Body.String() { t.Fatal("account replay differs") } var accountID int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM accounts WHERE label='Manual account'").Scan(&accountID)) project := personapi.ProjectFields{AccountID: accountID, Name: "Parity", Repository: "amadan.net/test/parity", DefaultBranch: "main", Kind: "repository", Owners: []personapi.DecisionOwner{{Decision: "work", Address: owner.Address}, {Decision: "merge", Address: owner.Address}}} // Thin v1 replaced POST /api/v1/projects (projects by repository from // the runner's allowlist); the old project model is created by its form. expectHTTP(t, formPost(t, f, owner, "/projects", url.Values{"request_id": {"project"}, "account_id": {fmt.Sprint(accountID)}, "name": {"Parity"}, "repository": {"amadan.net/test/parity"}, "default_branch": {"main"}, "kind": {"repository"}, "owner_work": {owner.Address}, "owner_merge": {owner.Address}}), 303) var pj personapi.Project must(t, f.DB.Writer().QueryRow("SELECT id FROM projects WHERE name='Parity'").Scan(&pj.ID)) expectHTTP(t, formPost(t, f, owner, "/projects/"+pj.ID, url.Values{"revision": {"1"}, "request_id": {"project-edit"}, "account_id": {fmt.Sprint(accountID)}, "name": {"Parity"}, "repository": {"amadan.net/test/parity"}, "default_branch": {"main"}, "kind": {"repository"}, "owner_work": {owner.Address}, "owner_merge": {owner.Address}}), 303) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/projects/"+pj.ID, jsonBody(t, project), "project-edit", `"1"`), 200) if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='project.save' AND record_id=?", pj.ID) != 2 { t.Fatal("project replay duplicated audit") } settings := apiRequest(t, f, owner, "GET", "/api/v1/projects/"+pj.ID+"/settings", "", "", "") expectHTTP(t, settings, 200) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/projects/"+pj.ID+"/settings", `{"action":"approval","approval_mode":"required"}`, "approval", settings.Header().Get("ETag")), 200) settings = apiRequest(t, f, owner, "GET", "/api/v1/projects/"+pj.ID+"/settings", "", "", "") expectHTTP(t, settings, 200) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/projects/"+pj.ID+"/settings", `{"action":"rules","rules":"Use the team's terminology."}`, "rules", settings.Header().Get("ETag")), 200) f.planConnections(t, 1) var connection string must(t, f.DB.Writer().QueryRow("SELECT id FROM connections WHERE person=? ORDER BY id LIMIT 1", owner.Address).Scan(&connection)) w = apiRequest(t, f, owner, "GET", "/api/v1/connections/"+connection, "", "", "") expectHTTP(t, w, 200) c := apiValue[personapi.Connection](t, w) expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/connections/"+connection, "", "", ""), 404) expectHTTP(t, formPost(t, f, owner, "/projects/"+pj.ID+"/connections", url.Values{"revision": {"1"}, "mode": {"best_fit"}, "connection_id": {connection}}), 303) expectHTTP(t, apiRequest(t, f, owner, "PUT", "/api/v1/projects/"+pj.ID+"/connections", jsonBody(t, personapi.ConnectionChoiceInput{ConnectionIDs: []string{connection}, Mode: "best_fit"}), "choices", `"2"`), 200) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/connections/"+connection, `{"label":"My account"}`, "label", fmt.Sprintf(`"%d"`, c.Revision)), 200) expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/connections/"+connection, `{}`, "revoke-connection", fmt.Sprintf(`"%d"`, c.Revision+1)), 200) if f.count(t, "SELECT count(*) FROM connection_invalidations WHERE connection_id=? AND reason='revoked'", connection) != 1 { t.Fatal("revocation did not request fencing") } expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/onboarding/advance", `{"step":"welcome"}`, "welcome", `"1"`), 200) expectHTTP(t, formPost(t, f, owner, "/onboarding/advance", url.Values{"step": {"welcome"}, "request_id": {"welcome"}, "revision": {"1"}}), 303) accountRunner(t, f) w = apiRequest(t, f, owner, "POST", "/api/v1/account-setups", `{"runner_id":"account-runner","provider":"codex","label":"Personal"}`, "setup", "") expectHTTP(t, w, 200) fields := apiValue[map[string]any](t, w) if len(fields) != 4 { t.Fatal("account setup exposes more than ID, state, mode, command", fields) } setupID := fields["id"].(string) expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/account-setups/"+setupID, "", "", ""), 404) expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/account-setups/"+setupID, `{}`, "cancel", w.Header().Get("ETag")), 200) } func TestPersonAPISharedPendingInvitation(t *testing.T) { f := newFixture(t) recipient := equipo.Actor{Address: "pending@example.com"} in, secret := issueInvite(t, f, recipient.Address) inviteSession(t, f, recipient) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/invites/"+in.ID, "", "", ""), 200) expectHTTP(t, apiRequest(t, f, recipient, "GET", "/api/v1/invites/"+in.ID, "", "", ""), 200) for _, path := range []string{"/people", "/tasks", "/conversation", "/accounts", "/runners", "/teams"} { expectHTTP(t, apiRequest(t, f, recipient, "GET", "/api/v1"+path, "", "", ""), 403) } expectHTTP(t, apiRequest(t, f, recipient, "POST", "/api/v1/invites/"+in.ID+"/accept", jsonBody(t, personapi.AcceptInviteInput{Secret: secret}), "accept", `"1"`), 200) expectHTTP(t, apiRequest(t, f, recipient, "POST", "/api/v1/invites/"+in.ID+"/accept", jsonBody(t, personapi.AcceptInviteInput{Secret: secret}), "accept", `"1"`), 200) expectHTTP(t, apiRequest(t, f, recipient, "GET", "/api/v1/people", "", "", ""), 200) } func TestPersonAPINativeAnswers(t *testing.T) { f, _, _, _, q := nativeConversationFixture(t) apiRouter(t, f, nil) cred := approvedDevice(t, f) path := "/api/v1/questions/" + q.ID + "/answer" body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` expectHTTP(t, deviceRequest(t, f, "notification-action", "POST", path, body, "unauth", `"1"`), 401) expectHTTP(t, deviceRequest(t, f, cred.Token, "POST", path, body, "stale", `"2"`), 409) expectHTTP(t, deviceRequest(t, f, cred.Token, "POST", path, body, "answer", `"1"`), 200) f.exec(t, "UPDATE questions SET state='invalid' WHERE id=?", q.ID) expectHTTP(t, deviceRequest(t, f, cred.Token, "POST", path, body, "cancelled", `"1"`), 409) f.exec(t, "UPDATE members SET role='member' WHERE address=?", owner.Address) f.exec(t, "UPDATE tasks SET requester=? WHERE id=?", peer.Address, q.TaskID) expectHTTP(t, deviceRequest(t, f, cred.Token, "POST", path, body, "other-recipient", `"1"`), 403) } func TestPersonAPIPaginationUnknown(t *testing.T) { f := newFixture(t) for _, name := range []string{"One", "Two", "Three"} { _, e := f.Store.CreateSpecialist(ctx, owner, specialistInput(name), equipo.Mutation{RequestID: name}) must(t, e) } f.exec(t, "DROP TABLE reservations") w := apiRequest(t, f, owner, "GET", "/api/v1/specialists?limit=1", "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.Page[personapi.Specialist]](t, w) if len(page.Items) != 1 || page.NextCursor == "" { t.Fatal("unbounded list", page) } if !strings.Contains(w.Body.String(), `"work_count":null`) { t.Fatal("unknown count became zero") } _, e := f.Store.CreateSpecialist(ctx, owner, specialistInput("Inserted"), equipo.Mutation{RequestID: "inserted"}) must(t, e) next := apiRequest(t, f, owner, "GET", "/api/v1/specialists?limit=1&cursor="+url.QueryEscape(page.NextCursor), "", "", "") expectHTTP(t, next, 200) if apiValue[personapi.Page[personapi.Specialist]](t, next).Items[0].ID == page.Items[0].ID { t.Fatal("repeated cursor item") } expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/specialists?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/playbooks?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/specialists?limit=101", "", "", ""), 422) for _, key := range []string{"template_base", "secret", "session_epoch"} { if strings.Contains(w.Body.String(), key) { t.Fatal("private field", key) } } } func TestPersonAPISchemaCompatibility(t *testing.T) { f := newFixture(t) for _, body := range []string{`{"role":"member","active":true,"session_epoch":0}`, `{"role":"member","role":"owner","active":true}`, `{"role":"member"}`} { expectHTTP(t, apiRequest(t, f, owner, "PUT", "/api/v1/roster/"+peer.Address, body, "invalid", `"1"`), 422) } expectHTTP(t, apiRequest(t, f, owner, "PUT", "/api/v1/budgets", `{"team":{},"projects":{"1":{"rogue":1}}}`, "nested", `"0"`), 422) raw, e := os.ReadFile("testdata/person-api-v1.json") must(t, e) var fixture struct { Device personapi.PersonCredential `json:"device"` AccountSetup personapi.AccountSetup `json:"account_setup"` } must(t, json.Unmarshal(raw, &fixture)) if fixture.Device.Audience != "equipo.person.v1" || fixture.AccountSetup.Command == "" { t.Fatal("v1 fixture changed") } } func TestPersonAPISharedConnectionContainment(t *testing.T) { f, _, _, claim := claimTools(t) apiRouter(t, f, nil) id := claim.Brief.Selection.ConnectionID expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/connections/"+id, `{}`, "contain", fmt.Sprintf(`"%d"`, claim.Brief.Selection.Revision)), 200) var state, containment string must(t, f.DB.Writer().QueryRow("SELECT state,containment FROM attempts WHERE id=?", claim.Handle.Attempt).Scan(&state, &containment)) if state != "stopping" || containment != "pending" { t.Fatal("revocation did not request coordinator containment", state, containment) } }