package plan3test import ( "encoding/json" "net/http" "os" "reflect" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo/personapi" "github.com/go-chi/chi/v5" ) func TestPersonAPIContractCoverage(t *testing.T) { personAPIContractCoverage(t) } // personAPIRoutes are the routes the person API registers, by path: // the methods, space separated. func personAPIRoutes() map[string]string { required := map[string]string{ "/me": "GET", "/capabilities": "GET", "/me/settings": "GET PATCH", "/people": "GET", "/conversation": "GET", "/conversation/messages": "POST", "/conversation/cards": "GET", "/cards/{id}": "GET", "/tasks": "GET POST", "/tasks/{id}": "GET", "/tasks/{id}/cancel": "POST", "/tasks/{id}/thread": "GET", "/tasks/{id}/thread/messages": "POST", "/conversation/messages/{id}/route": "POST", "/tasks/{id}/plan": "GET PATCH", "/tasks/{id}/plan/approve": "POST", "/tasks/{id}/project": "POST", "/questions/{id}": "GET", "/questions/{id}/answer": "POST", "/tasks/{id}/rendered-approval": "POST", "/tasks/{id}/acknowledge-merge": "POST", "/journey": "GET", "/needs-you": "GET", "/preferences": "GET POST", "/preferences/{id}": "PATCH DELETE", "/coordinator": "GET PATCH", "/coordinator/reset": "POST", "/coordinator/retry": "POST", "/coordinator/limits": "PATCH", } for path, methods := range map[string]string{ "/auth/devices/native": "POST", "/auth/devices": "GET POST", "/auth/devices/exchange": "POST", "/auth/devices/{id}/approve": "POST", "/auth/devices/{id}": "DELETE", "/roster": "GET", "/roster/{address}": "PUT", "/budgets": "GET PUT", "/teams": "GET", "/teams/links": "POST", "/teams/links/{id}": "PATCH DELETE", "/accounts": "GET POST", "/projects": "GET POST", "/projects/{id}": "GET PATCH", "/projects/{id}/settings": "GET PATCH", "/projects/{id}/my-settings": "PATCH", "/specialists": "GET POST", "/specialists/{id}": "GET PATCH DELETE", "/playbooks": "GET POST", "/playbooks/{id}": "GET PATCH DELETE", "/templates": "GET", "/templates/{id}": "GET", "/templates/{id}/install": "POST", "/specialists/{id}/template-diff": "GET", "/playbooks/{id}/template-diff": "GET", "/specialists/{id}/template-update": "POST", "/playbooks/{id}/template-update": "POST", "/connections": "GET", "/connections/{id}": "GET PATCH DELETE", "/projects/{id}/connections": "PUT", "/tasks/{id}/steps/{key}/selection": "POST", "/runners": "GET", "/runners/{id}": "GET DELETE", "/runners/enrol/approve": "POST", "/onboarding": "GET", "/onboarding/advance": "POST", "/account-setups": "POST", "/account-setups/{id}": "GET DELETE", "/notifications": "GET", "/notification-subscriptions": "POST", "/notification-subscriptions/{id}": "DELETE", "/notification-subscriptions/{id}/ack": "POST", "/invites": "POST", "/invites/{id}": "GET DELETE", "/invites/{id}/accept": "POST", } { required[path] = methods } return required } func personAPIContractCoverage(t *testing.T) { t.Helper() raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json") must(t, err) var doc struct { OpenAPI string `json:"openapi"` Info struct { Version string `json:"version"` } `json:"info"` Paths map[string]map[string]json.RawMessage `json:"paths"` } must(t, json.Unmarshal(raw, &doc)) if doc.OpenAPI != "3.1.0" || doc.Info.Version != "1.0.0" { t.Fatal("wrong API version") } required := personAPIRoutes() // The Assistant lane's routes (chat.MountAssistant) are Base's, not // personapi registrations: documented here under their own schemas, // with the device bearer alone. assistant := map[string]string{ "/assistant/snapshot": "GET", "/assistant/messages": "GET POST", "/assistant/turns/{id}/cancel": "POST", "/assistant/cards/{id}/answer": "POST", "/assistant/events": "GET", "/assistant/host": "PUT", "/assistant/cards/{id}/carry_on": "POST", "/assistant/time-zone": "PUT", "/assistant/abilities": "GET", "/assistant/abilities/refresh": "POST", } f := newFixture(t) registered := map[string]bool{} assistantRoutes := map[string]bool{} // The conversation engine's own routes, and those it shares with this // API, are TestPersonAPIDeviceContract's. engine := deviceEngineRoutes(t, f) shared := func(key string) bool { return engine[key] && deviceShared[key] != "" } thin := map[string]bool{} for key := range engine { method, path, _ := strings.Cut(key, " ") if !strings.Contains(" "+required[path]+" ", " "+method+" ") && !strings.HasPrefix(path, "/assistant/") { thin[key] = true } } must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { // The app-owned preview capability has a separate contract test. if method == "POST" && path == "/tasks/{id}/preview-pass" { return nil } if thin[method+" "+path] { return nil } if strings.Contains(" "+assistant[path]+" ", " "+method+" ") { assistantRoutes[method+" "+path] = true return nil } registered[method+" "+path] = true return nil })) operationIDs := map[string]string{} for _, r := range personapi.Routes { operationIDs[r.Method+" "+r.Path] = personapi.OperationID(r) } var document map[string]any must(t, json.Unmarshal(raw, &document)) var checkRefs func(any) checkRefs = func(v any) { switch value := v.(type) { case map[string]any: for k, x := range value { if k == "$ref" { ref := x.(string) var node any = document for _, part := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") { m, ok := node.(map[string]any) if !ok || m[part] == nil { t.Fatalf("missing schema reference %s", ref) } node = m[part] } } else { checkRefs(x) } } case []any: for _, x := range value { checkRefs(x) } } } checkRefs(document) schemes := document["components"].(map[string]any)["securitySchemes"].(map[string]any) if schemes["personBearer"] == nil { t.Fatal("person bearer is undocumented") } codes := document["components"].(map[string]any)["schemas"].(map[string]any)["Error"].(map[string]any)["properties"].(map[string]any)["code"].(map[string]any)["enum"].([]any) for _, code := range []string{"device_expired", "slow_down", "authorization_pending", "subscription_expired"} { found := false for _, value := range codes { if value == code { found = true } } if !found { t.Fatal("missing device error schema", code) } } // person is the person API's operation for a route it registers: on a // path the engine shares, the earlier operation kept in // x-earlierPersonAPI; nil where the engine replaced it. person := func(method, path string) map[string]any { op, _ := document["paths"].(map[string]any)[path].(map[string]any)[strings.ToLower(method)].(map[string]any) switch { case !shared(method + " " + path): return op case deviceShared[method+" "+path] == "replaced" || op == nil: return nil } earlier, _ := op["x-earlierPersonAPI"].(map[string]any) inner, _ := earlier["operation"].(map[string]any) if inner == nil { t.Fatal("missing earlier operation", method, path) } return inner } for _, r := range personapi.Routes { if r.Input == nil || deviceShared[r.Method+" "+r.Path] == "replaced" { continue } name := reflect.TypeOf(r.Input()).Elem().Name() if name == "" { name = "Empty" } operation := person(r.Method, r.Path) if operation == nil { t.Fatal("missing OpenAPI operation", r.Method, r.Path) } body := operation["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any) if body["$ref"] != "#/components/schemas/"+name { t.Fatal("request schema differs from registered DTO", r.Path, name, body) } } count := 0 for path, methods := range required { for _, method := range strings.Fields(methods) { count++ if !registered[method+" "+path] { t.Fatal("missing 3a route", method, path) } if _, ok := doc.Paths[path][strings.ToLower(method)]; !ok { t.Fatal("missing OpenAPI operation", method, path) } if deviceShared[method+" "+path] == "replaced" { continue } operation, err := json.Marshal(person(method, path)) must(t, err) var value struct { OperationID string `json:"operationId"` Parameters []struct { Name string Required bool } Responses map[string]struct { Content map[string]struct{ Schema json.RawMessage } } RequestBody struct { Required bool Content map[string]struct{ Schema json.RawMessage } } } must(t, json.Unmarshal(operation, &value)) if value.OperationID != operationIDs[method+" "+path] { t.Fatal("operation ID differs from registration", method, path, value.OperationID) } if len(value.Responses["200"].Content["application/json"].Schema) == 0 { t.Fatal("untyped response", method, path) } if method != "GET" { if !value.RequestBody.Required || len(value.RequestBody.Content["application/json"].Schema) == 0 { t.Fatal("untyped mutation", method, path) } key := false for _, p := range value.Parameters { if p.Name == "Idempotency-Key" && p.Required { key = true } } if !key && path != "/auth/devices/native" { t.Fatal("missing request key contract", method, path) } } } } if count != len(registered) { t.Fatal("unexpected API route", count, len(registered)) } documented := 0 for path, methods := range assistant { for _, method := range strings.Fields(methods) { documented++ if !assistantRoutes[method+" "+path] { t.Fatal("missing Assistant route", method, path) } operation, ok := doc.Paths[path][strings.ToLower(method)] if !ok { t.Fatal("missing OpenAPI operation", method, path) } var value struct { OperationID string `json:"operationId"` Security []map[string][]string `json:"security"` Responses map[string]struct { Content map[string]struct{ Schema json.RawMessage } } RequestBody struct { Content map[string]struct{ Schema json.RawMessage } } } must(t, json.Unmarshal(operation, &value)) if value.OperationID != personapi.OperationID(personapi.Route{Method: method, Path: path}) { t.Fatal("operation ID differs from the route", method, path, value.OperationID) } if len(value.Security) != 1 || len(value.Security[0]) != 1 || value.Security[0]["personBearer"] == nil { t.Fatal("an Assistant route takes the device bearer alone", method, path, value.Security) } typed := false for status, r := range value.Responses { for _, c := range r.Content { typed = typed || status[0] == '2' && len(c.Schema) > 0 } } if !typed { t.Fatal("untyped response", method, path) } if method != "GET" && len(value.RequestBody.Content["application/json"].Schema) == 0 { t.Fatal("untyped mutation", method, path) } } } if documented != len(assistantRoutes) { t.Fatal("unexpected Assistant route", documented, len(assistantRoutes)) } p := proposed(t, f) w := apiRequest(t, f, owner, "GET", "/api/v1/conversation/cards", "", "", "") expectHTTP(t, w, 200) cards := apiValue[personapi.Page[personapi.Card]](t, w) found := false for _, c := range cards.Items { if c.ResourceID == p.TaskID { found = true expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/cards/"+c.ID, "", "", ""), 200) expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/cards/"+c.ID, "", "", ""), 404) } } if !found { t.Fatal("missing current task card") } }