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 "database/sql"
6 "encoding/json"
7 "log/slog"
8 "os"
9 "path/filepath"
10 "slices"
11 "strings"
12 "sync"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/runner"
17 "amadan.net/oficina/equipo/internal/wire"
18 "amadan.net/oficina/equipo/internal/wire/wiretest"
19)
20
21// The two lanes of one person are two queues and two sessions: each
22// lane's next run is its own, and a session saved in one lane never
23// replaces the other's. A state file from before the Assistant keeps its
24// coordinator session, copied once.
25func TestStateKeepsLanesApart(t *testing.T) {
26 ctx := context.Background()
27 dir := t.TempDir()
28 old, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "thin.db"))
29 if err != nil {
30 t.Fatal(err)
31 }
32 if _, err = old.Exec(`CREATE TABLE sessions (person TEXT NOT NULL, provider TEXT NOT NULL, account TEXT NOT NULL, session_id TEXT NOT NULL, last_turn TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (person, provider));
33INSERT INTO sessions VALUES ('old@example.com', 'claude', 'acct#rule-x', 'sess-old', 't0', '2026-11-01T00:00:00Z');`); err != nil {
34 t.Fatal(err)
35 }
36 old.Close()
37 s, err := OpenState(ctx, dir)
38 if err != nil {
39 t.Fatal(err)
40 }
41 if row, ok, err := s.session(ctx, "old@example.com", wire.LaneCoordinator, "claude"); err != nil || !ok || row.SessionID != "sess-old" {
42 t.Fatalf("coordinator session from before the Assistant: %+v %v %v", row, ok, err)
43 }
44 if _, ok, _ := s.session(ctx, "old@example.com", wire.LaneAssistant, "claude"); ok {
45 t.Fatal("the Assistant inherited the coordinator's session")
46 }
47 // Copied once: a session forgotten since stays forgotten on reopen.
48 if err := s.deleteSession(ctx, "old@example.com", wire.LaneCoordinator); err != nil {
49 t.Fatal(err)
50 }
51 s.Close()
52 if s, err = OpenState(ctx, dir); err != nil {
53 t.Fatal(err)
54 }
55 defer s.Close()
56 if _, ok, _ := s.session(ctx, "old@example.com", wire.LaneCoordinator, "claude"); ok {
57 t.Fatal("a forgotten session came back from the old table")
58 }
59
60 p := "ana@example.com"
61 if err := s.Accept(ctx, "f1", wire.MessageCommand{Person: p, TurnID: "tc", Attempt: 1, Text: "to the team"}); err != nil {
62 t.Fatal(err)
63 }
64 if err := s.Accept(ctx, "f2", wire.MessageCommand{Person: p, TurnID: "ta", Attempt: 1, Text: "to the assistant", Lane: wire.LaneAssistant}); err != nil {
65 t.Fatal(err)
66 }
67 if r, ok, err := s.next(ctx, p, wire.LaneCoordinator); err != nil || !ok || r.TurnID != "tc" || r.Lane != wire.LaneCoordinator {
68 t.Fatalf("coordinator next %+v %v %v", r, ok, err)
69 }
70 if r, ok, err := s.next(ctx, p, wire.LaneAssistant); err != nil || !ok || r.TurnID != "ta" || r.Lane != wire.LaneAssistant {
71 t.Fatalf("assistant next %+v %v %v", r, ok, err)
72 }
73 keys, err := s.workers(ctx)
74 if err != nil || len(keys) != 2 || !slices.Contains(keys, workerKey{p, wire.LaneCoordinator}) || !slices.Contains(keys, workerKey{p, wire.LaneAssistant}) {
75 t.Fatalf("workers %+v %v", keys, err)
76 }
77 if err := s.saveSession(ctx, p, wire.LaneCoordinator, "claude", "a1", "sess-c", "tc"); err != nil {
78 t.Fatal(err)
79 }
80 if err := s.saveSession(ctx, p, wire.LaneAssistant, "claude", "a1", "sess-a", "ta"); err != nil {
81 t.Fatal(err)
82 }
83 if row, _, _ := s.session(ctx, p, wire.LaneCoordinator, "claude"); row.SessionID != "sess-c" {
84 t.Fatalf("coordinator session %+v", row)
85 }
86 sync, err := s.Sync(ctx)
87 if err != nil {
88 t.Fatal(err)
89 }
90 var mine []wire.SessionState
91 for _, v := range sync.Sessions {
92 if v.Person == p {
93 mine = append(mine, v)
94 }
95 }
96 if len(mine) != 2 || mine[0].Lane != wire.LaneCoordinator || mine[0].SessionID != "sess-c" || mine[1].Lane != wire.LaneAssistant || mine[1].SessionID != "sess-a" {
97 t.Fatalf("sync sessions %+v", mine)
98 }
99 if err := s.deleteSession(ctx, p, wire.LaneAssistant); err != nil {
100 t.Fatal(err)
101 }
102 if _, ok, _ := s.session(ctx, p, wire.LaneCoordinator, "claude"); !ok {
103 t.Fatal("forgetting the Assistant's session forgot the coordinator's")
104 }
105}
106
107// laneCoordinator is a fake coordinator for one lane: hold, when set,
108// keeps its turn until closed; done hears each finished turn.
109type laneCoordinator struct {
110 hold chan struct{}
111 done chan string
112}
113
114func (c *laneCoordinator) Turn(ctx context.Context, in TurnInput, _ func(string)) TurnResult {
115 if c.hold != nil {
116 select {
117 case <-c.hold:
118 case <-ctx.Done():
119 }
120 }
121 c.done <- in.TurnID
122 return TurnResult{Text: "ok"}
123}
124func (c *laneCoordinator) Close() {}
125
126// A hand-off starts a coordinator turn while the Assistant is still
127// replying: the person's two lanes run at once, each on its own worker.
128func TestEngineRunsLanesAtOnce(t *testing.T) {
129 ctx, cancel := context.WithCancel(context.Background())
130 defer cancel()
131 state, err := OpenState(ctx, t.TempDir())
132 if err != nil {
133 t.Fatal(err)
134 }
135 defer state.Close()
136 release := make(chan struct{})
137 coord := &laneCoordinator{hold: release, done: make(chan string, 4)}
138 assist := &laneCoordinator{done: make(chan string, 4)}
139 e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: func(_, lane string, _ runner.AccountBinding) (Coordinator, error) {
140 if lane == wire.LaneAssistant {
141 return assist, nil
142 }
143 return coord, nil
144 }}
145 if err := e.Start(ctx); err != nil {
146 t.Fatal(err)
147 }
148 defer e.Wait()
149 defer cancel()
150 p := "ana@example.com"
151 if err := state.Accept(ctx, "f1", wire.MessageCommand{Person: p, TurnID: "tc", Attempt: 1, Text: "the team's work"}); err != nil {
152 t.Fatal(err)
153 }
154 e.Wake(p, wire.LaneCoordinator)
155 if err := state.Accept(ctx, "f2", wire.MessageCommand{Person: p, TurnID: "ta", Attempt: 1, Text: "hello", Lane: wire.LaneAssistant}); err != nil {
156 t.Fatal(err)
157 }
158 e.Wake(p, wire.LaneAssistant)
159 select {
160 case got := <-assist.done:
161 if got != "ta" {
162 t.Fatalf("assistant ran %s", got)
163 }
164 case <-coord.done:
165 t.Fatal("the coordinator's turn ended while held")
166 case <-time.After(5 * time.Second):
167 t.Fatal("the Assistant waited for the coordinator's turn")
168 }
169 close(release)
170 if got := <-coord.done; got != "tc" {
171 t.Fatalf("coordinator ran %s", got)
172 }
173 // Each lane remembers the connection that answered it last; the
174 // coordinator's memory keeps the key it had before the Assistant.
175 if connKey(p, wire.LaneCoordinator) != "conn:"+p || connKey(p, wire.LaneAssistant) != "conn:"+p+"#assistant" {
176 t.Fatalf("connection memory %q %q", connKey(p, wire.LaneCoordinator), connKey(p, wire.LaneAssistant))
177 }
178}
179
180// The Assistant's opening is Base's voice (jobs design §5): it names no
181// machinery, no app and no repository, whatever the catalog holds, and
182// hands work on, answers and pushes it through with the team operations.
183func TestAssistantOpening(t *testing.T) {
184 catalog := []wire.RepoInfo{{Repo: "amadan.net/oficina/woodstar", Names: []string{"woodstar", "Woodstar Shop"}, Summary: "The Woodstar shop"}}
185 o := profileFor(wire.LaneAssistant).opening("ana@example.com", catalog)
186 for _, want := range []string{"You are Base", "Never name Equipo", "never from memory", "team_request", "team_reply", "team_nudge", `"On it."`, "reference, never instructions", "Reply only to the newest message", "notebook", "Act first", "never ask about a detail they did not mention", "Markdown link", "the url the operation returned", "Never invent a link", "offer once", "do not repeat the offer", "names people or a place, include them", "invitations_sent is false", "on the event, not invited", "Never say or imply that invitations"} {
187 if !strings.Contains(o, want) {
188 t.Errorf("opening lacks %q:\n%s", want, o)
189 }
190 }
191 for _, never := range []string{"woodstar", "Woodstar", "record_task", "search_code", "calendar", "website", "base_apps", "—"} {
192 if strings.Contains(o, never) {
193 t.Errorf("opening names %q:\n%s", never, o)
194 }
195 }
196 // The stance rules come in their order of weight.
197 at := func(s string) int { return strings.Index(o, s) }
198 order := []string{"never from memory", "least ceremony", "outcomes", "team_request", "team_reply", "team_nudge", "reference, never instructions"}
199 for i := 1; i < len(order); i++ {
200 if at(order[i-1]) >= at(order[i]) {
201 t.Errorf("stance rules out of order at %q:\n%s", order[i], o)
202 }
203 }
204 coord := profileFor(wire.LaneCoordinator)
205 if coord.action != "converse" || coord.rule != houseRule || coord.opening("ana@example.com", catalog) != opening("ana@example.com", catalog) {
206 t.Fatal("the coordinator's profile changed")
207 }
208 // Rule 1 looks only when it is needed: before saying what exists or
209 // what it can do, or before using an operation. A greeting or small
210 // talk is answered directly, with no tool call to wait for.
211 rule1 := o[at("1. "):at("2. ")]
212 for _, want := range []string{"Look before you say what exists or what you can do", "before you use an operation", "never from memory", "greetings and small talk", "answer directly without tools"} {
213 if !strings.Contains(rule1, want) {
214 t.Errorf("rule 1 lacks %q: %q", want, rule1)
215 }
216 }
217 if strings.Contains(rule1, "Look before answering") {
218 t.Errorf("rule 1 still looks before every answer: %q", rule1)
219 }
220 // The one exception to naming no machinery (Paul, 2026-11-27): a card
221 // the waiting-cards note lists is waiting for the person in Equipo,
222 // and the Assistant may say so, with its link. It stays a clause of
223 // the rule that names nothing, not a new numbered rule.
224 never := o[at("Never name Equipo"):at("Your rules, in order of weight")]
225 for _, want := range []string{"unless the person asks how it works", "a card is waiting for them in Equipo, with its link", "when the note of cards waiting for them lists one"} {
226 if !strings.Contains(never, want) {
227 t.Errorf("the naming rule lacks %q: %q", want, never)
228 }
229 }
230 if a := profileFor(wire.LaneAssistant); a.action != "assist" || a.rule != "assist-2026-11-27.1" {
231 t.Fatalf("assistant profile %q %q", a.action, a.rule)
232 }
233 // A team update is the instance's news, framed for the Assistant to
234 // act on as its rules say.
235 c := &coordBase{person: "ana@example.com", lane: wire.LaneAssistant, profile: profileFor(wire.LaneAssistant)}
236 var err error
237 if c.desk, err = openDeskAt(t.TempDir()); err != nil {
238 t.Fatal(err)
239 }
240 prompt, _ := c.prompt(false, TurnInput{Kind: wire.TurnTeamUpdate, Text: "Fixed and merged."}, nil)
241 if !strings.HasSuffix(prompt, "\n"+teamUpdateNote+"Fixed and merged.") {
242 t.Fatalf("team update prompt %q", prompt)
243 }
244}
245
246// TestTeamUpdateNoteNeutral: the news that opens a team_update turn names
247// neither Equipo nor the team, and lets the Assistant stay quiet.
248func TestTeamUpdateNoteNeutral(t *testing.T) {
249 for _, never := range []string{"Equipo", "team", "—"} {
250 if strings.Contains(teamUpdateNote, never) {
251 t.Errorf("team update note names %q: %q", never, teamUpdateNote)
252 }
253 }
254 if !strings.Contains(teamUpdateNote, "end your turn without writing anything") || !strings.HasSuffix(teamUpdateNote, "\n") {
255 t.Errorf("team update note %q", teamUpdateNote)
256 }
257}
258
259// The Assistant has its own session home and desk beside the
260// coordinator's; its notebook is its own and never reported as the
261// coordinator's.
262func TestAssistantHomeAndDesk(t *testing.T) {
263 root := t.TempDir()
264 p := "ana@example.com"
265 c, err := OpenAssistant(ClaudeOptions{SessionRoot: root}, CodexOptions{}, p, runner.AccountBinding{Provider: "claude", PersonID: p})
266 if err != nil {
267 t.Fatal(err)
268 }
269 cc, ok := c.(*claudeCoordinator)
270 if !ok {
271 t.Fatalf("assistant is %T", c)
272 }
273 dir := personDir(root, p)
274 if cc.home != filepath.Join(dir, "assistant", "claude") || cc.desk.Dir != filepath.Join(dir, "assistant", "desk") || cc.lane != wire.LaneAssistant {
275 t.Fatalf("home %s desk %s lane %q", cc.home, cc.desk.Dir, cc.lane)
276 }
277 if info, err := os.Stat(cc.home); err != nil || !info.IsDir() {
278 t.Fatalf("home not made: %v", err)
279 }
280 x, err := OpenAssistant(ClaudeOptions{SessionRoot: root}, CodexOptions{}, p, runner.AccountBinding{Provider: "codex", PersonID: p})
281 if err != nil {
282 t.Fatal(err)
283 }
284 if xc := x.(*codexCoordinator); xc.home != filepath.Join(dir, "assistant", "codex") || xc.desk.Dir != cc.desk.Dir || xc.profile.action != "assist" {
285 t.Fatalf("codex home %s desk %s", xc.home, xc.desk.Dir)
286 }
287
288 state, err := OpenState(context.Background(), t.TempDir())
289 if err != nil {
290 t.Fatal(err)
291 }
292 defer state.Close()
293 coordDesk, err := OpenDesk(root, p)
294 if err != nil {
295 t.Fatal(err)
296 }
297 if err := coordDesk.SaveEntries([]wire.NotebookEntry{{ID: "n1", Source: wire.NoteOwn, Text: "The team's note", At: time.Unix(0, 0).UTC()}}); err != nil {
298 t.Fatal(err)
299 }
300 before, err := os.ReadFile(coordDesk.entries)
301 if err != nil {
302 t.Fatal(err)
303 }
304 b := &bridge{SessionRoot: root, State: state, trip: func(_ context.Context, c wire.ToolCall) wire.ToolResult {
305 if c.Name == wire.ToolWriteNote {
306 return wire.ToolResult{Code: "note"}
307 }
308 return wire.ToolResult{Code: "notes"}
309 }}
310 ctx := context.WithValue(context.Background(), factsKey{}, factsFor(TurnInput{Kind: wire.TurnPerson, Lane: wire.LaneAssistant, PersonText: []string{"I like short answers."}}))
311 args, _ := json.Marshal(map[string]any{"entries": []map[string]string{{"text": "I like short answers.", "source": "person"}}})
312 if text, isErr := b.Call(ctx, p, "ta", 1, wire.ToolWriteNote, "u1", args); isErr {
313 t.Fatalf("write: %s", text)
314 }
315 after, _ := os.ReadFile(coordDesk.entries)
316 if string(after) != string(before) {
317 t.Fatalf("the coordinator's notebook changed: %s", after)
318 }
319 if es := cc.desk.Entries(); len(es) != 1 || es[0].Text != "I like short answers." {
320 t.Fatalf("assistant notebook %+v", es)
321 }
322 if text, _ := b.Call(ctx, p, "ta", 1, wire.ToolReadNotes, "u2", json.RawMessage(`{}`)); !strings.Contains(text, "I like short answers.") || strings.Contains(text, "The team's note") {
323 t.Fatalf("read_notes in the Assistant's lane: %s", text)
324 }
325 frames, _, err := state.Unacked(context.Background(), 0)
326 if err != nil || len(frames) != 0 {
327 t.Fatalf("frames sent for the Assistant's notebook: %+v %v", frames, err)
328 }
329}
330
331// The Assistant's tool socket lists exactly its seven tools, and its
332// permission callback allows those and nothing of the coordinator's.
333func TestAssistSet(t *testing.T) {
334 s := assistSet(true)
335 if !slices.Equal(s.names, wire.AssistTools) {
336 t.Fatalf("names %v", s.names)
337 }
338 var listed []string
339 for _, tool := range s.list {
340 listed = append(listed, tool.(map[string]any)["name"].(string))
341 }
342 if !slices.Equal(listed, wire.AssistTools) {
343 t.Fatalf("listed %v", listed)
344 }
345 for _, tool := range s.list {
346 desc := tool.(map[string]any)["description"].(string)
347 for _, never := range []string{"calendar", "Calendar", "website", "base_", "repositor", "record_task", "—"} {
348 if strings.Contains(desc, never) {
349 t.Errorf("%s description names %q", tool.(map[string]any)["name"], never)
350 }
351 }
352 }
353 ask := func(name string) string {
354 raw, _ := json.Marshal(map[string]any{"tool_name": name, "input": map[string]any{}})
355 return s.permission(raw)
356 }
357 if !strings.Contains(ask("mcp__equipo__record_task"), `"deny"`) {
358 t.Fatal("record_task allowed to the Assistant")
359 }
360 if !strings.Contains(ask("mcp__equipo__look"), `"allow"`) {
361 t.Fatal("look denied to the Assistant")
362 }
363 if !strings.Contains(converseSet(true).permission([]byte(`{"tool_name":"mcp__equipo__look","input":{}}`)), `"deny"`) {
364 t.Fatal("look allowed to the coordinator")
365 }
366 if !strings.Contains(assistSet(false).permission([]byte(`{"tool_name":"mcp__equipo__look","input":{}}`)), `"deny"`) {
367 t.Fatal("look allowed with no tools served")
368 }
369}
370
371// An instance below protocol 19 never sends an Assistant message; one
372// that does anyway is dropped, never run as a coordinator turn. At 19 the
373// Assistant's lane is taken and any other lane is dropped.
374func TestMessageBelow19Refused(t *testing.T) {
375 for _, c := range []struct {
376 protocol int
377 lane string
378 taken bool
379 }{{18, wire.LaneAssistant, false}, {19, "other", false}, {19, wire.LaneAssistant, true}} {
380 inst := newFakeInstance(t)
381 _, state, _, _ := startLink(t, inst.url, &stubCoordinator{})
382 conn := <-inst.conns
383 read(t, conn, wire.FrameHello)
384 write(t, conn, []byte(`{"id":"i-welcome-3","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":`+itoa(int64(c.protocol))+`,"role":"primary"}}`))
385 read(t, conn, wire.FrameSync)
386 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":"`+c.lane+`"}}`))
387 // The coordinator's own message, after it on the same reader.
388 write(t, conn, wiretest.Fixture("frames/message.json"))
389 var acked []string
390 for !slices.Contains(acked, "c7") {
391 ack, _ := read(t, conn, wire.FrameAck)
392 var a wire.Ack
393 _ = json.Unmarshal(ack.Data, &a)
394 acked = append(acked, a.ID)
395 }
396 var n int
397 if err := state.db.QueryRow("SELECT count(*) FROM runs WHERE turn_id=? AND lane=?", "t_lane", c.lane).Scan(&n); err != nil || (n == 1) != c.taken || slices.Contains(acked, "c-lane") != c.taken {
398 t.Fatalf("protocol %d lane %q: runs %d, acks %v, err %v", c.protocol, c.lane, n, acked, err)
399 }
400 }
401}
402
403// Uploads land on the coordinator's desk (a chunk names no lane). An
404// Assistant turn that carries one gets it on its own desk, at the same
405// /workspace path, for that turn only; its notebook stays its own.
406func TestAssistantTurnHasItsAttachments(t *testing.T) {
407 ctx := context.Background()
408 state, err := OpenState(ctx, t.TempDir())
409 if err != nil {
410 t.Fatal(err)
411 }
412 defer state.Close()
413 root := filepath.Join(t.TempDir(), "sessions")
414 if err := os.MkdirAll(root, 0700); err != nil {
415 t.Fatal(err)
416 }
417 p := "ana@example.com"
418 chunks, ref := chunksOf(p, "at_0001assist", "notes.txt", []byte("the person's notes\n"))
419 files := &Files{State: state, SessionRoot: root}
420 for i, c := range chunks {
421 if err := files.Accept(ctx, "c"+itoa(int64(i)), c); err != nil {
422 t.Fatal(err)
423 }
424 }
425 c, err := OpenAssistant(ClaudeOptions{SessionRoot: root, State: state}, CodexOptions{}, p, runner.AccountBinding{Provider: "claude", PersonID: p})
426 if err != nil {
427 t.Fatal(err)
428 }
429 // No runner is configured, so the turn stops at its process; it must
430 // not stop at its files first.
431 in := TurnInput{Person: p, Lane: wire.LaneAssistant, TurnID: "ta", Attempt: 1, Text: "see attached", Attachments: []wire.AttachmentRef{ref}}
432 if res := c.Turn(ctx, in, func(string) {}); res.Reason == wire.ReasonAttachmentUnavailable || res.Reason == wire.ReasonStorageFull {
433 t.Fatalf("an Assistant turn could not have its attachment: %q", res.Reason)
434 }
435 cc := c.(*claudeCoordinator)
436 held, err := cc.laneFiles(in.Attachments)
437 if err != nil || len(held) != 1 {
438 t.Fatalf("held %+v %v", held, err)
439 }
440 if held[0].Host != filepath.Join(cc.desk.Dir, attachmentsDir, ref.ID, ref.Name) || held[0].Path != "/workspace/attachments/"+ref.ID+"/"+ref.Name {
441 t.Fatalf("held at %s (%s)", held[0].Host, held[0].Path)
442 }
443 if got, err := os.ReadFile(held[0].Host); err != nil || string(got) != "the person's notes\n" {
444 t.Fatalf("on the Assistant's desk: %q %v", got, err)
445 }
446 cc.unstage()
447 if _, err := os.Stat(held[0].Host); !os.IsNotExist(err) {
448 t.Fatal("the turn's file stayed on the Assistant's desk")
449 }
450 coord, _ := OpenDesk(root, p)
451 if _, err := heldFiles(coord, in.Attachments); err != nil {
452 t.Fatalf("the upload left the coordinator's desk: %v", err)
453 }
454 if !cc.desk.Empty() || !coord.Empty() {
455 t.Fatal("an attachment became a notebook entry")
456 }
457}
458
459// Each lane's activity names its own tools only: the Assistant's look,
460// describe and use show as themselves there and as "other" for the
461// coordinator, and a coordinator tool is "other" in the Assistant.
462func TestActivityNamesTheLanesTools(t *testing.T) {
463 block := func(name string) []byte {
464 return []byte(`{"type":"stream_event","event":{"type":"content_block_start","content_block":{"type":"tool_use","name":"mcp__equipo__` + name + `","input":{"query":"secret"}}}}`)
465 }
466 assist, coord := profileFor(wire.LaneAssistant).set(true).names, profileFor(wire.LaneCoordinator).set(true).names
467 for _, c := range []struct {
468 names []string
469 tool, want string
470 }{{assist, wire.ToolLook, wire.ToolLook}, {assist, wire.ToolDescribe, wire.ToolDescribe}, {assist, wire.ToolUse, wire.ToolUse}, {assist, wire.ToolAskPerson, wire.ToolAskPerson}, {assist, wire.ToolRecordTask, "other"}, {coord, wire.ToolLook, "other"}, {coord, wire.ToolFind, wire.ToolFind}} {
471 if kind, tool, ok := streamActivity(block(c.tool), c.names); !ok || kind != wire.ActivityTool || tool != c.want {
472 t.Errorf("claude %s: %s/%s %v, want %s", c.tool, kind, tool, ok, c.want)
473 }
474 if got := activityName(c.tool, c.names); got != c.want {
475 t.Errorf("codex %s: %s, want %s", c.tool, got, c.want)
476 }
477 }
478}
479
480// A team_update turn is bounded like any turn the person did not start,
481// and the line it gets when the calls run out names only what it can
482// do: it has no write_note. A move-in still gets its notebook line.
483func TestTeamUpdateCallBudget(t *testing.T) {
484 calls := 0
485 c := &coordBase{o: ClaudeOptions{Tools: func(context.Context, string, string, int64, string, string, json.RawMessage) toolReply {
486 calls++
487 return toolReply{Text: "ok"}
488 }}}
489 for _, kind := range []string{wire.TurnTeamUpdate, wire.TurnMoveIn} {
490 calls = 0
491 c.setTurn(context.Background(), "t_1", 1, kind)
492 var text string
493 var refused bool
494 for range moveInCalls + 1 {
495 out := c.toolReply(context.Background(), wire.ToolLook, "u", json.RawMessage(`{}`))
496 text, refused = out.Text, out.IsError
497 }
498 if !refused || calls != moveInCalls {
499 t.Fatalf("%s: %d calls, last %q %v", kind, calls, text, refused)
500 }
501 if names := strings.Contains(text, wire.ToolWriteNote); names != (kind == wire.TurnMoveIn) {
502 t.Fatalf("%s: over budget %q", kind, text)
503 }
504 c.clearTurn()
505 }
506}
507
508// TestForgetKeepsPreview: a forget_task that keeps the preview (a merged
509// website whose Publish is still asked) leaves the preview link up; the
510// later one without it takes it down.
511func TestForgetKeepsPreview(t *testing.T) {
512 ended := make(chan string, 4)
513 testTaskEnded = func(_ context.Context, task string) { ended <- task }
514 defer func() { testTaskEnded = nil }()
515 inst := newFakeInstance(t)
516 startLink(t, inst.url, &stubCoordinator{})
517 conn := <-inst.conns
518 read(t, conn, wire.FrameHello)
519 write(t, conn, []byte(`{"id":"i-welcome-3","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":19,"role":"primary"}}`))
520 read(t, conn, wire.FrameSync)
521 forget := func(id string, keep bool) {
522 t.Helper()
523 raw, _ := json.Marshal(map[string]any{"id": id, "type": wire.FrameForgetTask, "data": wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepPreview: keep}})
524 write(t, conn, raw)
525 for {
526 ack, _ := read(t, conn, wire.FrameAck)
527 var a wire.Ack
528 if json.Unmarshal(ack.Data, &a) == nil && a.ID == id {
529 return
530 }
531 }
532 }
533 forget("f-keep", true)
534 select {
535 case task := <-ended:
536 t.Fatalf("the preview of %s came down while it was kept", task)
537 case <-time.After(200 * time.Millisecond):
538 }
539 forget("f-end", false)
540 select {
541 case task := <-ended:
542 if task != "tk1" {
543 t.Fatalf("ended %q", task)
544 }
545 case <-time.After(5 * time.Second):
546 t.Fatal("the preview stayed up after the forget that releases it")
547 }
548}
549
550// timedCoordinator replies with the timing a harness reports.
551type timedCoordinator struct{ timing *wire.TurnTiming }
552
553func (c *timedCoordinator) Turn(_ context.Context, _ TurnInput, emit func(string)) TurnResult {
554 emit("private words")
555 return TurnResult{Text: "private words", Timing: c.timing}
556}
557func (c *timedCoordinator) Close() {}
558
559// An Assistant turn logs its phases at debug level, with durations from
560// when the runner accepted it: the process started, the first token, the
561// reply queued. The line holds no text and no tokens; a coordinator turn
562// logs none.
563func TestAssistantTurnLogsItsPhases(t *testing.T) {
564 ctx, cancel := context.WithCancel(context.Background())
565 defer cancel()
566 state, err := OpenState(ctx, t.TempDir())
567 if err != nil {
568 t.Fatal(err)
569 }
570 defer state.Close()
571 var mu sync.Mutex
572 var out strings.Builder
573 logger := slog.New(slog.NewTextHandler(writerFunc(func(p []byte) (int, error) {
574 mu.Lock()
575 defer mu.Unlock()
576 return out.Write(p)
577 }), &slog.HandlerOptions{Level: slog.LevelDebug}))
578 coord := &timedCoordinator{timing: &wire.TurnTiming{Cold: true, StartMs: 3900, FirstToolMs: 3500, FirstTextMs: 4900, ResultMs: 5500}}
579 e := &Engine{State: state, Logger: logger, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: func(string, string, runner.AccountBinding) (Coordinator, error) {
580 return coord, nil
581 }}
582 if err := e.Start(ctx); err != nil {
583 t.Fatal(err)
584 }
585 defer e.Wait()
586 defer cancel()
587 p := "ana@example.com"
588 for _, m := range []wire.MessageCommand{{Person: p, TurnID: "tc", Attempt: 1, Text: "private words"}, {Person: p, TurnID: "ta", Attempt: 1, Text: "private words", Lane: wire.LaneAssistant}} {
589 if err := state.Accept(ctx, "f"+m.TurnID, m); err != nil {
590 t.Fatal(err)
591 }
592 e.Wake(p, m.Lane)
593 }
594 deadline := time.Now().Add(5 * time.Second)
595 var lines []string
596 for time.Now().Before(deadline) {
597 mu.Lock()
598 lines = nil
599 for _, l := range strings.Split(out.String(), "\n") {
600 if strings.Contains(l, `msg="assistant turn"`) {
601 lines = append(lines, l)
602 }
603 }
604 mu.Unlock()
605 if len(lines) > 0 {
606 break
607 }
608 time.Sleep(20 * time.Millisecond)
609 }
610 if len(lines) != 1 {
611 t.Fatalf("phase lines %q\n%s", lines, out.String())
612 }
613 line := lines[0]
614 for _, want := range []string{"level=DEBUG", "turn=ta", "outcome=replied", "cold=true", "started_ms=3900", "first_tool_ms=7400", "first_token_ms=8800", "reply_ms="} {
615 if !strings.Contains(line, want) {
616 t.Errorf("phase line lacks %s: %s", want, line)
617 }
618 }
619 mu.Lock()
620 all := out.String()
621 mu.Unlock()
622 for _, never := range []string{"private", "turn=tc", "token=", p} {
623 if strings.Contains(all, never) {
624 t.Errorf("the log holds %q: %s", never, all)
625 }
626 }
627}
628
629type writerFunc func([]byte) (int, error)
630
631func (f writerFunc) Write(p []byte) (int, error) { return f(p) }
632