package plan3test import ( "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "net/http/httptest" "net/url" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runnerproto" ) func jsonBody(t *testing.T, v any) string { t.Helper() b, e := json.Marshal(v) must(t, e) return string(b) } func TestPersonAPIMutations(t *testing.T) { f, _, _, b := coordinatorFixture(t) apiRouter(t, f, nil) var project int64 must(t, f.DB.Writer().QueryRow("SELECT project_id FROM tasks LIMIT 1").Scan(&project)) proposal := personapi.PlanInput{Kind: "recommendation", ProjectID: project, Steps: []personapi.PlanStep{{Key: "research", Specialist: "product", Action: "recommend", Instructions: "Read project material"}, {Key: "merge", Action: "person"}}} w := apiRequest(t, f, owner, "POST", "/api/v1/tasks", jsonBody(t, proposal), "proposal", "") expectHTTP(t, w, 200) plan := apiValue[personapi.Plan](t, w) taskPath := "/api/v1/tasks/" + plan.TaskID proposal.Steps[0].Instructions = "Read the current project material" w = apiRequest(t, f, owner, "PATCH", taskPath+"/plan", jsonBody(t, proposal), "edit", `"1"`) expectHTTP(t, w, 200) plan = apiValue[personapi.Plan](t, w) if plan.Revision != 2 { t.Fatal("edit did not increment revision") } expectHTTP(t, apiRequest(t, f, owner, "POST", taskPath+"/plan/approve", `{}`, "approve", `"2"`), 200) expectHTTP(t, apiRequest(t, f, owner, "POST", taskPath+"/project", fmt.Sprintf(`{"project_id":%d}`, project), "project", `"2"`), 200) msg := apiValue[personapi.Message](t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"route this"}`, "route-source", "")) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages/"+msg.ID+"/route", jsonBody(t, personapi.RouteInput{TaskID: plan.TaskID}), "route", `"1"`), 200) expectHTTP(t, apiRequest(t, f, peer, "POST", taskPath+"/thread/messages", `{"body":"shared answer"}`, "thread", ""), 200) w = apiRequest(t, f, owner, "POST", "/api/v1/preferences", `{"text":"Use plain words"}`, "preference", "") expectHTTP(t, w, 200) pref := apiValue[personapi.Preference](t, w) expectHTTP(t, apiRequest(t, f, peer, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"foreign"}`, "foreign", `"1"`), 404) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"Use short words"}`, "correct", `"1"`), 200) expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete", `"2"`), 200) expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete", `"2"`), 200) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/coordinator", `{"runner_id":"fixture-runner","connection_id":"codex"}`, "rebind", fmt.Sprintf(`"%d"`, b.Revision)), 200) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/coordinator/reset", `{}`, "reset", fmt.Sprintf(`"%d"`, b.Revision+1)), 200) w = apiRequest(t, f, owner, "PATCH", "/api/v1/coordinator/limits", jsonBody(t, personapi.LimitsInput{Person: owner.Address, Limits: personapi.Limits{Calls: 23, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}}), "api-limits", `"1"`) expectHTTP(t, w, 200) f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) expectHTTP(t, apiRequest(t, f, peer, "PATCH", "/api/v1/coordinator/limits", `{"person":"peer@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}`, "denied", `"0"`), 403) task, err := f.Store.Task(ctx, owner, plan.TaskID) must(t, err) for i := 0; i < 2; i++ { expectHTTP(t, apiRequest(t, f, owner, "POST", taskPath+"/cancel", `{}`, "cancel", fmt.Sprintf(`"%d"`, task.Revision)), 200) } if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='task.cancel' AND record_id=?", task.ID) != 1 { t.Fatal("cancel replay duplicated effect") } if f.count(t, "SELECT count(*) FROM person_api_requests WHERE request_id='proposal'") != 1 { t.Fatal("request metadata missing") } } func TestPersonAPIQuestions(t *testing.T) { t.Run("clarification", func(t *testing.T) { f, x, p, c := claimTools(t) apiRouter(t, f, nil) q := toolCall(t, x, p, c, "q", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose", "options": []map[string]string{{"id": "one", "label": "One"}}}) path := "/api/v1/questions/" + q.ResourceID expectHTTP(t, apiRequest(t, f, peer, "GET", path, "", "", ""), 404) w := apiRequest(t, f, owner, "GET", path, "", "", "") expectHTTP(t, w, 200) view := apiValue[personapi.Question](t, w) if view.Kind != "clarification" || !view.CanAnswer || len(view.Options) != 1 { t.Fatal(view) } expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", `{"kind":"clarification","option_id":"one"}`, "answer", `"2"`), 409) for i := 0; i < 2; i++ { expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", `{"kind":"clarification","option_id":"one"}`, "answer", `"1"`), 200) } if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='clarification.answer'") != 1 { t.Fatal("duplicate answer") } }) t.Run("native", func(t *testing.T) { f, _, _, _, q := nativeConversationFixture(t) apiRouter(t, f, nil) path := "/api/v1/questions/" + q.ID w := apiRequest(t, f, owner, "GET", path, "", "", "") expectHTTP(t, w, 200) view := apiValue[personapi.Question](t, w) if view.Kind != "native" || !view.CanAnswer || len(view.Fields) != 1 { t.Fatal(view) } expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", `{"kind":"native","text":"yes"}`, "invalid", `"1"`), 422) body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` for i := 0; i < 2; i++ { expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", body, "answer", `"1"`), 200) } expectHTTP(t, formPost(t, f, owner, "/tasks/"+q.TaskID+"/questions/"+q.ID+"/answer", url.Values{"revision": {"1"}, "behavior": {"allow"}, "answer_0": {"Blue"}}), 303) }) } func TestPersonAPICoordinatorRetry(t *testing.T) { f, _, _, _ := coordinatorFixture(t) apiRouter(t, f, nil) turn := queueCoordinator(t, f, "read", "retry-message") f.exec(t, "UPDATE coordinator_turns SET state='context_limit' WHERE id=?", turn.ID) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/coordinator/retry", jsonBody(t, personapi.RetryInput{TurnID: turn.ID}), "retry", fmt.Sprintf(`"%d"`, turn.Revision)), 200) } func TestPersonAPIPaginationAndValidation(t *testing.T) { f := newFixture(t) w := apiRequest(t, f, owner, "GET", "/api/v1/people?limit=1", "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.Page[personapi.Person]](t, w) if len(page.Items) != 1 || page.NextCursor == "" { t.Fatal(page) } expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 200) expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 410) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/preferences?cursor="+page.NextCursor, "", "", ""), 410) page.NextCursor += "x" expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 410) for _, query := range []string{"limit=0", "limit=101", "limit=x", "limit=1&limit=2", "person=peer@example.com"} { expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?"+query, "", "", ""), 422) } for _, body := range []string{`{"body":"a","body":"b"}`, `{"body":"a","address":"peer@example.com"}`, `{"body":"` + strings.Repeat("a", 16385) + `"}`, `{"body":"` + strings.Repeat("a", 65536) + `"}`} { expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", body, "invalid", ""), 422) } f.exec(t, "CREATE TRIGGER deny_api_metadata BEFORE INSERT ON person_api_requests BEGIN SELECT RAISE(ABORT,'fixture'); END") before := f.count(t, "SELECT count(*) FROM conversation_messages") expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"rollback"}`, "rollback", ""), 503) if f.count(t, "SELECT count(*) FROM conversation_messages") != before { t.Fatal("metadata failure left mutation committed") } } func TestPersonAPIBrowserCSRFRunner(t *testing.T) { f, x, principal, request, _ := nativeConversationFixture(t) apiRouter(t, f, nil) runnerToken := base64.RawURLEncoding.EncodeToString(make([]byte, 32)) hash := func(audience, token string) string { sum := sha256.Sum256([]byte(audience + "\x00" + token)) return hex.EncodeToString(sum[:]) } f.exec(t, "UPDATE runner_credentials SET token_hash=?,expires_at=? WHERE id='fixture-credential'", hash(runnerproto.RunnerAudience, runnerToken), time.Now().Add(time.Hour).UTC()) do := func(path, auth, body string, cookie bool) *httptest.ResponseRecorder { r := httptest.NewRequest("POST", path, strings.NewReader(body)) r.Header.Set("Content-Type", "application/json") r.Header.Set("Authorization", auth) if cookie { r.AddCookie(f.Cookies[owner.Address]) } w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } expectHTTP(t, do("/api/runner/v2/heartbeat", "Bearer "+runnerToken, `{"version":2,"request_id":"heartbeat"}`, false), 200) expectHTTP(t, do("/api/runner/v2/heartbeat", "Bearer "+runnerToken, `{"version":2,"request_id":"mixed"}`, true), 403) expectHTTP(t, do("/api/v1/conversation/messages", "Bearer "+runnerToken, `{"body":"wrong audience"}`, false), 401) cleanup := "fixture-cleanup" f.exec(t, "UPDATE runner_cleanups SET token_hash=? WHERE assignment_id=?", hash(runnerproto.CleanupAudience, cleanup), request.AssignmentID) request.RequestID = "cleanup-intent" request.Intent = &team.IntentSpec{Key: "cleanup-turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"research"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}} action, err := x.Mutate(ctx, principal, "intend", request) must(t, err) request.ActionID = action.(team.ActionID) request.Intent = nil request.RequestID = "cleanup-observation" request.Receipt = &team.Receipt{ID: "fixture-observation", Outcome: "success"} wire, err := runnerproto.Marshal(request) must(t, err) expectHTTP(t, do("/api/runner/v2/receipts", "Bearer "+runnerToken, string(wire), false), 200) request.RequestID = "cleanup-receipt" wire, err = runnerproto.Marshal(request) must(t, err) // Cleanup receipts are observations only; they cannot settle usage or admit work. expectHTTP(t, do("/api/runner/v2/receipts", "Cleanup "+cleanup, string(wire), false), 200) expectHTTP(t, do("/api/runner/v2/intend", "Cleanup "+cleanup, string(wire), false), 403) expectHTTP(t, do("/api/v1/conversation/messages", "Cleanup "+cleanup, `{"body":"wrong audience"}`, false), 401) } func TestPersonAPIProjectionParity(t *testing.T) { f := newFixture(t) expectHTTP(t, formPost(t, f, owner, "/preferences", url.Values{"request_id": {"html-preference"}, "revision": {"0"}, "text": {"Use plain words"}}), 303) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/preferences", `{"text":"Use plain words"}`, "html-preference", ""), 200) p := proposed(t, f) p.Steps[1].DependsOn = []string{p.Steps[0].Key} p, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "dependency", Revision: p.Revision}) must(t, err) w := apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+p.TaskID+"/plan", "", "", "") expectHTTP(t, w, 200) var value struct { Steps []struct { DependsOn []string `json:"depends_on"` } } must(t, json.Unmarshal(w.Body.Bytes(), &value)) if len(value.Steps[1].DependsOn) != 1 || value.Steps[1].DependsOn[0] != p.Steps[0].Key { t.Fatal("plan projection lost dependencies") } detail := apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+p.TaskID, "", "", "") expectHTTP(t, detail, 200) task := apiValue[personapi.Task](t, detail) if task.Usage != nil { t.Fatal("unknown task usage became known") } for _, step := range task.Steps { if step.Usage != nil || step.AllowanceRemaining != nil { t.Fatal("unknown step quantity became known") } } projected := apiValue[personapi.Plan](t, w) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/tasks/"+p.TaskID+"/plan", jsonBody(t, projected.PlanInput), "dependency-roundtrip", w.Header().Get("ETag")), 200) } func TestPersonAPIInitialBindingETag(t *testing.T) { f := newFixture(t) task := f.createTask(t) f.planConnections(t, task.ProjectID) apiRouter(t, f, nil) w := apiRequest(t, f, owner, "GET", "/api/v1/coordinator", "", "", "") expectHTTP(t, w, 200) if w.Header().Get("ETag") != `"0"` { t.Fatal("unset binding revision", w.Header()) } expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/coordinator", `{"runner_id":"fixture-runner","connection_id":"claude"}`, "initial-binding", w.Header().Get("ETag")), 200) } func TestPersonAPIUnavailableQuery(t *testing.T) { f := newFixture(t) f.exec(t, "DROP TABLE personal_preferences") w := apiRequest(t, f, owner, "GET", "/api/v1/preferences", "", "", "") expectHTTP(t, w, 503) failure := apiValue[personapi.Error](t, w) if failure.Code != "unavailable" || failure.CopyKey != "api.unavailable" { t.Fatal("query failure became an empty list", failure) } }