oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "amadan.net/oficina/equipo/internal/wire"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/url"
9 "strings"
10 "testing"
11)
12
13func (r *toolRig) movePlacement(id, repo string, revision int64) error {
14 return r.client.do(r.ctx, http.MethodPost, "/api/v1/tasks/"+id+"/move", wire.MoveTask{Repo: repo, Revision: revision}, nil)
15}
16
17func TestPlacementRestartContract(t *testing.T) {
18 r := newToolRigAt(t, wire.ProtocolCurrent)
19 id := r.shopTask("placement")
20 if got := r.call("placement-finding", wire.ToolAddFinding, map[string]any{"task": id, "text": "Keep this source context", "headline": "Original finding", "repo": "oficina/sample", "path": "README.md", "line": 1}); got.IsError {
21 t.Fatal(got)
22 }
23 r.begin("placement-start", id)
24 old := r.nextDispatch()
25 before := r.task(id)
26 if len(before.Findings) != 1 {
27 t.Fatal("fixture finding missing", before.Findings)
28 }
29 if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil {
30 t.Fatal(err)
31 }
32 if task := r.task(id); !task.Moving || task.Repo != before.Repo {
33 t.Fatalf("moved before termination: %+v", task)
34 }
35 // A cancellation acknowledgement, wrong attempt and terminal state do not prove termination.
36 _, body := r.expect(wire.FrameCancelStep)
37 cancel := body.(*wire.CancelStepCommand)
38 if cancel.StepID != old.StepID || cancel.Attempt != old.Attempt {
39 t.Fatal(cancel)
40 }
41 r.step("placement-unproven", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepCancelled})
42 if task := r.task(id); !task.Moving || task.Repo != before.Repo {
43 t.Fatal("terminal without proof moved", task)
44 }
45 r.step("placement-wrong-attempt", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt + 1, State: wire.StepCancelled, Termination: true})
46 if task := r.task(id); !task.Moving {
47 t.Fatal("wrong attempt moved", task)
48 }
49 r.step("placement-proven", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepCancelled, Termination: true})
50 fresh := r.nextDispatch()
51 if fresh.Repo != "amadan.net/oficina/equipo" || fresh.Branch == old.Branch || fresh.StepID == old.StepID || fresh.BaseSHA != "" || fresh.Round != 0 || fresh.Republish {
52 t.Fatalf("not a fresh destination: %+v", fresh)
53 }
54 after := r.task(id)
55 if after.Moving || after.ID != before.ID || after.Brief != before.Brief || len(after.Findings) != len(before.Findings) || after.CandidateSHA != "" || after.Checks != "" || after.Verdict != "" || len(after.EarlierSteps) != 1 {
56 t.Fatalf("move lost context or kept evidence: %+v", after)
57 }
58 // No command produced by the move may dispatch, publish or merge the old branch.
59 var rows []struct{ Kind, Body string }
60 if err := r.inst.DB.G.Table("runner_commands").Where("kind IN ?", []string{wire.FrameDispatch, wire.FramePublish}).Order("seq").Scan(&rows).Error; err != nil {
61 t.Fatal(err)
62 }
63 count := 0
64 for _, row := range rows {
65 var d struct {
66 Branch string `json:"branch"`
67 }
68 json.Unmarshal([]byte(row.Body), &d)
69 if d.Branch == old.Branch {
70 count++
71 }
72 }
73 if count != 1 {
74 t.Fatalf("old branch received new work: %+v", rows)
75 }
76 r.step("placement-late", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepDone, Termination: true, Pushed: true, BaseSHA: baseX, CandidateSHA: candX})
77 if task := r.task(id); task.CandidateSHA != "" || task.Branch != fresh.Branch {
78 t.Fatal("late report revived old branch", task)
79 }
80 notes, err := r.client.Notebook(r.ctx)
81 if err != nil {
82 t.Fatal(err)
83 }
84 found := false
85 for _, n := range notes.Entries {
86 found = found || strings.Contains(n.Text, "oficina/equipo") && strings.Contains(n.Text, "oficina/sample")
87 }
88 if !found {
89 t.Fatal("missing correction", notes)
90 }
91}
92
93func TestPlacementAfterPushReviewAndReady(t *testing.T) {
94 for _, stage := range []string{wire.StageInProgress, wire.StageInReview, wire.StageReadyToMerge} {
95 t.Run(stage, func(t *testing.T) {
96 r := newToolRigAt(t, wire.ProtocolCurrent)
97 id := r.shopTask("stage")
98 now := r.inst.Store.Chat().Now()
99 _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,pushed,terminated,candidate_sha,base_sha,revision,created_at,updated_at) VALUES('s_old',?,1,'engineering',?,'done',1,1,1,?,?,1,?,?)", id, Owner, candX, baseX, now, now)
100 if err != nil {
101 t.Fatal(err)
102 }
103 if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET stage=?,base_sha=?,ready_sha=?,merge_eligible=? WHERE id=?", stage, baseX, candX, candX, id); err != nil {
104 t.Fatal(err)
105 }
106 before := r.task(id)
107 if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil {
108 t.Fatal(err)
109 }
110 d := r.nextDispatch()
111 if d.Branch == before.Branch || d.Repo == before.Repo || d.BaseSHA != "" {
112 t.Fatal("old branch reused", d)
113 }
114 after := r.task(id)
115 if after.CandidateSHA != "" || after.Verdict != "" || after.MergeOffered || after.Merged != nil {
116 t.Fatal("old evidence carried over", after)
117 }
118 if len(after.Thread) == 0 || !strings.Contains(after.Thread[len(after.Thread)-1].Text, before.Branch) {
119 t.Fatal("no old branch note", after.Thread)
120 }
121 })
122 }
123}
124
125func TestPlacementConsentContract(t *testing.T) {
126 r := newToolRigAt(t, wire.ProtocolCurrent)
127 if res := r.call("create-unasked", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/fresh"}); !res.IsError || res.Code != "placement_required" {
128 t.Fatal(res)
129 }
130 if res := r.call("choose", wire.ToolAskPerson, map[string]any{"question": "Create whatever you want?", "options": []string{"Create a new project for it"}, "placement": wire.Placement{Repos: []string{"oficina/sample", "oficina/equipo"}, NewRepo: "oficina/fresh"}}); res.Code != "asked" {
131 t.Fatal(res)
132 }
133 if res := r.call("record-premature", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Premature", "brief": "Don't start yet"}); !res.IsError || res.Code != "placement_pending" {
134 t.Fatal(res)
135 }
136 snap, _ := r.client.Snapshot(r.ctx)
137 var card wire.Card
138 for _, c := range snap.Cards {
139 if c.Kind == wire.CardQuestion {
140 card = c
141 }
142 }
143 if len(card.Options) != 3 || card.Options[0] != "Add to oficina/sample" || card.Options[2] != "New project: oficina/fresh" {
144 t.Fatal(card)
145 }
146 if status, _ := r.post(r.inst.Cookie(), "/conversation/cards/"+card.ID+"/visibility", url.Values{"revision": {itoa(int(card.Revision))}, "aside": {"true"}}); status != http.StatusSeeOther {
147 t.Fatal(status)
148 }
149 if res := r.call("create-aside", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/fresh"}); !res.IsError {
150 t.Fatal("aside authorised", res)
151 }
152}
153
154func TestPlacementNewProjectAction(t *testing.T) {
155 r := newToolRigAt(t, wire.ProtocolCurrent)
156 id := r.shopTask("new-placement")
157 if err := r.runner.Send(r.ctx, "finish-old", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Recorded."}); err != nil {
158 t.Fatal(err)
159 }
160 r.wait("old turn ends", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
161 before := r.task(id)
162 status, where := r.post(r.inst.Cookie(), "/tasks/"+id+"/move", url.Values{"new": {"1"}, "repo": {"oficina/new-project"}, "revision": {itoa(int(before.Revision))}})
163 if status != http.StatusSeeOther || where != "/tasks/"+id {
164 t.Fatalf("new project action %d %s", status, where)
165 }
166 if after := r.task(id); !after.Moving || !after.PreparingProject || after.Repo != before.Repo {
167 t.Fatal("new project did not hold task", after)
168 }
169 _, body := r.expect(wire.FrameMessage)
170 msg := body.(*wire.MessageCommand)
171 if !strings.Contains(msg.Text, id) || !strings.Contains(msg.Text, "Do not record another task") {
172 t.Fatal("missing correction context", msg)
173 }
174 r.turn = msg.TurnID
175 if got := r.call("make-new", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/new-project"}); got.Code != "create" {
176 t.Fatal("own explicit tap not authorised", got)
177 }
178 if got := r.call("make-new/created", wire.ToolProjectCreated, map[string]string{"repo": "amadan.net/oficina/new-project"}); got.Code != "created" {
179 t.Fatal(got)
180 }
181 // Creation precedes the runner's refreshed repository inventory. It is
182 // durable pending state, and even a task with no steps resumes on hello.
183 hello := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent)
184 hello.Repos = append(hello.Repos, "amadan.net/oficina/new-project")
185 if err := r.runner.Send(r.ctx, "new-project-hello", wire.FrameHello, hello); err != nil {
186 t.Fatal(err)
187 }
188 r.wait("new project move finishes", func(c *Conversation) bool {
189 return c.Tasks[id].Repo == "amadan.net/oficina/new-project" && !c.Tasks[id].Moving
190 })
191 after := r.task(id)
192 if after.ID != before.ID || after.Brief != before.Brief || after.Stage != wire.StageNoted || len(after.Steps) > 0 {
193 t.Fatal("new project started unstarted work", after)
194 }
195}
196
197func TestPlacementAnswerAuthorizesOnlySelectedRepo(t *testing.T) {
198 r := newToolRigSaying(t, wire.ProtocolCurrent, "Make a calendar")
199 if res := r.call("placement-q", wire.ToolAskPerson, map[string]any{"question": "Where?", "placement": wire.Placement{Repos: []string{"oficina/sample"}, NewRepo: "oficina/calendar"}}); res.Code != "asked" {
200 t.Fatal(res)
201 }
202 if err := r.runner.Send(r.ctx, "finish-ask", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Where should it go?"}); err != nil {
203 t.Fatal(err)
204 }
205 r.wait("ask turn ends", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
206 snap, _ := r.client.Snapshot(r.ctx)
207 var card wire.Card
208 for _, c := range snap.Cards {
209 if c.Kind == wire.CardQuestion {
210 card = c
211 }
212 }
213 if _, err := r.client.Answer(r.ctx, card.ID, "Made up choice", card.Revision); err == nil {
214 t.Fatal("forged choice accepted")
215 }
216 if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision+1); err == nil {
217 t.Fatal("stale choice accepted")
218 }
219 if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision); err != nil {
220 t.Fatal(err)
221 }
222 _, body := r.expect(wire.FrameMessage)
223 msg := body.(*wire.MessageCommand)
224 r.turn = msg.TurnID
225 if !strings.Contains(msg.Text, "Make a calendar") {
226 t.Fatal("lost original request", msg.Text)
227 }
228 if got := r.call("wrong-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/other"}); !got.IsError {
229 t.Fatal("wrong repository consent", got)
230 }
231 if got := r.call("wrong-placement-record", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Misfiled calendar", "brief": "Make the calendar"}); !got.IsError {
232 t.Fatal("recorded outside the chosen project", got)
233 }
234 if got := r.call("right-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); got.Code != "create" {
235 t.Fatal(got)
236 }
237 if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision); err == nil {
238 t.Fatal("repeated answer accepted")
239 }
240}
241
242func TestPlacementPreservesResearchAndThreads(t *testing.T) {
243 r := newToolRigSaying(t, wire.ProtocolCurrent, personWords)
244 r.researchOn()
245 r.inventoryOn()
246 research := r.runningResearch("move-research")
247 r.step("move-research-done", wire.StepReport{TaskID: research.TaskID, StepID: research.StepID, Attempt: research.Attempt, State: wire.StepDone, Termination: true, Summary: "Read the source pages.", Research: &wire.ResearchResult{Findings: findingsJSON(t, goodFindings()), Fetches: fetchLog()}})
248 eng := r.nextDispatch()
249 id := eng.TaskID
250 now := r.inst.Store.Chat().Now()
251 if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_questions(id,task_id,step_id,asker,idempotency_key,specialist,text,state,answer,attempt,revision,created_at,updated_at) VALUES('q_saved',?,?,?,'saved','engineering','Why this colour?','answered','From the original brand.',1,1,?,?)", id, eng.StepID, Owner, now, now); err != nil {
252 t.Fatal(err)
253 }
254 if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_card_threads(id,card_id,person,text,created_at) SELECT 'ct_saved',id,?,'Keep the brand.',? FROM chat_cards WHERE task_id=? LIMIT 1", Owner, now, id); err != nil {
255 t.Fatal(err)
256 }
257 before := r.task(id)
258 if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil {
259 t.Fatal(err)
260 }
261 r.expect(wire.FrameCancelStep)
262 r.step("move-research-proof", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: eng.Attempt, State: wire.StepCancelled, Termination: true})
263 r.nextDispatch()
264 after := r.task(id)
265 found := false
266 for _, s := range after.Steps {
267 if s.ID == research.StepID && s.Research != nil && s.Summary == "Read the source pages." {
268 found = true
269 }
270 }
271 if !found || len(after.Questions) != 1 || after.Questions[0].Answer != "From the original brand." {
272 t.Fatal("lost research or specialist thread", after)
273 }
274 var count int
275 if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_card_threads WHERE id='ct_saved'").Scan(&count); err != nil || count != 1 {
276 t.Fatal("lost sub-chat", count, err)
277 }
278}
279
280func TestPlacementPendingKeepsUsageAndFinishingResearch(t *testing.T) {
281 r := newToolRigSaying(t, wire.ProtocolCurrent, personWords)
282 r.researchOn()
283 r.inventoryOn()
284 research := r.runningResearch("pending-research")
285 before := r.task(research.TaskID)
286 if err := r.movePlacement(before.ID, "oficina/equipo", before.Revision); err != nil {
287 t.Fatal(err)
288 }
289 r.expect(wire.FrameCancelStep)
290 tokens := int64(123)
291 usage := []wire.Usage{{Provider: "codex", Connection: "codex", Model: "test", Attempt: research.Attempt, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &tokens}}
292 r.step("research-await-proof", wire.StepReport{TaskID: before.ID, StepID: research.StepID, Attempt: research.Attempt, State: wire.StepDone, Usage: usage})
293 var got int64
294 if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(sum(input_tokens),0) FROM chat_usage WHERE step_id=?", research.StepID).Scan(&got); err != nil {
295 t.Fatal(err)
296 }
297 if got != tokens {
298 t.Fatalf("lost pending usage: %d", got)
299 }
300 r.step("research-proof-and-findings", wire.StepReport{TaskID: before.ID, StepID: research.StepID, Attempt: research.Attempt, State: wire.StepDone, Termination: true, Summary: "Finished the source pages.", Research: &wire.ResearchResult{Findings: findingsJSON(t, goodFindings()), Fetches: fetchLog()}})
301 d := r.nextDispatch()
302 if d.Repo != "amadan.net/oficina/equipo" {
303 t.Fatal(d)
304 }
305 after := r.task(before.ID)
306 found := false
307 for _, s := range after.Steps {
308 if s.ID == research.StepID && s.Research != nil && len(s.Research.Fetches) > 0 && s.Summary == "Finished the source pages." {
309 found = true
310 }
311 }
312 if !found {
313 t.Fatal("lost Research that finished during cancellation", after.Steps)
314 }
315}
316
317func TestPlacementWaitsForPendingPublication(t *testing.T) {
318 r := newToolRigAt(t, wire.ProtocolCurrent)
319 id := r.shopTask("pending-publish")
320 now := r.inst.Store.Chat().Now()
321 if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,terminated,publication,candidate_sha,revision,created_at,updated_at) VALUES('s_publish',?,1,'engineering',?,'done',1,1,'pending',?,1,?,?)", id, Owner, candX, now, now); err != nil {
322 t.Fatal(err)
323 }
324 before := r.task(id)
325 if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil {
326 t.Fatal(err)
327 }
328 if task := r.task(id); !task.Moving || task.Repo != before.Repo {
329 t.Fatal("moved while old publication was unsettled", task)
330 }
331}
332
333func TestPlacementMergeDuringStopRefusesMove(t *testing.T) {
334 r := newToolRigAt(t, wire.ProtocolCurrent)
335 id := r.shopTask("merge-during-stop")
336 now := r.inst.Store.Chat().Now()
337 if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,terminated,pushed,candidate_sha,revision,created_at,updated_at) VALUES('s_eng',?,1,'engineering',?,'done',1,1,1,?,1,?,?)", id, Owner, candX, now, now); err != nil {
338 t.Fatal(err)
339 }
340 if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,terminated,runner_id,candidate_sha,revision,created_at,updated_at) VALUES('s_review',?,2,'review',?,'running',1,0,?,?,1,?,?)", id, Owner, r.runner.Welcome.RunnerID, candX, now, now); err != nil {
341 t.Fatal(err)
342 }
343 if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET stage='in_review' WHERE id=?", id); err != nil {
344 t.Fatal(err)
345 }
346 before := r.task(id)
347 if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil {
348 t.Fatal(err)
349 }
350 r.expect(wire.FrameCancelStep)
351 if err := r.runner.Send(r.ctx, "merged-while-stopping", wire.FrameMerged, wire.MergedReport{TaskID: id, CandidateSHA: candX}); err != nil {
352 t.Fatal(err)
353 }
354 r.wait("merge recorded", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
355 r.step("review-stopped-after-merge", wire.StepReport{TaskID: id, StepID: "s_review", Attempt: 1, State: wire.StepCancelled, Termination: true})
356 after := r.task(id)
357 if after.Repo != before.Repo || after.Stage != wire.StageDone || after.Moving {
358 t.Fatal("move restarted a merged task", after)
359 }
360}
361
362func TestPlacementReconnectProofRestarts(t *testing.T) {
363 for _, failed := range []bool{false, true} {
364 t.Run(fmt.Sprintf("failed-%v", failed), func(t *testing.T) {
365 r := newToolRigAt(t, wire.ProtocolCurrent)
366 id := r.shopTask("sync-move")
367 r.begin("sync-start", id)
368 old := r.nextDispatch()
369 if failed {
370 r.step("failed-unproven", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepFailed, Reason: "interrupted"})
371 }
372 before := r.task(id)
373 if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil {
374 t.Fatal(err)
375 }
376 r.expect(wire.FrameCancelStep)
377 if err := r.runner.Send(r.ctx, "sync-placement-proof", wire.FrameSync, wire.Sync{Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{}}); err != nil {
378 t.Fatal(err)
379 }
380 // Sync is not acknowledged. The next tool result is a barrier
381 // on this ordered connection, so the sync has committed by then.
382 if result := r.call("sync-barrier", wire.ToolStatus, map[string]any{}); result.IsError {
383 t.Fatal(result)
384 }
385
386 after := r.task(id)
387 if after.Moving || after.Repo != "amadan.net/oficina/equipo" || after.Stage != wire.StageInProgress {
388 t.Fatal("reconnect proof lost pending restart", after.Stage, after.Repo, after.Moving)
389 }
390 })
391 }
392}
393