oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "gorm.io/gorm"
8 "net/http/httptest"
9 "net/url"
10 "sort"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/equipo"
15 "amadan.net/oficina/equipo/internal/equipo/personapi"
16 "amadan.net/oficina/equipo/internal/runnerproto"
17)
18
19func TestCoordinatorAcceptance3A(t *testing.T) {
20 t.Run("active_cancel", acceptanceActiveCancel)
21 t.Run("account_scope", TestCoordinatorToolScope)
22 t.Run("claim_identity", TestCoordinatorAuthorityClaimTampering)
23 t.Run("uncertain_requires_person", acceptanceUncertainRequiresPerson)
24 t.Run("recency", TestPersonAPIRecencyAcrossPages)
25 t.Run("task_card_recency", TestPersonAPITaskAndCardRecency)
26 t.Run("read_epoch", TestPersonAPIReadEpochTransaction)
27 t.Run("stream_cursors", TestPersonAPIStreamCursorIsolation)
28 t.Run("html_cursor_retention", TestConversationCursorRetention)
29 t.Run("delivery_receipt", TestCoordinatorSessionTrustedReceipt)
30 t.Run("atomic_delivery", TestCoordinatorTurnDeliveryAtomic)
31 t.Run("plan_replay", TestCoordinatorToolCommitCrash)
32 t.Run("recommendation", TestPlanWorkflowRecommendationDelivery)
33 t.Run("question", TestPersonAPIQuestions)
34 t.Run("human_merge", TestPersonAPIRenderedAndMerge)
35 t.Run("preferences", TestPreferencesCorrectionAndDelete)
36}
37
38func acceptanceUncertainRequiresPerson(t *testing.T) {
39 f, x, p, b := coordinatorFixture(t)
40 x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
41 turn := queueCoordinator(t, f, "first", "first")
42 c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision)
43 must(t, err)
44 must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle}))
45 next := queueCoordinator(t, f, "later", "later")
46 _, err = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision)
47 var refusal *runnerproto.RefusalError
48 if err == nil || errors.As(err, &refusal) && refusal.CoordinatorDefinitive() {
49 t.Fatal("uncertain turn fenced without person's choice", err)
50 }
51 var state string
52 must(t, f.DB.Writer().QueryRow("SELECT state FROM coordinator_turns WHERE id=?", turn.ID).Scan(&state))
53 if state != "uncertain" {
54 t.Fatal("uncertainty lost", state)
55 }
56 offers, err := x.PollCoordinator(ctx, p)
57 must(t, err)
58 if len(offers) != 0 {
59 t.Fatal("uncertain turn released queue", offers)
60 }
61 _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision})
62 must(t, err)
63 _, err = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision)
64 if !errors.As(err, &refusal) || !refusal.CoordinatorDefinitive() {
65 t.Fatal("explicit reset did not fence old turn", err)
66 }
67 offers, err = x.PollCoordinator(ctx, p)
68 must(t, err)
69 if len(offers) != 1 || offers[0].MessageID != next.MessageID {
70 t.Fatal("explicit reset lost queued request", offers)
71 }
72}
73
74func TestPersonAPIRecencyAcrossPages(t *testing.T) {
75 f := newFixture(t)
76 for i, id := range []string{"a-old", "z-new", "b-tie"} {
77 _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: id, Status: "confirmed"}, equipo.Mutation{RequestID: id})
78 must(t, err)
79 var old string
80 must(t, f.DB.Writer().QueryRow("SELECT id FROM personal_preferences WHERE text=?", id).Scan(&old))
81 f.exec(t, "UPDATE personal_preferences SET id=? WHERE id=?", id, old)
82 at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
83 if i > 0 {
84 at = at.Add(time.Hour)
85 }
86 f.exec(t, "UPDATE audit_events SET record_id=?,at=? WHERE record_id=?", id, at, old)
87 }
88 cursor := ""
89 for _, want := range []string{"b-tie", "z-new", "a-old"} {
90 w := apiRequest(t, f, owner, "GET", "/api/v1/preferences?limit=1&cursor="+url.QueryEscape(cursor), "", "", "")
91 expectHTTP(t, w, 200)
92 page := apiValue[personapi.Page[personapi.Preference]](t, w)
93 if len(page.Items) != 1 || page.Items[0].ID != want {
94 t.Fatalf("recency order: got %+v want %s", page.Items, want)
95 }
96 cursor = page.NextCursor
97 }
98 if cursor != "" {
99 t.Fatal("extra page")
100 }
101}
102
103func TestPersonAPIReadEpochTransaction(t *testing.T) {
104 f := newFixture(t)
105 // Advance the epoch after the HTTP authentication read and before the data read.
106 fired := false
107 must(t, f.DB.G.Callback().Query().After("gorm:query").Register("task11_epoch", func(tx *gorm.DB) {
108 if !fired && tx.Statement.Table == "members" && tx.Statement.Context.Value(epochTestKey{}) != nil {
109 fired = true
110 f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Unix()+100, owner.Address)
111 }
112 }))
113 t.Cleanup(func() { _ = f.DB.G.Callback().Query().Remove("task11_epoch") })
114 r := httptest.NewRequest("GET", "/api/v1/conversation", nil).WithContext(context.WithValue(ctx, epochTestKey{}, true))
115 r.AddCookie(f.Cookies[owner.Address])
116 w := httptest.NewRecorder()
117 f.Handler.ServeHTTP(w, r)
118 if !fired {
119 t.Fatal("race hook not reached")
120 }
121 expectHTTP(t, w, 403)
122}
123
124type epochTestKey struct{}
125
126func TestPersonAPIStreamCursorIsolation(t *testing.T) {
127 f := newFixture(t)
128 p := proposed(t, f)
129 otherTask := f.task(t, owner, "other-thread")
130 for i := 0; i < 3; i++ {
131 _, err := f.Store.SendMessage(ctx, owner, "", "private", equipo.Mutation{RequestID: fmt.Sprint("p", i)})
132 must(t, err)
133 _, err = f.Store.SendMessage(ctx, owner, p.TaskID, "shared", equipo.Mutation{RequestID: fmt.Sprint("t", i)})
134 must(t, err)
135 }
136 for _, path := range []string{"/api/v1/conversation", "/api/v1/tasks/" + p.TaskID + "/thread"} {
137 w := apiRequest(t, f, owner, "GET", path+"?limit=1", "", "", "")
138 expectHTTP(t, w, 200)
139 page := apiValue[personapi.ConversationPage](t, w)
140 if page.NextCursor == "" {
141 t.Fatal("missing cursor")
142 }
143 expectHTTP(t, apiRequest(t, f, peer, "GET", path+"?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410)
144 expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+otherTask.ID+"/thread?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410)
145 other := "/api/v1/conversation"
146 if path == other {
147 other = "/api/v1/tasks/" + p.TaskID + "/thread"
148 }
149 expectHTTP(t, apiRequest(t, f, owner, "GET", other+"?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410)
150 }
151}
152func TestConversationCursorRetention(t *testing.T) {
153 f := newFixture(t)
154 for i := 0; i < 3; i++ {
155 _, err := f.Store.SendMessage(ctx, owner, "", "page", equipo.Mutation{RequestID: fmt.Sprint(i)})
156 must(t, err)
157 }
158 page, err := f.Store.Conversation(ctx, owner, "", 1)
159 must(t, err)
160 if page.NextCursor == "" {
161 t.Fatal("missing cursor")
162 }
163 f.exec(t, "UPDATE conversation_cursors SET expires_at=?", time.Now().Add(-time.Hour))
164 _, err = f.Store.Conversation(ctx, owner, "", 1)
165 must(t, err)
166 if f.count(t, "SELECT count(*) FROM conversation_cursors WHERE expires_at <= ?", time.Now()) != 0 {
167 t.Fatal("expired HTML cursors retained")
168 }
169}
170
171func TestPersonAPITaskAndCardRecency(t *testing.T) {
172 f := newFixture(t)
173 p := proposed(t, f)
174 ids := []string{p.TaskID}
175 for i := 0; i < 2; i++ {
176 p.TaskID = ""
177 p.Revision = 0
178 next, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: fmt.Sprint("recency", i)})
179 must(t, err)
180 ids = append(ids, next.TaskID)
181 }
182 sort.Strings(ids)
183 for i, id := range ids {
184 f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=?", time.Now().UTC().Add(time.Duration(i+1)*time.Hour), id)
185 }
186 for _, path := range []string{"tasks", "journey", "conversation/cards"} {
187 t.Run(path, func(t *testing.T) {
188 cursor := ""
189 for i := len(ids) - 1; i >= 0; i-- {
190 w := apiRequest(t, f, owner, "GET", "/api/v1/"+path+"?limit=1&cursor="+url.QueryEscape(cursor), "", "", "")
191 expectHTTP(t, w, 200)
192 page := apiValue[personapi.Page[struct {
193 ID string `json:"id"`
194 ResourceID string `json:"resource_id"`
195 }]](t, w)
196 if len(page.Items) != 1 {
197 t.Fatal("missing page", page)
198 }
199 id := page.Items[0].ID
200 if path == "conversation/cards" {
201 id = page.Items[0].ResourceID
202 }
203 if id != ids[i] {
204 t.Fatalf("recency: got %s want %s", id, ids[i])
205 }
206 cursor = page.NextCursor
207 }
208 })
209 }
210}
211
212func TestPreferencesInferredDeleteFailure(t *testing.T) {
213 f, x, p, c := claimTools(t)
214 toolCall(t, x, p, c, "suggest", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "Keep the explanation brief"})
215 prefs, err := f.Store.Preferences(ctx, owner)
216 must(t, err)
217 if len(prefs) != 1 || prefs[0].Status != "inferred" {
218 t.Fatal(prefs)
219 }
220 before := f.count(t, "SELECT count(*) FROM audit_events")
221 f.exec(t, `CREATE TRIGGER reject_preference_delete BEFORE INSERT ON personal_preferences BEGIN SELECT RAISE(ABORT,'fixture write failure'); END`)
222 err = f.Store.DeletePreference(ctx, owner, prefs[0].ID, equipo.Mutation{RequestID: "delete", Revision: prefs[0].Revision})
223 if err == nil {
224 t.Fatal("failed inferred deletion reported success")
225 }
226 if f.count(t, "SELECT count(*) FROM audit_events") != before {
227 t.Fatal("failed deletion committed audit")
228 }
229}
230
231func acceptanceActiveCancel(t *testing.T) {
232 f, x, principal, q, question := nativeConversationFixture(t)
233 x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
234 apiRouter(t, f, nil)
235 path := "/api/v1/tasks/" + question.TaskID
236 current, err := f.Store.Task(ctx, owner, question.TaskID)
237 must(t, err)
238 response := apiRequest(t, f, owner, "POST", path+"/cancel", `{}`, "cancel-active", fmt.Sprintf(`"%d"`, current.Revision))
239 expectHTTP(t, response, 200)
240 current, err = f.Store.Task(ctx, owner, question.TaskID)
241 must(t, err)
242 if current.State != "cancel_requested" {
243 t.Fatal("active cancellation invented containment", current.State)
244 }
245 if err = x.Core.ValidateHandle(ctx, q.Scope, q.Handle); err == nil {
246 t.Fatal("cancelled attempt retained authority")
247 }
248 q.RequestID = "contained"
249 _, err = x.Mutate(ctx, principal, "contained", q)
250 must(t, err)
251 current, err = f.Store.Task(ctx, owner, question.TaskID)
252 must(t, err)
253 if current.State != "cancelled" {
254 t.Fatal("contained cancellation did not finish", current.State)
255 }
256}
257