package thintest import ( "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // Research's sources, card and scheduling (Research spec ยง2, slice R2). // The coordinator's research tool only requests a run; it starts at the // task's next fixed point (task start, or the boundary before the next // Engineering round), one per fixed point and three per task. While it is // pending or running, that Engineering round is held, and it is released // when Research ends, however it ends. // personWords is the person's message on the task: a URL and a bare // domain, both theirs, so read without asking. const personWords = "Make mockups for the barber shop. Its site is shop.example.com and the hours are on https://shop.example.com/hours." // researchOn adds Research to the team: proposed, then the owner's Add. func (r *toolRig) researchOn() { r.t.Helper() if res := r.call("on-propose", wire.ToolProposeSpecialist, researchArgs()); res.IsError { r.t.Fatalf("propose: %+v", res) } card := r.specialistCard(wire.CardOpen) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil { r.t.Fatal(err) } } // inventoryOn gives the primary a confirmed site inventory, so a // Research step may be dispatched: its hello reports one address, and // that address's prefix is recorded as an owner's Confirm records it // (research_inventory_contract_test.go confirms through the card). func (r *toolRig) inventoryOn() { r.t.Helper() r.addresses(1, "81.2.69.7") if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_research_prefixes(runner_id, prefix, confirmed_by, confirmed_at, card_id) VALUES (?,?,?,?,?) ON CONFLICT DO NOTHING", r.runner.Welcome.RunnerID, "81.2.69.7/32", Owner, time.Now().UTC().Format(time.RFC3339Nano), ""); err != nil { r.t.Fatal(err) } } // shopTask records a change task for the shop. func (r *toolRig) shopTask(key string) string { r.t.Helper() return taskID(r.t, r.call(key+"-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Shop mockups", "brief": "Mockups that match the shop.", "separate": true})) } func (r *toolRig) research(key, task string, urls ...string) wire.ToolResult { r.t.Helper() if urls == nil { urls = []string{} } return r.call(key, wire.ToolResearch, map[string]any{"task": task, "question": "Its colours, logo and opening hours.", "urls": urls}) } func (r *toolRig) begin(key, task string) { r.t.Helper() if res := r.call(key, wire.ToolStartTask, map[string]string{"task": task, "brief": "Make them."}); res.IsError { r.t.Fatalf("start: %+v", res) } } func stepsOf(k wire.Task, specialist string) []wire.Step { var out []wire.Step for _, s := range k.Steps { if s.Specialist == specialist { out = append(out, s) } } return out } // newest is the task's newest step of specialist. func (r *toolRig) newest(id, specialist string) wire.Step { r.t.Helper() all := stepsOf(r.task(id), specialist) if len(all) == 0 { r.t.Fatalf("no %s step", specialist) } return all[len(all)-1] } // heldForResearch checks the task's newest Engineering step waits for Research and // nothing was sent for it. func (r *toolRig) heldForResearch(id string) wire.Step { r.t.Helper() e := r.newest(id, wire.SpecialistEngineering) if e.State != wire.StepQueued || e.Placement != wire.PlacementResearch || e.RunnerID != "" { r.t.Fatalf("Engineering is not held: %+v", e) } if n := r.commandsLike(wire.FrameDispatch, `"step_id":"`+e.ID+`"`); n != 0 { r.t.Fatalf("a held Engineering step was dispatched %d times", n) } return e } func (r *toolRig) sourcesCard(state string) wire.Card { r.t.Helper() var card wire.Card r.wait("sources card "+state, func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardResearchSources && k.State == state { card = k return true } } return false }) return card } func (r *toolRig) sourcesCards() int { r.t.Helper() n := 0 for _, c := range r.snapshotCards() { if c.Kind == wire.CardResearchSources { n++ } } return n } func (r *toolRig) researchDispatches() int { r.t.Helper() return r.commandsLike(wire.FrameDispatch, `"specialist":"research"`) } // TestResearchAtTaskStartHoldsEngineering: research before start_task // waits for the task's start; the person's own URL and bare domain are // its sources, with no card. At start it is at its fixed point and // Engineering is held; while the primary has no confirmed site inventory // (here its hello has not said which addresses it has, so there is // nothing to confirm yet and no card) it is never dispatched, and says // so. func TestResearchAtTaskStartHoldsEngineering(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() id := r.shopTask("a") res := r.research("a-r", id) if res.IsError || res.Code != "requested" || res.Text == "" { t.Fatalf("request: %+v", res) } s := r.newest(id, wire.SpecialistResearch) if s.State != wire.StepQueued || s.Placement != wire.PlacementBoundary || s.RunnerID != "" { t.Fatalf("before the start %+v", s) } if r.sourcesCards() != 0 { t.Fatal("a card for the person's own URLs") } if n := r.rows("SELECT count(*) FROM chat_research_sources WHERE step_id = ? AND origin = ? AND approved = 1", s.ID, wire.ResearchOriginPerson); n != 2 { t.Fatalf("%d of the person's sources", n) } if n := r.rows("SELECT count(*) FROM chat_research_sources WHERE step_id = ? AND url IN (?, ?)", s.ID, "https://shop.example.com/", "https://shop.example.com/hours"); n != 2 { t.Fatalf("the sources are not canonical: %d", n) } r.begin("a-start", id) r.heldForResearch(id) if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepQueued || s.Placement != wire.PlacementInventory { t.Fatalf("at the start %+v", s) } if r.researchDispatches() != 0 || r.commands(wire.FrameDispatch) != 0 { t.Fatal("dispatched without a confirmed inventory") } if r.inventoryCards() != 0 { t.Fatal("an inventory card with no address to confirm") } if k := r.task(id); k.Stage != wire.StageInProgress || k.NeedsYou != "" || k.CandidateSHA != "" { t.Fatalf("the task while Research waits %+v", k) } // The pages still render with a waiting Research step and a held one. r.get(r.inst.SessionFor(t, Owner), "/tasks/"+id, 200) r.get(r.inst.SessionFor(t, Owner), "/work", 200) } // TestResearchRunsThenReleasesEngineering: with the inventory confirmed, // the Research step is dispatched to the primary with its inputs and no // repository, branch or SHA; Engineering goes when it is done, and // Research never becomes the task's last word. func TestResearchRunsThenReleasesEngineering(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() id := r.shopTask("b") r.research("b-r", id) r.begin("b-start", id) d := r.nextDispatch() if d.Specialist != wire.SpecialistResearch || d.Repo != "" || d.Branch != "" || d.BaseSHA != "" || d.CandidateSHA != "" || d.Title != "Shop mockups" || d.Research == nil { t.Fatalf("research dispatch %+v", d) } rd := d.Research want := []wire.ResearchSource{{ID: "s1", URL: "https://shop.example.com/", Origin: wire.ResearchOriginPerson}, {ID: "s2", URL: "https://shop.example.com/hours", Origin: wire.ResearchOriginPerson}} if rd.Question != "Its colours, logo and opening hours." || !slices.Equal(rd.Sources, want) || !slices.Equal(rd.Inventory, []string{"81.2.69.7/32"}) || !slices.Contains(rd.PersonWords, personWords) { t.Fatalf("research inputs %+v", rd) } // The approved specialist's brief, at its revision (Astra security // finding 6). list, err := r.client.Specialists(r.ctx) if err != nil || len(list.Items) != 1 { t.Fatalf("%+v %v", list, err) } if rd.SpecialistBrief != researchArgs()["brief"] || rd.SpecialistRevision != list.Items[0].Revision || rd.SpecialistRevision < 1 { t.Fatalf("specialist brief %q at %d", rd.SpecialistBrief, rd.SpecialistRevision) } r.heldForResearch(id) r.step("b-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning}) if k := r.task(id); k.NeedsYou != "" || r.newest(id, wire.SpecialistResearch).State != wire.StepRunning { t.Fatalf("running %+v", k) } // A report that names a SHA is not a Research report. r.step("b-sha", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: baseX, Termination: true}) if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepRunning || r.task(id).BaseSHA != "" { t.Fatalf("a report with a SHA counted %+v", s) } r.step("b-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Termination: true, Summary: "Read two pages."}) e := r.nextDispatch() if e.Specialist != wire.SpecialistEngineering || e.Round != 0 || e.Research != nil { t.Fatalf("Engineering after Research %+v", e) } k := r.task(id) if s := stepsOf(k, wire.SpecialistResearch); len(s) != 1 || s[0].State != wire.StepDone || s[0].Index >= stepsOf(k, wire.SpecialistEngineering)[0].Index { t.Fatalf("steps %+v", k.Steps) } // Engineering's push is judged as ever: Research is not a judgement. r.step("b-e-done", wire.StepReport{TaskID: id, StepID: e.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: baseX, CandidateSHA: candX, Pushed: true, Termination: true}) r.dispatched(wire.SpecialistChecks, baseX, candX, 0) if k := r.task(id); k.CandidateSHA != candX || k.Stage != wire.StageInReview || k.NeedsYou != "" { t.Fatalf("after Engineering %+v", k) } } // TestResearchWaitsForTheRoundBoundary: a request while Engineering runs // waits; checks go on as ever; the fix round is the next fixed point, so // Research runs then with that round held, and a failed Research releases // it. func TestResearchWaitsForTheRoundBoundary(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() id := r.shopTask("c") r.begin("c-start", id) eng := r.nextDispatch() r.step("c-run", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: baseX}) if res := r.research("c-r", id); res.IsError { t.Fatalf("request mid-step %+v", res) } if s := r.newest(id, wire.SpecialistResearch); s.Placement != wire.PlacementBoundary || r.researchDispatches() != 0 { t.Fatalf("started mid-step %+v", s) } r.step("c-done", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: baseX, CandidateSHA: candX, Pushed: true, Termination: true}) c := r.dispatched(wire.SpecialistChecks, baseX, candX, 0) if r.researchDispatches() != 0 { t.Fatal("Research ran beside checks") } r.checks("c-c", c, wire.ChecksFailed, exit(2), "", "FAIL\n") d := r.nextDispatch() if d.Specialist != wire.SpecialistResearch { t.Fatalf("at the round boundary %+v", d) } fix := r.heldForResearch(id) if fix.Round != 1 || r.newest(id, wire.SpecialistResearch).Index >= fix.Index { t.Fatalf("the held round %+v", fix) } r.step("c-r-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) e := r.nextDispatch() if e.Specialist != wire.SpecialistEngineering || e.Round != 1 || e.StepID != fix.ID || e.BaseSHA != candX { t.Fatalf("released round %+v", e) } if k := r.task(id); k.NeedsYou != "" || k.Stage != wire.StageInProgress { t.Fatalf("a failed Research needs the person: %+v", k) } } // TestResearchOnePerBoundaryAndThreePerTask: a second request for the // same fixed point is refused, a cancelled run still counts, and a // fourth run is refused. func TestResearchOnePerBoundaryAndThreePerTask(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() id := r.shopTask("d") if res := r.research("d-1", id); res.IsError { t.Fatalf("first %+v", res) } if res := r.research("d-1b", id); !res.IsError || res.Code != "boundary_taken" { t.Fatalf("a second at the start %+v", res) } r.begin("d-start", id) d1 := r.nextDispatch() r.step("d-1-done", wire.StepReport{TaskID: id, StepID: d1.StepID, Attempt: 1, State: wire.StepDone, Termination: true}) eng := r.nextDispatch() if res := r.research("d-2", id); res.IsError { t.Fatalf("second %+v", res) } if res := r.research("d-2b", id); !res.IsError || res.Code != "boundary_taken" { t.Fatalf("a second at round 1 %+v", res) } r.step("d-e", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: baseX, CandidateSHA: candX, Pushed: true, Termination: true}) c := r.dispatched(wire.SpecialistChecks, baseX, candX, 0) r.checks("d-c", c, wire.ChecksFailed, exit(2), "", "FAIL\n") d2 := r.nextDispatch() if d2.Specialist != wire.SpecialistResearch { t.Fatalf("second run %+v", d2) } // Cancelled by the runner: Engineering goes, and the run counts. r.step("d-2-cancel", wire.StepReport{TaskID: id, StepID: d2.StepID, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Termination: true}) if e := r.nextDispatch(); e.Specialist != wire.SpecialistEngineering || e.Round != 1 { t.Fatalf("after a cancelled Research %+v", e) } if res := r.research("d-3", id); res.IsError { t.Fatalf("third %+v", res) } if res := r.research("d-4", id); !res.IsError || res.Code != "research_limit" { t.Fatalf("a fourth %+v", res) } if n := len(stepsOf(r.task(id), wire.SpecialistResearch)); n != 3 { t.Fatalf("%d Research steps", n) } } // TestResearchRefused: no grant, a bad question, a proposal that breaks // the rules, another person's task, an ended task or nothing to read are // refused before any step or card. func TestResearchRefused(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) id := r.shopTask("e") if res := r.research("e-ng", id); !res.IsError || res.Code != "no_grant" || res.Text == "" { t.Fatalf("without a grant %+v", res) } r.researchOn() q := func(question string) map[string]any { return map[string]any{"task": id, "question": question, "urls": []string{}} } u := func(urls ...string) map[string]any { return map[string]any{"task": id, "question": "Colours?", "urls": urls} } eleven := make([]string, 11) for i := range eleven { eleven[i] = "https://shop.example.com/p" + itoa(i) } for name, c := range map[string]struct { args map[string]any code string }{ "no question": {q(""), "question"}, "a question too long": {q(strings.Repeat("q", wire.MaxResearchQuestion+1)), "question"}, "a secret-looking one": {q("Use token=abcd1234efgh5678 to sign in"), "secret"}, "a query": {u("https://shop.example.com/?ref=x"), "query_refused"}, "an IP literal": {u("http://81.2.69.9/"), "ip_literal"}, "a tailnet host": {u("https://box.example.ts.net/"), "host_refused"}, "a secret in the path": {u("https://shop.example.com/ghp_abcdefghijklmnopqrstuvwxyz0123"), "secret_refused"}, "a long path": {u("https://shop.example.com/" + strings.Repeat("a", 101)), "path_too_long"}, "another scheme": {u("ftp://shop.example.com/"), "scheme_refused"}, "eleven URLs": {u(eleven...), "too_many_urls"}, "an unknown field": {map[string]any{"task": id, "question": "Colours?", "urls": []string{}, "depth": 2}, "invalid"}, "no such task": {map[string]any{"task": "tk_nothing", "question": "Colours?", "urls": []string{}}, "not_found"}, "urls missing, not empty": {map[string]any{"task": id, "question": "Colours?", "urls": "https://shop.example.com/"}, "invalid"}, } { res := r.call("e-"+strings.ReplaceAll(name, " ", "-"), wire.ToolResearch, c.args) if !res.IsError || res.Code != c.code || res.Text == "" { t.Errorf("%s: %+v", name, res) } } // Another owner's coordinator may read the task but not research it. b := personToolRigAt(t, r, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) if res := b.research("e-b", id); !res.IsError || res.Code != "not_yours" { t.Fatalf("a teammate's turn %+v", res) } if n := len(stepsOf(r.task(id), wire.SpecialistResearch)); n != 0 || r.sourcesCards() != 0 || r.rows("SELECT count(*) FROM chat_research_sources") != 0 { t.Fatal("a refused request left something") } // A task with no URL in the person's words and none proposed has // nothing to read. own := b.shopTask("e-own") if res := b.research("e-none", own); !res.IsError || res.Code != "no_sources" { t.Fatalf("nothing to read %+v", res) } // An ended task. if _, err := r.client.CancelTask(r.ctx, id); err != nil { t.Fatal(err) } if res := r.research("e-ended", id); !res.IsError || res.Code != "task_ended" { t.Fatalf("an ended task %+v", res) } } // TestResearchSourcesCard: the person's own words (their message, not a // report the coordinator added) are read without asking; the coordinator's // proposals raise one card with every URL in full, bound to the step and // that list; a stale revision, another person or another answer is // refused; the step waits for the card at its fixed point, and Allow // sends every source. func TestResearchSourcesCard(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() id := r.shopTask("f") if res := r.call("f-rep", wire.ToolAddReport, map[string]string{"task": id, "text": "And the prices, on shop.example.com/prices."}); res.IsError { t.Fatalf("report %+v", res) } proposed := []string{"https://maps.example.org/place/barber-shop-on-main-street", "https://shop.example.com/hours", "https://www.example.net/reviews/barber-shop"} if res := r.research("f-r", id, proposed...); res.IsError { t.Fatalf("request %+v", res) } card := r.sourcesCard(wire.CardOpen) s := r.newest(id, wire.SpecialistResearch) v := card.Research if v == nil || v.StepID != s.ID || card.TaskID != id || card.Question == "" || v.Question != "Its colours, logo and opening hours." || !slices.Equal(card.Options, []string{wire.ChoiceAllow, wire.ChoiceSkip}) { t.Fatalf("card %+v %+v", card, v) } // The person's own hours page needs no asking; the two proposals are // shown exactly as they will be requested. if !slices.Equal(v.URLs, []string{"https://maps.example.org/place/barber-shop-on-main-street", "https://www.example.net/reviews/barber-shop"}) { t.Fatalf("card URLs %v", v.URLs) } if r.sourcesCards() != 1 { t.Fatal("more than one card") } // The conversation still renders with the card in it (slice R5 draws it). r.get(r.inst.SessionFor(t, Owner), "/conversation", 200) // The report the coordinator added is its own text, not the person's // (Astra security finding 1): its prices page is not a source. if n := r.rows("SELECT count(*) FROM chat_research_sources WHERE step_id = ? AND origin = ? AND approved = 1", s.ID, wire.ResearchOriginPerson); n != 2 { t.Fatalf("%d of the person's sources", n) } if n := r.rows("SELECT count(*) FROM chat_research_sources WHERE step_id = ? AND origin = ? AND approved = 0", s.ID, wire.ResearchOriginProposed); n != 2 { t.Fatalf("%d proposals waiting", n) } for _, rev := range []int64{card.Revision + 1, card.Revision - 1} { if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, rev); Status(err) != 409 { t.Fatalf("revision %d: %v", rev, err) } } if _, err := r.client.Answer(r.ctx, card.ID, "maybe", card.Revision); Status(err) != 422 { t.Fatalf("another answer: %v", err) } b := personToolRigAt(t, r, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) if _, err := b.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 404 { t.Fatalf("a teammate answered: %v", err) } r.inventoryOn() r.begin("f-start", id) r.heldForResearch(id) if s := r.newest(id, wire.SpecialistResearch); s.Placement != wire.PlacementSources || r.researchDispatches() != 0 { t.Fatalf("at the start before the answer %+v", s) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil { t.Fatal(err) } if done := r.sourcesCard(wire.CardAnswered); done.Choice != wire.ChoiceAllow { t.Fatalf("answered %+v", done) } d := r.nextDispatch() if d.Specialist != wire.SpecialistResearch || d.Research == nil { t.Fatalf("after Allow %+v", d) } var urls, origins []string for _, src := range d.Research.Sources { urls, origins = append(urls, src.URL), append(origins, src.Origin) } if !slices.Equal(urls, []string{"https://shop.example.com/", "https://shop.example.com/hours", "https://maps.example.org/place/barber-shop-on-main-street", "https://www.example.net/reviews/barber-shop"}) || !slices.Equal(origins, []string{"person", "person", "proposed", "proposed"}) { t.Fatalf("sources %v %v", urls, origins) } if !slices.Equal(d.Research.PersonWords, []string{personWords}) { t.Fatalf("person words %v", d.Research.PersonWords) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 409 { t.Fatalf("answered twice: %v", err) } } // TestResearchCardOwner: only the card's person answers it, and only // while they are an owner, read in the answer's transaction. func TestResearchCardOwner(t *testing.T) { a := newToolRigAt(t, wire.ProtocolCurrent) a.researchOn() b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) id := b.shopTask("g") if res := b.research("g-r", id, "https://maps.example.org/place/shop"); res.IsError { t.Fatalf("B's request %+v", res) } card := b.sourcesCard(wire.CardOpen) if _, err := a.client.Answer(a.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 404 { t.Fatalf("another person answered: %v", err) } 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(a.ctx, equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleMember, true, revision); err != nil { t.Fatal(err) } if _, err := b.client.Answer(a.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 403 { t.Fatalf("a teammate allowed it: %v", err) } if a.rows("SELECT count(*) FROM chat_research_sources WHERE approved = 1") != 0 { t.Fatal("approved without an owner") } } // TestResearchSkipWithNothingLeft: Skip drops the proposals; with none of // the person's own, the step ends done with a gap and Engineering goes. func TestResearchSkipWithNothingLeft(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.researchOn() r.inventoryOn() id := r.shopTask("h") r.research("h-r", id, "https://maps.example.org/place/shop") card := r.sourcesCard(wire.CardOpen) r.begin("h-start", id) r.heldForResearch(id) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceSkip, card.Revision); err != nil { t.Fatal(err) } e := r.nextDispatch() if e.Specialist != wire.SpecialistEngineering { t.Fatalf("after Skip %+v", e) } s := r.newest(id, wire.SpecialistResearch) if s.State != wire.StepDone || s.Reason != wire.ReasonResearchNoSources || r.researchDispatches() != 0 { t.Fatalf("Research after Skip %+v", s) } if r.rows("SELECT count(*) FROM chat_research_sources WHERE approved = 1") != 0 { t.Fatal("Skip approved something") } if done := r.sourcesCard(wire.CardAnswered); done.Choice != wire.ChoiceSkip { t.Fatalf("card %+v", done) } } // TestResearchRevokeCancelsWaiting: revoking Research cancels its steps // that have not run, withdraws their cards, and releases Engineering. func TestResearchRevokeCancelsWaiting(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.researchOn() id := r.shopTask("i") r.research("i-r", id, "https://maps.example.org/place/shop") card := r.sourcesCard(wire.CardOpen) r.begin("i-start", id) r.heldForResearch(id) list, err := r.client.Specialists(r.ctx) if err != nil || len(list.Items) != 1 { t.Fatalf("%+v %v", list, err) } if _, err := r.client.RevokeSpecialist(r.ctx, list.Items[0].ID, list.Items[0].Revision); err != nil { t.Fatal(err) } if e := r.nextDispatch(); e.Specialist != wire.SpecialistEngineering { t.Fatalf("after revoke %+v", e) } if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepCancelled || s.Reason != wire.ReasonResearchNoGrant || !s.Terminated { t.Fatalf("Research after revoke %+v", s) } gone := r.sourcesCard(wire.CardResolved) if gone.ID != card.ID { t.Fatalf("withdrawn %+v", gone) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, gone.Revision); Status(err) != 409 { t.Fatalf("answered a withdrawn card: %v", err) } if r.researchDispatches() != 0 { t.Fatal("dispatched after revoke") } } // TestResearchOlderPrimary: a primary at protocol 11 gets the update // message for research, and nothing is requested. func TestResearchOlderPrimary(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolPreviewHost, personWords) id := r.shopTask("j") res := r.research("j-r", id) if !res.IsError || res.Code != "research_unsupported" || res.Text != "Equipo needs an update before it can research." { t.Fatalf("at 11: %+v", res) } if len(stepsOf(r.task(id), wire.SpecialistResearch)) != 0 || r.researchDispatches() != 0 { t.Fatal("requested at 11") } } // TestResearchFencedOnAnOlderPrimary (mixed version): a Research step // dispatched at 13 whose primary comes back at 12 (metered connections, // no Research) or 11 is cancelled research_unsupported, its dispatch is // never delivered there, and Engineering is released to the older // runner. func TestResearchFencedOnAnOlderPrimary(t *testing.T) { for _, back := range []int{wire.Protocol12, wire.Protocol11} { t.Run(itoa(back), func(t *testing.T) { researchFencedAt(t, back) }) } } func researchFencedAt(t *testing.T, back int) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() id := r.shopTask("k") r.research("k-r", id) r.begin("k-start", id) if d := r.nextDispatch(); d.Specialist != wire.SpecialistResearch { t.Fatalf("%+v", d) } old, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, primaryAt(wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, back)) if err != nil { t.Fatal(err) } defer old.Close() // The copy the runner may hold is cancelled; then Engineering arrives. var body any for { f, b, err := old.Next(r.ctx) if err != nil { t.Fatal(err) } if f.Type == wire.FrameDispatch { body = b break } } if e := body.(*wire.DispatchCommand); e.Specialist != wire.SpecialistEngineering { t.Fatalf("to the older runner %+v", e) } for _, raw := range old.Received { if strings.Contains(string(raw), `"specialist":"research"`) { t.Fatalf("a research dispatch reached protocol %d: %s", back, raw) } } if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepCancelled || s.Reason != wire.ReasonResearchUnsupported { t.Fatalf("fenced %+v", s) } } // TestResearchCardBindsTheList: Allow approves exactly the URLs the card // showed. If the step's proposals no longer match them, the answer is a // conflict and nothing is approved. func TestResearchCardBindsTheList(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.researchOn() id := r.shopTask("l") r.research("l-r", id, "https://maps.example.org/place/shop", "https://www.example.net/reviews/shop") card := r.sourcesCard(wire.CardOpen) s := r.newest(id, wire.SpecialistResearch) if _, err := r.inst.DB.Writer().Exec("UPDATE chat_research_sources SET url = ? WHERE step_id = ? AND idx = 2", "https://www.example.net/other", s.ID); err != nil { t.Fatal(err) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 409 { t.Fatalf("Allow on a changed list: %v", err) } if r.rows("SELECT count(*) FROM chat_research_sources WHERE approved = 1") != 0 { t.Fatal("approved a list the card did not show") } if _, err := r.inst.DB.Writer().Exec("UPDATE chat_research_sources SET url = ? WHERE step_id = ? AND idx = 2", "https://www.example.net/reviews/shop", s.ID); err != nil { t.Fatal(err) } // Allowed before the task starts, it still waits for its fixed point. r.inventoryOn() if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil { t.Fatal(err) } if r.rows("SELECT count(*) FROM chat_research_sources WHERE step_id = ? AND approved = 1", s.ID) != 2 { t.Fatal("Allow did not approve the list") } if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepQueued || s.Placement != wire.PlacementBoundary || r.researchDispatches() != 0 { t.Fatalf("Allow started it before the task's start %+v", s) } } // TestResearchGrantCheckedAtDispatch: the grant is checked again when a // step reaches dispatch: its approver is no longer an owner, so the step // ends research_no_grant and Engineering goes. func TestResearchGrantCheckedAtDispatch(t *testing.T) { a := newToolRigAt(t, wire.ProtocolCurrent) a.researchOn() a.inventoryOn() b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) id := b.shopTask("m") if res := b.research("m-r", id, "https://maps.example.org/place/shop"); res.IsError { t.Fatalf("request %+v", res) } card := b.sourcesCard(wire.CardOpen) if _, err := b.client.Answer(b.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil { t.Fatal(err) } var revision int64 if err := a.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", Owner).Scan(&revision); err != nil { t.Fatal(err) } if err := a.inst.Store.SetMember(a.ctx, equipo.Actor{Address: "second@example.com"}, Owner, equipo.RoleMember, true, revision); err != nil { t.Fatal(err) } b.begin("m-start", id) if e := b.nextDispatch(); e.Specialist != wire.SpecialistEngineering { t.Fatalf("after the grant lapsed %+v", e) } if s := b.newest(id, wire.SpecialistResearch); s.State != wire.StepCancelled || s.Reason != wire.ReasonResearchNoGrant { t.Fatalf("Research without a grant %+v", s) } if b.researchDispatches() != 0 { t.Fatal("dispatched without a grant") } } // TestResearchNeverDispatchedToAnOlderPrimary (mixed version): a step // that reaches dispatch while its primary speaks 11 is never sent: it // ends research_unsupported and Engineering goes to that runner. func TestResearchNeverDispatchedToAnOlderPrimary(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.researchOn() r.inventoryOn() id := r.shopTask("n") r.research("n-r", id, "https://maps.example.org/place/shop") card := r.sourcesCard(wire.CardOpen) r.begin("n-start", id) r.heldForResearch(id) old, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, primaryAt(wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, wire.ProtocolPreviewHost)) if err != nil { t.Fatal(err) } defer old.Close() r.wait("the primary at 11", func(c *Conversation) bool { return c.Runner.Online }) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil { t.Fatal(err) } f, body, err := old.Expect(r.ctx, wire.FrameDispatch) if err != nil { t.Fatal(err) } if e := body.(*wire.DispatchCommand); f.Type != wire.FrameDispatch || e.Specialist != wire.SpecialistEngineering { t.Fatalf("to the older runner %+v", e) } if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepCancelled || s.Reason != wire.ReasonResearchUnsupported { t.Fatalf("at 11 %+v", s) } if r.researchDispatches() != 0 { t.Fatal("a research dispatch was written for a primary at 11") } }