package plan3test import ( "context" "errors" "fmt" "gorm.io/gorm" "net/http/httptest" "net/url" "sort" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/runnerproto" ) func TestCoordinatorAcceptance3A(t *testing.T) { t.Run("active_cancel", acceptanceActiveCancel) t.Run("account_scope", TestCoordinatorToolScope) t.Run("claim_identity", TestCoordinatorAuthorityClaimTampering) t.Run("uncertain_requires_person", acceptanceUncertainRequiresPerson) t.Run("recency", TestPersonAPIRecencyAcrossPages) t.Run("task_card_recency", TestPersonAPITaskAndCardRecency) t.Run("read_epoch", TestPersonAPIReadEpochTransaction) t.Run("stream_cursors", TestPersonAPIStreamCursorIsolation) t.Run("html_cursor_retention", TestConversationCursorRetention) t.Run("delivery_receipt", TestCoordinatorSessionTrustedReceipt) t.Run("atomic_delivery", TestCoordinatorTurnDeliveryAtomic) t.Run("plan_replay", TestCoordinatorToolCommitCrash) t.Run("recommendation", TestPlanWorkflowRecommendationDelivery) t.Run("question", TestPersonAPIQuestions) t.Run("human_merge", TestPersonAPIRenderedAndMerge) t.Run("preferences", TestPreferencesCorrectionAndDelete) } func acceptanceUncertainRequiresPerson(t *testing.T) { f, x, p, b := coordinatorFixture(t) x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) turn := queueCoordinator(t, f, "first", "first") c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) must(t, err) must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) next := queueCoordinator(t, f, "later", "later") _, err = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision) var refusal *runnerproto.RefusalError if err == nil || errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { t.Fatal("uncertain turn fenced without person's choice", err) } var state string must(t, f.DB.Writer().QueryRow("SELECT state FROM coordinator_turns WHERE id=?", turn.ID).Scan(&state)) if state != "uncertain" { t.Fatal("uncertainty lost", state) } offers, err := x.PollCoordinator(ctx, p) must(t, err) if len(offers) != 0 { t.Fatal("uncertain turn released queue", offers) } _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) must(t, err) _, err = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision) if !errors.As(err, &refusal) || !refusal.CoordinatorDefinitive() { t.Fatal("explicit reset did not fence old turn", err) } offers, err = x.PollCoordinator(ctx, p) must(t, err) if len(offers) != 1 || offers[0].MessageID != next.MessageID { t.Fatal("explicit reset lost queued request", offers) } } func TestPersonAPIRecencyAcrossPages(t *testing.T) { f := newFixture(t) for i, id := range []string{"a-old", "z-new", "b-tie"} { _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) must(t, err) var old string must(t, f.DB.Writer().QueryRow("SELECT id FROM personal_preferences WHERE text=?", id).Scan(&old)) f.exec(t, "UPDATE personal_preferences SET id=? WHERE id=?", id, old) at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) if i > 0 { at = at.Add(time.Hour) } f.exec(t, "UPDATE audit_events SET record_id=?,at=? WHERE record_id=?", id, at, old) } cursor := "" for _, want := range []string{"b-tie", "z-new", "a-old"} { w := apiRequest(t, f, owner, "GET", "/api/v1/preferences?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.Page[personapi.Preference]](t, w) if len(page.Items) != 1 || page.Items[0].ID != want { t.Fatalf("recency order: got %+v want %s", page.Items, want) } cursor = page.NextCursor } if cursor != "" { t.Fatal("extra page") } } func TestPersonAPIReadEpochTransaction(t *testing.T) { f := newFixture(t) // Advance the epoch after the HTTP authentication read and before the data read. fired := false must(t, f.DB.G.Callback().Query().After("gorm:query").Register("task11_epoch", func(tx *gorm.DB) { if !fired && tx.Statement.Table == "members" && tx.Statement.Context.Value(epochTestKey{}) != nil { fired = true f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Unix()+100, owner.Address) } })) t.Cleanup(func() { _ = f.DB.G.Callback().Query().Remove("task11_epoch") }) r := httptest.NewRequest("GET", "/api/v1/conversation", nil).WithContext(context.WithValue(ctx, epochTestKey{}, true)) r.AddCookie(f.Cookies[owner.Address]) w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) if !fired { t.Fatal("race hook not reached") } expectHTTP(t, w, 403) } type epochTestKey struct{} func TestPersonAPIStreamCursorIsolation(t *testing.T) { f := newFixture(t) p := proposed(t, f) otherTask := f.task(t, owner, "other-thread") for i := 0; i < 3; i++ { _, err := f.Store.SendMessage(ctx, owner, "", "private", equipo.Mutation{RequestID: fmt.Sprint("p", i)}) must(t, err) _, err = f.Store.SendMessage(ctx, owner, p.TaskID, "shared", equipo.Mutation{RequestID: fmt.Sprint("t", i)}) must(t, err) } for _, path := range []string{"/api/v1/conversation", "/api/v1/tasks/" + p.TaskID + "/thread"} { w := apiRequest(t, f, owner, "GET", path+"?limit=1", "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.ConversationPage](t, w) if page.NextCursor == "" { t.Fatal("missing cursor") } expectHTTP(t, apiRequest(t, f, peer, "GET", path+"?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+otherTask.ID+"/thread?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) other := "/api/v1/conversation" if path == other { other = "/api/v1/tasks/" + p.TaskID + "/thread" } expectHTTP(t, apiRequest(t, f, owner, "GET", other+"?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) } } func TestConversationCursorRetention(t *testing.T) { f := newFixture(t) for i := 0; i < 3; i++ { _, err := f.Store.SendMessage(ctx, owner, "", "page", equipo.Mutation{RequestID: fmt.Sprint(i)}) must(t, err) } page, err := f.Store.Conversation(ctx, owner, "", 1) must(t, err) if page.NextCursor == "" { t.Fatal("missing cursor") } f.exec(t, "UPDATE conversation_cursors SET expires_at=?", time.Now().Add(-time.Hour)) _, err = f.Store.Conversation(ctx, owner, "", 1) must(t, err) if f.count(t, "SELECT count(*) FROM conversation_cursors WHERE expires_at <= ?", time.Now()) != 0 { t.Fatal("expired HTML cursors retained") } } func TestPersonAPITaskAndCardRecency(t *testing.T) { f := newFixture(t) p := proposed(t, f) ids := []string{p.TaskID} for i := 0; i < 2; i++ { p.TaskID = "" p.Revision = 0 next, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: fmt.Sprint("recency", i)}) must(t, err) ids = append(ids, next.TaskID) } sort.Strings(ids) for i, id := range ids { f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=?", time.Now().UTC().Add(time.Duration(i+1)*time.Hour), id) } for _, path := range []string{"tasks", "journey", "conversation/cards"} { t.Run(path, func(t *testing.T) { cursor := "" for i := len(ids) - 1; i >= 0; i-- { w := apiRequest(t, f, owner, "GET", "/api/v1/"+path+"?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") expectHTTP(t, w, 200) page := apiValue[personapi.Page[struct { ID string `json:"id"` ResourceID string `json:"resource_id"` }]](t, w) if len(page.Items) != 1 { t.Fatal("missing page", page) } id := page.Items[0].ID if path == "conversation/cards" { id = page.Items[0].ResourceID } if id != ids[i] { t.Fatalf("recency: got %s want %s", id, ids[i]) } cursor = page.NextCursor } }) } } func TestPreferencesInferredDeleteFailure(t *testing.T) { f, x, p, c := claimTools(t) toolCall(t, x, p, c, "suggest", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "Keep the explanation brief"}) prefs, err := f.Store.Preferences(ctx, owner) must(t, err) if len(prefs) != 1 || prefs[0].Status != "inferred" { t.Fatal(prefs) } before := f.count(t, "SELECT count(*) FROM audit_events") f.exec(t, `CREATE TRIGGER reject_preference_delete BEFORE INSERT ON personal_preferences BEGIN SELECT RAISE(ABORT,'fixture write failure'); END`) err = f.Store.DeletePreference(ctx, owner, prefs[0].ID, equipo.Mutation{RequestID: "delete", Revision: prefs[0].Revision}) if err == nil { t.Fatal("failed inferred deletion reported success") } if f.count(t, "SELECT count(*) FROM audit_events") != before { t.Fatal("failed deletion committed audit") } } func acceptanceActiveCancel(t *testing.T) { f, x, principal, q, question := nativeConversationFixture(t) x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) apiRouter(t, f, nil) path := "/api/v1/tasks/" + question.TaskID current, err := f.Store.Task(ctx, owner, question.TaskID) must(t, err) response := apiRequest(t, f, owner, "POST", path+"/cancel", `{}`, "cancel-active", fmt.Sprintf(`"%d"`, current.Revision)) expectHTTP(t, response, 200) current, err = f.Store.Task(ctx, owner, question.TaskID) must(t, err) if current.State != "cancel_requested" { t.Fatal("active cancellation invented containment", current.State) } if err = x.Core.ValidateHandle(ctx, q.Scope, q.Handle); err == nil { t.Fatal("cancelled attempt retained authority") } q.RequestID = "contained" _, err = x.Mutate(ctx, principal, "contained", q) must(t, err) current, err = f.Store.Task(ctx, owner, question.TaskID) must(t, err) if current.State != "cancelled" { t.Fatal("contained cancellation did not finish", current.State) } }