oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "fmt"
8 "html"
9 "net/http"
10 "net/url"
11 "slices"
12 "strconv"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/equipo"
18 "amadan.net/oficina/equipo/internal/equipo/personapi"
19 "amadan.net/oficina/equipo/internal/wire"
20)
21
22// Job threads in Equipo's pages (jobs design, J6): /jobs lists the
23// person's job threads under "From Base", /jobs/{id} shows one with the
24// conversation page's template and a reply field, and /conversation
25// links there once the person has one.
26
27// jobThread is the request's thread as JobThread reads it for the owner.
28func (o *teamRig) jobThread(request string) wire.Snapshot {
29 o.t.Helper()
30 ctx := personapi.WithVerifiedPrincipal(context.Background(), personapi.PersonPrincipal{Address: Owner, SessionEpoch: time.Now().Unix()})
31 snap, err := o.inst.Store.Chat().JobThread(ctx, Owner, request)
32 if err != nil {
33 o.t.Fatalf("job thread %s: %v", request, err)
34 }
35 return snap
36}
37
38// jobCard is the card of kind on the task in the request's thread, as
39// JobThread reads it.
40func (o *teamRig) jobCard(request, kind, task string) wire.Card {
41 o.t.Helper()
42 for _, c := range o.jobThread(request).Cards {
43 if c.Kind == kind && c.TaskID == task {
44 return c
45 }
46 }
47 return wire.Card{}
48}
49
50// TestContractTeamJobThreadPage: signed in as the hand-off's person,
51// /jobs lists it and /jobs/<request> shows the person's words, the
52// thread's reply and its card; a reply posted there is the thread's next
53// message, dispatched in its lane and audited by id. Another member sees
54// an empty list and gets 404 for the thread and its reply; a legacy
55// hand-off has no thread. /conversation links to /jobs only once the
56// person has a job.
57func TestContractTeamJobThreadPage(t *testing.T) {
58 o := newTeamRig(t)
59 owner := o.inst.Cookie()
60 if page := o.get(owner, "/conversation", http.StatusOK); strings.Contains(page, `href="/jobs"`) {
61 t.Fatal("/conversation links to /jobs before any job")
62 }
63 if page := o.get(owner, "/jobs", http.StatusOK); !strings.Contains(page, `data-empty-state="jobs.empty"`) {
64 t.Fatalf("/jobs with no job: %.300s", page)
65 }
66 o.ask("Can we fix a bug in Tito? Login is broken")
67 request, cmd := o.handoff("jp1", "Login is broken", "")
68 lane := wire.JobLane(request)
69 o.in(cmd.TurnID, func() {
70 if res := o.call("jp-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page is it?", "options": []string{"Web", "App"}}); res.Code != "asked" {
71 t.Fatalf("ask %+v", res)
72 }
73 })
74 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 {
75 t.Fatal(err)
76 }
77 o.until("the thread's reply", func() bool { return o.turnState(cmd.TurnID) == wire.TurnReplied })
78 card, _ := o.threadQuestion(request)
79
80 list := o.get(owner, "/jobs", http.StatusOK)
81 if !strings.Contains(list, `href="/jobs/`+request+`"`) || !strings.Contains(list, "Login is broken") || strings.Contains(list, `data-empty-state="jobs.empty"`) {
82 t.Fatalf("/jobs %.600s", list)
83 }
84 if page := o.get(owner, "/conversation", http.StatusOK); !strings.Contains(page, `href="/jobs"`) {
85 t.Fatal("/conversation has no From Base link once the person has a job")
86 }
87 page := html.UnescapeString(o.get(owner, "/jobs/"+request, http.StatusOK))
88 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"`} {
89 if !strings.Contains(page, want) {
90 t.Fatalf("/jobs/%s lacks %q", request, want)
91 }
92 }
93 if strings.Contains(page, "data-chat-stream") {
94 t.Fatal("the thread page follows the person's own conversation stream")
95 }
96
97 // A reply posted on the thread page is the thread's next message.
98 status, loc := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"It is the web one."}, "request_id": {"jp-reply-1"}})
99 if status != http.StatusSeeOther || loc != "/jobs/"+request {
100 t.Fatalf("reply: %d %q", status, loc)
101 }
102 var id, turn string
103 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 {
104 t.Fatalf("the reply is not in the thread: %v", err)
105 }
106 if next := o.message(lane); next.TurnID != turn || !slices.Equal(next.PersonText, []string{"It is the web one."}) {
107 t.Fatalf("the reply's frame %+v", next)
108 }
109 if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = ? AND record_id = ? AND actor = ?", "job.send", id, Owner); n != 1 {
110 t.Fatalf("%d job.send audits for the reply", n)
111 }
112 // The same request again is the same message.
113 if status, _ := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"It is the web one."}, "request_id": {"jp-reply-1"}}); status != http.StatusSeeOther {
114 t.Fatalf("repeat: %d", status)
115 }
116 if n := o.rows("SELECT count(*) FROM chat_messages WHERE lane = ? AND text = ?", lane, "It is the web one."); n != 1 {
117 t.Fatalf("%d copies of the reply", n)
118 }
119 if n := o.rows("SELECT count(*) FROM chat_messages WHERE coalesce(lane, '') = '' AND text = ?", "It is the web one."); n != 0 {
120 t.Fatal("the reply reached their own conversation")
121 }
122
123 // Another member has no jobs and cannot read or reply to this one.
124 mate := o.memberCookie()
125 if page := o.get(mate, "/jobs", http.StatusOK); strings.Contains(page, request) || !strings.Contains(page, `data-empty-state="jobs.empty"`) {
126 t.Fatalf("another member's /jobs %.300s", page)
127 }
128 o.get(mate, "/jobs/"+request, http.StatusNotFound)
129 if status, _ := o.post(mate, "/jobs/"+request+"/messages", url.Values{"body": {"Mine now."}, "request_id": {"jp-mate"}}); status != http.StatusNotFound {
130 t.Fatalf("another member's reply: %d", status)
131 }
132 if n := o.rows("SELECT count(*) FROM chat_messages WHERE text = ?", "Mine now."); n != 0 {
133 t.Fatal("another member's reply was stored")
134 }
135
136 // A legacy hand-off and an unknown id have no thread.
137 legacy, _ := o.legacyHandoff("jp", "Checkout is slow")
138 o.get(owner, "/jobs/"+legacy, http.StatusNotFound)
139 o.get(owner, "/jobs/h_unknown", http.StatusNotFound)
140 if list := o.get(owner, "/jobs", http.StatusOK); strings.Contains(list, legacy) || strings.Contains(list, "Checkout is slow") {
141 t.Fatal("/jobs lists a legacy hand-off")
142 }
143
144 // A primary back below protocol 22 cannot carry the thread: a new
145 // reply is refused and stored nowhere; one already sent answers as it
146 // did.
147 o.runner.Close()
148 o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online })
149 o.dialAt(wire.Protocol21)
150 if status, _ := o.post(owner, "/jobs/"+request+"/messages", url.Values{"body": {"Any news?"}, "request_id": {"jp-old"}}); status != http.StatusConflict {
151 t.Fatalf("a reply at 21: %d", status)
152 }
153 if n := o.rows("SELECT count(*) FROM chat_messages WHERE text = ?", "Any news?"); n != 0 {
154 t.Fatal("a reply at 21 was stored")
155 }
156 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 {
157 t.Fatalf("the sent reply again at 21: %d %q", status, loc)
158 }
159}
160
161// TestContractTeamJobThreadAnswer: a question card answered from the
162// thread page is answered in the job's lane: the answer is the thread's
163// next message, dispatched there, and the page returns to the thread.
164func TestContractTeamJobThreadAnswer(t *testing.T) {
165 o := newTeamRig(t)
166 owner := o.inst.Cookie()
167 o.ask("Can we fix a bug in Tito? Login is broken")
168 request, cmd := o.handoff("ja1", "Login is broken", "")
169 lane := wire.JobLane(request)
170 o.in(cmd.TurnID, func() {
171 if res := o.call("ja-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page is it?", "options": []string{"Web", "App"}}); res.Code != "asked" {
172 t.Fatalf("ask %+v", res)
173 }
174 })
175 o.reply(cmd.TurnID)
176 card, revision := o.threadQuestion(request)
177 page := o.get(owner, "/jobs/"+request, http.StatusOK)
178 form := `action="/conversation/cards/` + card + `/answer"`
179 if !strings.Contains(page, form) || !strings.Contains(page, `name="job" value="`+request+`"`) {
180 t.Fatalf("the thread's card form: %.2000s", page)
181 }
182 status, loc := o.post(owner, "/conversation/cards/"+card+"/answer", url.Values{"revision": {strconv.FormatInt(revision, 10)}, "choice": {"Web"}, "from": {"job"}, "job": {request}})
183 if status != http.StatusSeeOther || loc != "/jobs/"+request+"#conversation-end" {
184 t.Fatalf("answer: %d %q", status, loc)
185 }
186 var id, turn string
187 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 {
188 t.Fatalf("the card is not answered: %v", err)
189 }
190 if o.laneOf(turn) != lane || o.rows("SELECT count(*) FROM chat_messages WHERE id = ? AND lane = ?", id, lane) != 1 {
191 t.Fatal("the answer is not in the thread")
192 }
193 if next := o.message(lane); next.TurnID != turn || len(next.PersonText) != 0 {
194 t.Fatalf("the answer's frame %+v", next)
195 }
196 // A job id that is not one returns to the conversation.
197 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" {
198 t.Fatalf("a bad job id: %d %q", status, loc)
199 }
200}
201
202// The job card (jobs design §3; D1 to D5): one Assistant card per
203// hand-off, kind job, its question the job's title, its result the short
204// status and its detail one sentence more, rewritten in place as the
205// work moves. Nobody answers it.
206
207// jobCardID is the request's job card ("" while it has none).
208func (o *teamRig) jobCardID(request string) string {
209 o.t.Helper()
210 var id string
211 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)
212 if err != nil && err != sql.ErrNoRows {
213 o.t.Fatal(err)
214 }
215 return id
216}
217
218// jobOf waits for the request's job card, as the Assistant snapshot
219// shows it, to match (any, with match nil).
220func (o *teamRig) jobOf(request, what string, match func(wire.AssistantCard) bool) wire.AssistantCard {
221 o.t.Helper()
222 var out wire.AssistantCard
223 o.until(what, func() bool {
224 id := o.jobCardID(request)
225 if id == "" {
226 return false
227 }
228 snap, err := o.a.Snapshot(o.ctx)
229 if err != nil {
230 o.t.Fatal(err)
231 }
232 for _, c := range snap.Cards {
233 if c.ID == id && (match == nil || match(c)) {
234 out = c
235 return true
236 }
237 }
238 return false
239 })
240 return out
241}
242
243// jobEvents are the card's events in the Assistant lane, oldest first,
244// as stored: the card each carried.
245func (o *teamRig) jobEvents(card string) []wire.AssistantCard {
246 o.t.Helper()
247 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)
248 if err != nil {
249 o.t.Fatal(err)
250 }
251 defer rows.Close()
252 var out []wire.AssistantCard
253 for rows.Next() {
254 var body string
255 if err := rows.Scan(&body); err != nil {
256 o.t.Fatal(err)
257 }
258 var e wire.Event
259 var c wire.AssistantCard
260 if err := json.Unmarshal([]byte(body), &e); err != nil {
261 o.t.Fatal(err)
262 }
263 if e.ID != card {
264 continue
265 }
266 if err := json.Unmarshal(e.Data, &c); err != nil {
267 o.t.Fatal(err)
268 }
269 out = append(out, c)
270 }
271 if err := rows.Err(); err != nil {
272 o.t.Fatal(err)
273 }
274 return out
275}
276
277// jobStatus is a working job's status and detail for a stage key.
278func jobStatus(key string) (string, string) {
279 return equipo.RunnerCopy("assistant.job.status." + key), equipo.RunnerCopy("assistant.job.detail." + key)
280}
281
282// jobWords is the status and detail of a job in state (not working).
283func jobWords(state string) (string, string) {
284 return equipo.RunnerCopy("assistant.job." + state), equipo.RunnerCopy("assistant.job.detail." + state)
285}
286
287// equipoLink is a job card's link to its thread in Equipo.
288func (o *teamRig) equipoLink(request string) wire.CardLink {
289 return wire.CardLink{Label: equipo.RunnerCopy("assistant.job.open"), URL: o.inst.URL + "/jobs/" + request, Rel: wire.LinkEquipo}
290}
291
292// TestContractTeamJobCard: team_request raises one job card in the
293// Assistant lane: the job's title as its question, no options, "Getting
294// started" and its detail, started when the hand-off was made, and one
295// link, to the job's thread in Equipo. The same request under a new
296// call id is the same card; nobody answers it; /jobs shows its status
297// beside its title.
298func TestContractTeamJobCard(t *testing.T) {
299 o := newTeamRig(t)
300 o.ask("Build me a quick website")
301 in := map[string]any{"words": "Build me a quick website", "title": "Building your website"}
302 request := o.request("jc1", in)
303 o.message(wire.JobLane(request))
304 card := o.jobOf(request, "the job card", nil)
305 var created time.Time
306 if err := o.inst.DB.Writer().QueryRow("SELECT created_at FROM chat_handoffs WHERE id = ?", request).Scan(&created); err != nil {
307 t.Fatal(err)
308 }
309 status, detail := jobStatus("starting")
310 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 {
311 t.Fatalf("job card %+v (hand-off made %v)", card, created)
312 }
313 if !slices.Equal(card.Links, []wire.CardLink{o.equipoLink(request)}) {
314 t.Fatalf("job card links %+v", card.Links)
315 }
316 // As Base reads it: an empty list of options, and the link's rel.
317 code, _, snap := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "")
318 want := `"options":[],"links":[{"label":"` + equipo.RunnerCopy("assistant.job.open") + `","url":"` + o.inst.URL + "/jobs/" + request + `","rel":"equipo"}]`
319 if code != http.StatusOK || !strings.Contains(string(snap), want) {
320 t.Fatalf("snapshot %d %s", code, snap)
321 }
322 // The same request under a new call id is the same job.
323 if again := o.request("jc2", in); again != request {
324 t.Fatalf("again %s, first %s", again, request)
325 }
326 if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ?", wire.CardJob); n != 1 {
327 t.Fatalf("%d job cards", n)
328 }
329 if events := o.jobEvents(card.ID); len(events) != 1 {
330 t.Fatalf("job card events %+v", events)
331 }
332 // Nobody answers a job card.
333 if _, err := o.a.Answer(o.ctx, card.ID, status, card.Revision); Status(err) != http.StatusNotFound {
334 t.Fatalf("an answer to the job card: %v", err)
335 }
336 // /jobs shows its status beside its title.
337 list := html.UnescapeString(o.get(o.inst.Cookie(), "/jobs", http.StatusOK))
338 if !strings.Contains(list, "Building your website") || !strings.Contains(list, `data-job-status>`+status+`<`) {
339 t.Fatalf("/jobs %.800s", list)
340 }
341}
342
343// TestContractTeamJobStatuses: while the job works, its status follows
344// its task: noted, investigated, in progress, in review and ready to
345// merge, one card event each, each with its detail; then the go-ahead
346// makes it ready.
347func TestContractTeamJobStatuses(t *testing.T) {
348 o := newTeamRig(t)
349 o.sitesOn(wire.ProtocolAssistant, false)
350 o.shipsNo(o.project())
351 o.ask("Can we fix a bug in Tito? Login is broken")
352 request, cmd := o.handoff("js1", "Login is broken", "")
353 job := o.jobOf(request, "the job card", nil).ID
354 stage := func(id, want string) {
355 t.Helper()
356 o.wait(want, func(c *Conversation) bool { return c.Tasks[id].Stage == want })
357 }
358 shown := func(n int) {
359 t.Helper()
360 o.until(fmt.Sprintf("%d job card events", n), func() bool { return len(o.jobEvents(job)) >= n })
361 }
362 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
363 var id string
364 o.in(cmd.TurnID, func() {
365 id = o.record("js-rec", "Fix the login")
366 stage(id, wire.StageNoted)
367 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 {
368 t.Fatalf("finding %+v", res)
369 }
370 stage(id, wire.StageInvestigated)
371 shown(2)
372 if res := o.call("js-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
373 t.Fatalf("start %+v", res)
374 }
375 _, body := o.expect(wire.FrameDispatch)
376 d := body.(*wire.DispatchCommand)
377 o.step("js-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
378 stage(id, wire.StageInProgress)
379 shown(3)
380 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"})
381 o.expect(wire.FrameWatchMerge)
382 c := o.dispatched(wire.SpecialistChecks, base, cand, 0)
383 stage(id, wire.StageInReview)
384 shown(4)
385 o.checks("js-c", c, wire.ChecksNone, nil, "", "")
386 o.verdict("js-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove)
387 })
388 o.assistantCard("the go-ahead", isMergeOutcome)
389 o.jobOf(request, "ready", func(c wire.AssistantCard) bool { return c.State == wire.JobReady })
390 events := o.jobEvents(job)
391 keys := []string{"starting", "planning", "building", "checking", "finishing"}
392 if len(events) != len(keys)+1 {
393 t.Fatalf("job card events %+v", events)
394 }
395 for i, key := range keys {
396 status, detail := jobStatus(key)
397 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)}) {
398 t.Fatalf("event %d (%s) %+v", i, key, e)
399 }
400 }
401 if status, detail := jobWords(wire.JobReady); events[len(keys)].State != wire.JobReady || events[len(keys)].Result != status || events[len(keys)].Detail != detail {
402 t.Fatalf("the go-ahead's event %+v", events[len(keys)])
403 }
404}
405
406// jobThroughStates hands a quick website to the team and takes its job
407// through every state the work can bring it to: ready with the go-ahead
408// (its first link the preview), working once it is given, ready again
409// with the Publish card, done once published (its first link the site);
410// and another job, cancelled with team_cancel, stopped. It returns the
411// first request, its task and the cancelled request.
412func (o *teamRig) jobThroughStates() (request, id, cancelled string) {
413 t := o.t
414 t.Helper()
415 o.sitesOn(wire.ProtocolCurrent, true)
416 o.ask("Build me a quick website, and Login is broken too")
417 request, cmd := o.handoff("jt1", "Build me a quick website", "")
418 job := o.jobCardID(request)
419 base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
420 o.in(cmd.TurnID, func() { id, _ = o.websiteReady("jt", "Quick website", base, cand, true) })
421 pv := o.previewDispatch(cand)
422 o.built("jt-pv-built", pv, digestA)
423 link := "https://eq-" + id + ".docs-t1.example.ts.net/"
424 o.previewDone("jt-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed})
425 ready := o.jobOf(request, "ready to try", func(c wire.AssistantCard) bool { return c.State == wire.JobReady && len(c.Links) == 2 })
426 status, detail := jobWords(wire.JobReady)
427 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)}) {
428 t.Fatalf("ready %+v", ready)
429 }
430 ahead := o.assistantCard("the go-ahead", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 })
431 if ahead.Job != job {
432 t.Fatalf("the go-ahead's job %q, not %q", ahead.Job, job)
433 }
434 if _, err := o.a.Answer(o.ctx, ahead.ID, wire.ChoiceMerge, ahead.Revision); err != nil {
435 t.Fatal(err)
436 }
437 working := o.jobOf(request, "working after the go-ahead", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking })
438 if status, detail := jobStatus("finishing"); working.Result != status || working.Detail != detail || !slices.Equal(working.Links, []wire.CardLink{o.equipoLink(request)}) {
439 t.Fatalf("working %+v", working)
440 }
441 o.mergedStep("jt-m", o.dispatched(wire.SpecialistMerge, base, cand, 0), merged)
442 o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
443 publish := o.assistantCard("the Publish card", isPublishOutcome)
444 if publish.Job != job {
445 t.Fatalf("the Publish card's job %q, not %q", publish.Job, job)
446 }
447 if again := o.jobOf(request, "ready to publish", func(c wire.AssistantCard) bool { return c.State == wire.JobReady }); again.Result != status || again.Detail != detail {
448 t.Fatalf("ready to publish %+v", again)
449 }
450 if _, err := o.a.Answer(o.ctx, publish.ID, wire.ChoicePublish, publish.Revision); err != nil {
451 t.Fatal(err)
452 }
453 d := o.publishDispatch()
454 if refused := o.lease(o.runner, "jt-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" {
455 t.Fatalf("start refused %q", refused)
456 }
457 o.publishReport("jt-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
458 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 != "" {
459 t.Fatalf("deploy refused %q", refused)
460 }
461 site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
462 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})
463 done := o.jobOf(request, "done", func(c wire.AssistantCard) bool { return c.State == wire.JobDone })
464 status, detail = jobWords(wire.JobDone)
465 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)}) {
466 t.Fatalf("done %+v", done)
467 }
468
469 // Another job, cancelled with team_cancel, is stopped.
470 cancelled, _ = o.handoff("jt2", "Login is broken", "")
471 if res := o.use("jt-cancel", "team_cancel", map[string]any{"request": cancelled}); res.IsError {
472 t.Fatalf("cancel %+v", res)
473 }
474 stopped := o.jobOf(cancelled, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped })
475 status, detail = jobWords(wire.JobStopped)
476 if stopped.Result != status || stopped.Detail != detail || !slices.Equal(stopped.Links, []wire.CardLink{o.equipoLink(cancelled)}) {
477 t.Fatalf("stopped %+v", stopped)
478 }
479 return request, id, cancelled
480}
481
482// TestContractTeamJobStates: the job card is ready while a go-ahead or
483// Publish card of its job waits on the person (each of those names the
484// job card), working between them, done once published and stopped once
485// cancelled. A save that changes nothing about the job emits nothing.
486func TestContractTeamJobStates(t *testing.T) {
487 o := newTeamRigAt(t, wire.ProtocolCurrent)
488 request, id, _ := o.jobThroughStates()
489 job := o.jobCardID(request)
490 n := len(o.jobEvents(job))
491 if _, err := o.client.PostThread(o.ctx, id, "For the record.", "jt-note"); err != nil {
492 t.Fatal(err)
493 }
494 time.Sleep(50 * time.Millisecond)
495 if after := o.jobEvents(job); len(after) != n {
496 t.Fatalf("a save that changed nothing: %d job card events, %d before", len(after), n)
497 }
498}
499
500// TestContractTeamJobEventsWaitForTheAssistant (ruling P5j): the job card
501// says the job is asking or stopped only once the Assistant's team_update
502// turn about it has ended: read in order from the Assistant's events,
503// every event of the job card before that turn's end says working, and
504// one after it says asking (an open question) or stopped (a thread that
505// ended with no work; an access card).
506func TestContractTeamJobEventsWaitForTheAssistant(t *testing.T) {
507 cases := []struct {
508 name, want string
509 run func(o *teamRig, cmd *wire.MessageCommand)
510 }{
511 {"question", wire.JobAsking, func(o *teamRig, cmd *wire.MessageCommand) {
512 o.in(cmd.TurnID, func() {
513 if res := o.call("ew-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
514 o.t.Fatalf("ask %+v", res)
515 }
516 })
517 }},
518 {"no_work", wire.JobStopped, func(o *teamRig, cmd *wire.MessageCommand) { o.reply(cmd.TurnID) }},
519 {"access", wire.JobStopped, func(o *teamRig, cmd *wire.MessageCommand) {
520 o.in(cmd.TurnID, func() {
521 if res := o.call("ew-find", wire.ToolFind, map[string]string{"query": "moonbeam/app"}); res.Code != "none" {
522 o.t.Fatalf("find %+v", res)
523 }
524 })
525 o.reply(cmd.TurnID)
526 }},
527 }
528 for _, c := range cases {
529 t.Run(c.name, func(t *testing.T) {
530 o := newTeamRig(t)
531 o.ask("Can we fix a bug in Tito? Login is broken")
532 request, cmd := o.handoff("ew1", "Login is broken", "")
533 job := o.jobOf(request, "the job card", nil).ID
534 c.run(o, cmd)
535 o.until("the team_update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 })
536 o.reply(o.turn)
537 u := o.message(wire.LaneAssistant)
538 if u.Kind != wire.TurnTeamUpdate {
539 t.Fatalf("update frame %+v", u)
540 }
541 time.Sleep(20 * time.Millisecond)
542 if now := o.jobOf(request, "the job card", nil); now.State != wire.JobWorking {
543 t.Fatalf("while the Assistant's turn runs %+v", now)
544 }
545 o.reply(u.TurnID)
546 o.jobOf(request, c.want, func(card wire.AssistantCard) bool { return card.State == c.want })
547
548 n := o.rows("SELECT count(*) FROM chat_events WHERE person = ? AND lane = ?", Owner, wire.LaneAssistant)
549 s, err := o.a.Open(o.ctx, 0)
550 if err != nil {
551 t.Fatal(err)
552 }
553 defer s.Close()
554 var events []wire.Event
555 assistEvents(t, s, "every Assistant event", &events, func(es []wire.Event) bool { return len(es) >= n })
556 ended := slices.IndexFunc(events, func(e wire.Event) bool {
557 var turn wire.Turn
558 return e.Type == wire.EventTurn && e.ID == u.TurnID && json.Unmarshal(e.Data, &turn) == nil && wire.Terminal(turn.State)
559 })
560 if ended < 0 {
561 t.Fatal("no event ends the team_update turn")
562 }
563 after := false
564 for i, e := range events {
565 if e.Type != wire.EventCard || e.ID != job {
566 continue
567 }
568 var card wire.AssistantCard
569 if err := json.Unmarshal(e.Data, &card); err != nil {
570 t.Fatal(err)
571 }
572 if i < ended && card.State != wire.JobWorking {
573 t.Fatalf("event %d, before the turn ended (%d), says %s", i, ended, card.State)
574 }
575 after = after || i > ended && card.State == c.want
576 }
577 if !after {
578 t.Fatalf("no %s event after the turn ended", c.want)
579 }
580 })
581 }
582}
583
584// TestContractTeamJobLegacy: a hand-off made before job cards gets one
585// on its next change, named for its words, with no link into Equipo (it
586// has no thread there).
587func TestContractTeamJobLegacy(t *testing.T) {
588 o := newTeamRig(t)
589 o.ask("Can we fix a bug in Tito? Login is broken")
590 request, turn := o.legacyHandoff("jl", "Login is broken")
591 if o.jobCardID(request) != "" {
592 t.Fatal("a job card before the legacy hand-off changed")
593 }
594 o.in(turn, func() { o.record("jl-rec", "Fix the login") })
595 o.reply(turn)
596 card := o.jobOf(request, "the legacy job card", nil)
597 status, detail := jobStatus("starting")
598 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 {
599 t.Fatalf("legacy job card %+v", card)
600 }
601}
602
603// TestContractTeamJobLeaksNoMachinery: through every state, the job
604// cards and their events carry nothing of the team's machinery: no task
605// id (but in a preview's host, R9), repository, branch, SHA, /tasks/ or
606// team key; each card has exactly its keys.
607func TestContractTeamJobLeaksNoMachinery(t *testing.T) {
608 o := newTeamRigAt(t, wire.ProtocolCurrent)
609 request, id, cancelled := o.jobThroughStates()
610 k, err := o.client.Task(o.ctx, id)
611 if err != nil || k.Branch == "" {
612 t.Fatalf("task %+v %v", k, err)
613 }
614 check := noMachinery(t, id, []string{"amadan.net/oficina/sample", "oficina/sample", k.Branch, "/tasks/"})
615 jobs := []string{o.jobCardID(request), o.jobCardID(cancelled)}
616 n := o.rows("SELECT count(*) FROM chat_events WHERE person = ? AND lane = ?", Owner, wire.LaneAssistant)
617 s, err := o.a.Open(o.ctx, 0)
618 if err != nil {
619 t.Fatal(err)
620 }
621 defer s.Close()
622 var events []wire.Event
623 assistEvents(t, s, "every Assistant event", &events, func(es []wire.Event) bool { return len(es) >= n })
624 states := map[string]bool{}
625 for _, e := range events {
626 if e.Type != wire.EventCard || !slices.Contains(jobs, e.ID) {
627 continue
628 }
629 b, _ := json.Marshal(e)
630 var v, card any
631 if json.Unmarshal(b, &v) != nil || json.Unmarshal(e.Data, &card) != nil {
632 t.Fatalf("event %s", b)
633 }
634 check("a job card event", v, false)
635 cardKeys(t, "a job card event", card)
636 states[card.(map[string]any)["state"].(string)] = true
637 }
638 for _, want := range []string{wire.JobWorking, wire.JobReady, wire.JobDone, wire.JobStopped} {
639 if !states[want] {
640 t.Fatalf("no %s job card event among %v", want, states)
641 }
642 }
643 code, _, snap := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "")
644 var sv map[string]any
645 if code != http.StatusOK || json.Unmarshal(snap, &sv) != nil {
646 t.Fatalf("snapshot %d %s", code, snap)
647 }
648 seen := 0
649 for _, c := range sv["cards"].([]any) {
650 if c.(map[string]any)["kind"] == wire.CardJob {
651 seen++
652 check("a job card", c, false)
653 cardKeys(t, "a job card", c)
654 }
655 }
656 if seen != 2 {
657 t.Fatalf("%d job cards in the snapshot", seen)
658 }
659}
660
661// TestContractTeamJobGoingLiveFailed (ruling R19): a Publish asked
662// again because going live failed is ready to try (D5), as any open
663// Publish is. Once the person says Not now to it, the failed go-live
664// reads stopped, after the Assistant's turn about it ends.
665func TestContractTeamJobGoingLiveFailed(t *testing.T) {
666 o := newTeamRigAt(t, wire.ProtocolCurrent)
667 id, _, _, _ := o.mergedWebsite("jf", true)
668 request := o.requestOf(id)
669 var ships string
670 var revision int64
671 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 {
672 t.Fatal(err)
673 }
674 if _, err := o.client.Answer(o.ctx, ships, wire.ChoiceNotShips, revision); err != nil {
675 t.Fatal(err)
676 }
677 card := o.assistantCard("the publish outcome", isPublishOutcome)
678 if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil {
679 t.Fatal(err)
680 }
681 o.publishReport("jf-failed", o.publishDispatch(), wire.StepFailed, nil)
682 o.until("the Publish asked again", func() bool {
683 cards := o.coordinatorCards(wire.CardPublish, id)
684 return len(cards) == 2 && cards[1].State == wire.CardOpen
685 })
686 o.noteFor("the publish failure's note", blockedOn("going live failed, and they need to try it again"))
687 again := o.assistantCard("the Publish asked again", func(c wire.AssistantCard) bool {
688 return isPublishOutcome(c) && c.ID != card.ID && c.State == wire.CardOpen
689 })
690 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") {
691 t.Fatalf("after going live failed %+v", now)
692 }
693 if _, err := o.a.Answer(o.ctx, again.ID, wire.ChoiceNotNow, again.Revision); err != nil {
694 t.Fatal(err)
695 }
696 time.Sleep(20 * time.Millisecond)
697 if now := o.jobOf(request, "the job card", nil); now.State != wire.JobWorking {
698 t.Fatalf("after Not now, while the Assistant's turn waits %+v", now)
699 }
700 o.reply(o.turn)
701 u := o.message(wire.LaneAssistant)
702 if u.Kind != wire.TurnTeamUpdate {
703 t.Fatalf("update frame %+v", u)
704 }
705 o.reply(u.TurnID)
706 o.jobOf(request, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped })
707}
708
709// TestContractTeamJobNotPublished: "Not now" on the Publish card leaves
710// the merged work done, with no site to open: the job card follows the
711// answer itself.
712func TestContractTeamJobNotPublished(t *testing.T) {
713 o := newTeamRigAt(t, wire.ProtocolCurrent)
714 id, _, _, _ := o.mergedWebsite("jn", true)
715 request := o.requestOf(id)
716 card := o.assistantCard("the publish outcome", isPublishOutcome)
717 o.jobOf(request, "ready to publish", func(c wire.AssistantCard) bool { return c.State == wire.JobReady })
718 if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceNotNow, card.Revision); err != nil {
719 t.Fatal(err)
720 }
721 done := o.jobOf(request, "done", func(c wire.AssistantCard) bool { return c.State == wire.JobDone })
722 if status, detail := jobWords(wire.JobDone); done.Result != status || done.Detail != detail || !slices.Equal(done.Links, []wire.CardLink{o.equipoLink(request)}) {
723 t.Fatalf("done %+v", done)
724 }
725}
726