package thintest import ( "encoding/json" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // moveInRig is a rig with a fake runner that said hello, and no turn yet. type moveInRig struct { *toolRig } func newMoveInRig(t *testing.T) *moveInRig { r := newRig(t) runner := r.dial(0) hello := wire.Hello{Generation: runner.Welcome.Generation, Repos: []string{"amadan.net/oficina/sample"}, 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"}}}, Connections: []wire.HeldConnection{}, Versions: map[string]string{}} if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) return &moveInRig{&toolRig{rig: r, runner: runner}} } // moveIn asks for a turn of kind and returns its message command, acked. func (r *moveInRig) moveIn(frame, kind string) *wire.MessageCommand { r.t.Helper() if err := r.runner.Send(r.ctx, frame, wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: kind}); err != nil { r.t.Fatal(err) } return r.dispatched(kind) } // dispatched reads frames until a message command of kind arrives, acks // it and waits for its turn to run. func (r *moveInRig) dispatched(kind string) *wire.MessageCommand { r.t.Helper() for { f, body, err := r.runner.Next(r.ctx) if err != nil { r.t.Fatal(err) } cmd, ok := body.(*wire.MessageCommand) if !ok { continue } if cmd.Kind != kind { r.t.Fatalf("dispatched kind %q, want %q: %+v", cmd.Kind, kind, cmd) } if err = r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { r.t.Fatal(err) } r.wait("running", func(c *Conversation) bool { return c.Turns[cmd.TurnID].State == wire.TurnRunning }) r.turn = cmd.TurnID return cmd } } func (r *moveInRig) reply(turn, text string) { r.t.Helper() if err := r.runner.Send(r.ctx, "r-reply-"+turn, wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: text}); err != nil { r.t.Fatal(err) } r.wait("replied", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnReplied }) } // The runner asks for a move-in; the instance starts one move_in turn, // shows the coordinator moving in, scopes its tools to looking around // and taking notes, and posts its reply as the one introduction. func TestContractMoveIn(t *testing.T) { r := newMoveInRig(t) if err := r.runner.Send(r.ctx, "r-mi-1", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: wire.TurnMoveIn}); err != nil { t.Fatal(err) } shape(t, "frames/move_in.json", r.runner.Sent[len(r.runner.Sent)-1]) cmd := r.dispatched(wire.TurnMoveIn) shape(t, "frames/message.json", r.runner.Received[len(r.runner.Received)-1]) if withoutProjectContext(t, cmd.Text) != "" || cmd.Person != Owner { t.Fatalf("move-in command %+v", cmd) } r.wait("moving in", func(c *Conversation) bool { return c.Coordinator.State == wire.CoordinatorMovingIn && c.Coordinator.TurnID == cmd.TurnID }) snap, err := r.client.Snapshot(r.ctx) if err != nil || snap.Coordinator.State != wire.CoordinatorMovingIn || snap.Coordinator.ID != Owner { t.Fatalf("snapshot coordinator %+v %v", snap.Coordinator, err) } shape(t, "api/snapshot.json", snap) // A second request while one is in flight starts nothing. if err := r.runner.Send(r.ctx, "r-mi-2", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: wire.TurnMoveIn}); err != nil { t.Fatal(err) } // Another person's move-in is not this runner's to ask for. if err := r.runner.Send(r.ctx, "r-mi-3", wire.FrameMoveIn, wire.MoveIn{Person: "someone@example.com", Kind: wire.TurnMoveIn}); err != nil { t.Fatal(err) } if err := r.runner.Send(r.ctx, "r-mi-4", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: "party"}); err != nil { t.Fatal(err) } // Activity names the repository it reads, as moving in. if err := r.runner.Send(r.ctx, "r-a-mi", wire.FrameActivity, wire.ActivityReport{TurnID: cmd.TurnID, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile, Repo: "amadan.net/oficina/sample"}); err != nil { t.Fatal(err) } shape(t, "frames/activity.json", r.runner.Sent[len(r.runner.Sent)-1]) // A repository outside the catalog is never named. if err := r.runner.Send(r.ctx, "r-a-mi2", wire.FrameActivity, wire.ActivityReport{TurnID: cmd.TurnID, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile, Repo: "amadan.net/secret/thing"}); err != nil { t.Fatal(err) } var acts []wire.Activity r.wait("activity", func(c *Conversation) bool { acts = c.Activity[cmd.TurnID]; return len(acts) == 2 }) if acts[0].Label != "Moving in… reading oficina/sample" || acts[0].Repo != "oficina/sample" { t.Fatalf("move-in activity %+v", acts[0]) } if acts[1].Repo != "" || strings.Contains(acts[1].Label, "secret") { t.Fatalf("unknown repository named: %+v", acts[1]) } // Only looking around and taking notes. if res := r.call("m1", wire.ToolStatus, map[string]string{}); res.Code != "ok" || !strings.Contains(res.Text, `"coordinator":"moving_in"`) { t.Fatalf("status while moving in: %+v", res) } for _, c := range []struct { name string args any }{ {wire.ToolAddProject, map[string]string{"repo": "oficina/sample"}}, {wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/site"}}, {wire.ToolAskPerson, map[string]any{"question": "Which repository?", "options": []string{"a", "b"}}}, {wire.ToolSetProjectHome, map[string]string{"namespace": "oficina"}}, } { if res := r.call("m-"+c.name, c.name, c.args); !res.IsError || res.Code != "moving_in" { t.Fatalf("%s while moving in: %+v", c.name, res) } } if res := r.call("n1", wire.ToolWriteNote, map[string]any{"entries": 3, "bytes": 120}); res.Code != "note" || res.IsError { t.Fatalf("write_note: %+v", res) } for i, bad := range []map[string]any{{"entries": wire.MaxNoteEntries + 1, "bytes": 1}, {"entries": 1, "bytes": wire.MaxNotebookBytes + 1}, {"entries": -1, "bytes": 1}, {"entries": 1, "bytes": 1, "text": "smuggled"}, {"name": "notebook.md", "bytes": 1}} { if res := r.call("nb"+itoa(i), wire.ToolWriteNote, bad); !res.IsError || res.Code != "invalid" { t.Fatalf("write_note %v: %+v", bad, res) } } if res := r.call("n2", wire.ToolReadNotes, map[string]string{}); res.Code != "notes" || res.IsError { t.Fatalf("read_notes: %+v", res) } r.reply(cmd.TurnID, "Hi, I'm your coordinator. I can see oficina/sample (Woodstar).") r.wait("ready", func(c *Conversation) bool { return c.Coordinator.State == wire.CoordinatorReady && c.Coordinator.MovedInAt != nil && c.Coordinator.TurnID == "" }) var moveIns int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_turns WHERE kind = ?", wire.TurnMoveIn).Scan(&moveIns); err != nil || moveIns != 1 { t.Fatalf("move-in turns %d %v; the repeated request must start nothing", moveIns, err) } var intro []wire.Message r.conv.Locked(func(c *Conversation) { intro = c.Replies() }) if len(intro) != 1 || intro[0].TurnID != cmd.TurnID { t.Fatalf("introduction %+v", intro) } turn, err := r.client.Turn(r.ctx, cmd.TurnID) if err != nil || turn.Kind != wire.TurnMoveIn || len(turn.MessageIDs) != 0 { t.Fatalf("move-in turn %+v %v", turn, err) } // The coordinator event matches its fixture. s, err := r.client.Open(r.ctx, 0) if err != nil { t.Fatal(err) } defer s.Close() for e := range s.Events { if e.Type == wire.EventCoordinator { raw, _ := json.Marshal(e) shape(t, "api/event-coordinator.json", raw) break } } // Another person's move-in is never started by this runner. if err := r.runner.Send(r.ctx, "r-mi-5", wire.FrameMoveIn, wire.MoveIn{Person: "someone@example.com", Kind: wire.TurnMoveIn}); err != nil { t.Fatal(err) } for { _, body, err := r.runner.Next(r.ctx) if err != nil { t.Fatal(err) } if a, ok := body.(*wire.Ack); ok && a.ID == "r-mi-5" { break } } if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_turns WHERE kind = ?", wire.TurnMoveIn).Scan(&moveIns); err != nil || moveIns != 1 { t.Fatalf("move-in turns %d %v after another person's request", moveIns, err) } // Notes and moving-in tools need a running turn like any other. if res := r.call("n3", wire.ToolWriteNote, map[string]any{"entries": 1, "bytes": 1}); res.Code != "turn_ended" { t.Fatalf("write_note after the turn: %+v", res) } } // A person's message never waits behind a move-in: the running move-in // gives way (cancelled, reason yielded), the person is answered, then the // move-in continues in a new turn. A queued move-in goes after them too. func TestMoveInYieldsToThePerson(t *testing.T) { r := newMoveInRig(t) first := r.moveIn("r-mi-1", wire.TurnMoveIn) sent, err := r.client.Send(r.ctx, "hello", "k-y1") if err != nil { t.Fatal(err) } var cancel *wire.CancelCommand for cancel == nil { f, body, err := r.runner.Next(r.ctx) if err != nil { t.Fatal(err) } switch v := body.(type) { case *wire.CancelCommand: cancel = v _ = r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) case *wire.MessageCommand: t.Fatalf("dispatched before the move-in gave way: %+v", v) } } if cancel.TurnID != first.TurnID || cancel.Attempt != 1 { t.Fatalf("cancel %+v", cancel) } if err = r.runner.Send(r.ctx, "r-t-y", wire.FrameTurn, wire.TurnReport{TurnID: first.TurnID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}); err != nil { t.Fatal(err) } r.wait("yielded", func(c *Conversation) bool { return c.Turns[first.TurnID].State == wire.TurnCancelled && c.Turns[first.TurnID].Reason == wire.ReasonYielded }) person := r.dispatched(wire.TurnPerson) if person.TurnID != sent.Turn.ID || withoutProjectContext(t, person.Text) != "hello" { t.Fatalf("person turn %+v", person) } var cont string r.wait("still moving in", func(c *Conversation) bool { cont = c.Coordinator.TurnID return c.Coordinator.State == wire.CoordinatorMovingIn && cont != "" && cont != first.TurnID }) r.reply(person.TurnID, "Hello.") next := r.dispatched(wire.TurnMoveIn) if next.TurnID != cont { t.Fatalf("continued in %s, want %s", next.TurnID, cont) } r.reply(next.TurnID, "Hi, I'm your coordinator.") r.wait("ready", func(c *Conversation) bool { return c.Coordinator.State == wire.CoordinatorReady }) // After an access change the runner asks to explore the difference. if err := r.runner.Send(r.ctx, "r-ex-1", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: wire.TurnExplore}); err != nil { t.Fatal(err) } explore := r.dispatched(wire.TurnExplore) r.reply(explore.TurnID, "") var replies []wire.Message r.conv.Locked(func(c *Conversation) { replies = c.Replies() }) if len(replies) != 2 { t.Fatalf("an empty explore reply posts nothing; replies %+v", replies) } // A queued move-in waits for a person turn sent after it. held, err := r.client.Send(r.ctx, "sleep:1 first", "k-y2") if err != nil { t.Fatal(err) } busy := r.dispatched(wire.TurnPerson) if err := r.runner.Send(r.ctx, "r-ex-2", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: wire.TurnExplore}); err != nil { t.Fatal(err) } later, err := r.client.Send(r.ctx, "second", "k-y3") if err != nil { t.Fatal(err) } r.reply(busy.TurnID, "Ok.") if again := r.dispatched(wire.TurnPerson); again.TurnID != later.Turn.ID || held.Turn.ID != busy.TurnID { t.Fatalf("person turn after a queued explore: %+v", again) } } // Astra 2b review 3: the instance's coordinator state is the authority on // introductions. Once ready, a move-in request (a runner that lost its // desk record) becomes an explore turn: it may look around again, but // never introduces itself twice. func TestMoveInAfterReadyNeverIntroducesTwice(t *testing.T) { r := newMoveInRig(t) first := r.moveIn("r-mi-1", wire.TurnMoveIn) r.reply(first.TurnID, "Hi, I'm your coordinator.") r.wait("ready", func(c *Conversation) bool { return c.Coordinator.State == wire.CoordinatorReady }) if err := r.runner.Send(r.ctx, "r-mi-2", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: wire.TurnMoveIn}); err != nil { t.Fatal(err) } again := r.dispatched(wire.TurnExplore) r.reply(again.TurnID, "Hi again, I'm your coordinator.") var intros, replies int r.conv.Locked(func(c *Conversation) { for _, m := range c.Replies() { replies++ if c.Turns[m.TurnID].Kind == wire.TurnMoveIn { intros++ } } }) if intros != 1 { t.Fatalf("introductions %d", intros) } r.conv.Locked(func(c *Conversation) { if c.Coordinator.State != wire.CoordinatorReady { t.Fatalf("coordinator %+v", c.Coordinator) } }) } // Astra 2b review 1: the owner sees the notebook with each entry's // source, as the runner reports it; Reset is refused while a turn runs, // then clears it, tells the runner (which empties the desk and forgets // the session) and lets the coordinator move in again. func TestContractNotebook(t *testing.T) { r := newMoveInRig(t) empty, err := r.client.Notebook(r.ctx) if err != nil || len(empty.Entries) != 0 || empty.ID != Owner { t.Fatalf("empty notebook %+v %v", empty, err) } report := wire.NotebookReport{Person: Owner, Entries: []wire.NotebookEntry{ {ID: "n1", Source: wire.NotePerson, Text: "I like short replies.", At: time.Now().UTC()}, {ID: "n2", Source: wire.NoteRepo, Repo: "oficina/equipo", Path: "README.md", Text: "Equipo runs a team's coordinator.", At: time.Now().UTC()}, }} if err := r.runner.Send(r.ctx, "r-nb-1", wire.FrameNotebook, report); err != nil { t.Fatal(err) } shape(t, "frames/notebook.json", r.runner.Sent[len(r.runner.Sent)-1]) // Another person's notebook is not this runner's to report. if err := r.runner.Send(r.ctx, "r-nb-2", wire.FrameNotebook, wire.NotebookReport{Person: "someone@example.com", Entries: []wire.NotebookEntry{{ID: "x", Source: wire.NoteOwn, Text: "planted"}}}); err != nil { t.Fatal(err) } for { _, body, err := r.runner.Next(r.ctx) if err != nil { t.Fatal(err) } if a, ok := body.(*wire.Ack); ok && a.ID == "r-nb-2" { break } } got, err := r.client.Notebook(r.ctx) if err != nil || len(got.Entries) != 2 || got.Entries[1].Repo != "oficina/equipo" || got.Entries[0].Source != wire.NoteOwn { t.Fatalf("notebook %+v %v", got, err) } shape(t, "api/notebook.json", got) // Refused while a turn is in flight. first := r.moveIn("r-mi-1", wire.TurnMoveIn) if _, err := r.client.ResetNotebook(r.ctx); Status(err) != 409 { t.Fatalf("reset during a turn: %v", err) } r.reply(first.TurnID, "Hi, I'm your coordinator.") r.wait("ready", func(c *Conversation) bool { return c.Coordinator.State == wire.CoordinatorReady }) c, err := r.client.ResetNotebook(r.ctx) if err != nil || c.State != wire.CoordinatorNew { t.Fatalf("reset %+v %v", c, err) } f, body, err := r.runner.Expect(r.ctx, wire.FrameReset) if err != nil || body.(*wire.ResetCommand).Person != Owner { t.Fatalf("reset frame %v %v", body, err) } shape(t, "frames/reset.json", r.runner.Received[len(r.runner.Received)-1]) _ = r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) if got, _ := r.client.Notebook(r.ctx); len(got.Entries) != 0 { t.Fatalf("notebook after reset %+v", got) } // Moving in again introduces itself again: the person asked for it. again := r.moveIn("r-mi-2", wire.TurnMoveIn) r.reply(again.TurnID, "Hi again.") r.wait("ready again", func(c *Conversation) bool { return c.Coordinator.State == wire.CoordinatorReady }) }