package plan3test import ( "fmt" "net/http/httptest" "net/url" "sort" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/taskplan" ) func TestPersonAPICurrentRevision(t *testing.T) { f, _, _, b := coordinatorFixture(t) apiRouter(t, f, nil) p := apiFixPlan(t, f) pref, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "original", Status: "confirmed"}, equipo.Mutation{RequestID: "pref"}) must(t, err) p.Steps[0].Instructions = "updated" p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "advance-plan", Revision: p.Revision}) must(t, err) pref.Text = "updated" pref, err = f.Store.SetPreference(ctx, owner, pref, equipo.Mutation{RequestID: "advance-pref", Revision: pref.Revision}) must(t, err) b, err = f.Store.SaveCoordinatorBinding(ctx, owner, "fixture-runner", "codex", equipo.Mutation{RequestID: "advance-binding", Revision: b.Revision}) must(t, err) expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/me/settings", `{"landing":"work"}`, "advance-settings", `"1"`), 200) cases := []struct { name, path, body, rev string want int64 }{ {"plan", "/tasks/" + p.TaskID + "/plan", jsonBody(t, personapi.ProjectPlan(p).PlanInput), `"99"`, p.Revision}, {"preference", "/preferences/" + pref.ID, `{"text":"changed"}`, `"99"`, pref.Revision}, {"binding", "/coordinator", `{"runner_id":"fixture-runner","connection_id":"codex"}`, `"99"`, b.Revision}, {"settings", "/me/settings", `{"landing":"work"}`, `"99"`, 2}, {"limits", "/coordinator/limits", `{"person":"owner@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}`, `"99"`, 1}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { w := apiRequest(t, f, owner, "PATCH", "/api/v1"+tc.path, tc.body, tc.name, tc.rev) expectHTTP(t, w, 409) e := apiValue[personapi.Error](t, w) if e.Code != "revision_conflict" || e.CurrentRevision == nil || *e.CurrentRevision != tc.want { t.Fatalf("current revision: %+v; want %d", e, tc.want) } }) } expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete-pref", fmt.Sprintf(`"%d"`, pref.Revision)), 200) conflict := apiRequest(t, f, owner, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"restore"}`, "stale-deleted", `"1"`) expectHTTP(t, conflict, 409) e := apiValue[personapi.Error](t, conflict) if e.CurrentRevision == nil || *e.CurrentRevision != pref.Revision+1 { t.Fatal("missing deleted preference revision", e) } expectHTTP(t, apiRequest(t, f, peer, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"foreign"}`, "foreign", `"1"`), 404) } func TestPersonAPIReplayBeforeStale(t *testing.T) { for _, op := range []string{"plan", "route", "binding", "limits"} { t.Run(op, func(t *testing.T) { f, _, _, b := coordinatorFixture(t) apiRouter(t, f, nil) p := apiFixPlan(t, f) method, path, body, changed, rev := "PATCH", "", "", "", `"1"` switch op { case "plan": path = "/api/v1/tasks/" + p.TaskID + "/plan" in := personapi.ProjectPlan(p).PlanInput in.Steps[0].Instructions = "First edit" body = jsonBody(t, in) in.Steps[0].Instructions = "Different edit" changed = jsonBody(t, in) case "route": msg, err := f.Store.SendMessage(ctx, owner, "", "route source", equipo.Mutation{RequestID: "source"}) must(t, err) method, path = "POST", "/api/v1/conversation/messages/"+msg.ID+"/route" body = jsonBody(t, personapi.RouteInput{TaskID: p.TaskID}) other := apiFixPlan(t, f) changed = jsonBody(t, personapi.RouteInput{TaskID: other.TaskID}) case "binding": path = "/api/v1/coordinator" body = `{"runner_id":"fixture-runner","connection_id":"codex"}` changed = `{"runner_id":"fixture-runner","connection_id":"claude"}` rev = fmt.Sprintf(`"%d"`, b.Revision) case "limits": path = "/api/v1/coordinator/limits" body = `{"person":"owner@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}` changed = strings.Replace(body, `"calls":23`, `"calls":22`, 1) } first := apiRequest(t, f, owner, method, path, body, "retry", rev) expectHTTP(t, first, 200) if op == "route" { f.exec(t, "UPDATE conversation_messages SET revision=revision+1 WHERE id=?", strings.Split(path, "/")[5]) } replay := apiRequest(t, f, owner, method, path, body, "retry", rev) expectHTTP(t, replay, 200) if first.Body.String() != replay.Body.String() { t.Fatal("saved result changed") } expectHTTP(t, apiRequest(t, f, owner, method, path, changed, "retry", rev), 409) expectHTTP(t, apiRequest(t, f, owner, method, path, body, "new-key", rev), 409) f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) expectHTTP(t, apiRequest(t, f, owner, method, path, body, "retry", rev), 403) }) } } func TestPersonAPIListReadsNoWrites(t *testing.T) { f := newFixture(t) p := proposed(t, f) for i := 0; i < 3; i++ { _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: fmt.Sprintf("private %d", i), Status: "confirmed"}, equipo.Mutation{RequestID: fmt.Sprint(i)}) must(t, err) _, err = f.Store.SendMessage(ctx, owner, "", "message", equipo.Mutation{RequestID: fmt.Sprintf("main-%d", i)}) must(t, err) _, err = f.Store.SendMessage(ctx, owner, p.TaskID, "thread", equipo.Mutation{RequestID: fmt.Sprintf("thread-%d", i)}) must(t, err) } // Reject every attempted write, including lazy stream creation and cursor inserts. rows, err := f.DB.Writer().Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") must(t, err) var tables []string for rows.Next() { var table string must(t, rows.Scan(&table)) tables = append(tables, table) } must(t, rows.Close()) for _, table := range tables { for _, event := range []string{"INSERT", "UPDATE", "DELETE"} { f.exec(t, fmt.Sprintf(`CREATE TRIGGER "deny_%s_%s" BEFORE %s ON "%s" BEGIN SELECT RAISE(ABORT,'read attempted write'); END`, table, event, event, table)) } } for _, path := range []string{"people", "preferences", "conversation/cards", "tasks", "journey", "needs-you", "conversation", "tasks/" + p.TaskID + "/thread"} { t.Run(path, func(t *testing.T) { for repeat := 0; repeat < 3; repeat++ { cursor := "" for page := 0; page < 20; page++ { w := apiRequest(t, f, owner, "GET", "/api/v1/"+path+"?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") expectHTTP(t, w, 200) value := apiValue[struct { NextCursor string `json:"next_cursor"` }](t, w) cursor = value.NextCursor if cursor == "" { break } if page == 19 { t.Fatal("paging did not terminate") } } } }) } for _, path := range []string{"conversation", "preferences", "conversation/cards"} { expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/"+path, "", "", ""), 200) } if f.count(t, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='person_api_cursors'") != 0 && f.count(t, "SELECT count(*) FROM person_api_cursors") != 0 { t.Fatal("paging persisted cursor rows") } } func TestPersonAPICursorFreshnessAndOrder(t *testing.T) { f := newFixture(t) for _, id := range []string{"b", "d", "f"} { _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) must(t, err) f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "secret-"+id) f.exec(t, "UPDATE audit_events SET record_id=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", id, "secret-"+id) f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) } read := func(cursor string) personapi.Page[personapi.Preference] { w := apiRequest(t, f, owner, "GET", "/api/v1/preferences?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") expectHTTP(t, w, 200) return apiValue[personapi.Page[personapi.Preference]](t, w) } first := read("") if len(first.Items) != 1 || first.Items[0].ID != "b" { t.Fatal(first) } expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/d", `{}`, "delete", `"1"`), 200) for _, id := range []string{"a", "c"} { _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) must(t, err) f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "secret-"+id) f.exec(t, "UPDATE audit_events SET record_id=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", id, "secret-"+id) f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) } var ids []string cursor := first.NextCursor for pages := 0; cursor != ""; pages++ { if pages > 20 { t.Fatal("cursor never advanced") } page := read(cursor) for _, item := range page.Items { if item.Text == "secret-d" { t.Fatal("deleted text served") } ids = append(ids, item.ID) } cursor = page.NextCursor } if strings.Join(ids, ",") != "c,f" { t.Fatalf("unstable keyset: %v", ids) } expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/preferences?cursor="+url.QueryEscape(first.NextCursor+"x"), "", "", ""), 410) } func TestPersonAPINativeReplayAfterResolution(t *testing.T) { f, _, _, _, q := nativeConversationFixture(t) apiRouter(t, f, nil) path := "/api/v1/questions/" + q.ID + "/answer" body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` first := apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`) expectHTTP(t, first, 200) f.exec(t, "UPDATE questions SET state='invalid',expires_at=? WHERE id=?", time.Now().Add(-time.Hour), q.ID) f.exec(t, "UPDATE runner_assignments SET state='finished' WHERE id=?", q.AssignmentID) replay := apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`) expectHTTP(t, replay, 200) if first.Body.String() != replay.Body.String() { t.Fatal("replay result changed") } expectHTTP(t, apiRequest(t, f, owner, "POST", path, strings.Replace(body, "Blue", "Red", 1), "answer", `"1"`), 409) expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "new", `"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, apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`), 403) f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`), 403) } func TestPersonAPIEncodedPathCSRF(t *testing.T) { f := newFixture(t) for _, path := range []string{"/api%2Fv1/me", "/api%2fv1/conversation/messages", "/api%2Frunner/v2/heartbeat", "/api%2Fenrolments"} { for _, method := range []string{"GET", "POST"} { r := httptest.NewRequest(method, path, strings.NewReader(`{}`)) r.AddCookie(f.Cookies[owner.Address]) r.Header.Set("Origin", "https://evil.example") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) if w.Code != 422 && w.Code != 403 { t.Fatalf("%s %s bypassed dispatcher protection: %d", method, path, w.Code) } } } } func TestPersonAPITaskListParity(t *testing.T) { f := newFixture(t) base := f.createTask(t) f.exec(t, "DELETE FROM tasks WHERE id=?", base.ID) for _, id := range []string{"active", "peer-task", "old-finished", "recent-finished"} { task := base task.PlanRevision = 0 task.ID = id task.RequestID = id if id == "peer-task" { task.Requester = peer.Address } must(t, f.DB.G.Create(&task).Error) f.exec(t, "INSERT INTO task_outboxes(task_id,state,engineering,review) VALUES(?,?,?,?)", id, "pending", "", "") } for _, id := range []string{"old-finished", "recent-finished"} { f.exec(t, "UPDATE tasks SET state='cancelled' WHERE id=?", id) at := time.Now() if id == "old-finished" { at = at.Add(-14 * 24 * time.Hour) } f.exec(t, "INSERT INTO audit_events(actor,kind,record_id,at) VALUES(?,?,?,?)", owner.Address, "task.cancel", id, at) } w := apiRequest(t, f, owner, "GET", "/api/v1/tasks", "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.Page[personapi.Task]](t, w) var ids []string for _, task := range page.Items { ids = append(ids, task.ID) } sort.Strings(ids) if strings.Join(ids, ",") != "active,peer-task,recent-finished" { t.Fatal(ids) } html := f.get(t, owner, "/journey") expectHTTP(t, html, 200) for _, id := range []string{"active", "peer-task", "old-finished", "recent-finished"} { present := strings.Contains(html.Body.String(), `href="/tasks/`+id+`"`) if present != (id != "old-finished") { t.Fatalf("HTML selection differs for %s", id) } } } func apiFixPlan(t *testing.T, f *fixture) taskplan.Plan { t.Helper() var project int64 must(t, f.DB.Writer().QueryRow("SELECT project_id FROM tasks LIMIT 1").Scan(&project)) p := taskplan.BugPlan("", project) p.Steps[0].Instructions = "fixture symptom" p.Revision = 0 out, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: fmt.Sprintf("plan-%d", time.Now().UnixNano())}) must(t, err) return out }