package thintest import ( "context" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/specialist" "amadan.net/oficina/equipo/internal/wire" ) // Specialists as data (Research spec ยง6, slice R0): the coordinator // proposes Research from the closed menu, one card asks an owner, and // only an owner's Add, in one transaction, makes it active with its // grant and audit rows. // researchArgs is a proposal of the research-v1 profile exactly. func researchArgs() map[string]any { return map[string]any{"profile": specialist.ProfileResearch, "name": "Research", "brief": "Look up the shop's public pages for its colours, logo and opening hours.", "capabilities": []string{specialist.CapabilityWebResearch}, "tools": []string{specialist.ToolSubmitFindings, specialist.ToolKeepImage}} } // specialistCard waits for the person's specialist card in state. func (r *toolRig) specialistCard(state string) wire.Card { r.t.Helper() var card wire.Card r.wait("specialist card "+state, func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardSpecialist && k.State == state { card = k return true } } return false }) return card } func (r *toolRig) rows(q string, args ...any) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow(q, args...).Scan(&n); err != nil { r.t.Fatal(err) } return n } func (r *toolRig) specialistCards() int { r.t.Helper() snap, err := r.client.Snapshot(r.ctx) if err != nil { r.t.Fatal(err) } n := 0 for _, c := range snap.Cards { if c.Kind == wire.CardSpecialist { n++ } } return n } // TestSpecialistProposeAndAdd: propose -> one card with the profile's // capability in plain words and the brief, answers Add and Not now; a // replayed call returns the stored result; a second open proposal is // refused; Add makes it active with one grant at its revision and the // audit rows; then the profile answers already approved. func TestSpecialistProposeAndAdd(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) res := r.call("p1", wire.ToolProposeSpecialist, researchArgs()) if res.IsError || res.Code != "proposed" || res.Text == "" { t.Fatalf("propose: %+v", res) } card := r.specialistCard(wire.CardOpen) if !slices.Equal(card.Options, []string{wire.ChoiceAdd, wire.ChoiceNotNow}) || card.Question == "" || card.Name != "Research" || card.TurnID != r.turn { t.Fatalf("card %+v", card) } s := card.Specialist if s == nil || s.Profile != specialist.ProfileResearch || s.State != wire.SpecialistProposed || !strings.Contains(s.Brief, "opening hours") || len(s.Capabilities) != 1 || s.Capabilities[0].ID != specialist.CapabilityWebResearch || s.Capabilities[0].Words == "" || strings.Contains(s.Capabilities[0].Words, "chat.") { t.Fatalf("card's specialist %+v", s) } // The same call id again: the stored result, and nothing new. if again := r.call("p1", wire.ToolProposeSpecialist, researchArgs()); again != res { t.Fatalf("replay %+v vs %+v", again, res) } // Another proposal while one is open is refused. if second := r.call("p2", wire.ToolProposeSpecialist, researchArgs()); !second.IsError || second.Code != "already_proposed" { t.Fatalf("second proposal %+v", second) } if n := r.specialistCards(); n != 1 || r.rows("SELECT count(*) FROM chat_specialists") != 1 { t.Fatalf("%d cards", n) } if r.rows("SELECT count(*) FROM chat_capability_grants") != 0 { t.Fatal("granted before Add") } // The conversation page shows it as simply as the direction card: // the question, the capability in words, the brief, Add and Not now. page := r.get(r.inst.SessionFor(t, Owner), "/conversation", 200) for _, want := range []string{`equipo-card="specialist"`, card.Question, s.Capabilities[0].Words, "opening hours", `data-specialist-choice="add"`, `data-specialist-choice="not_now"`, ">Add<", ">Not now<"} { if !strings.Contains(page, want) { t.Fatalf("the open card lacks %q", want) } } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil { t.Fatal(err) } done := r.specialistCard(wire.CardAnswered) if done.Choice != wire.ChoiceAdd || done.Specialist.State != wire.SpecialistActive { t.Fatalf("answered %+v", done) } list, err := r.client.Specialists(r.ctx) if err != nil || len(list.Items) != 1 { t.Fatalf("list %+v %v", list, err) } sp := list.Items[0] if sp.State != wire.SpecialistActive || sp.Approver != Owner || sp.ApprovedAt == nil || sp.ProposedBy != Owner || !slices.Equal(sp.Capabilities, []string{specialist.CapabilityWebResearch}) || !slices.Equal(sp.Tools, []string{specialist.ToolSubmitFindings, specialist.ToolKeepImage}) || sp.ID != s.ID { t.Fatalf("specialist %+v", sp) } if n := r.rows("SELECT count(*) FROM chat_capability_grants WHERE specialist_id = ? AND capability = ? AND revision = ? AND granted_by = ? AND revoked_at IS NULL", sp.ID, specialist.CapabilityWebResearch, sp.Revision, Owner); n != 1 || r.rows("SELECT count(*) FROM chat_capability_grants") != 1 { t.Fatalf("%d grants", n) } if n := r.rows("SELECT count(*) FROM chat_specialist_audit WHERE specialist_id = ? AND action = 'approved' AND actor = ? AND revision = ?", sp.ID, Owner, sp.Revision); n != 1 { t.Fatalf("%d approval audit rows", n) } if n := r.rows("SELECT count(*) FROM chat_specialist_audit WHERE specialist_id = ? AND action = 'proposed'", sp.ID); n != 1 { t.Fatalf("%d proposal audit rows", n) } // Answered: a replay is a conflict, and the profile is approved. if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 409 { t.Fatalf("replayed answer: %v", err) } if third := r.call("p3", wire.ToolProposeSpecialist, researchArgs()); !third.IsError || third.Code != "already_active" { t.Fatalf("after Add %+v", third) } // Answered, the card says so and offers nothing. if page := r.get(r.inst.SessionFor(t, Owner), "/conversation", 200); !strings.Contains(page, "Added to your team.") || strings.Contains(page, `data-specialist-choice`) { t.Fatal("the answered card") } } // TestSpecialistProposalRefused: anything that is not exactly the // research-v1 profile is refused before any card or row. func TestSpecialistProposalRefused(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) for name, c := range map[string]struct { edit func(map[string]any) code string }{ "an extra capability": {func(a map[string]any) { a["capabilities"] = []string{"web.research", "repo.read"} }, "exclusive"}, "another capability": {func(a map[string]any) { a["capabilities"] = []string{"attachments.read"} }, "not_on_menu"}, "an extra tool": {func(a map[string]any) { a["tools"] = []string{"submit_findings", "keep_image", "start_task"} }, "exclusive"}, "a missing tool": {func(a map[string]any) { a["tools"] = []string{"submit_findings"} }, "not_on_menu"}, "an unknown profile": {func(a map[string]any) { a["profile"] = "release-v1" }, "unknown_profile"}, "an over-long brief": {func(a map[string]any) { a["brief"] = strings.Repeat("b", specialist.MaxBrief+1) }, "brief"}, "a built-in's name": {func(a map[string]any) { a["name"] = "Engineering" }, "name"}, "an unknown field": {func(a map[string]any) { a["model"] = "gpt-6-astra" }, "invalid"}, "no tools at all": {func(a map[string]any) { delete(a, "tools") }, "not_on_menu"}, "capabilities a string": {func(a map[string]any) { a["capabilities"] = "web.research" }, "invalid"}, } { args := researchArgs() c.edit(args) res := r.call("x-"+strings.ReplaceAll(name, " ", "-"), wire.ToolProposeSpecialist, args) if !res.IsError || res.Code != c.code || res.Text == "" { t.Errorf("%s: %+v", name, res) } } if r.specialistCards() != 0 || r.rows("SELECT count(*) FROM chat_specialists") != 0 || r.rows("SELECT count(*) FROM chat_specialist_audit") != 0 { t.Fatal("a refused proposal left something") } } // TestSpecialistNotNow: Not now declines it with an audit row and no // grant; the coordinator cannot propose that profile and scope again for // 7 days (spec 2026-11-28-dynamic-specialists.md, section 4). func TestSpecialistNotNow(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.call("n1", wire.ToolProposeSpecialist, researchArgs()) card := r.specialistCard(wire.CardOpen) if _, err := r.client.Answer(r.ctx, card.ID, "maybe", card.Revision); Status(err) != 422 { t.Fatalf("another answer: %v", err) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceNotNow, card.Revision); err != nil { t.Fatal(err) } done := r.specialistCard(wire.CardAnswered) if done.Choice != wire.ChoiceNotNow || done.Specialist.State != wire.SpecialistDeclined { t.Fatalf("answered %+v", done) } if r.rows("SELECT count(*) FROM chat_capability_grants") != 0 || r.rows("SELECT count(*) FROM chat_specialist_audit WHERE action = 'declined' AND actor = ?", Owner) != 1 { t.Fatal("Not now granted, or was not audited") } if res := r.call("n2", wire.ToolProposeSpecialist, researchArgs()); !res.IsError || res.Code != "declined_recently" { t.Fatalf("proposed again within 7 days %+v", res) } } // TestSpecialistAnswerAuthority: a stale revision is a conflict; only the // card's person answers it (another member's answer finds nothing), and // only while they are still an owner, checked in the answer's // transaction. Nothing is granted. func TestSpecialistAnswerAuthority(t *testing.T) { a := newToolRigAt(t, wire.ProtocolCurrent) ctx := a.ctx b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) m := personToolRig(t, a, "member@example.com", equipo.RoleMember) if res := b.call("b1", wire.ToolProposeSpecialist, researchArgs()); res.IsError { t.Fatalf("B's proposal %+v", res) } card := b.specialistCard(wire.CardOpen) for _, rev := range []int64{card.Revision + 1, card.Revision - 1} { if _, err := b.client.Answer(ctx, card.ID, wire.ChoiceAdd, rev); Status(err) != 409 { t.Fatalf("revision %d: %v", rev, err) } } // Someone else's card: not theirs to answer. for _, other := range []*toolRig{a, m} { if _, err := other.client.Answer(ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 404 { t.Fatalf("another person answered: %v", err) } } // B is made a teammate: their own card no longer takes their Add. var revision int64 if err := a.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", "second@example.com").Scan(&revision); err != nil { t.Fatal(err) } if err := a.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleMember, true, revision); err != nil { t.Fatal(err) } if _, err := b.client.Answer(ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 403 { t.Fatalf("a teammate added it: %v", err) } if a.rows("SELECT count(*) FROM chat_capability_grants") != 0 || a.rows("SELECT count(*) FROM chat_specialists WHERE state = ?", wire.SpecialistProposed) != 1 { t.Fatal("granted without an owner") } } // TestSpecialistRevoke: only an owner revokes, at the current revision; // the grant is revoked with an audit row, and the profile may be // proposed again. func TestSpecialistRevoke(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) m := personToolRig(t, r, "member@example.com", equipo.RoleMember) r.call("r1", wire.ToolProposeSpecialist, researchArgs()) card := r.specialistCard(wire.CardOpen) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil { t.Fatal(err) } list, _ := m.client.Specialists(r.ctx) if len(list.Items) != 1 || list.Items[0].State != wire.SpecialistActive { t.Fatalf("a teammate reads %+v", list) } sp := list.Items[0] if _, err := m.client.RevokeSpecialist(r.ctx, sp.ID, sp.Revision); Status(err) != 403 { t.Fatalf("a teammate revoked: %v", err) } if _, err := r.client.RevokeSpecialist(r.ctx, sp.ID, sp.Revision-1); Status(err) != 409 { t.Fatalf("a stale revoke: %v", err) } if _, err := r.client.RevokeSpecialist(r.ctx, "sp_nothing", sp.Revision); Status(err) != 404 { t.Fatalf("no such specialist: %v", err) } if r.rows("SELECT count(*) FROM chat_capability_grants WHERE revoked_at IS NULL") != 1 { t.Fatal("a refused revoke changed the grant") } out, err := r.client.RevokeSpecialist(r.ctx, sp.ID, sp.Revision) if err != nil || out.State != wire.SpecialistRevoked || out.RevokedBy != Owner || out.RevokedAt == nil || out.Revision != sp.Revision+1 { t.Fatalf("revoked %+v %v", out, err) } if r.rows("SELECT count(*) FROM chat_capability_grants WHERE revoked_at IS NULL") != 0 || r.rows("SELECT count(*) FROM chat_capability_grants WHERE revoked_by = ?", Owner) != 1 { t.Fatal("the grant is still live") } if r.rows("SELECT count(*) FROM chat_specialist_audit WHERE specialist_id = ? AND action = 'revoked' AND actor = ? AND revision = ?", sp.ID, Owner, out.Revision) != 1 { t.Fatal("no revoke audit row") } if _, err := r.client.RevokeSpecialist(r.ctx, sp.ID, out.Revision); Status(err) != 409 { t.Fatalf("revoked twice: %v", err) } if res := r.call("r2", wire.ToolProposeSpecialist, researchArgs()); res.IsError || res.Code != "proposed" { t.Fatalf("proposed after revoke %+v", res) } } // TestSpecialistOlderRunner: a primary speaking protocol 11 gets the // update message for propose_specialist, and nothing is proposed. func TestSpecialistOlderRunner(t *testing.T) { r := newToolRigAt(t, wire.ProtocolPreviewHost) res := r.call("o1", wire.ToolProposeSpecialist, researchArgs()) if !res.IsError || res.Code != "research_unsupported" || res.Text != "Equipo needs an update before it can research." { t.Fatalf("at 11: %+v", res) } if r.specialistCards() != 0 || r.rows("SELECT count(*) FROM chat_specialists") != 0 { t.Fatal("proposed at 11") } }