package thintest import ( "encoding/json" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" ) // stepFrame sends one step report and waits for the instance's ack. func (r *toolRig) step(id string, rep wire.StepReport) { r.t.Helper() if err := r.runner.Send(r.ctx, id, wire.FrameStep, rep); err != nil { r.t.Fatal(err) } for { f, body, err := r.runner.Next(r.ctx) if err != nil { r.t.Fatal(err) } if a, ok := body.(*wire.Ack); ok && f.Type == wire.FrameAck && a.ID == id { return } if f.Type != wire.FrameAck { // A command the report caused (the next step's dispatch). r.held = append(r.held, heldFrame{f, body, r.runner.Received[len(r.runner.Received)-1]}) } } } // expectDispatch reads frames until a dispatch arrives, acking it. func (r *toolRig) expect(kind string) (wire.Frame, any) { r.t.Helper() for i, h := range r.held { if h.f.Type == kind { r.held = append(r.held[:i:i], r.held[i+1:]...) r.runner.Received = append(r.runner.Received, h.raw) if err := r.runner.Send(r.ctx, "a-"+h.f.ID, wire.FrameAck, wire.Ack{ID: h.f.ID}); err != nil { r.t.Fatal(err) } return h.f, h.body } } for { f, body, err := r.runner.Next(r.ctx) if err != nil { r.t.Fatal(err) } if f.Type == kind { if f.Durable() { if err := r.runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { r.t.Fatal(err) } } return f, body } } } func taskID(t *testing.T, res wire.ToolResult) string { t.Helper() var v struct { Task string `json:"task"` } if res.IsError || json.Unmarshal([]byte(res.Text), &v) != nil || v.Task == "" { t.Fatalf("no task in %+v", res) } return v.Task } // TestContractTasks records a task the moment the person reports it, // attaches a finding, dispatches its Engineering step and follows the // runner's reports to a pushed branch, with Retry refused until the // runner has confirmed termination of the current attempt. func TestContractTasks(t *testing.T) { r := newToolRig(t) ctx := r.ctx res := r.call("k1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back from the edge does nothing", "brief": "On iOS, swiping from the left edge does not go back."}) if res.Code != "recorded" { t.Fatalf("record: %+v", res) } id := taskID(t, res) // The coordinator links the task by its title in its reply. if !strings.Contains(res.Text, `"link":"/tasks/`+id+`"`) || !strings.Contains(res.Text, `"title":"Swipe back from the edge does nothing"`) || strings.Contains(res.Text, "task card") { t.Fatalf("record_task result lacks the link: %s", res.Text) } r.wait("noted task, its card and project", func(c *Conversation) bool { k, ok := c.Tasks[id] cards := 0 for _, card := range c.Cards { if card.Kind == wire.CardTask && card.TaskID == id && card.TurnID == r.turn { cards++ } } return ok && k.Stage == wire.StageNoted && cards == 1 && len(c.Projects) == 1 }) task, err := r.client.Task(ctx, id) if err != nil { t.Fatal(err) } if task.Branch != wire.TaskBranch(id, task.Title) || task.Project != "Sample" || task.Repo != "amadan.net/oficina/sample" || task.Creator != Owner || len(task.Steps) != 0 { t.Fatalf("task %+v", task) } var project wire.Project r.conv.Locked(func(c *Conversation) { for _, p := range c.Projects { project = p } }) // Projects are products: named from the catalog, with the repository attached. if project.Title != "Sample" || len(project.Attachments) != 1 || project.Attachments[0].Ref != "amadan.net/oficina/sample" || task.ProjectID != project.ID { t.Fatalf("project %+v", project) } // Findings: only for the team's task, a repository in the catalog and a clean path. for _, bad := range []map[string]any{ {"task": "tk-nope", "text": "x", "repo": "oficina/sample", "path": "a.go", "line": 1}, {"task": id, "text": "x", "repo": "oficina/secret", "path": "a.go", "line": 1}, {"task": id, "text": "x", "repo": "oficina/sample", "path": "../etc/passwd", "line": 1}, {"task": id, "text": "", "repo": "oficina/sample", "path": "a.go", "line": 1}, } { if res := r.call("bad-"+itoa(len(r.runner.Sent)), wire.ToolAddFinding, bad); !res.IsError { t.Fatalf("finding accepted: %v -> %+v", bad, res) } } res = r.call("k2", wire.ToolAddFinding, map[string]any{"task": id, "text": "EdgeSwipe returns false, so back never fires.", "repo": "oficina/sample", "path": "panes/swipe.go", "line": 4}) if res.IsError || res.Code != "finding" { t.Fatalf("finding: %+v", res) } r.wait("investigated", func(c *Conversation) bool { k := c.Tasks[id] return k.Stage == wire.StageInvestigated && len(k.Findings) == 1 && k.Findings[0].Line == 4 }) // Retry before any step: nothing to retry. if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 { t.Fatalf("retry before a step: %v", err) } res = r.call("k3", wire.ToolStartTask, map[string]string{"task": id, "brief": "Make EdgeSwipe go back."}) if res.IsError || res.Code != "started" || !strings.Contains(res.Text, `"link":"/tasks/`+id+`"`) { t.Fatalf("start: %+v", res) } if again := r.call("k3b", wire.ToolStartTask, map[string]string{"task": id, "brief": "again"}); !again.IsError { t.Fatalf("second start accepted: %+v", again) } f, body := r.expect(wire.FrameDispatch) shape(t, "frames/dispatch.json", r.runner.Received[len(r.runner.Received)-1]) d := body.(*wire.DispatchCommand) if d.Person != Owner || d.TaskID != id || d.Attempt != 1 || d.Repo != "amadan.net/oficina/sample" || d.Branch != task.Branch || d.BaseSHA != "" || d.Specialist != wire.SpecialistEngineering || len(d.Findings) != 1 || !strings.Contains(d.Brief, "Make EdgeSwipe go back.") { t.Fatalf("dispatch %s %+v", f.ID, d) } r.wait("in progress", func(c *Conversation) bool { k := c.Tasks[id] return k.Stage == wire.StageInProgress && len(k.Steps) == 1 && k.Steps[0].State == wire.StepQueued }) base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) r.step("r-s1", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Findings: []wire.Finding{}}) shape(t, "frames/step.json", r.runner.Sent[len(r.runner.Sent)-1]) r.wait("running with base", func(c *Conversation) bool { k := c.Tasks[id] return k.BaseSHA == base && len(k.Steps) == 1 && k.Steps[0].State == wire.StepRunning }) if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 { t.Fatalf("retry while running: %v", err) } // A failure without termination proof does not allow Retry. r.step("r-s2", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed"}) if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 { t.Fatalf("retry without termination: %v", err) } r.step("r-s3", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) r.wait("failed, terminated", func(c *Conversation) bool { s := c.Steps[d.StepID] return s.State == wire.StepFailed && s.Terminated }) acc, err := r.client.RetryTask(ctx, id) if err != nil || acc.Attempt != 2 { t.Fatalf("retry: %+v %v", acc, err) } shape(t, "api/task-accepted.json", acc) if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 { t.Fatalf("second retry: %v", err) } _, body = r.expect(wire.FrameDispatch) d2 := body.(*wire.DispatchCommand) if d2.Attempt != 2 || d2.StepID != d.StepID || d2.BaseSHA != base { t.Fatalf("retry dispatch %+v", d2) } // Reports for the old attempt are ignored once a new one exists. r.step("r-s4", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: strings.Repeat("9", 40), Pushed: true, Termination: true}) r.step("r-s5", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepRunning, BaseSHA: base}) r.step("r-s6", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand}) // The candidate of an attempt never changes, and a step never goes back. r.step("r-s7", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepRunning, BaseSHA: base, CandidateSHA: strings.Repeat("3", 40)}) r.step("r-s7b", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepDone, BaseSHA: base, CandidateSHA: strings.Repeat("3", 40), Pushed: true, Termination: true}) if k, _ := r.client.Task(ctx, id); k.Steps[0].CandidateSHA != cand || k.Steps[0].State != wire.StepRunning { t.Fatalf("candidate changed or done with another candidate: %+v", k.Steps[0]) } r.step("r-s8", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Summary: "EdgeSwipe goes back now.", LogTail: "Edit panes/swipe.go"}) r.step("r-s9", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 2, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand}) r.wait("pushed", func(c *Conversation) bool { s := c.Steps[d.StepID] k := c.Tasks[id] return s.State == wire.StepDone && s.Pushed && s.CandidateSHA == cand && s.Attempt == 2 && strings.HasPrefix(k.URL, "https://amadan.net/oficina/sample?branch=equipo/") }) task, err = r.client.Task(ctx, id) // Pushed, the candidate goes to review: its checks are dispatched (slice 4). if err != nil || task.Stage != wire.StageInReview || len(task.Steps) != 2 || task.Steps[1].Specialist != wire.SpecialistChecks || task.Steps[0].Summary != "EdgeSwipe goes back now." { t.Fatalf("task after push %+v %v", task, err) } shape(t, "api/task.json", task) r.dispatched(wire.SpecialistChecks, base, cand, 0) if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 { t.Fatalf("retry after done: %v", err) } log, err := r.client.StepLog(ctx, d.StepID) if err != nil || log.Tail != "Edit panes/swipe.go" || log.Attempt != 2 { t.Fatalf("log %+v %v", log, err) } shape(t, "api/step-log.json", log) entry, err := r.client.PostThread(ctx, id, "It happens on the iPhone only.", "k-th") if err != nil || entry.Author != Owner { t.Fatalf("thread %+v %v", entry, err) } if again, err := r.client.PostThread(ctx, id, "It happens on the iPhone only.", "k-th"); err != nil || again.ID != entry.ID { t.Fatalf("thread repeat %+v %v", again, err) } list, err := r.client.Tasks(ctx) if err != nil || len(list.Items) != 1 || len(list.Items[0].Thread) != 1 { t.Fatalf("tasks %+v %v", list, err) } shape(t, "api/tasks.json", list) read := r.call("k4", wire.ToolReadTask, map[string]string{"task": id}) for _, want := range []string{task.Branch, cand, "It happens on the iPhone only.", "EdgeSwipe returns false", `"link":"/tasks/` + id + `"`} { if !strings.Contains(read.Text, want) { t.Fatalf("read_task lacks %q: %s", want, read.Text) } } // A second task: cancelled while noted ends at once. res = r.call("k5", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Typo in the README", "brief": "teh"}) other := taskID(t, res) if acc, err := r.client.CancelTask(ctx, other); err != nil || acc.Attempt != 0 { t.Fatalf("cancel noted: %+v %v", acc, err) } r.wait("cancelled", func(c *Conversation) bool { return c.Tasks[other].Stage == wire.StageCancelled }) if _, err := r.client.CancelTask(ctx, other); Status(err) != 409 { t.Fatalf("cancel twice: %v", err) } if res := r.call("k6", wire.ToolStartTask, map[string]string{"task": other, "brief": "x"}); !res.IsError { t.Fatalf("started a cancelled task: %+v", res) } // A third: cancelled while its step runs ends only on the runner's report. third := taskID(t, r.call("k7", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Another", "brief": "b"})) r.call("k8", wire.ToolStartTask, map[string]string{"task": third, "brief": "go"}) _, body = r.expect(wire.FrameDispatch) d3 := body.(*wire.DispatchCommand) r.step("r-t1", wire.StepReport{TaskID: third, StepID: d3.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base}) acc, err = r.client.CancelTask(ctx, third) if err != nil || acc.Attempt != 1 { t.Fatalf("cancel running: %+v %v", acc, err) } _, body = r.expect(wire.FrameCancelStep) shape(t, "frames/cancel_step.json", r.runner.Received[len(r.runner.Received)-1]) if c := body.(*wire.CancelStepCommand); c.StepID != d3.StepID || c.Attempt != 1 || c.Person != Owner { t.Fatalf("cancel_step %+v", c) } snap, _ := r.client.Task(ctx, third) if snap.Stage == wire.StageCancelled { t.Fatal("cancelled before the runner reported termination") } r.step("r-t2", wire.StepReport{TaskID: third, StepID: d3.StepID, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Termination: true}) r.wait("third cancelled", func(c *Conversation) bool { return c.Tasks[third].Stage == wire.StageCancelled }) if _, err := r.client.RetryTask(ctx, third); Status(err) != 409 { t.Fatalf("retry of a cancelled task: %v", err) } // Events carry the task and step resources. var sawTask, sawStep bool r.conv.Locked(func(c *Conversation) { sawTask, sawStep = len(c.Tasks) == 3, len(c.Steps) == 3 }) if !sawTask || !sawStep { t.Fatal("task and step events missing") } } // TestContractStepSync settles a step the runner no longer holds: after // a reconnect its sync proves nothing runs, so the step failed with // termination and Retry is allowed. func TestContractStepSync(t *testing.T) { r := newToolRig(t) id := taskID(t, r.call("s1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Sync me", "brief": "b"})) r.call("s2", wire.ToolStartTask, map[string]string{"task": id, "brief": "go"}) _, body := r.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) r.step("r-s1", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)}) // A sync that still holds the step changes nothing. if err := r.runner.Send(r.ctx, "r-sync-a", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{{TaskID: id, StepID: d.StepID, Attempt: 1, State: "running"}}}); err != nil { t.Fatal(err) } // A durable no-op after it: once acked, the sync was applied. r.step("r-s1b", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning}) if k, _ := r.client.Task(r.ctx, id); k.Steps[0].State != wire.StepRunning { t.Fatalf("a held step was settled: %+v", k.Steps[0]) } // A second task whose dispatch the runner has not acked yet. other := taskID(t, r.call("s3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Not yet", "brief": "b"})) r.call("s4", wire.ToolStartTask, map[string]string{"task": other, "brief": "go"}) if err := r.runner.Send(r.ctx, "r-sync-b", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{}}); err != nil { t.Fatal(err) } // The runner no longer holds the step: interrupted, a passing stop, // so Equipo retries it once on its own (needs-you triage). r.wait("retried after the sync", func(c *Conversation) bool { s := c.Steps[d.StepID] return s.Attempt == 2 && s.State == wire.StepQueued }) if acc, err := r.client.RetryTask(r.ctx, id); Status(err) != 409 { t.Fatalf("a person's retry on top of Equipo's: %+v %v", acc, err) } if k, _ := r.client.Task(r.ctx, other); k.Steps[0].State != wire.StepQueued { t.Fatalf("a step whose dispatch is unacked was settled: %+v", k.Steps[0]) } } // TestContractTaskToolsNeedAPersonTurn: a move-in turn cannot record or // start work, and a task of another team member's runner is not reported. func TestContractTaskToolsScope(t *testing.T) { r := newToolRig(t) if res := r.call("x1", wire.ToolStartTask, map[string]string{"task": "tknope", "brief": "go"}); !res.IsError || res.Code != "not_found" { t.Fatalf("unknown task: %+v", res) } if res := r.call("x2", wire.ToolRecordTask, map[string]string{"repo": "oficina/secret", "title": "x", "brief": "y"}); !res.IsError || res.Code != "not_allowed" { t.Fatalf("repo outside the allowlist: %+v", res) } if res := r.call("x3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "", "brief": "y"}); !res.IsError { t.Fatalf("empty title: %+v", res) } // A step report for a task the runner was never sent is refused. if err := r.runner.Send(r.ctx, "r-ghost", wire.FrameStep, wire.StepReport{TaskID: "tkghost", StepID: "s_ghost", Attempt: 1, State: wire.StepDone, Termination: true}); err != nil { t.Fatal(err) } if _, _, err := r.runner.Next(r.ctx); err == nil { // The instance closes the stream on a frame it cannot apply, or // acks nothing; either way no task appears. r.conv.Locked(func(c *Conversation) { if len(c.Tasks) != 0 { t.Fatalf("ghost task: %+v", c.Tasks) } }) } } // TestContractGrantCard: nothing reachable puts an access card with the // namespace the name says; acting on it asks the runner to check now, // and the card resolves itself once a hello's catalog reaches the name. func TestContractGrantCard(t *testing.T) { r := newToolRig(t) res := r.call("g1", wire.ToolFind, map[string]string{"query": "moonbeam/web"}) if res.Code != "none" || strings.Contains(res.Text, "end with") { t.Fatalf("find: %+v", res) } var card wire.Card r.wait("access card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardAccess { card = k } } return card.ID != "" }) if card.Name != "moonbeam/web" || card.Choice != "equipo-test" || card.State != wire.CardOpen { t.Fatalf("card %+v", card) } if _, err := r.client.Answer(r.ctx, card.ID, "something", card.Revision); Status(err) != 422 { t.Fatalf("other answer: %v", err) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceCheck, card.Revision); err != nil { t.Fatal(err) } r.expect(wire.FrameRecheck) shape(t, "frames/recheck.json", r.runner.Received[len(r.runner.Received)-1]) // A hello that still does not reach it changes nothing. hello := wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Agent: "equipo-test", Catalog: []wire.RepoInfo{{Repo: "amadan.net/oficina/sample", Names: []string{"sample"}, Hints: []string{}}}, Connections: []wire.HeldConnection{}, Versions: map[string]string{}} if err := r.runner.Send(r.ctx, "h-g1", wire.FrameHello, hello); err != nil { t.Fatal(err) } // An unrelated repository that merely matches a word of the query // (app) does not resolve it. hello.Catalog = append(hello.Catalog, wire.RepoInfo{Repo: "amadan.net/other/app", Summary: "An app.", Names: []string{"app", "Moonbeams"}, Hints: []string{}}) if err := r.runner.Send(r.ctx, "h-g1b", wire.FrameHello, hello); err != nil { t.Fatal(err) } // A durable no-op round trip, so the hello was applied. r.call("g-sync", wire.ToolStatus, map[string]string{}) if c, _ := r.client.Snapshot(r.ctx); func() string { for _, k := range c.Cards { if k.ID == card.ID { return k.State } } return "" }() != wire.CardOpen { t.Fatal("resolved by an unrelated repository") } hello.Catalog = append(hello.Catalog, wire.RepoInfo{Repo: "amadan.net/moonbeam/web", Names: []string{"web", "Moonbeam"}, Hints: []string{}}) if err := r.runner.Send(r.ctx, "h-g2", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("resolved", func(c *Conversation) bool { return c.Cards[card.ID].State == wire.CardResolved }) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceCheck, card.Revision); Status(err) != 409 { t.Fatalf("check on a resolved card: %v", err) } } // TestContractSyncBeforeReplay: the runner reported a failure without // termination proof and lost the connection before the ack; on // reconnect its sync (attempt present, termination unverified) arrives // before the outbox replay. The instance must not infer termination // from that sync, and Retry stays refused after the replayed report. func TestContractSyncBeforeReplay(t *testing.T) { r := newToolRig(t) id := taskID(t, r.call("q1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Replay order", "brief": "b"})) r.call("q2", wire.ToolStartTask, map[string]string{"task": id, "brief": "go"}) _, body := r.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) r.step("r-q1", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)}) // Reconnect order: sync first, holding the attempt as pending. if err := r.runner.Send(r.ctx, "r-sync-q", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{{TaskID: id, StepID: d.StepID, Attempt: 1, State: "pending"}}}); err != nil { t.Fatal(err) } // Then the replayed report, still without termination. r.step("r-q2", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed"}) k, err := r.client.Task(r.ctx, id) if err != nil || k.Steps[0].State != wire.StepFailed || k.Steps[0].Terminated { t.Fatalf("termination inferred: %+v %v", k.Steps, err) } if _, err := r.client.RetryTask(r.ctx, id); Status(err) != 409 { t.Fatalf("retry without verified termination: %v", err) } // The proof, when it comes, allows Retry. r.step("r-q3", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) if acc, err := r.client.RetryTask(r.ctx, id); err != nil || acc.Attempt != 2 { t.Fatalf("retry after the proof: %+v %v", acc, err) } }