oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "encoding/json"
6 "os"
7 "path/filepath"
8 "slices"
9 "strings"
10 "sync"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/runner"
15 "amadan.net/oficina/equipo/internal/runner/provider"
16 "amadan.net/oficina/equipo/internal/wire"
17 "amadan.net/oficina/equipo/internal/wire/wiretest"
18)
19
20// A job lane is a Coordinator thread: the coordinator's action, rule,
21// opening and tools, never the Assistant's.
22func TestJobLaneProfile(t *testing.T) {
23 catalog := []wire.RepoInfo{{Repo: "amadan.net/oficina/sample", Names: []string{"sample"}, Summary: "A sample"}}
24 p := profileFor(wire.JobLane("h_a"))
25 if p.action != "converse" || p.rule != houseRule {
26 t.Fatalf("job lane profile %q %q", p.action, p.rule)
27 }
28 if p.opening("ana@example.com", catalog) != opening("ana@example.com", catalog) {
29 t.Fatal("a job lane opens as something other than the coordinator")
30 }
31 if s := p.set(true); len(s.names) == 0 || !slices.Equal(s.names, provider.ConverseTools()) {
32 t.Fatalf("job lane tools %v", s.names)
33 }
34}
35
36// A job lane has its own session homes and desk under the person's
37// job/<id>; its notebook is its own and never reported as the person's,
38// it knows the catalog as the main lane does, and a fresh session starts
39// with the main notebook as reference after the opening.
40func TestJobLaneHomeAndDesk(t *testing.T) {
41 root := t.TempDir()
42 p := "ana@example.com"
43 lane := wire.JobLane("h_a")
44 state, err := OpenState(context.Background(), t.TempDir())
45 if err != nil {
46 t.Fatal(err)
47 }
48 defer state.Close()
49 c, err := openLane(ClaudeOptions{SessionRoot: root, State: state}, CodexOptions{}, p, lane, runner.AccountBinding{Provider: "claude", PersonID: p})
50 if err != nil {
51 t.Fatal(err)
52 }
53 cc, ok := c.(*claudeCoordinator)
54 if !ok {
55 t.Fatalf("job lane is %T", c)
56 }
57 dir := personDir(root, p)
58 if cc.home != filepath.Join(dir, "job", "h_a", "claude") || cc.desk.Dir != filepath.Join(dir, "job", "h_a", "desk") || cc.lane != lane || cc.profile.action != "converse" {
59 t.Fatalf("home %s desk %s lane %q action %q", cc.home, cc.desk.Dir, cc.lane, cc.profile.action)
60 }
61 x, err := openLane(ClaudeOptions{SessionRoot: root}, CodexOptions{}, p, lane, runner.AccountBinding{Provider: "codex", PersonID: p})
62 if err != nil {
63 t.Fatal(err)
64 }
65 if xc := x.(*codexCoordinator); xc.home != filepath.Join(dir, "job", "h_a", "codex") || xc.desk.Dir != cc.desk.Dir || xc.lane != lane {
66 t.Fatalf("codex home %s desk %s lane %q", xc.home, xc.desk.Dir, xc.lane)
67 }
68 if _, err := openLane(ClaudeOptions{SessionRoot: root}, CodexOptions{}, p, "job:../x", runner.AccountBinding{Provider: "claude", PersonID: p}); err == nil {
69 t.Fatal("a malformed job lane opened")
70 }
71
72 mainDesk, err := OpenDesk(root, p)
73 if err != nil {
74 t.Fatal(err)
75 }
76 if err := mainDesk.SaveEntries([]wire.NotebookEntry{{ID: "n1", Source: wire.NoteOwn, Text: "Ana ships on Fridays", At: time.Unix(0, 0).UTC()}}); err != nil {
77 t.Fatal(err)
78 }
79 before, err := os.ReadFile(mainDesk.entries)
80 if err != nil {
81 t.Fatal(err)
82 }
83 b := &bridge{SessionRoot: root, State: state, Index: &Index{catalog: []wire.RepoInfo{{Repo: "amadan.net/oficina/sample"}}}, trip: func(_ context.Context, c wire.ToolCall) wire.ToolResult {
84 if c.Name == wire.ToolWriteNote {
85 return wire.ToolResult{Code: "note"}
86 }
87 return wire.ToolResult{Code: "notes"}
88 }}
89 ctx := context.WithValue(context.Background(), factsKey{}, factsFor(TurnInput{Kind: wire.TurnPerson, Lane: lane, PersonText: []string{"Keep it blue."}}))
90 args, _ := json.Marshal(map[string]any{"entries": []map[string]string{{"text": "Keep it blue.", "source": "person"}, {"text": "The sample app is the shop", "source": "own", "repo": "oficina/sample"}}})
91 if text, isErr := b.Call(ctx, p, "tj", 1, wire.ToolWriteNote, "u1", args); isErr {
92 t.Fatalf("write: %s", text)
93 }
94 if after, _ := os.ReadFile(mainDesk.entries); string(after) != string(before) {
95 t.Fatalf("the main notebook changed: %s", after)
96 }
97 if es := cc.desk.Entries(); len(es) != 2 || es[0].Text != "Keep it blue." || es[1].Repo != "oficina/sample" {
98 t.Fatalf("job notebook %+v", es)
99 }
100 frames, _, err := state.Unacked(context.Background(), 0)
101 if err != nil || len(frames) != 0 {
102 t.Fatalf("frames sent for a job's notebook: %+v %v", frames, err)
103 }
104
105 // The main notebook is reference in a fresh job session only, after
106 // the opening; reading it leaves the main desk as it was.
107 fresh, _ := cc.prompt(true, TurnInput{Kind: wire.TurnPerson, Lane: lane, Text: "Make it blue."}, nil)
108 at := strings.Index(fresh, "Ana ships on Fridays")
109 if !strings.HasPrefix(fresh, opening(p, nil)) || at < len(opening(p, nil)) || !strings.Contains(fresh, "Keep it blue.") {
110 t.Fatalf("fresh job frame:\n%s", fresh)
111 }
112 if later, _ := cc.prompt(false, TurnInput{Kind: wire.TurnPerson, Lane: lane, Text: "And green."}, nil); strings.Contains(later, "Ana ships on Fridays") {
113 t.Fatalf("a resumed job session got the main notebook again:\n%s", later)
114 }
115 mainLane := &coordBase{o: ClaudeOptions{SessionRoot: root}, person: p, lane: wire.LaneCoordinator, profile: profileFor(wire.LaneCoordinator), desk: mainDesk}
116 if own, _ := mainLane.prompt(true, TurnInput{Kind: wire.TurnPerson, Text: "Hi."}, nil); strings.Count(own, "Ana ships on Fridays") != 1 || strings.Contains(own, "Keep it blue.") {
117 t.Fatalf("the main lane's fresh frame:\n%s", own)
118 }
119 if after, _ := os.ReadFile(mainDesk.entries); string(after) != string(before) {
120 t.Fatalf("reading the main notebook changed it: %s", after)
121 }
122 // A person with no main desk yet gets none made by a job.
123 other := "bo@example.com"
124 oc, err := openLane(ClaudeOptions{SessionRoot: root}, CodexOptions{}, other, lane, runner.AccountBinding{Provider: "claude", PersonID: other})
125 if err != nil {
126 t.Fatal(err)
127 }
128 oc.(*claudeCoordinator).prompt(true, TurnInput{Kind: wire.TurnPerson, Lane: lane, Text: "Hi."}, nil)
129 if _, err := os.Stat(filepath.Join(personDir(root, other), "desk")); !os.IsNotExist(err) {
130 t.Fatalf("a job made the main desk: %v", err)
131 }
132}
133
134// sessionCoordinator replies with the session its lane resumes: the
135// durable row for the person, lane and provider.
136type sessionCoordinator struct {
137 state *State
138 lane string
139 hold chan struct{}
140 done chan [2]string
141}
142
143func (c *sessionCoordinator) Turn(ctx context.Context, in TurnInput, _ func(string)) TurnResult {
144 if c.hold != nil {
145 select {
146 case <-c.hold:
147 case <-ctx.Done():
148 }
149 }
150 row, _, _ := c.state.session(ctx, in.Person, c.lane, "claude")
151 c.done <- [2]string{in.TurnID, row.SessionID}
152 return TurnResult{Text: row.SessionID}
153}
154func (c *sessionCoordinator) Close() {}
155
156// Two jobs of one person run at once, beside a main lane turn that is
157// still running, each on its own worker and its own session.
158func TestJobLanesRunAtOnce(t *testing.T) {
159 ctx, cancel := context.WithCancel(context.Background())
160 defer cancel()
161 state, err := OpenState(ctx, t.TempDir())
162 if err != nil {
163 t.Fatal(err)
164 }
165 defer state.Close()
166 p := "ana@example.com"
167 a, b := wire.JobLane("h_a"), wire.JobLane("h_b")
168 for lane, id := range map[string]string{wire.LaneCoordinator: "sess-main", a: "sess-a", b: "sess-b"} {
169 if err := state.saveSession(ctx, p, lane, "claude", "acct", id, "t0"); err != nil {
170 t.Fatal(err)
171 }
172 }
173 release := make(chan struct{})
174 done := make(chan [2]string, 4)
175 var mu sync.Mutex
176 opened := map[string]int{}
177 e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: func(_, lane string, _ runner.AccountBinding) (Coordinator, error) {
178 mu.Lock()
179 opened[lane]++
180 mu.Unlock()
181 c := &sessionCoordinator{state: state, lane: lane, done: done}
182 if lane == wire.LaneCoordinator {
183 c.hold = release
184 }
185 return c, nil
186 }}
187 if err := e.Start(ctx); err != nil {
188 t.Fatal(err)
189 }
190 defer e.Wait()
191 defer cancel()
192 for i, m := range []wire.MessageCommand{{TurnID: "tm", Lane: wire.LaneCoordinator}, {TurnID: "ja", Lane: a}, {TurnID: "jb", Lane: b}} {
193 m.Person, m.Attempt, m.Text = p, 1, "go"
194 if err := state.Accept(ctx, "f"+itoa(int64(i)), m); err != nil {
195 t.Fatal(err)
196 }
197 e.Wake(p, m.Lane)
198 }
199 got := map[string]string{}
200 for len(got) < 2 {
201 select {
202 case d := <-done:
203 got[d[0]] = d[1]
204 case <-time.After(5 * time.Second):
205 t.Fatalf("job turns waited: %v", got)
206 }
207 }
208 if got["ja"] != "sess-a" || got["jb"] != "sess-b" {
209 t.Fatalf("job replies %v", got)
210 }
211 close(release)
212 if d := <-done; d != [2]string{"tm", "sess-main"} {
213 t.Fatalf("main lane %v", d)
214 }
215 mu.Lock()
216 defer mu.Unlock()
217 if opened[a] != 1 || opened[b] != 1 || opened[wire.LaneCoordinator] != 1 {
218 t.Fatalf("opened %v", opened)
219 }
220 if connKey(p, a) != "conn:"+p+"#job:h_a" {
221 t.Fatalf("job connection memory %q", connKey(p, a))
222 }
223}
224
225// A job lane needs protocol 22, and only a well-formed job lane is
226// taken: anything else is dropped, never run as a Coordinator turn.
227func TestMessageJobLaneRefused(t *testing.T) {
228 for _, c := range []struct {
229 protocol int
230 lane string
231 taken bool
232 }{{21, "job:h_a", false}, {22, "job:../x", false}, {22, "job:", false}, {22, "jobs", false}, {22, "job:h_a", true}, {22, wire.LaneAssistant, true}} {
233 inst := newFakeInstance(t)
234 _, state, _, _ := startLink(t, inst.url, &stubCoordinator{})
235 conn := <-inst.conns
236 read(t, conn, wire.FrameHello)
237 write(t, conn, []byte(`{"id":"i-welcome-3","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":`+itoa(int64(c.protocol))+`,"role":"primary"}}`))
238 read(t, conn, wire.FrameSync)
239 lane, _ := json.Marshal(c.lane)
240 write(t, conn, []byte(`{"id":"c-lane","type":"message","data":{"person":"owner@example.com","turn_id":"t_lane","attempt":1,"kind":"","text":"wait","person_text":["wait"],"tail":[],"lane":`+string(lane)+`}}`))
241 write(t, conn, wiretest.Fixture("frames/message.json"))
242 var acked []string
243 for !slices.Contains(acked, "c7") {
244 ack, _ := read(t, conn, wire.FrameAck)
245 var a wire.Ack
246 _ = json.Unmarshal(ack.Data, &a)
247 acked = append(acked, a.ID)
248 }
249 var n int
250 if err := state.db.QueryRow("SELECT count(*) FROM runs WHERE turn_id=?", "t_lane").Scan(&n); err != nil || (n == 1) != c.taken || slices.Contains(acked, "c-lane") != c.taken {
251 t.Fatalf("protocol %d lane %q: runs %d, acks %v, err %v", c.protocol, c.lane, n, acked, err)
252 }
253 }
254}
255
256// Moving in and exploring are the person's own conversation's: such a
257// turn in any other lane is dropped, never run against that lane's desk.
258func TestMessageMoveInOnlyMainLane(t *testing.T) {
259 for _, c := range []struct {
260 kind, lane string
261 taken bool
262 }{{wire.TurnMoveIn, "job:h_a", false}, {wire.TurnExplore, "job:h_a", false}, {wire.TurnMoveIn, wire.LaneAssistant, false}, {wire.TurnExplore, wire.LaneAssistant, false}, {wire.TurnMoveIn, wire.LaneCoordinator, true}, {wire.TurnExplore, wire.LaneCoordinator, true}} {
263 inst := newFakeInstance(t)
264 _, state, _, _ := startLink(t, inst.url, &stubCoordinator{})
265 conn := <-inst.conns
266 read(t, conn, wire.FrameHello)
267 write(t, conn, []byte(`{"id":"i-welcome-3","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":22,"role":"primary"}}`))
268 read(t, conn, wire.FrameSync)
269 write(t, conn, []byte(`{"id":"c-kind","type":"message","data":{"person":"owner@example.com","turn_id":"t_kind","attempt":1,"kind":"`+c.kind+`","text":"","person_text":[],"tail":[],"lane":"`+c.lane+`"}}`))
270 write(t, conn, wiretest.Fixture("frames/message.json"))
271 var acked []string
272 for !slices.Contains(acked, "c7") {
273 ack, _ := read(t, conn, wire.FrameAck)
274 var a wire.Ack
275 _ = json.Unmarshal(ack.Data, &a)
276 acked = append(acked, a.ID)
277 }
278 var n int
279 if err := state.db.QueryRow("SELECT count(*) FROM runs WHERE turn_id=?", "t_kind").Scan(&n); err != nil || (n == 1) != c.taken || slices.Contains(acked, "c-kind") != c.taken {
280 t.Fatalf("%s in lane %q: runs %d, acks %v, err %v", c.kind, c.lane, n, acked, err)
281 }
282 }
283}
284
285// A cancel reaches the turn running in a job lane.
286func TestCancelFindsJobLane(t *testing.T) {
287 ctx, cancel := context.WithCancel(context.Background())
288 defer cancel()
289 state, err := OpenState(ctx, t.TempDir())
290 if err != nil {
291 t.Fatal(err)
292 }
293 defer state.Close()
294 started := make(chan struct{}, 1)
295 e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: func(string, string, runner.AccountBinding) (Coordinator, error) {
296 return &startedCoordinator{started: started}, nil
297 }}
298 if err := e.Start(ctx); err != nil {
299 t.Fatal(err)
300 }
301 defer e.Wait()
302 defer cancel()
303 p, lane := "ana@example.com", wire.JobLane("h_a")
304 if err := state.Accept(ctx, "f1", wire.MessageCommand{Person: p, TurnID: "tj", Attempt: 1, Text: "go", Lane: lane}); err != nil {
305 t.Fatal(err)
306 }
307 e.Wake(p, lane)
308 select {
309 case <-started:
310 case <-time.After(5 * time.Second):
311 t.Fatal("the job turn never started")
312 }
313 e.Cancel(p, "tj", 1)
314 waitFor(t, func() bool {
315 var st string
316 _ = state.db.QueryRow("SELECT state FROM runs WHERE turn_id=?", "tj").Scan(&st)
317 return st == runReported
318 })
319 frames, _, err := state.Unacked(ctx, 0)
320 if err != nil || len(frames) == 0 || !strings.Contains(string(frames[len(frames)-1].Data), `"cancelled"`) {
321 t.Fatalf("cancel report %+v %v", frames, err)
322 }
323}
324
325// startedCoordinator says when its turn started and runs until cancelled.
326type startedCoordinator struct{ started chan struct{} }
327
328func (c *startedCoordinator) Turn(ctx context.Context, _ TurnInput, _ func(string)) TurnResult {
329 c.started <- struct{}{}
330 <-ctx.Done()
331 return TurnResult{Reason: "cancelled"}
332}
333func (c *startedCoordinator) Close() {}
334
335// A reset of the person's conversation clears the main lane's desk and
336// session; job threads keep theirs.
337func TestResetLeavesJobLanes(t *testing.T) {
338 ctx := context.Background()
339 root := t.TempDir()
340 state, err := OpenState(ctx, t.TempDir())
341 if err != nil {
342 t.Fatal(err)
343 }
344 defer state.Close()
345 p, lane := "ana@example.com", wire.JobLane("h_a")
346 for l, id := range map[string]string{wire.LaneCoordinator: "sess-main", lane: "sess-job"} {
347 if err := state.saveSession(ctx, p, l, "claude", "acct", id, "t0"); err != nil {
348 t.Fatal(err)
349 }
350 d, err := openDeskAt(laneDir(root, p, l))
351 if err != nil {
352 t.Fatal(err)
353 }
354 if err := d.SaveEntries([]wire.NotebookEntry{{ID: "n1", Source: wire.NoteOwn, Text: "note " + id, At: time.Unix(0, 0).UTC()}}); err != nil {
355 t.Fatal(err)
356 }
357 }
358 if err := resetConversation(ctx, state, root, p); err != nil {
359 t.Fatal(err)
360 }
361 if _, ok, _ := state.session(ctx, p, wire.LaneCoordinator, "claude"); ok {
362 t.Fatal("the main lane's session survived the reset")
363 }
364 if row, ok, _ := state.session(ctx, p, lane, "claude"); !ok || row.SessionID != "sess-job" {
365 t.Fatalf("the job's session %+v %v", row, ok)
366 }
367 mainDesk, _ := OpenDesk(root, p)
368 jobDesk, _ := openDeskAt(laneDir(root, p, lane))
369 if !mainDesk.Empty() || len(jobDesk.Entries()) != 1 {
370 t.Fatalf("main %+v job %+v", mainDesk.Entries(), jobDesk.Entries())
371 }
372}
373