package thintest import ( "context" "database/sql" "encoding/json" "fmt" "html" "net/http" "net/url" "slices" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/wire" ) // Job threads in Equipo's pages (jobs design, J6): /jobs lists the // person's job threads under "From Base", /jobs/{id} shows one with the // conversation page's template and a reply field, and /conversation // links there once the person has one. // jobThread is the request's thread as JobThread reads it for the owner. func (o *teamRig) jobThread(request string) wire.Snapshot { o.t.Helper() ctx := personapi.WithVerifiedPrincipal(context.Background(), personapi.PersonPrincipal{Address: Owner, SessionEpoch: time.Now().Unix()}) snap, err := o.inst.Store.Chat().JobThread(ctx, Owner, request) if err != nil { o.t.Fatalf("job thread %s: %v", request, err) } return snap } // jobCard is the card of kind on the task in the request's thread, as // JobThread reads it. func (o *teamRig) jobCard(request, kind, task string) wire.Card { o.t.Helper() for _, c := range o.jobThread(request).Cards { if c.Kind == kind && c.TaskID == task { return c } } return wire.Card{} } // TestContractTeamJobThreadPage: signed in as the hand-off's person, // /jobs lists it and /jobs/ shows the person's words, the // thread's reply and its card; a reply posted there is the thread's next // message, dispatched in its lane and audited by id. Another member sees // an empty list and gets 404 for the thread and its reply; a legacy // hand-off has no thread. /conversation links to /jobs only once the // person has a job. func TestContractTeamJobThreadPage(t *testing.T) { o := newTeamRig(t) owner := o.inst.Cookie() if page := o.get(owner, "/conversation", http.StatusOK); strings.Contains(page, `href="/jobs"`) { t.Fatal("/conversation links to /jobs before any job") } if page := o.get(owner, "/jobs", http.StatusOK); !strings.Contains(page, `data-empty-state="jobs.empty"`) { t.Fatalf("/jobs with no job: %.300s", page) } o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("jp1", "Login is broken", "") lane := wire.JobLane(request) o.in(cmd.TurnID, func() { if res := o.call("jp-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page is it?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) if err := o.runner.Send(o.ctx, "r-jp-reply", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Looking at the sign in page."}); err != nil { t.Fatal(err) } o.until("the thread's reply", func() bool { return o.turnState(cmd.TurnID) == wire.TurnReplied }) card, _ := o.threadQuestion(request) list := o.get(owner, "/jobs", http.StatusOK) if !strings.Contains(list, `href="/jobs/`+request+`"`) || !strings.Contains(list, "Login is broken") || strings.Contains(list, `data-empty-state="jobs.empty"`) { t.Fatalf("/jobs %.600s", list) } if page := o.get(owner, "/conversation", http.StatusOK); !strings.Contains(page, `href="/jobs"`) { t.Fatal("/conversation has no From Base link once the person has a job") } page := html.UnescapeString(o.get(owner, "/jobs/"+request, http.StatusOK)) for _, want := range []string{"Login is broken", "Looking at the sign in page.", "Which login page is it?", `data-card="` + card + `"`, `action="/jobs/` + request + `/messages"`, `href="/conversation"`, `href="/jobs"`, `id="conversation-end"`} { if !strings.Contains(page, want) { t.Fatalf("/jobs/%s lacks %q", request, want) } } if strings.Contains(page, "data-chat-stream") { t.Fatal("the thread page follows the person's own conversation stream") } // A reply posted on the thread page is the thread's next message. status, loc := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"It is the web one."}, "request_id": {"jp-reply-1"}}) if status != http.StatusSeeOther || loc != "/jobs/"+request { t.Fatalf("reply: %d %q", status, loc) } var id, turn string if err := o.inst.DB.Writer().QueryRow("SELECT id, turn_id FROM chat_messages WHERE lane = ? AND role = ? AND text = ?", lane, wire.RolePerson, "It is the web one.").Scan(&id, &turn); err != nil { t.Fatalf("the reply is not in the thread: %v", err) } if next := o.message(lane); next.TurnID != turn || !slices.Equal(next.PersonText, []string{"It is the web one."}) { t.Fatalf("the reply's frame %+v", next) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = ? AND record_id = ? AND actor = ?", "job.send", id, Owner); n != 1 { t.Fatalf("%d job.send audits for the reply", n) } // The same request again is the same message. if status, _ := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"It is the web one."}, "request_id": {"jp-reply-1"}}); status != http.StatusSeeOther { t.Fatalf("repeat: %d", status) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE lane = ? AND text = ?", lane, "It is the web one."); n != 1 { t.Fatalf("%d copies of the reply", n) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE coalesce(lane, '') = '' AND text = ?", "It is the web one."); n != 0 { t.Fatal("the reply reached their own conversation") } // Another member has no jobs and cannot read or reply to this one. mate := o.memberCookie() if page := o.get(mate, "/jobs", http.StatusOK); strings.Contains(page, request) || !strings.Contains(page, `data-empty-state="jobs.empty"`) { t.Fatalf("another member's /jobs %.300s", page) } o.get(mate, "/jobs/"+request, http.StatusNotFound) if status, _ := o.post(mate, "/jobs/"+request+"/messages", url.Values{"body": {"Mine now."}, "request_id": {"jp-mate"}}); status != http.StatusNotFound { t.Fatalf("another member's reply: %d", status) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE text = ?", "Mine now."); n != 0 { t.Fatal("another member's reply was stored") } // A legacy hand-off and an unknown id have no thread. legacy, _ := o.legacyHandoff("jp", "Checkout is slow") o.get(owner, "/jobs/"+legacy, http.StatusNotFound) o.get(owner, "/jobs/h_unknown", http.StatusNotFound) if list := o.get(owner, "/jobs", http.StatusOK); strings.Contains(list, legacy) || strings.Contains(list, "Checkout is slow") { t.Fatal("/jobs lists a legacy hand-off") } // A primary back below protocol 22 cannot carry the thread: a new // reply is refused and stored nowhere; one already sent answers as it // did. o.runner.Close() o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) o.dialAt(wire.Protocol21) if status, _ := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"Any news?"}, "request_id": {"jp-old"}}); status != http.StatusConflict { t.Fatalf("a reply at 21: %d", status) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE text = ?", "Any news?"); n != 0 { t.Fatal("a reply at 21 was stored") } if status, loc := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"It is the web one."}, "request_id": {"jp-reply-1"}}); status != http.StatusSeeOther || loc != "/jobs/"+request { t.Fatalf("the sent reply again at 21: %d %q", status, loc) } } // TestContractTeamJobThreadAnswer: a question card answered from the // thread page is answered in the job's lane: the answer is the thread's // next message, dispatched there, and the page returns to the thread. func TestContractTeamJobThreadAnswer(t *testing.T) { o := newTeamRig(t) owner := o.inst.Cookie() o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("ja1", "Login is broken", "") lane := wire.JobLane(request) o.in(cmd.TurnID, func() { if res := o.call("ja-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page is it?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.reply(cmd.TurnID) card, revision := o.threadQuestion(request) page := o.get(owner, "/jobs/"+request, http.StatusOK) form := `action="/conversation/cards/` + card + `/answer"` if !strings.Contains(page, form) || !strings.Contains(page, `name="job" value="`+request+`"`) { t.Fatalf("the thread's card form: %.2000s", page) } status, loc := o.post(owner, "/conversation/cards/"+card+"/answer", url.Values{"revision": {strconv.FormatInt(revision, 10)}, "choice": {"Web"}, "from": {"job"}, "job": {request}}) if status != http.StatusSeeOther || loc != "/jobs/"+request+"#conversation-end" { t.Fatalf("answer: %d %q", status, loc) } var id, turn string if err := o.inst.DB.Writer().QueryRow("SELECT m.id, m.turn_id FROM chat_cards c JOIN chat_messages m ON m.id = c.answer_message WHERE c.id = ? AND c.state = ? AND c.choice = ?", card, wire.CardAnswered, "Web").Scan(&id, &turn); err != nil { t.Fatalf("the card is not answered: %v", err) } if o.laneOf(turn) != lane || o.rows("SELECT count(*) FROM chat_messages WHERE id = ? AND lane = ?", id, lane) != 1 { t.Fatal("the answer is not in the thread") } if next := o.message(lane); next.TurnID != turn || len(next.PersonText) != 0 { t.Fatalf("the answer's frame %+v", next) } // A job id that is not one returns to the conversation. if status, loc := o.post(owner, "/conversation/cards/"+card+"/answer", url.Values{"revision": {strconv.FormatInt(revision, 10)}, "choice": {"Web"}, "from": {"job"}, "job": {"../tasks"}}); status != http.StatusSeeOther || loc != "/conversation#conversation-end" { t.Fatalf("a bad job id: %d %q", status, loc) } } // The job card (jobs design ยง3; D1 to D5): one Assistant card per // hand-off, kind job, its question the job's title, its result the short // status and its detail one sentence more, rewritten in place as the // work moves. Nobody answers it. // jobCardID is the request's job card ("" while it has none). func (o *teamRig) jobCardID(request string) string { o.t.Helper() var id string err := o.inst.DB.Writer().QueryRow("SELECT id FROM chat_cards WHERE kind = ? AND handoff_id = ? AND lane = ?", wire.CardJob, request, wire.LaneAssistant).Scan(&id) if err != nil && err != sql.ErrNoRows { o.t.Fatal(err) } return id } // jobOf waits for the request's job card, as the Assistant snapshot // shows it, to match (any, with match nil). func (o *teamRig) jobOf(request, what string, match func(wire.AssistantCard) bool) wire.AssistantCard { o.t.Helper() var out wire.AssistantCard o.until(what, func() bool { id := o.jobCardID(request) if id == "" { return false } snap, err := o.a.Snapshot(o.ctx) if err != nil { o.t.Fatal(err) } for _, c := range snap.Cards { if c.ID == id && (match == nil || match(c)) { out = c return true } } return false }) return out } // jobEvents are the card's events in the Assistant lane, oldest first, // as stored: the card each carried. func (o *teamRig) jobEvents(card string) []wire.AssistantCard { o.t.Helper() rows, err := o.inst.DB.Writer().Query("SELECT body FROM chat_events WHERE person = ? AND lane = ? AND type = ? ORDER BY id", Owner, wire.LaneAssistant, wire.EventCard) if err != nil { o.t.Fatal(err) } defer rows.Close() var out []wire.AssistantCard for rows.Next() { var body string if err := rows.Scan(&body); err != nil { o.t.Fatal(err) } var e wire.Event var c wire.AssistantCard if err := json.Unmarshal([]byte(body), &e); err != nil { o.t.Fatal(err) } if e.ID != card { continue } if err := json.Unmarshal(e.Data, &c); err != nil { o.t.Fatal(err) } out = append(out, c) } if err := rows.Err(); err != nil { o.t.Fatal(err) } return out } // jobStatus is a working job's status and detail for a stage key. func jobStatus(key string) (string, string) { return equipo.RunnerCopy("assistant.job.status." + key), equipo.RunnerCopy("assistant.job.detail." + key) } // jobWords is the status and detail of a job in state (not working). func jobWords(state string) (string, string) { return equipo.RunnerCopy("assistant.job." + state), equipo.RunnerCopy("assistant.job.detail." + state) } // equipoLink is a job card's link to its thread in Equipo. func (o *teamRig) equipoLink(request string) wire.CardLink { return wire.CardLink{Label: equipo.RunnerCopy("assistant.job.open"), URL: o.inst.URL + "/jobs/" + request, Rel: wire.LinkEquipo} } // TestContractTeamJobCard: team_request raises one job card in the // Assistant lane: the job's title as its question, no options, "Getting // started" and its detail, started when the hand-off was made, and one // link, to the job's thread in Equipo. The same request under a new // call id is the same card; nobody answers it; /jobs shows its status // beside its title. func TestContractTeamJobCard(t *testing.T) { o := newTeamRig(t) o.ask("Build me a quick website") in := map[string]any{"words": "Build me a quick website", "title": "Building your website"} request := o.request("jc1", in) o.message(wire.JobLane(request)) card := o.jobOf(request, "the job card", nil) var created time.Time if err := o.inst.DB.Writer().QueryRow("SELECT created_at FROM chat_handoffs WHERE id = ?", request).Scan(&created); err != nil { t.Fatal(err) } status, detail := jobStatus("starting") if card.Kind != wire.CardJob || card.State != wire.JobWorking || card.Question != "Building your website" || card.Options == nil || len(card.Options) != 0 || card.Result != status || card.Detail != detail || card.StartedAt == nil || !card.StartedAt.Equal(created) || card.Job != "" || card.Revision != 1 { t.Fatalf("job card %+v (hand-off made %v)", card, created) } if !slices.Equal(card.Links, []wire.CardLink{o.equipoLink(request)}) { t.Fatalf("job card links %+v", card.Links) } // As Base reads it: an empty list of options, and the link's rel. code, _, snap := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "") want := `"options":[],"links":[{"label":"` + equipo.RunnerCopy("assistant.job.open") + `","url":"` + o.inst.URL + "/jobs/" + request + `","rel":"equipo"}]` if code != http.StatusOK || !strings.Contains(string(snap), want) { t.Fatalf("snapshot %d %s", code, snap) } // The same request under a new call id is the same job. if again := o.request("jc2", in); again != request { t.Fatalf("again %s, first %s", again, request) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ?", wire.CardJob); n != 1 { t.Fatalf("%d job cards", n) } if events := o.jobEvents(card.ID); len(events) != 1 { t.Fatalf("job card events %+v", events) } // Nobody answers a job card. if _, err := o.a.Answer(o.ctx, card.ID, status, card.Revision); Status(err) != http.StatusNotFound { t.Fatalf("an answer to the job card: %v", err) } // /jobs shows its status beside its title. list := html.UnescapeString(o.get(o.inst.Cookie(), "/jobs", http.StatusOK)) if !strings.Contains(list, "Building your website") || !strings.Contains(list, `data-job-status>`+status+`<`) { t.Fatalf("/jobs %.800s", list) } } // TestContractTeamJobStatuses: while the job works, its status follows // its task: noted, investigated, in progress, in review and ready to // merge, one card event each, each with its detail; then the go-ahead // makes it ready. func TestContractTeamJobStatuses(t *testing.T) { o := newTeamRig(t) o.sitesOn(wire.ProtocolAssistant, false) o.shipsNo(o.project()) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("js1", "Login is broken", "") job := o.jobOf(request, "the job card", nil).ID stage := func(id, want string) { t.Helper() o.wait(want, func(c *Conversation) bool { return c.Tasks[id].Stage == want }) } shown := func(n int) { t.Helper() o.until(fmt.Sprintf("%d job card events", n), func() bool { return len(o.jobEvents(job)) >= n }) } base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id = o.record("js-rec", "Fix the login") stage(id, wire.StageNoted) if res := o.call("js-find", wire.ToolAddFinding, map[string]any{"task": id, "headline": "The sign in button posts to the old address.", "text": "login.js posts to /v1/login.", "repo": "oficina/sample", "path": "login.js", "line": 3}); res.IsError { t.Fatalf("finding %+v", res) } stage(id, wire.StageInvestigated) shown(2) if res := o.call("js-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) o.step("js-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) stage(id, wire.StageInProgress) shown(3) o.step("js-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a"}) o.expect(wire.FrameWatchMerge) c := o.dispatched(wire.SpecialistChecks, base, cand, 0) stage(id, wire.StageInReview) shown(4) o.checks("js-c", c, wire.ChecksNone, nil, "", "") o.verdict("js-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove) }) o.assistantCard("the go-ahead", isMergeOutcome) o.jobOf(request, "ready", func(c wire.AssistantCard) bool { return c.State == wire.JobReady }) events := o.jobEvents(job) keys := []string{"starting", "planning", "building", "checking", "finishing"} if len(events) != len(keys)+1 { t.Fatalf("job card events %+v", events) } for i, key := range keys { status, detail := jobStatus(key) if e := events[i]; e.State != wire.JobWorking || e.Result != status || e.Detail != detail || e.Revision != int64(i+1) || !slices.Equal(e.Links, []wire.CardLink{o.equipoLink(request)}) { t.Fatalf("event %d (%s) %+v", i, key, e) } } if status, detail := jobWords(wire.JobReady); events[len(keys)].State != wire.JobReady || events[len(keys)].Result != status || events[len(keys)].Detail != detail { t.Fatalf("the go-ahead's event %+v", events[len(keys)]) } } // jobThroughStates hands a quick website to the team and takes its job // through every state the work can bring it to: ready with the go-ahead // (its first link the preview), working once it is given, ready again // with the Publish card, done once published (its first link the site); // and another job, cancelled with team_cancel, stopped. It returns the // first request, its task and the cancelled request. func (o *teamRig) jobThroughStates() (request, id, cancelled string) { t := o.t t.Helper() o.sitesOn(wire.ProtocolCurrent, true) o.ask("Build me a quick website, and Login is broken too") request, cmd := o.handoff("jt1", "Build me a quick website", "") job := o.jobCardID(request) base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) o.in(cmd.TurnID, func() { id, _ = o.websiteReady("jt", "Quick website", base, cand, true) }) pv := o.previewDispatch(cand) o.built("jt-pv-built", pv, digestA) link := "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone("jt-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) ready := o.jobOf(request, "ready to try", func(c wire.AssistantCard) bool { return c.State == wire.JobReady && len(c.Links) == 2 }) status, detail := jobWords(wire.JobReady) if ready.ID != job || ready.Result != status || ready.Detail != detail || !slices.Equal(ready.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: link}, o.equipoLink(request)}) { t.Fatalf("ready %+v", ready) } ahead := o.assistantCard("the go-ahead", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 }) if ahead.Job != job { t.Fatalf("the go-ahead's job %q, not %q", ahead.Job, job) } if _, err := o.a.Answer(o.ctx, ahead.ID, wire.ChoiceMerge, ahead.Revision); err != nil { t.Fatal(err) } working := o.jobOf(request, "working after the go-ahead", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking }) if status, detail := jobStatus("finishing"); working.Result != status || working.Detail != detail || !slices.Equal(working.Links, []wire.CardLink{o.equipoLink(request)}) { t.Fatalf("working %+v", working) } o.mergedStep("jt-m", o.dispatched(wire.SpecialistMerge, base, cand, 0), merged) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) publish := o.assistantCard("the Publish card", isPublishOutcome) if publish.Job != job { t.Fatalf("the Publish card's job %q, not %q", publish.Job, job) } if again := o.jobOf(request, "ready to publish", func(c wire.AssistantCard) bool { return c.State == wire.JobReady }); again.Result != status || again.Detail != detail { t.Fatalf("ready to publish %+v", again) } if _, err := o.a.Answer(o.ctx, publish.ID, wire.ChoicePublish, publish.Revision); err != nil { t.Fatal(err) } d := o.publishDispatch() if refused := o.lease(o.runner, "jt-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } o.publishReport("jt-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) if refused := o.lease(o.runner, "jt-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: d.Publish.Destination}); refused != "" { t.Fatalf("deploy refused %q", refused) } site := "https://" + d.Publish.App + ".bds.oncarlos.com/" o.publishReport("jt-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true}) done := o.jobOf(request, "done", func(c wire.AssistantCard) bool { return c.State == wire.JobDone }) status, detail = jobWords(wire.JobDone) if done.Result != status || done.Detail != detail || !slices.Equal(done.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.publish_site"), URL: site}, o.equipoLink(request)}) { t.Fatalf("done %+v", done) } // Another job, cancelled with team_cancel, is stopped. cancelled, _ = o.handoff("jt2", "Login is broken", "") if res := o.use("jt-cancel", "team_cancel", map[string]any{"request": cancelled}); res.IsError { t.Fatalf("cancel %+v", res) } stopped := o.jobOf(cancelled, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped }) status, detail = jobWords(wire.JobStopped) if stopped.Result != status || stopped.Detail != detail || !slices.Equal(stopped.Links, []wire.CardLink{o.equipoLink(cancelled)}) { t.Fatalf("stopped %+v", stopped) } return request, id, cancelled } // TestContractTeamJobStates: the job card is ready while a go-ahead or // Publish card of its job waits on the person (each of those names the // job card), working between them, done once published and stopped once // cancelled. A save that changes nothing about the job emits nothing. func TestContractTeamJobStates(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) request, id, _ := o.jobThroughStates() job := o.jobCardID(request) n := len(o.jobEvents(job)) if _, err := o.client.PostThread(o.ctx, id, "For the record.", "jt-note"); err != nil { t.Fatal(err) } time.Sleep(50 * time.Millisecond) if after := o.jobEvents(job); len(after) != n { t.Fatalf("a save that changed nothing: %d job card events, %d before", len(after), n) } } // TestContractTeamJobEventsWaitForTheAssistant (ruling P5j): the job card // says the job is asking or stopped only once the Assistant's team_update // turn about it has ended: read in order from the Assistant's events, // every event of the job card before that turn's end says working, and // one after it says asking (an open question) or stopped (a thread that // ended with no work; an access card). func TestContractTeamJobEventsWaitForTheAssistant(t *testing.T) { cases := []struct { name, want string run func(o *teamRig, cmd *wire.MessageCommand) }{ {"question", wire.JobAsking, func(o *teamRig, cmd *wire.MessageCommand) { o.in(cmd.TurnID, func() { if res := o.call("ew-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { o.t.Fatalf("ask %+v", res) } }) }}, {"no_work", wire.JobStopped, func(o *teamRig, cmd *wire.MessageCommand) { o.reply(cmd.TurnID) }}, {"access", wire.JobStopped, func(o *teamRig, cmd *wire.MessageCommand) { o.in(cmd.TurnID, func() { if res := o.call("ew-find", wire.ToolFind, map[string]string{"query": "moonbeam/app"}); res.Code != "none" { o.t.Fatalf("find %+v", res) } }) o.reply(cmd.TurnID) }}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("ew1", "Login is broken", "") job := o.jobOf(request, "the job card", nil).ID c.run(o, cmd) o.until("the team_update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 }) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { t.Fatalf("update frame %+v", u) } time.Sleep(20 * time.Millisecond) if now := o.jobOf(request, "the job card", nil); now.State != wire.JobWorking { t.Fatalf("while the Assistant's turn runs %+v", now) } o.reply(u.TurnID) o.jobOf(request, c.want, func(card wire.AssistantCard) bool { return card.State == c.want }) n := o.rows("SELECT count(*) FROM chat_events WHERE person = ? AND lane = ?", Owner, wire.LaneAssistant) s, err := o.a.Open(o.ctx, 0) if err != nil { t.Fatal(err) } defer s.Close() var events []wire.Event assistEvents(t, s, "every Assistant event", &events, func(es []wire.Event) bool { return len(es) >= n }) ended := slices.IndexFunc(events, func(e wire.Event) bool { var turn wire.Turn return e.Type == wire.EventTurn && e.ID == u.TurnID && json.Unmarshal(e.Data, &turn) == nil && wire.Terminal(turn.State) }) if ended < 0 { t.Fatal("no event ends the team_update turn") } after := false for i, e := range events { if e.Type != wire.EventCard || e.ID != job { continue } var card wire.AssistantCard if err := json.Unmarshal(e.Data, &card); err != nil { t.Fatal(err) } if i < ended && card.State != wire.JobWorking { t.Fatalf("event %d, before the turn ended (%d), says %s", i, ended, card.State) } after = after || i > ended && card.State == c.want } if !after { t.Fatalf("no %s event after the turn ended", c.want) } }) } } // TestContractTeamJobLegacy: a hand-off made before job cards gets one // on its next change, named for its words, with no link into Equipo (it // has no thread there). func TestContractTeamJobLegacy(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, turn := o.legacyHandoff("jl", "Login is broken") if o.jobCardID(request) != "" { t.Fatal("a job card before the legacy hand-off changed") } o.in(turn, func() { o.record("jl-rec", "Fix the login") }) o.reply(turn) card := o.jobOf(request, "the legacy job card", nil) status, detail := jobStatus("starting") if card.Kind != wire.CardJob || card.State != wire.JobWorking || card.Question != "Login is broken" || card.Result != status || card.Detail != detail || card.Links == nil || len(card.Links) != 0 || card.StartedAt == nil { t.Fatalf("legacy job card %+v", card) } } // TestContractTeamJobLeaksNoMachinery: through every state, the job // cards and their events carry nothing of the team's machinery: no task // id (but in a preview's host, R9), repository, branch, SHA, /tasks/ or // team key; each card has exactly its keys. func TestContractTeamJobLeaksNoMachinery(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) request, id, cancelled := o.jobThroughStates() k, err := o.client.Task(o.ctx, id) if err != nil || k.Branch == "" { t.Fatalf("task %+v %v", k, err) } check := noMachinery(t, id, []string{"amadan.net/oficina/sample", "oficina/sample", k.Branch, "/tasks/"}) jobs := []string{o.jobCardID(request), o.jobCardID(cancelled)} n := o.rows("SELECT count(*) FROM chat_events WHERE person = ? AND lane = ?", Owner, wire.LaneAssistant) s, err := o.a.Open(o.ctx, 0) if err != nil { t.Fatal(err) } defer s.Close() var events []wire.Event assistEvents(t, s, "every Assistant event", &events, func(es []wire.Event) bool { return len(es) >= n }) states := map[string]bool{} for _, e := range events { if e.Type != wire.EventCard || !slices.Contains(jobs, e.ID) { continue } b, _ := json.Marshal(e) var v, card any if json.Unmarshal(b, &v) != nil || json.Unmarshal(e.Data, &card) != nil { t.Fatalf("event %s", b) } check("a job card event", v, false) cardKeys(t, "a job card event", card) states[card.(map[string]any)["state"].(string)] = true } for _, want := range []string{wire.JobWorking, wire.JobReady, wire.JobDone, wire.JobStopped} { if !states[want] { t.Fatalf("no %s job card event among %v", want, states) } } code, _, snap := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "") var sv map[string]any if code != http.StatusOK || json.Unmarshal(snap, &sv) != nil { t.Fatalf("snapshot %d %s", code, snap) } seen := 0 for _, c := range sv["cards"].([]any) { if c.(map[string]any)["kind"] == wire.CardJob { seen++ check("a job card", c, false) cardKeys(t, "a job card", c) } } if seen != 2 { t.Fatalf("%d job cards in the snapshot", seen) } } // TestContractTeamJobGoingLiveFailed (ruling R19): a Publish asked // again because going live failed is ready to try (D5), as any open // Publish is. Once the person says Not now to it, the failed go-live // reads stopped, after the Assistant's turn about it ends. func TestContractTeamJobGoingLiveFailed(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) id, _, _, _ := o.mergedWebsite("jf", true) request := o.requestOf(id) var ships string var revision int64 if err := o.inst.DB.Writer().QueryRow("SELECT id, revision FROM chat_cards WHERE kind = ? AND state = ?", wire.CardMergeShips, wire.CardOpen).Scan(&ships, &revision); err != nil { t.Fatal(err) } if _, err := o.client.Answer(o.ctx, ships, wire.ChoiceNotShips, revision); err != nil { t.Fatal(err) } card := o.assistantCard("the publish outcome", isPublishOutcome) if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil { t.Fatal(err) } o.publishReport("jf-failed", o.publishDispatch(), wire.StepFailed, nil) o.until("the Publish asked again", func() bool { cards := o.coordinatorCards(wire.CardPublish, id) return len(cards) == 2 && cards[1].State == wire.CardOpen }) o.noteFor("the publish failure's note", blockedOn("going live failed, and they need to try it again")) again := o.assistantCard("the Publish asked again", func(c wire.AssistantCard) bool { return isPublishOutcome(c) && c.ID != card.ID && c.State == wire.CardOpen }) if now := o.jobOf(request, "ready after going live failed", func(c wire.AssistantCard) bool { return c.State == wire.JobReady }); now.Result != equipo.RunnerCopy("assistant.job.ready") { t.Fatalf("after going live failed %+v", now) } if _, err := o.a.Answer(o.ctx, again.ID, wire.ChoiceNotNow, again.Revision); err != nil { t.Fatal(err) } time.Sleep(20 * time.Millisecond) if now := o.jobOf(request, "the job card", nil); now.State != wire.JobWorking { t.Fatalf("after Not now, while the Assistant's turn waits %+v", now) } o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { t.Fatalf("update frame %+v", u) } o.reply(u.TurnID) o.jobOf(request, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped }) } // TestContractTeamJobNotPublished: "Not now" on the Publish card leaves // the merged work done, with no site to open: the job card follows the // answer itself. func TestContractTeamJobNotPublished(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) id, _, _, _ := o.mergedWebsite("jn", true) request := o.requestOf(id) card := o.assistantCard("the publish outcome", isPublishOutcome) o.jobOf(request, "ready to publish", func(c wire.AssistantCard) bool { return c.State == wire.JobReady }) if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceNotNow, card.Revision); err != nil { t.Fatal(err) } done := o.jobOf(request, "done", func(c wire.AssistantCard) bool { return c.State == wire.JobDone }) if status, detail := jobWords(wire.JobDone); done.Result != status || done.Detail != detail || !slices.Equal(done.Links, []wire.CardLink{o.equipoLink(request)}) { t.Fatalf("done %+v", done) } }