package thin import ( "context" "database/sql" "encoding/json" "log/slog" "os" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/wiretest" ) // The two lanes of one person are two queues and two sessions: each // lane's next run is its own, and a session saved in one lane never // replaces the other's. A state file from before the Assistant keeps its // coordinator session, copied once. func TestStateKeepsLanesApart(t *testing.T) { ctx := context.Background() dir := t.TempDir() old, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "thin.db")) if err != nil { t.Fatal(err) } 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)); INSERT INTO sessions VALUES ('old@example.com', 'claude', 'acct#rule-x', 'sess-old', 't0', '2026-11-01T00:00:00Z');`); err != nil { t.Fatal(err) } old.Close() s, err := OpenState(ctx, dir) if err != nil { t.Fatal(err) } if row, ok, err := s.session(ctx, "old@example.com", wire.LaneCoordinator, "claude"); err != nil || !ok || row.SessionID != "sess-old" { t.Fatalf("coordinator session from before the Assistant: %+v %v %v", row, ok, err) } if _, ok, _ := s.session(ctx, "old@example.com", wire.LaneAssistant, "claude"); ok { t.Fatal("the Assistant inherited the coordinator's session") } // Copied once: a session forgotten since stays forgotten on reopen. if err := s.deleteSession(ctx, "old@example.com", wire.LaneCoordinator); err != nil { t.Fatal(err) } s.Close() if s, err = OpenState(ctx, dir); err != nil { t.Fatal(err) } defer s.Close() if _, ok, _ := s.session(ctx, "old@example.com", wire.LaneCoordinator, "claude"); ok { t.Fatal("a forgotten session came back from the old table") } p := "ana@example.com" if err := s.Accept(ctx, "f1", wire.MessageCommand{Person: p, TurnID: "tc", Attempt: 1, Text: "to the team"}); err != nil { t.Fatal(err) } if err := s.Accept(ctx, "f2", wire.MessageCommand{Person: p, TurnID: "ta", Attempt: 1, Text: "to the assistant", Lane: wire.LaneAssistant}); err != nil { t.Fatal(err) } if r, ok, err := s.next(ctx, p, wire.LaneCoordinator); err != nil || !ok || r.TurnID != "tc" || r.Lane != wire.LaneCoordinator { t.Fatalf("coordinator next %+v %v %v", r, ok, err) } if r, ok, err := s.next(ctx, p, wire.LaneAssistant); err != nil || !ok || r.TurnID != "ta" || r.Lane != wire.LaneAssistant { t.Fatalf("assistant next %+v %v %v", r, ok, err) } keys, err := s.workers(ctx) if err != nil || len(keys) != 2 || !slices.Contains(keys, workerKey{p, wire.LaneCoordinator}) || !slices.Contains(keys, workerKey{p, wire.LaneAssistant}) { t.Fatalf("workers %+v %v", keys, err) } if err := s.saveSession(ctx, p, wire.LaneCoordinator, "claude", "a1", "sess-c", "tc"); err != nil { t.Fatal(err) } if err := s.saveSession(ctx, p, wire.LaneAssistant, "claude", "a1", "sess-a", "ta"); err != nil { t.Fatal(err) } if row, _, _ := s.session(ctx, p, wire.LaneCoordinator, "claude"); row.SessionID != "sess-c" { t.Fatalf("coordinator session %+v", row) } sync, err := s.Sync(ctx) if err != nil { t.Fatal(err) } var mine []wire.SessionState for _, v := range sync.Sessions { if v.Person == p { mine = append(mine, v) } } if len(mine) != 2 || mine[0].Lane != wire.LaneCoordinator || mine[0].SessionID != "sess-c" || mine[1].Lane != wire.LaneAssistant || mine[1].SessionID != "sess-a" { t.Fatalf("sync sessions %+v", mine) } if err := s.deleteSession(ctx, p, wire.LaneAssistant); err != nil { t.Fatal(err) } if _, ok, _ := s.session(ctx, p, wire.LaneCoordinator, "claude"); !ok { t.Fatal("forgetting the Assistant's session forgot the coordinator's") } } // laneCoordinator is a fake coordinator for one lane: hold, when set, // keeps its turn until closed; done hears each finished turn. type laneCoordinator struct { hold chan struct{} done chan string } func (c *laneCoordinator) Turn(ctx context.Context, in TurnInput, _ func(string)) TurnResult { if c.hold != nil { select { case <-c.hold: case <-ctx.Done(): } } c.done <- in.TurnID return TurnResult{Text: "ok"} } func (c *laneCoordinator) Close() {} // A hand-off starts a coordinator turn while the Assistant is still // replying: the person's two lanes run at once, each on its own worker. func TestEngineRunsLanesAtOnce(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() release := make(chan struct{}) coord := &laneCoordinator{hold: release, done: make(chan string, 4)} assist := &laneCoordinator{done: make(chan string, 4)} e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: func(_, lane string, _ runner.AccountBinding) (Coordinator, error) { if lane == wire.LaneAssistant { return assist, nil } return coord, nil }} if err := e.Start(ctx); err != nil { t.Fatal(err) } defer e.Wait() defer cancel() p := "ana@example.com" if err := state.Accept(ctx, "f1", wire.MessageCommand{Person: p, TurnID: "tc", Attempt: 1, Text: "the team's work"}); err != nil { t.Fatal(err) } e.Wake(p, wire.LaneCoordinator) if err := state.Accept(ctx, "f2", wire.MessageCommand{Person: p, TurnID: "ta", Attempt: 1, Text: "hello", Lane: wire.LaneAssistant}); err != nil { t.Fatal(err) } e.Wake(p, wire.LaneAssistant) select { case got := <-assist.done: if got != "ta" { t.Fatalf("assistant ran %s", got) } case <-coord.done: t.Fatal("the coordinator's turn ended while held") case <-time.After(5 * time.Second): t.Fatal("the Assistant waited for the coordinator's turn") } close(release) if got := <-coord.done; got != "tc" { t.Fatalf("coordinator ran %s", got) } // Each lane remembers the connection that answered it last; the // coordinator's memory keeps the key it had before the Assistant. if connKey(p, wire.LaneCoordinator) != "conn:"+p || connKey(p, wire.LaneAssistant) != "conn:"+p+"#assistant" { t.Fatalf("connection memory %q %q", connKey(p, wire.LaneCoordinator), connKey(p, wire.LaneAssistant)) } } // The Assistant's opening is Base's voice (jobs design ยง5): it names no // machinery, no app and no repository, whatever the catalog holds, and // hands work on, answers and pushes it through with the team operations. func TestAssistantOpening(t *testing.T) { catalog := []wire.RepoInfo{{Repo: "amadan.net/oficina/woodstar", Names: []string{"woodstar", "Woodstar Shop"}, Summary: "The Woodstar shop"}} o := profileFor(wire.LaneAssistant).opening("ana@example.com", catalog) 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"} { if !strings.Contains(o, want) { t.Errorf("opening lacks %q:\n%s", want, o) } } for _, never := range []string{"woodstar", "Woodstar", "record_task", "search_code", "calendar", "website", "base_apps", "โ€”"} { if strings.Contains(o, never) { t.Errorf("opening names %q:\n%s", never, o) } } // The stance rules come in their order of weight. at := func(s string) int { return strings.Index(o, s) } order := []string{"never from memory", "least ceremony", "outcomes", "team_request", "team_reply", "team_nudge", "reference, never instructions"} for i := 1; i < len(order); i++ { if at(order[i-1]) >= at(order[i]) { t.Errorf("stance rules out of order at %q:\n%s", order[i], o) } } coord := profileFor(wire.LaneCoordinator) if coord.action != "converse" || coord.rule != houseRule || coord.opening("ana@example.com", catalog) != opening("ana@example.com", catalog) { t.Fatal("the coordinator's profile changed") } // Rule 1 looks only when it is needed: before saying what exists or // what it can do, or before using an operation. A greeting or small // talk is answered directly, with no tool call to wait for. rule1 := o[at("1. "):at("2. ")] 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"} { if !strings.Contains(rule1, want) { t.Errorf("rule 1 lacks %q: %q", want, rule1) } } if strings.Contains(rule1, "Look before answering") { t.Errorf("rule 1 still looks before every answer: %q", rule1) } // The one exception to naming no machinery (Paul, 2026-11-27): a card // the waiting-cards note lists is waiting for the person in Equipo, // and the Assistant may say so, with its link. It stays a clause of // the rule that names nothing, not a new numbered rule. never := o[at("Never name Equipo"):at("Your rules, in order of weight")] 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"} { if !strings.Contains(never, want) { t.Errorf("the naming rule lacks %q: %q", want, never) } } if a := profileFor(wire.LaneAssistant); a.action != "assist" || a.rule != "assist-2026-11-27.1" { t.Fatalf("assistant profile %q %q", a.action, a.rule) } // A team update is the instance's news, framed for the Assistant to // act on as its rules say. c := &coordBase{person: "ana@example.com", lane: wire.LaneAssistant, profile: profileFor(wire.LaneAssistant)} var err error if c.desk, err = openDeskAt(t.TempDir()); err != nil { t.Fatal(err) } prompt, _ := c.prompt(false, TurnInput{Kind: wire.TurnTeamUpdate, Text: "Fixed and merged."}, nil) if !strings.HasSuffix(prompt, "\n"+teamUpdateNote+"Fixed and merged.") { t.Fatalf("team update prompt %q", prompt) } } // TestTeamUpdateNoteNeutral: the news that opens a team_update turn names // neither Equipo nor the team, and lets the Assistant stay quiet. func TestTeamUpdateNoteNeutral(t *testing.T) { for _, never := range []string{"Equipo", "team", "โ€”"} { if strings.Contains(teamUpdateNote, never) { t.Errorf("team update note names %q: %q", never, teamUpdateNote) } } if !strings.Contains(teamUpdateNote, "end your turn without writing anything") || !strings.HasSuffix(teamUpdateNote, "\n") { t.Errorf("team update note %q", teamUpdateNote) } } // The Assistant has its own session home and desk beside the // coordinator's; its notebook is its own and never reported as the // coordinator's. func TestAssistantHomeAndDesk(t *testing.T) { root := t.TempDir() p := "ana@example.com" c, err := OpenAssistant(ClaudeOptions{SessionRoot: root}, CodexOptions{}, p, runner.AccountBinding{Provider: "claude", PersonID: p}) if err != nil { t.Fatal(err) } cc, ok := c.(*claudeCoordinator) if !ok { t.Fatalf("assistant is %T", c) } dir := personDir(root, p) if cc.home != filepath.Join(dir, "assistant", "claude") || cc.desk.Dir != filepath.Join(dir, "assistant", "desk") || cc.lane != wire.LaneAssistant { t.Fatalf("home %s desk %s lane %q", cc.home, cc.desk.Dir, cc.lane) } if info, err := os.Stat(cc.home); err != nil || !info.IsDir() { t.Fatalf("home not made: %v", err) } x, err := OpenAssistant(ClaudeOptions{SessionRoot: root}, CodexOptions{}, p, runner.AccountBinding{Provider: "codex", PersonID: p}) if err != nil { t.Fatal(err) } if xc := x.(*codexCoordinator); xc.home != filepath.Join(dir, "assistant", "codex") || xc.desk.Dir != cc.desk.Dir || xc.profile.action != "assist" { t.Fatalf("codex home %s desk %s", xc.home, xc.desk.Dir) } state, err := OpenState(context.Background(), t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() coordDesk, err := OpenDesk(root, p) if err != nil { t.Fatal(err) } if err := coordDesk.SaveEntries([]wire.NotebookEntry{{ID: "n1", Source: wire.NoteOwn, Text: "The team's note", At: time.Unix(0, 0).UTC()}}); err != nil { t.Fatal(err) } before, err := os.ReadFile(coordDesk.entries) if err != nil { t.Fatal(err) } b := &bridge{SessionRoot: root, State: state, trip: func(_ context.Context, c wire.ToolCall) wire.ToolResult { if c.Name == wire.ToolWriteNote { return wire.ToolResult{Code: "note"} } return wire.ToolResult{Code: "notes"} }} ctx := context.WithValue(context.Background(), factsKey{}, factsFor(TurnInput{Kind: wire.TurnPerson, Lane: wire.LaneAssistant, PersonText: []string{"I like short answers."}})) args, _ := json.Marshal(map[string]any{"entries": []map[string]string{{"text": "I like short answers.", "source": "person"}}}) if text, isErr := b.Call(ctx, p, "ta", 1, wire.ToolWriteNote, "u1", args); isErr { t.Fatalf("write: %s", text) } after, _ := os.ReadFile(coordDesk.entries) if string(after) != string(before) { t.Fatalf("the coordinator's notebook changed: %s", after) } if es := cc.desk.Entries(); len(es) != 1 || es[0].Text != "I like short answers." { t.Fatalf("assistant notebook %+v", es) } 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") { t.Fatalf("read_notes in the Assistant's lane: %s", text) } frames, _, err := state.Unacked(context.Background(), 0) if err != nil || len(frames) != 0 { t.Fatalf("frames sent for the Assistant's notebook: %+v %v", frames, err) } } // The Assistant's tool socket lists exactly its seven tools, and its // permission callback allows those and nothing of the coordinator's. func TestAssistSet(t *testing.T) { s := assistSet(true) if !slices.Equal(s.names, wire.AssistTools) { t.Fatalf("names %v", s.names) } var listed []string for _, tool := range s.list { listed = append(listed, tool.(map[string]any)["name"].(string)) } if !slices.Equal(listed, wire.AssistTools) { t.Fatalf("listed %v", listed) } for _, tool := range s.list { desc := tool.(map[string]any)["description"].(string) for _, never := range []string{"calendar", "Calendar", "website", "base_", "repositor", "record_task", "โ€”"} { if strings.Contains(desc, never) { t.Errorf("%s description names %q", tool.(map[string]any)["name"], never) } } } ask := func(name string) string { raw, _ := json.Marshal(map[string]any{"tool_name": name, "input": map[string]any{}}) return s.permission(raw) } if !strings.Contains(ask("mcp__equipo__record_task"), `"deny"`) { t.Fatal("record_task allowed to the Assistant") } if !strings.Contains(ask("mcp__equipo__look"), `"allow"`) { t.Fatal("look denied to the Assistant") } if !strings.Contains(converseSet(true).permission([]byte(`{"tool_name":"mcp__equipo__look","input":{}}`)), `"deny"`) { t.Fatal("look allowed to the coordinator") } if !strings.Contains(assistSet(false).permission([]byte(`{"tool_name":"mcp__equipo__look","input":{}}`)), `"deny"`) { t.Fatal("look allowed with no tools served") } } // An instance below protocol 19 never sends an Assistant message; one // that does anyway is dropped, never run as a coordinator turn. At 19 the // Assistant's lane is taken and any other lane is dropped. func TestMessageBelow19Refused(t *testing.T) { for _, c := range []struct { protocol int lane string taken bool }{{18, wire.LaneAssistant, false}, {19, "other", false}, {19, wire.LaneAssistant, true}} { inst := newFakeInstance(t) _, state, _, _ := startLink(t, inst.url, &stubCoordinator{}) conn := <-inst.conns read(t, conn, wire.FrameHello) write(t, conn, []byte(`{"id":"i-welcome-3","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":`+itoa(int64(c.protocol))+`,"role":"primary"}}`)) read(t, conn, wire.FrameSync) 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+`"}}`)) // The coordinator's own message, after it on the same reader. write(t, conn, wiretest.Fixture("frames/message.json")) var acked []string for !slices.Contains(acked, "c7") { ack, _ := read(t, conn, wire.FrameAck) var a wire.Ack _ = json.Unmarshal(ack.Data, &a) acked = append(acked, a.ID) } var n int 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 { t.Fatalf("protocol %d lane %q: runs %d, acks %v, err %v", c.protocol, c.lane, n, acked, err) } } } // Uploads land on the coordinator's desk (a chunk names no lane). An // Assistant turn that carries one gets it on its own desk, at the same // /workspace path, for that turn only; its notebook stays its own. func TestAssistantTurnHasItsAttachments(t *testing.T) { ctx := context.Background() state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() root := filepath.Join(t.TempDir(), "sessions") if err := os.MkdirAll(root, 0700); err != nil { t.Fatal(err) } p := "ana@example.com" chunks, ref := chunksOf(p, "at_0001assist", "notes.txt", []byte("the person's notes\n")) files := &Files{State: state, SessionRoot: root} for i, c := range chunks { if err := files.Accept(ctx, "c"+itoa(int64(i)), c); err != nil { t.Fatal(err) } } c, err := OpenAssistant(ClaudeOptions{SessionRoot: root, State: state}, CodexOptions{}, p, runner.AccountBinding{Provider: "claude", PersonID: p}) if err != nil { t.Fatal(err) } // No runner is configured, so the turn stops at its process; it must // not stop at its files first. in := TurnInput{Person: p, Lane: wire.LaneAssistant, TurnID: "ta", Attempt: 1, Text: "see attached", Attachments: []wire.AttachmentRef{ref}} if res := c.Turn(ctx, in, func(string) {}); res.Reason == wire.ReasonAttachmentUnavailable || res.Reason == wire.ReasonStorageFull { t.Fatalf("an Assistant turn could not have its attachment: %q", res.Reason) } cc := c.(*claudeCoordinator) held, err := cc.laneFiles(in.Attachments) if err != nil || len(held) != 1 { t.Fatalf("held %+v %v", held, err) } if held[0].Host != filepath.Join(cc.desk.Dir, attachmentsDir, ref.ID, ref.Name) || held[0].Path != "/workspace/attachments/"+ref.ID+"/"+ref.Name { t.Fatalf("held at %s (%s)", held[0].Host, held[0].Path) } if got, err := os.ReadFile(held[0].Host); err != nil || string(got) != "the person's notes\n" { t.Fatalf("on the Assistant's desk: %q %v", got, err) } cc.unstage() if _, err := os.Stat(held[0].Host); !os.IsNotExist(err) { t.Fatal("the turn's file stayed on the Assistant's desk") } coord, _ := OpenDesk(root, p) if _, err := heldFiles(coord, in.Attachments); err != nil { t.Fatalf("the upload left the coordinator's desk: %v", err) } if !cc.desk.Empty() || !coord.Empty() { t.Fatal("an attachment became a notebook entry") } } // Each lane's activity names its own tools only: the Assistant's look, // describe and use show as themselves there and as "other" for the // coordinator, and a coordinator tool is "other" in the Assistant. func TestActivityNamesTheLanesTools(t *testing.T) { block := func(name string) []byte { return []byte(`{"type":"stream_event","event":{"type":"content_block_start","content_block":{"type":"tool_use","name":"mcp__equipo__` + name + `","input":{"query":"secret"}}}}`) } assist, coord := profileFor(wire.LaneAssistant).set(true).names, profileFor(wire.LaneCoordinator).set(true).names for _, c := range []struct { names []string tool, want string }{{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}} { if kind, tool, ok := streamActivity(block(c.tool), c.names); !ok || kind != wire.ActivityTool || tool != c.want { t.Errorf("claude %s: %s/%s %v, want %s", c.tool, kind, tool, ok, c.want) } if got := activityName(c.tool, c.names); got != c.want { t.Errorf("codex %s: %s, want %s", c.tool, got, c.want) } } } // A team_update turn is bounded like any turn the person did not start, // and the line it gets when the calls run out names only what it can // do: it has no write_note. A move-in still gets its notebook line. func TestTeamUpdateCallBudget(t *testing.T) { calls := 0 c := &coordBase{o: ClaudeOptions{Tools: func(context.Context, string, string, int64, string, string, json.RawMessage) toolReply { calls++ return toolReply{Text: "ok"} }}} for _, kind := range []string{wire.TurnTeamUpdate, wire.TurnMoveIn} { calls = 0 c.setTurn(context.Background(), "t_1", 1, kind) var text string var refused bool for range moveInCalls + 1 { out := c.toolReply(context.Background(), wire.ToolLook, "u", json.RawMessage(`{}`)) text, refused = out.Text, out.IsError } if !refused || calls != moveInCalls { t.Fatalf("%s: %d calls, last %q %v", kind, calls, text, refused) } if names := strings.Contains(text, wire.ToolWriteNote); names != (kind == wire.TurnMoveIn) { t.Fatalf("%s: over budget %q", kind, text) } c.clearTurn() } } // TestForgetKeepsPreview: a forget_task that keeps the preview (a merged // website whose Publish is still asked) leaves the preview link up; the // later one without it takes it down. func TestForgetKeepsPreview(t *testing.T) { ended := make(chan string, 4) testTaskEnded = func(_ context.Context, task string) { ended <- task } defer func() { testTaskEnded = nil }() inst := newFakeInstance(t) startLink(t, inst.url, &stubCoordinator{}) conn := <-inst.conns read(t, conn, wire.FrameHello) write(t, conn, []byte(`{"id":"i-welcome-3","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":19,"role":"primary"}}`)) read(t, conn, wire.FrameSync) forget := func(id string, keep bool) { t.Helper() raw, _ := json.Marshal(map[string]any{"id": id, "type": wire.FrameForgetTask, "data": wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepPreview: keep}}) write(t, conn, raw) for { ack, _ := read(t, conn, wire.FrameAck) var a wire.Ack if json.Unmarshal(ack.Data, &a) == nil && a.ID == id { return } } } forget("f-keep", true) select { case task := <-ended: t.Fatalf("the preview of %s came down while it was kept", task) case <-time.After(200 * time.Millisecond): } forget("f-end", false) select { case task := <-ended: if task != "tk1" { t.Fatalf("ended %q", task) } case <-time.After(5 * time.Second): t.Fatal("the preview stayed up after the forget that releases it") } } // timedCoordinator replies with the timing a harness reports. type timedCoordinator struct{ timing *wire.TurnTiming } func (c *timedCoordinator) Turn(_ context.Context, _ TurnInput, emit func(string)) TurnResult { emit("private words") return TurnResult{Text: "private words", Timing: c.timing} } func (c *timedCoordinator) Close() {} // An Assistant turn logs its phases at debug level, with durations from // when the runner accepted it: the process started, the first token, the // reply queued. The line holds no text and no tokens; a coordinator turn // logs none. func TestAssistantTurnLogsItsPhases(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() var mu sync.Mutex var out strings.Builder logger := slog.New(slog.NewTextHandler(writerFunc(func(p []byte) (int, error) { mu.Lock() defer mu.Unlock() return out.Write(p) }), &slog.HandlerOptions{Level: slog.LevelDebug})) coord := &timedCoordinator{timing: &wire.TurnTiming{Cold: true, StartMs: 3900, FirstToolMs: 3500, FirstTextMs: 4900, ResultMs: 5500}} e := &Engine{State: state, Logger: logger, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: func(string, string, runner.AccountBinding) (Coordinator, error) { return coord, nil }} if err := e.Start(ctx); err != nil { t.Fatal(err) } defer e.Wait() defer cancel() p := "ana@example.com" 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}} { if err := state.Accept(ctx, "f"+m.TurnID, m); err != nil { t.Fatal(err) } e.Wake(p, m.Lane) } deadline := time.Now().Add(5 * time.Second) var lines []string for time.Now().Before(deadline) { mu.Lock() lines = nil for _, l := range strings.Split(out.String(), "\n") { if strings.Contains(l, `msg="assistant turn"`) { lines = append(lines, l) } } mu.Unlock() if len(lines) > 0 { break } time.Sleep(20 * time.Millisecond) } if len(lines) != 1 { t.Fatalf("phase lines %q\n%s", lines, out.String()) } line := lines[0] 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="} { if !strings.Contains(line, want) { t.Errorf("phase line lacks %s: %s", want, line) } } mu.Lock() all := out.String() mu.Unlock() for _, never := range []string{"private", "turn=tc", "token=", p} { if strings.Contains(all, never) { t.Errorf("the log holds %q: %s", never, all) } } } type writerFunc func([]byte) (int, error) func (f writerFunc) Write(p []byte) (int, error) { return f(p) }