| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/base64" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "net/http/httptest" |
| 10 | "net/url" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/equipo" |
| 16 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 17 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 18 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 19 | ) |
| 20 | |
| 21 | func jsonBody(t *testing.T, v any) string { |
| 22 | t.Helper() |
| 23 | b, e := json.Marshal(v) |
| 24 | must(t, e) |
| 25 | return string(b) |
| 26 | } |
| 27 | func TestPersonAPIMutations(t *testing.T) { |
| 28 | f, _, _, b := coordinatorFixture(t) |
| 29 | apiRouter(t, f, nil) |
| 30 | var project int64 |
| 31 | must(t, f.DB.Writer().QueryRow("SELECT project_id FROM tasks LIMIT 1").Scan(&project)) |
| 32 | proposal := personapi.PlanInput{Kind: "recommendation", ProjectID: project, Steps: []personapi.PlanStep{{Key: "research", Specialist: "product", Action: "recommend", Instructions: "Read project material"}, {Key: "merge", Action: "person"}}} |
| 33 | w := apiRequest(t, f, owner, "POST", "/api/v1/tasks", jsonBody(t, proposal), "proposal", "") |
| 34 | expectHTTP(t, w, 200) |
| 35 | plan := apiValue[personapi.Plan](t, w) |
| 36 | taskPath := "/api/v1/tasks/" + plan.TaskID |
| 37 | proposal.Steps[0].Instructions = "Read the current project material" |
| 38 | w = apiRequest(t, f, owner, "PATCH", taskPath+"/plan", jsonBody(t, proposal), "edit", `"1"`) |
| 39 | expectHTTP(t, w, 200) |
| 40 | plan = apiValue[personapi.Plan](t, w) |
| 41 | if plan.Revision != 2 { |
| 42 | t.Fatal("edit did not increment revision") |
| 43 | } |
| 44 | expectHTTP(t, apiRequest(t, f, owner, "POST", taskPath+"/plan/approve", `{}`, "approve", `"2"`), 200) |
| 45 | expectHTTP(t, apiRequest(t, f, owner, "POST", taskPath+"/project", fmt.Sprintf(`{"project_id":%d}`, project), "project", `"2"`), 200) |
| 46 | msg := apiValue[personapi.Message](t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"route this"}`, "route-source", "")) |
| 47 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages/"+msg.ID+"/route", jsonBody(t, personapi.RouteInput{TaskID: plan.TaskID}), "route", `"1"`), 200) |
| 48 | expectHTTP(t, apiRequest(t, f, peer, "POST", taskPath+"/thread/messages", `{"body":"shared answer"}`, "thread", ""), 200) |
| 49 | w = apiRequest(t, f, owner, "POST", "/api/v1/preferences", `{"text":"Use plain words"}`, "preference", "") |
| 50 | expectHTTP(t, w, 200) |
| 51 | pref := apiValue[personapi.Preference](t, w) |
| 52 | expectHTTP(t, apiRequest(t, f, peer, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"foreign"}`, "foreign", `"1"`), 404) |
| 53 | expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"Use short words"}`, "correct", `"1"`), 200) |
| 54 | expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete", `"2"`), 200) |
| 55 | expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete", `"2"`), 200) |
| 56 | expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/coordinator", `{"runner_id":"fixture-runner","connection_id":"codex"}`, "rebind", fmt.Sprintf(`"%d"`, b.Revision)), 200) |
| 57 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/coordinator/reset", `{}`, "reset", fmt.Sprintf(`"%d"`, b.Revision+1)), 200) |
| 58 | 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"`) |
| 59 | expectHTTP(t, w, 200) |
| 60 | f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| 61 | 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) |
| 62 | task, err := f.Store.Task(ctx, owner, plan.TaskID) |
| 63 | must(t, err) |
| 64 | for i := 0; i < 2; i++ { |
| 65 | expectHTTP(t, apiRequest(t, f, owner, "POST", taskPath+"/cancel", `{}`, "cancel", fmt.Sprintf(`"%d"`, task.Revision)), 200) |
| 66 | } |
| 67 | if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='task.cancel' AND record_id=?", task.ID) != 1 { |
| 68 | t.Fatal("cancel replay duplicated effect") |
| 69 | } |
| 70 | if f.count(t, "SELECT count(*) FROM person_api_requests WHERE request_id='proposal'") != 1 { |
| 71 | t.Fatal("request metadata missing") |
| 72 | } |
| 73 | } |
| 74 | func TestPersonAPIQuestions(t *testing.T) { |
| 75 | t.Run("clarification", func(t *testing.T) { |
| 76 | f, x, p, c := claimTools(t) |
| 77 | apiRouter(t, f, nil) |
| 78 | 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"}}}) |
| 79 | path := "/api/v1/questions/" + q.ResourceID |
| 80 | expectHTTP(t, apiRequest(t, f, peer, "GET", path, "", "", ""), 404) |
| 81 | w := apiRequest(t, f, owner, "GET", path, "", "", "") |
| 82 | expectHTTP(t, w, 200) |
| 83 | view := apiValue[personapi.Question](t, w) |
| 84 | if view.Kind != "clarification" || !view.CanAnswer || len(view.Options) != 1 { |
| 85 | t.Fatal(view) |
| 86 | } |
| 87 | expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", `{"kind":"clarification","option_id":"one"}`, "answer", `"2"`), 409) |
| 88 | for i := 0; i < 2; i++ { |
| 89 | expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", `{"kind":"clarification","option_id":"one"}`, "answer", `"1"`), 200) |
| 90 | } |
| 91 | if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='clarification.answer'") != 1 { |
| 92 | t.Fatal("duplicate answer") |
| 93 | } |
| 94 | }) |
| 95 | t.Run("native", func(t *testing.T) { |
| 96 | f, _, _, _, q := nativeConversationFixture(t) |
| 97 | apiRouter(t, f, nil) |
| 98 | path := "/api/v1/questions/" + q.ID |
| 99 | w := apiRequest(t, f, owner, "GET", path, "", "", "") |
| 100 | expectHTTP(t, w, 200) |
| 101 | view := apiValue[personapi.Question](t, w) |
| 102 | if view.Kind != "native" || !view.CanAnswer || len(view.Fields) != 1 { |
| 103 | t.Fatal(view) |
| 104 | } |
| 105 | expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", `{"kind":"native","text":"yes"}`, "invalid", `"1"`), 422) |
| 106 | body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` |
| 107 | for i := 0; i < 2; i++ { |
| 108 | expectHTTP(t, apiRequest(t, f, owner, "POST", path+"/answer", body, "answer", `"1"`), 200) |
| 109 | } |
| 110 | expectHTTP(t, formPost(t, f, owner, "/tasks/"+q.TaskID+"/questions/"+q.ID+"/answer", url.Values{"revision": {"1"}, "behavior": {"allow"}, "answer_0": {"Blue"}}), 303) |
| 111 | }) |
| 112 | } |
| 113 | func TestPersonAPICoordinatorRetry(t *testing.T) { |
| 114 | f, _, _, _ := coordinatorFixture(t) |
| 115 | apiRouter(t, f, nil) |
| 116 | turn := queueCoordinator(t, f, "read", "retry-message") |
| 117 | f.exec(t, "UPDATE coordinator_turns SET state='context_limit' WHERE id=?", turn.ID) |
| 118 | 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) |
| 119 | } |
| 120 | func TestPersonAPIPaginationAndValidation(t *testing.T) { |
| 121 | f := newFixture(t) |
| 122 | w := apiRequest(t, f, owner, "GET", "/api/v1/people?limit=1", "", "", "") |
| 123 | expectHTTP(t, w, 200) |
| 124 | page := apiValue[personapi.Page[personapi.Person]](t, w) |
| 125 | if len(page.Items) != 1 || page.NextCursor == "" { |
| 126 | t.Fatal(page) |
| 127 | } |
| 128 | expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 200) |
| 129 | expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 410) |
| 130 | expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/preferences?cursor="+page.NextCursor, "", "", ""), 410) |
| 131 | page.NextCursor += "x" |
| 132 | expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 410) |
| 133 | for _, query := range []string{"limit=0", "limit=101", "limit=x", "limit=1&limit=2", "person=peer@example.com"} { |
| 134 | expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?"+query, "", "", ""), 422) |
| 135 | } |
| 136 | for _, body := range []string{`{"body":"a","body":"b"}`, `{"body":"a","address":"peer@example.com"}`, `{"body":"` + strings.Repeat("a", 16385) + `"}`, `{"body":"` + strings.Repeat("a", 65536) + `"}`} { |
| 137 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", body, "invalid", ""), 422) |
| 138 | } |
| 139 | f.exec(t, "CREATE TRIGGER deny_api_metadata BEFORE INSERT ON person_api_requests BEGIN SELECT RAISE(ABORT,'fixture'); END") |
| 140 | before := f.count(t, "SELECT count(*) FROM conversation_messages") |
| 141 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"rollback"}`, "rollback", ""), 503) |
| 142 | if f.count(t, "SELECT count(*) FROM conversation_messages") != before { |
| 143 | t.Fatal("metadata failure left mutation committed") |
| 144 | } |
| 145 | } |
| 146 | func TestPersonAPIBrowserCSRFRunner(t *testing.T) { |
| 147 | f, x, principal, request, _ := nativeConversationFixture(t) |
| 148 | apiRouter(t, f, nil) |
| 149 | runnerToken := base64.RawURLEncoding.EncodeToString(make([]byte, 32)) |
| 150 | hash := func(audience, token string) string { |
| 151 | sum := sha256.Sum256([]byte(audience + "\x00" + token)) |
| 152 | return hex.EncodeToString(sum[:]) |
| 153 | } |
| 154 | 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()) |
| 155 | do := func(path, auth, body string, cookie bool) *httptest.ResponseRecorder { |
| 156 | r := httptest.NewRequest("POST", path, strings.NewReader(body)) |
| 157 | r.Header.Set("Content-Type", "application/json") |
| 158 | r.Header.Set("Authorization", auth) |
| 159 | if cookie { |
| 160 | r.AddCookie(f.Cookies[owner.Address]) |
| 161 | } |
| 162 | w := httptest.NewRecorder() |
| 163 | f.Handler.ServeHTTP(w, r) |
| 164 | return w |
| 165 | } |
| 166 | expectHTTP(t, do("/api/runner/v2/heartbeat", "Bearer "+runnerToken, `{"version":2,"request_id":"heartbeat"}`, false), 200) |
| 167 | expectHTTP(t, do("/api/runner/v2/heartbeat", "Bearer "+runnerToken, `{"version":2,"request_id":"mixed"}`, true), 403) |
| 168 | expectHTTP(t, do("/api/v1/conversation/messages", "Bearer "+runnerToken, `{"body":"wrong audience"}`, false), 401) |
| 169 | cleanup := "fixture-cleanup" |
| 170 | f.exec(t, "UPDATE runner_cleanups SET token_hash=? WHERE assignment_id=?", hash(runnerproto.CleanupAudience, cleanup), request.AssignmentID) |
| 171 | request.RequestID = "cleanup-intent" |
| 172 | request.Intent = &team.IntentSpec{Key: "cleanup-turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"research"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}} |
| 173 | action, err := x.Mutate(ctx, principal, "intend", request) |
| 174 | must(t, err) |
| 175 | request.ActionID = action.(team.ActionID) |
| 176 | request.Intent = nil |
| 177 | request.RequestID = "cleanup-observation" |
| 178 | request.Receipt = &team.Receipt{ID: "fixture-observation", Outcome: "success"} |
| 179 | wire, err := runnerproto.Marshal(request) |
| 180 | must(t, err) |
| 181 | expectHTTP(t, do("/api/runner/v2/receipts", "Bearer "+runnerToken, string(wire), false), 200) |
| 182 | request.RequestID = "cleanup-receipt" |
| 183 | wire, err = runnerproto.Marshal(request) |
| 184 | must(t, err) |
| 185 | // Cleanup receipts are observations only; they cannot settle usage or admit work. |
| 186 | expectHTTP(t, do("/api/runner/v2/receipts", "Cleanup "+cleanup, string(wire), false), 200) |
| 187 | expectHTTP(t, do("/api/runner/v2/intend", "Cleanup "+cleanup, string(wire), false), 403) |
| 188 | expectHTTP(t, do("/api/v1/conversation/messages", "Cleanup "+cleanup, `{"body":"wrong audience"}`, false), 401) |
| 189 | } |
| 190 | |
| 191 | func TestPersonAPIProjectionParity(t *testing.T) { |
| 192 | f := newFixture(t) |
| 193 | expectHTTP(t, formPost(t, f, owner, "/preferences", url.Values{"request_id": {"html-preference"}, "revision": {"0"}, "text": {"Use plain words"}}), 303) |
| 194 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/preferences", `{"text":"Use plain words"}`, "html-preference", ""), 200) |
| 195 | p := proposed(t, f) |
| 196 | p.Steps[1].DependsOn = []string{p.Steps[0].Key} |
| 197 | p, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "dependency", Revision: p.Revision}) |
| 198 | must(t, err) |
| 199 | w := apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+p.TaskID+"/plan", "", "", "") |
| 200 | expectHTTP(t, w, 200) |
| 201 | var value struct { |
| 202 | Steps []struct { |
| 203 | DependsOn []string `json:"depends_on"` |
| 204 | } |
| 205 | } |
| 206 | must(t, json.Unmarshal(w.Body.Bytes(), &value)) |
| 207 | if len(value.Steps[1].DependsOn) != 1 || value.Steps[1].DependsOn[0] != p.Steps[0].Key { |
| 208 | t.Fatal("plan projection lost dependencies") |
| 209 | } |
| 210 | detail := apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+p.TaskID, "", "", "") |
| 211 | expectHTTP(t, detail, 200) |
| 212 | task := apiValue[personapi.Task](t, detail) |
| 213 | if task.Usage != nil { |
| 214 | t.Fatal("unknown task usage became known") |
| 215 | } |
| 216 | for _, step := range task.Steps { |
| 217 | if step.Usage != nil || step.AllowanceRemaining != nil { |
| 218 | t.Fatal("unknown step quantity became known") |
| 219 | } |
| 220 | } |
| 221 | projected := apiValue[personapi.Plan](t, w) |
| 222 | expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/tasks/"+p.TaskID+"/plan", jsonBody(t, projected.PlanInput), "dependency-roundtrip", w.Header().Get("ETag")), 200) |
| 223 | } |
| 224 | func TestPersonAPIInitialBindingETag(t *testing.T) { |
| 225 | f := newFixture(t) |
| 226 | task := f.createTask(t) |
| 227 | f.planConnections(t, task.ProjectID) |
| 228 | apiRouter(t, f, nil) |
| 229 | w := apiRequest(t, f, owner, "GET", "/api/v1/coordinator", "", "", "") |
| 230 | expectHTTP(t, w, 200) |
| 231 | if w.Header().Get("ETag") != `"0"` { |
| 232 | t.Fatal("unset binding revision", w.Header()) |
| 233 | } |
| 234 | expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/coordinator", `{"runner_id":"fixture-runner","connection_id":"claude"}`, "initial-binding", w.Header().Get("ETag")), 200) |
| 235 | } |
| 236 | |
| 237 | func TestPersonAPIUnavailableQuery(t *testing.T) { |
| 238 | f := newFixture(t) |
| 239 | f.exec(t, "DROP TABLE personal_preferences") |
| 240 | w := apiRequest(t, f, owner, "GET", "/api/v1/preferences", "", "", "") |
| 241 | expectHTTP(t, w, 503) |
| 242 | failure := apiValue[personapi.Error](t, w) |
| 243 | if failure.Code != "unavailable" || failure.CopyKey != "api.unavailable" { |
| 244 | t.Fatal("query failure became an empty list", failure) |
| 245 | } |
| 246 | } |
| 247 | |