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 "context"
5 "encoding/json"
6 "strings"
7 "testing"
8 "time"
9
10 "amadan.net/oficina/equipo/internal/wire"
11)
12
13// toolRig is a rig with a fake runner holding a running turn.
14type toolRig struct {
15 *rig
16 runner *FakeRunner
17 turn string
18 seq int
19 // attempt is the turn attempt calls belong to (0: 1).
20 attempt int64
21 // held are frames other than tool results that arrived during a call,
22 // for expect.
23 held []heldFrame
24 // placeOnMerge: a merge confirms the place card it raises (sitesOn).
25 placeOnMerge bool
26}
27
28type heldFrame struct {
29 f wire.Frame
30 body any
31 raw []byte
32}
33
34func newToolRig(t *testing.T) *toolRig { return newToolRigAt(t, wire.Protocol1) }
35
36// primaryAt is a Linux primary's protocol 2+ hello fields.
37func primaryAt(h wire.Hello, protocol int) wire.Hello {
38 h.Protocol, h.Platform, h.Label, h.Sandbox = protocol, &wire.Platform{OS: "linux", Arch: "amd64"}, "docs-t1", wire.SandboxBubblewrap
39 h.Capabilities = &wire.Capabilities{Tags: []string{wire.TagLinux, wire.TagClaude, wire.TagCodex, wire.TagGo}}
40 return h
41}
42
43// newToolRigAt is a tool rig whose runner speaks protocol: 1 is the
44// slice 4 wire; wire.ProtocolMergeFacts lets Equipo merge on its own.
45func newToolRigAt(t *testing.T, protocol int) *toolRig { return newToolRigSaying(t, protocol, "hello") }
46
47// newToolRigSaying is newToolRigAt whose turn is the person's message text.
48func newToolRigSaying(t *testing.T, protocol int, text string) *toolRig {
49 r := newRig(t)
50 // Housekeeping's clock runs from midday UTC today, so no test meets
51 // the default quiet hours (22:00 to 08:00) because of when it runs.
52 r.inst.Store.Chat().SetHousekeepingClock(daytime())
53 var runner *FakeRunner
54 if protocol <= wire.Protocol1 {
55 runner = r.dial(0)
56 } else {
57 f, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, primaryAt(wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, protocol))
58 if err != nil {
59 t.Fatal(err)
60 }
61 t.Cleanup(f.Close)
62 runner = f
63 }
64 hello := toolHello(runner.Welcome.Generation)
65 if protocol > wire.Protocol1 {
66 hello = primaryAt(hello, protocol)
67 }
68 if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil {
69 t.Fatal(err)
70 }
71 if protocol <= wire.Protocol1 {
72 shape(t, "frames/hello.json", runner.Sent[len(runner.Sent)-1])
73 }
74 r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
75 sent, err := r.client.Send(r.ctx, text, "k-tools")
76 if err != nil {
77 t.Fatal(err)
78 }
79 f, _, err := runner.Expect(r.ctx, wire.FrameMessage)
80 if err != nil {
81 t.Fatal(err)
82 }
83 if err = runner.Send(r.ctx, "a-msg", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
84 t.Fatal(err)
85 }
86 r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning })
87 return &toolRig{rig: r, runner: runner, turn: sent.Turn.ID}
88}
89
90// call sends one tool_call and returns the tool_result, acking it.
91func (r *toolRig) call(id, name string, args any) wire.ToolResult {
92 r.t.Helper()
93 raw, _ := json.Marshal(args)
94 r.seq++
95 frame := "r-tc-" + id + "-" + itoa(r.seq)
96 attempt := max(r.attempt, 1)
97 if err := r.runner.Send(r.ctx, frame, wire.FrameToolCall, wire.ToolCall{CallID: r.turn + "/" + itoa(int(attempt)) + "/" + id, TurnID: r.turn, Attempt: attempt, Name: name, Args: raw}); err != nil {
98 r.t.Fatal(err)
99 }
100 for {
101 f, body, err := r.runner.Next(r.ctx)
102 if err != nil {
103 r.t.Fatal(err)
104 }
105 if f.Type != wire.FrameAck && f.Type != wire.FrameToolResult {
106 r.held = append(r.held, heldFrame{f, body, r.runner.Received[len(r.runner.Received)-1]})
107 continue
108 }
109 if res, ok := body.(*wire.ToolResult); ok {
110 shape(r.t, "frames/tool_result.json", r.runner.Received[len(r.runner.Received)-1])
111 if err := r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
112 r.t.Fatal(err)
113 }
114 return *res
115 }
116 }
117}
118
119func itoa(n int) string { raw, _ := json.Marshal(n); return string(raw) }
120
121func TestContractTools(t *testing.T) {
122 r := newToolRigSaying(t, wire.Protocol1, "Create a new project for the site.")
123 shape(t, "frames/tool_call.json", func() []byte {
124 raw, _ := json.Marshal(wire.Frame{ID: "x", Type: wire.FrameToolCall, Data: json.RawMessage(`{"call_id":"c","turn_id":"t","attempt":1,"name":"add_project","args":{"repo":"oficina/sample"}}`)})
125 return raw
126 }())
127
128 // Not on the runner's allowlist: refused, nothing added.
129 res := r.call("u1", wire.ToolAddProject, map[string]string{"repo": "oficina/secret"})
130 if !res.IsError || res.Code != "not_allowed" || !strings.Contains(res.Text, "oficina/equipo, oficina/sample") {
131 t.Fatalf("not allowed: %+v", res)
132 }
133 res = r.call("u2", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"})
134 if res.IsError || res.Code != "added" || res.Repo != "amadan.net/oficina/sample" {
135 t.Fatalf("add: %+v", res)
136 }
137 r.wait("card and project", func(c *Conversation) bool { return len(c.Cards) == 1 && len(c.Projects) == 1 })
138 // The same call id again returns the stored result and adds nothing.
139 again := r.call("u2", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"})
140 if again != res {
141 t.Fatalf("repeat: %+v vs %+v", again, res)
142 }
143 snap, _ := r.client.Snapshot(r.ctx)
144 if len(snap.Cards) != 1 || len(snap.Projects) != 1 {
145 t.Fatalf("repeat added: %+v", snap)
146 }
147 shape(t, "api/snapshot.json", snap)
148 list, err := r.client.Projects(r.ctx)
149 if err != nil || len(list.Items) != 1 || len(list.Allowed) != 2 {
150 t.Fatalf("projects %+v %v", list, err)
151 }
152 shape(t, "api/projects.json", list)
153
154 status := r.call("u3", wire.ToolStatus, map[string]string{})
155 for _, want := range []string{`"projects":[{"name":"oficina/sample"}]`, `"can_add":["oficina/equipo","oficina/sample"]`, `"create_in":["oficina"]`} {
156 if !strings.Contains(status.Text, want) {
157 t.Fatalf("status lacks %s: %s", want, status.Text)
158 }
159 }
160 if strings.Contains(status.Text, "token") || strings.Contains(status.Text, "/home/") {
161 t.Fatalf("status leaks: %s", status.Text)
162 }
163 found := r.call("u4", wire.ToolFind, map[string]string{"query": "oficina/sample"})
164 if found.Code != "found" || !strings.Contains(found.Text, "oficina/sample") {
165 t.Fatalf("find: %+v", found)
166 }
167 // On the runner's list but not read yet: said so, not "unreachable".
168 if res := r.call("u5", wire.ToolReadFile, map[string]string{"repo": "oficina/equipo", "path": "README.md"}); !res.IsError || res.Code != "not_indexed" {
169 t.Fatalf("read outside the catalog: %+v", res)
170 }
171 if res := r.call("u5b", wire.ToolReadFile, map[string]string{"repo": "oficina/secret", "path": "README.md"}); !res.IsError || res.Code != "unreachable" {
172 t.Fatalf("read outside the allowlist: %+v", res)
173 }
174 if res := r.call("u6", wire.ToolSearchCode, map[string]string{"repo": "oficina/sample", "query": "Edge"}); res.IsError || res.Code != "read" || res.Repo != "amadan.net/oficina/sample" {
175 t.Fatalf("read: %+v", res)
176 }
177 if res := r.call("u7", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/carlos/site"}); !res.IsError || res.Code != "no_create" {
178 t.Fatalf("create outside create_in: %+v", res)
179 }
180 // project_created is accepted only after this turn authorised it.
181 if res := r.call("u8/created", wire.ToolProjectCreated, map[string]string{"repo": "amadan.net/oficina/site"}); !res.IsError {
182 t.Fatalf("unauthorised created: %+v", res)
183 }
184 if res := r.call("u9", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/site"}); res.Code != "create" {
185 t.Fatalf("authorise: %+v", res)
186 }
187 if res := r.call("u9/created", wire.ToolProjectCreated, map[string]string{"repo": "amadan.net/oficina/site"}); res.Code != "created" {
188 t.Fatalf("created: %+v", res)
189 }
190 q := r.call("u10", wire.ToolAskPerson, map[string]any{"question": "Slide on iPad too?", "options": []string{"Yes", "No"}})
191 if q.Code != "asked" {
192 t.Fatalf("ask: %+v", q)
193 }
194 var card wire.Card
195 r.wait("question card", func(c *Conversation) bool {
196 for _, k := range c.Cards {
197 if k.Kind == wire.CardQuestion {
198 card = k
199 }
200 }
201 return card.ID != ""
202 })
203 shape(t, "api/card.json", card)
204 ans, err := r.client.Answer(r.ctx, card.ID, "Yes", card.Revision)
205 if err != nil {
206 t.Fatal(err)
207 }
208 shape(t, "api/answered.json", ans)
209 _, err = r.client.Answer(r.ctx, card.ID, "Yes", ans.Card.Revision)
210 st, ok := err.(*ErrStatus)
211 if !ok || st.Status != 409 {
212 t.Fatalf("second answer %v", err)
213 }
214 shape(t, "api/error-card-conflict.json", st.Body)
215
216 // Activity becomes an event with the copy label, never the input.
217 if err := r.runner.Send(r.ctx, "r-a-1", wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolAddProject}); err != nil {
218 t.Fatal(err)
219 }
220 shape(t, "frames/activity.json", r.runner.Sent[len(r.runner.Sent)-1])
221
222 // Events from the start match the fixtures.
223 s, err := r.client.Open(r.ctx, 0)
224 if err != nil {
225 t.Fatal(err)
226 }
227 defer s.Close()
228 kinds := map[string]bool{}
229 deadline := time.After(5 * time.Second)
230 for !kinds[wire.EventActivity] || !kinds[wire.EventCard] || !kinds[wire.EventProject] {
231 select {
232 case e := <-s.Events:
233 raw, _ := json.Marshal(e)
234 switch e.Type {
235 case wire.EventCard:
236 shape(t, "api/event-card.json", raw)
237 case wire.EventProject:
238 shape(t, "api/event-project.json", raw)
239 case wire.EventActivity:
240 shape(t, "api/event-activity.json", raw)
241 var a wire.Activity
242 _ = json.Unmarshal(e.Data, &a)
243 if (a.Label != "Adding a project…" && a.Label != "Adding oficina/sample…") || a.Tool != wire.ToolAddProject {
244 t.Fatalf("activity %+v", a)
245 }
246 }
247 kinds[e.Type] = true
248 case <-deadline:
249 t.Fatalf("events seen %v", kinds)
250 }
251 }
252
253 // After the turn ends, its tools do nothing.
254 if err := r.runner.Send(r.ctx, "r-reply", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Done."}); err != nil {
255 t.Fatal(err)
256 }
257 r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
258 if res := r.call("u11", wire.ToolAddProject, map[string]string{"repo": "oficina/equipo"}); res.Code != "turn_ended" {
259 t.Fatalf("after the turn: %+v", res)
260 }
261}
262
263func TestContractProjectsAPI(t *testing.T) {
264 r := newToolRig(t)
265 if _, err := r.client.AddProject(r.ctx, "oficina/secret"); Status(err) != 422 {
266 t.Fatalf("not allowed: %v", err)
267 }
268 p, err := r.client.AddProject(r.ctx, "oficina/equipo")
269 if err != nil || p.Name != "oficina/equipo" || p.State != wire.ProjectActive {
270 t.Fatalf("add %+v %v", p, err)
271 }
272 shape(t, "api/project.json", p)
273 gone, err := r.client.RemoveProject(r.ctx, p.ID)
274 if err != nil || gone.State != wire.ProjectRemoved || gone.Revision != p.Revision+1 {
275 t.Fatalf("remove %+v %v", gone, err)
276 }
277 if again, err := r.client.RemoveProject(r.ctx, p.ID); err != nil || again.Revision != gone.Revision {
278 t.Fatalf("remove twice %+v %v", again, err)
279 }
280 if _, err := r.client.RemoveProject(r.ctx, "p_missing"); Status(err) != 404 {
281 t.Fatalf("missing: %v", err)
282 }
283 // A teammate is not an owner: they cannot add or remove projects.
284 if _, err := r.inst.DB.Writer().Exec("UPDATE members SET role = 'member' WHERE address = ?", Owner); err != nil {
285 t.Fatal(err)
286 }
287 if _, err := r.client.AddProject(r.ctx, "oficina/equipo"); Status(err) != 403 {
288 t.Fatalf("member add: %v", err)
289 }
290}
291
292// Every coordinator tool has an activity label.
293func TestActivityLabels(t *testing.T) {
294 r := newToolRig(t)
295 for i, tool := range wire.ConverseTools {
296 if err := r.runner.Send(r.ctx, "r-al-"+itoa(i), wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: tool}); err != nil {
297 t.Fatal(err)
298 }
299 }
300 r.wait("labels", func(c *Conversation) bool { return len(c.Activity[r.turn]) == len(wire.ConverseTools) })
301 r.conv.Locked(func(c *Conversation) {
302 for _, a := range c.Activity[r.turn] {
303 if a.Label == "" || a.Label == "Working…" {
304 t.Fatalf("no label for %s: %q", a.Tool, a.Label)
305 }
306 }
307 })
308}
309
310// Review fix 1: a stored authorisation is not returned after the owner
311// is demoted mid-turn, and a call id cannot be replayed for another tool,
312// arguments or attempt.
313func TestToolReplayRevalidates(t *testing.T) {
314 r := newToolRigSaying(t, wire.Protocol1, "Create a new project for the site.")
315 if res := r.call("rv1", wire.ToolSearchCode, map[string]string{"repo": "oficina/sample", "query": "x"}); res.Code != "read" {
316 t.Fatalf("read: %+v", res)
317 }
318 if res := r.call("rv2", wire.ToolStatus, map[string]string{}); res.Code != "ok" {
319 t.Fatalf("status: %+v", res)
320 }
321 // Same call id, other tool or arguments: refused, not the stored result.
322 if res := r.call("rv1", wire.ToolSearchCode, map[string]string{"repo": "oficina/sample", "query": "other"}); !res.IsError || res.Code != "invalid" {
323 t.Fatalf("replay with other arguments: %+v", res)
324 }
325 // A stored create authorisation is not returned once the turn ended.
326 if res := r.call("rv3", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/site"}); res.Code != "create" {
327 t.Fatalf("authorise: %+v", res)
328 }
329 if err := r.runner.Send(r.ctx, "r-reply-rv", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Done."}); err != nil {
330 t.Fatal(err)
331 }
332 r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
333 if res := r.call("rv3", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/site"}); res.Code != "turn_ended" {
334 t.Fatalf("replay after the turn ended: %+v", res)
335 }
336 if _, err := r.inst.DB.Writer().Exec("UPDATE members SET role = 'member' WHERE address = ?", Owner); err != nil {
337 t.Fatal(err)
338 }
339 // A demoted person's runner holds no turn: the replay gets no
340 // authorisation back (no result is delivered to it at all).
341 raw, _ := json.Marshal(map[string]string{"repo": "oficina/sample", "query": "x"})
342 if err := r.runner.Send(r.ctx, "r-tc-rv1-again", wire.FrameToolCall, wire.ToolCall{CallID: r.turn + "/1/rv1", TurnID: r.turn, Attempt: 1, Name: wire.ToolSearchCode, Args: raw}); err != nil {
343 t.Fatal(err)
344 }
345 ctx, cancel := context.WithTimeout(r.ctx, 2*time.Second)
346 defer cancel()
347 for {
348 _, body, err := r.runner.Next(ctx)
349 if err != nil {
350 return
351 }
352 if res, ok := body.(*wire.ToolResult); ok && (res.Code == "read" || !res.IsError) {
353 t.Fatalf("replay after demotion kept authority: %+v", res)
354 }
355 }
356}
357
358// Review fix 3: an answer dispatched at once carries its question; a
359// Change carries the project it replaces.
360func TestAnswerDispatchCarriesContext(t *testing.T) {
361 r := newToolRig(t)
362 if res := r.call("q1", wire.ToolAskPerson, map[string]any{"question": "Slide on iPad too?", "options": []string{"Yes", "No"}}); res.Code != "asked" {
363 t.Fatalf("ask: %+v", res)
364 }
365 if res := r.call("q2", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"}); res.Code != "added" {
366 t.Fatalf("add: %+v", res)
367 }
368 if err := r.runner.Send(r.ctx, "r-reply-q", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Asked."}); err != nil {
369 t.Fatal(err)
370 }
371 r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
372 var question, project wire.Card
373 r.conv.Locked(func(c *Conversation) {
374 for _, k := range c.Cards {
375 if k.Kind == wire.CardQuestion {
376 question = k
377 } else if k.Kind == wire.CardProject {
378 project = k
379 }
380 }
381 })
382 next := func(want, own string) {
383 t.Helper()
384 for {
385 f, body, err := r.runner.Next(r.ctx)
386 if err != nil {
387 t.Fatal(err)
388 }
389 if m, ok := body.(*wire.MessageCommand); ok {
390 if !strings.Contains(m.Text, want) {
391 t.Fatalf("dispatched %q, want it to contain %q", m.Text, want)
392 }
393 // Astra 2b round 2: the person's own words travel apart
394 // from the model's question.
395 if own == "" && len(m.PersonText) != 0 || own != "" && (len(m.PersonText) != 1 || m.PersonText[0] != own) {
396 t.Fatalf("person_text %q, want [%q]", m.PersonText, own)
397 }
398 _ = r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID})
399 _ = r.runner.Send(r.ctx, "r-reply-"+f.ID, wire.FrameReply, wire.Reply{TurnID: m.TurnID, Attempt: 1, Text: "Ok."})
400 return
401 }
402 }
403 }
404 ans, err := r.client.Answer(r.ctx, question.ID, "Yes", question.Revision)
405 if err != nil {
406 t.Fatal(err)
407 }
408 next(`(My answer to your question "Slide on iPad too?") Yes`, "")
409 r.wait("answer turn replied", func(c *Conversation) bool { return c.Turns[ans.Turn.ID].State == wire.TurnReplied })
410 if _, err := r.client.Answer(r.ctx, project.ID, "oficina/equipo", project.Revision); err != nil {
411 t.Fatal(err)
412 }
413 next("(Use this repository instead of oficina/sample for that work) oficina/equipo", "")
414}
415
416// Review minor: an actionable project card with a stale revision is
417// card_stale, not card_answered.
418func TestProjectCardStaleRevision(t *testing.T) {
419 r := newToolRig(t)
420 r.call("s1", wire.ToolAddProject, map[string]string{"repo": "oficina/sample"})
421 var card wire.Card
422 r.wait("card", func(c *Conversation) bool {
423 for _, k := range c.Cards {
424 card = k
425 }
426 return card.ID != ""
427 })
428 _, err := r.client.Answer(r.ctx, card.ID, "oficina/equipo", card.Revision+5)
429 var conflict wire.CardConflict
430 st, ok := err.(*ErrStatus)
431 if !ok || st.Status != 409 || json.Unmarshal(st.Body, &conflict) != nil || conflict.Code != "card_stale" {
432 t.Fatalf("stale project card: %v", err)
433 }
434}
435
436// next ends the running turn with a reply and starts a turn for text.
437func (r *toolRig) next(text string) {
438 r.t.Helper()
439 prev := r.turn
440 if err := r.runner.Send(r.ctx, "r-reply-"+prev, wire.FrameReply, wire.Reply{TurnID: prev, Attempt: 1, Text: "Ok."}); err != nil {
441 r.t.Fatal(err)
442 }
443 r.wait("replied", func(c *Conversation) bool { return c.Turns[prev].State == wire.TurnReplied })
444 r.seq++
445 sent, err := r.client.Send(r.ctx, text, "k-next-"+itoa(r.seq))
446 if err != nil {
447 r.t.Fatal(err)
448 }
449 f, _, err := r.runner.Expect(r.ctx, wire.FrameMessage)
450 if err != nil {
451 r.t.Fatal(err)
452 }
453 if err = r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
454 r.t.Fatal(err)
455 }
456 r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning })
457 r.turn = sent.Turn.ID
458}
459
460func (r *toolRig) homeCard() wire.Card {
461 r.t.Helper()
462 var card wire.Card
463 r.wait("home card", func(c *Conversation) bool {
464 card = wire.Card{}
465 for _, k := range c.Cards {
466 if k.Kind == wire.CardHome && k.TurnID == r.turn {
467 card = k
468 }
469 }
470 return card.ID != ""
471 })
472 return card
473}
474
475// setHome asks for a home change and taps the card, as the person does,
476// returning the card (now a receipt with Undo).
477func (r *toolRig) setHome(id, ns string) wire.Card {
478 r.t.Helper()
479 if res := r.call(id, wire.ToolSetProjectHome, map[string]string{"namespace": ns}); res.Code != "asked_owner" {
480 r.t.Fatalf("set_project_home %q: %+v", ns, res)
481 }
482 card := r.homeCard()
483 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); err != nil {
484 r.t.Fatal(err)
485 }
486 r.wait("set", func(c *Conversation) bool { card = c.Cards[card.ID]; return card.State == wire.CardHomeSet })
487 return card
488}
489
490// The team's home for new projects: unset by default; a change needs the
491// person's tap and leaves a receipt with Undo, which restores the value
492// before it (never set, or the earlier namespace).
493func TestProjectHomeSetting(t *testing.T) {
494 r := newToolRig(t)
495 if res := r.call("h1", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":""`) {
496 t.Fatalf("unset home: %s", res.Text)
497 }
498 if res := r.call("h2", wire.ToolSetProjectHome, map[string]string{"namespace": "carlos"}); !res.IsError || res.Code != "no_create" {
499 t.Fatalf("home outside create_in: %+v", res)
500 }
501 if res := r.call("h2c", wire.ToolSetProjectHome, map[string]string{"namespace": ""}); !res.IsError || res.Code != "no_home" {
502 t.Fatalf("clear with no home: %+v", res)
503 }
504 card := r.setHome("h3", "oficina")
505 shape(t, "api/card.json", card)
506 if res := r.call("h4", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"oficina"`) {
507 t.Fatalf("home after the tap: %s", res.Text)
508 }
509 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceUndo, card.Revision); err != nil {
510 t.Fatal(err)
511 }
512 if res := r.call("h4u", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":""`) {
513 t.Fatalf("home after undo: %s", res.Text)
514 }
515 r.wait("undone", func(c *Conversation) bool { return c.Cards[card.ID].State == wire.CardUndone })
516 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceUndo, card.Revision+1); err == nil {
517 t.Fatal("undo twice")
518 }
519 r.next("Use oficina again.")
520 r.setHome("h5s", "oficina")
521 r.next("Clear it.")
522 cleared := r.setHome("h5", "")
523 if res := r.call("h6", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":""`) {
524 t.Fatalf("home after clear: %s", res.Text)
525 }
526 if _, err := r.client.Answer(r.ctx, cleared.ID, wire.ChoiceUndo, cleared.Revision); err != nil {
527 t.Fatal(err)
528 }
529 if res := r.call("h7", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"oficina"`) {
530 t.Fatalf("home after undoing the clear: %s", res.Text)
531 }
532}
533
534// Astra re-check 2: an explicit clear means no home, even when the
535// runner advertises its own default; never set falls back to it.
536func TestProjectHomeClearBeatsRunnerDefault(t *testing.T) {
537 r := newToolRigSaying(t, wire.Protocol1, "Create a new project for the site.")
538 hello := wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{"oficina", "work"}, Home: "work", Agent: "equipo-test", Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{}}
539 if err := r.runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil {
540 t.Fatal(err)
541 }
542 waitHome := func(want string) {
543 t.Helper()
544 deadline := time.Now().Add(5 * time.Second)
545 for {
546 p, err := r.client.Projects(r.ctx)
547 if err != nil {
548 t.Fatal(err)
549 }
550 if p.Home == want {
551 return
552 }
553 if time.Now().After(deadline) {
554 t.Fatalf("home %q, want %q", p.Home, want)
555 }
556 time.Sleep(50 * time.Millisecond)
557 }
558 }
559 waitHome("work")
560 if res := r.call("d1", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"work"`) {
561 t.Fatalf("runner default: %s", res.Text)
562 }
563 r.next("Unset the home for new projects, please.")
564 if k := r.setHome("d2", ""); k.Question != "work" {
565 t.Fatalf("clear card names %q, want the runner default work", k.Question)
566 }
567 waitHome("")
568 if res := r.call("d3", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":""`) {
569 t.Fatalf("status after clear: %s", res.Text)
570 }
571 r.next("Create a new project for the site.")
572 if res := r.call("d4", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/work/site"}); !res.IsError {
573 t.Fatalf("create in the runner default after a clear: %+v", res)
574 }
575 if res := r.call("d5", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/site"}); res.Code != "create" {
576 t.Fatalf("create in a related namespace: %+v", res)
577 }
578}
579
580// Astra 2b review 4: Undo is bound to the change it made. After
581// unset -> oficina -> work -> oficina, the first card's Undo is refused
582// although the value matches again.
583func TestProjectHomeStaleUndo(t *testing.T) {
584 r := newToolRig(t)
585 hello := wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{"oficina", "work"}, Agent: "equipo-test", Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{}}
586 if err := r.runner.Send(r.ctx, "h-su", wire.FrameHello, hello); err != nil {
587 t.Fatal(err)
588 }
589 var cards []wire.Card
590 for i, ns := range []string{"oficina", "work", "oficina"} {
591 r.next("Put new projects in " + ns + ".")
592 deadline := time.Now().Add(5 * time.Second)
593 for {
594 // The second hello (create_in with work) may still be on its way.
595 if res := r.call("su"+itoa(i)+"-"+itoa(int(time.Now().UnixNano()%1e6)), wire.ToolSetProjectHome, map[string]string{"namespace": ns}); res.Code == "asked_owner" {
596 break
597 } else if time.Now().After(deadline) {
598 t.Fatalf("set %s: %+v", ns, res)
599 }
600 time.Sleep(50 * time.Millisecond)
601 }
602 card := r.homeCard()
603 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); err != nil {
604 t.Fatal(err)
605 }
606 r.wait("set", func(c *Conversation) bool { card = c.Cards[card.ID]; return card.State == wire.CardHomeSet })
607 cards = append(cards, card)
608 }
609 first := cards[0]
610 r.wait("first card", func(c *Conversation) bool { first = c.Cards[first.ID]; return true })
611 _, err := r.client.Answer(r.ctx, first.ID, wire.ChoiceUndo, first.Revision)
612 if st, ok := err.(*ErrStatus); !ok || st.Status != 409 {
613 t.Fatalf("superseded undo: %v", err)
614 }
615 if res := r.call("su-check", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"oficina"`) {
616 t.Fatalf("home after a refused undo: %s", res.Text)
617 }
618 last := cards[2]
619 if _, err := r.client.Answer(r.ctx, last.ID, wire.ChoiceUndo, last.Revision); err != nil {
620 t.Fatalf("latest undo: %v", err)
621 }
622 if res := r.call("su-after", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"work"`) {
623 t.Fatalf("latest undo restores work: %s", res.Text)
624 }
625}
626
627// Astra 2b round 2, item 2: no text is parsed for intent any more. A
628// set_project_home call never changes the setting, however the person
629// phrased it; it posts the one-tap card, and only the person's tap on
630// that card, at its current revision, changes it. A clear asks "Stop
631// using X for new projects?".
632func TestProjectHomeOnlyByTap(t *testing.T) {
633 r := newToolRig(t)
634 for i, text := range []string{"New projects go to oficina.", `Explain the phrase "use oficina for new projects".`, "Don’t put new projects in oficina.", "hello"} {
635 r.next(text)
636 res := r.call("ot"+itoa(i), wire.ToolSetProjectHome, map[string]string{"namespace": "oficina"})
637 if res.IsError || res.Code != "asked_owner" {
638 t.Fatalf("%q: %+v", text, res)
639 }
640 if res := r.call("os"+itoa(i), wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":""`) {
641 t.Fatalf("%q: a tool call alone changed the home: %s", text, res.Text)
642 }
643 if k := r.homeCard(); k.State != wire.CardHomeAsk || k.Name != "oficina" {
644 t.Fatalf("%q: card %+v", text, k)
645 }
646 }
647 card := r.homeCard()
648 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision+1); Status(err) != 409 {
649 t.Fatalf("tap at a stale revision: %v", err)
650 }
651 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); err != nil {
652 t.Fatal(err)
653 }
654 if res := r.call("ot-set", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"oficina"`) {
655 t.Fatalf("home after the tap: %s", res.Text)
656 }
657 // Clearing asks too, naming what it stops using.
658 r.next("Clear where new projects go.")
659 if res := r.call("oc", wire.ToolSetProjectHome, map[string]string{"namespace": ""}); res.Code != "asked_owner" {
660 t.Fatalf("clear: %+v", res)
661 }
662 if res := r.call("oc-s", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":"oficina"`) {
663 t.Fatalf("a clear call alone changed the home: %s", res.Text)
664 }
665 clear := r.homeCard()
666 if clear.State != wire.CardHomeAsk || clear.Name != "" || clear.Question != "oficina" {
667 t.Fatalf("clear card %+v", clear)
668 }
669 if _, err := r.client.Answer(r.ctx, clear.ID, wire.ChoiceConfirm, clear.Revision); err != nil {
670 t.Fatal(err)
671 }
672 if res := r.call("oc-after", wire.ToolStatus, map[string]string{}); !strings.Contains(res.Text, `"home":""`) {
673 t.Fatalf("home after the clear tap: %s", res.Text)
674 }
675}
676
677// daytime is a housekeeping clock at midday UTC today, moving with real
678// time from when it was made.
679func daytime() func() time.Time {
680 start := time.Now()
681 base := start.UTC().Truncate(24 * time.Hour).Add(12 * time.Hour)
682 return func() time.Time { return base.Add(time.Since(start)) }
683}
684
685// toolHello is the tool rig's hello (protocol 1). The agent reads
686// moonbeam/docs only (a reader grant: catalog, not Repos), so moonbeam is
687// a namespace Equipo knows, and an unreached repository there gets an
688// access card (#48).
689func toolHello(generation int64) wire.Hello {
690 return wire.Hello{Generation: generation, Repos: []string{"amadan.net/oficina/sample", "amadan.net/oficina/equipo"}, CreateIn: []string{"oficina"}, Agent: "equipo-test", Catalog: []wire.RepoInfo{{Repo: "amadan.net/oficina/sample", DefaultBranch: "main", Summary: "Woodstar is a reading app.", Names: []string{"sample", "Woodstar"}, Hints: []string{"go"}, Gate: "make ci", HeadSHA: strings.Repeat("9", 40), HeadSubject: "Trim the compose sheet"}, {Repo: "amadan.net/moonbeam/docs", DefaultBranch: "main", Names: []string{"docs"}, Hints: []string{}}}, Connections: []wire.HeldConnection{{LocalID: "claude-a", Person: Owner, Provider: "claude", Kind: "subscription", Label: Owner, State: "healthy"}}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}}
691}
692