oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package headless
2
3import (
4 "context"
5 "encoding/json"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "slices"
10 "strings"
11 "sync"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/runner/forge"
16 "amadan.net/oficina/equipo/internal/runner/forge/forgetest"
17 "amadan.net/oficina/equipo/internal/runner/thin"
18 "amadan.net/oficina/equipo/internal/runner/workspace"
19 "amadan.net/oficina/equipo/internal/stagingtest"
20 "amadan.net/oficina/equipo/internal/thintest"
21 "amadan.net/oficina/equipo/internal/wire"
22)
23
24// localForge stands in for Amadan: bare repositories on disk, reached with
25// the file protocol and no password, and creation in one namespace.
26type localForge struct {
27 root string
28 mu sync.Mutex
29 repos []string
30 hidden []string
31 createIn []string
32 // hubUpdated: the hub makes the first merge into an empty repository
33 // (amadan#139); before it, such a merge is refused unborn_default.
34 hubUpdated bool
35}
36
37func gitRun(t *testing.T, dir string, args ...string) {
38 t.Helper()
39 cmd := exec.Command("git", args...)
40 cmd.Dir = dir
41 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com", "GIT_CONFIG_GLOBAL=/dev/null")
42 if out, err := cmd.CombinedOutput(); err != nil {
43 t.Fatalf("git %v: %v %s", args, err, out)
44 }
45}
46
47// newLocalForge makes oficina/sample (Woodstar, a Go app) and oficina/equipo.
48// oficina/notes is reachable through the namespace grant but not in the
49// credential file, like a repository the agent was granted later.
50func newLocalForge(t *testing.T, root string) *localForge {
51 t.Helper()
52 f := &localForge{root: private(t, filepath.Join(root, "forge")), createIn: []string{"oficina"}}
53 files := map[string]map[string]string{
54 "sample": {"README.md": "# Woodstar\n\nWoodstar is a reading app with sliding panes. Woodstar keeps your place.\n\nIt has a typo: teh panes.\n", "go.mod": "module amadan.net/oficina/sample\n\ngo 1.26\n", "panes/swipe.go": "package panes\n\n// EdgeSwipe goes back when a finger slides from the edge.\nfunc EdgeSwipe() bool { return false }\n",
55 // The repository's own gate: fails while the README has the typo,
56 // printing the edit that fixes it; and an iOS file.
57 ".equipo/gates.json": "{\"version\":1,\"files\":[]}\n",
58 "Makefile": "ci:\n\t@if grep -q 'teh panes' README.md; then echo 'README.md still says teh panes. edit:README.md|teh panes|the panes'; exit 1; fi\n\t@test -d .git && git rev-parse HEAD\n\t@echo README ok\n",
59 "ios/App.swift": "import SwiftUI\n\nlet edgeSwipe = false\n"},
60 "equipo": {"README.md": "# Equipo\n\nEquipo runs a team's coordinator and specialists.\n", "go.mod": "module amadan.net/oficina/equipo\n\ngo 1.26\n"},
61 "notes": {"README.md": "# Notes\n\nShared notes.\n"},
62 }
63 for name, tree := range files {
64 work := filepath.Join(root, "seed-"+name)
65 for p, body := range tree {
66 if err := os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0700); err != nil {
67 t.Fatal(err)
68 }
69 if err := os.WriteFile(filepath.Join(work, p), []byte(body), 0600); err != nil {
70 t.Fatal(err)
71 }
72 }
73 gitRun(t, work, "init", "-q", "-b", "main")
74 gitRun(t, work, "add", "-A")
75 gitRun(t, work, "commit", "-q", "-m", "seed")
76 // A second commit in sample, so the index's depth-1 fetch leaves
77 // its clone shallow, as a real repository with history does.
78 if name != "sample" {
79 gitRun(t, root, "clone", "-q", "--bare", work, f.path("amadan.net/oficina/"+name))
80 continue
81 }
82 if err := os.WriteFile(filepath.Join(work, "CHANGES"), []byte("second\n"), 0600); err != nil {
83 t.Fatal(err)
84 }
85 gitRun(t, work, "add", "-A")
86 gitRun(t, work, "commit", "-q", "-m", "second")
87 gitRun(t, root, "clone", "-q", "--bare", work, f.path("amadan.net/oficina/"+name))
88 }
89 f.repos = []string{"amadan.net/oficina/equipo", "amadan.net/oficina/sample"}
90 f.hidden = []string{"amadan.net/oficina/notes"}
91 return f
92}
93
94// localForgeState is a local forge as a runner subprocess reads it.
95type localForgeState struct {
96 Root string
97 Repos []string
98 Hidden []string
99 CreateIn []string
100 HubUpdated bool
101}
102
103func (f *localForge) state() *localForgeState {
104 f.mu.Lock()
105 defer f.mu.Unlock()
106 return &localForgeState{Root: f.root, Repos: slices.Clone(f.repos), Hidden: slices.Clone(f.hidden), CreateIn: slices.Clone(f.createIn), HubUpdated: f.hubUpdated}
107}
108
109func (s *localForgeState) forge() *localForge {
110 return &localForge{root: s.Root, repos: s.Repos, hidden: s.Hidden, createIn: s.CreateIn, hubUpdated: s.HubUpdated}
111}
112
113// grant makes a new repository reachable, like a namespace granted to
114// the agent: hidden from the credential file, reachable for the index.
115func (f *localForge) grant(t *testing.T, root, repo string) {
116 t.Helper()
117 work := filepath.Join(root, "seed-"+strings.ReplaceAll(strings.TrimPrefix(repo, "amadan.net/"), "/", "__"))
118 if err := os.MkdirAll(work, 0700); err != nil {
119 t.Fatal(err)
120 }
121 name := filepath.Base(repo)
122 if err := os.WriteFile(filepath.Join(work, "README.md"), []byte("# "+name+"\n\n"+name+" keeps the kitchen's recipes.\n"), 0600); err != nil {
123 t.Fatal(err)
124 }
125 gitRun(t, work, "init", "-q", "-b", "main")
126 gitRun(t, work, "add", "-A")
127 gitRun(t, work, "commit", "-q", "-m", "seed")
128 gitRun(t, root, "clone", "-q", "--bare", work, f.path(repo))
129 f.mu.Lock()
130 f.hidden = append(f.hidden, repo)
131 f.mu.Unlock()
132}
133
134// grantEmpty makes a new repository with no commits reachable, like a
135// repository created on the hub and not pushed to yet.
136func (f *localForge) grantEmpty(t *testing.T, repo string) {
137 t.Helper()
138 if err := os.MkdirAll(f.root, 0700); err != nil {
139 t.Fatal(err)
140 }
141 gitRun(t, f.root, "init", "-q", "--bare", "-b", "main", f.path(repo))
142 f.mu.Lock()
143 f.hidden = append(f.hidden, repo)
144 f.mu.Unlock()
145}
146
147// revoke makes a repository unreachable again.
148func (f *localForge) revoke(repo string) {
149 f.mu.Lock()
150 defer f.mu.Unlock()
151 f.hidden = slices.DeleteFunc(f.hidden, func(r string) bool { return r == repo })
152 f.repos = slices.DeleteFunc(f.repos, func(r string) bool { return r == repo })
153}
154
155func (f *localForge) path(repo string) string {
156 return filepath.Join(f.root, strings.ReplaceAll(strings.TrimPrefix(repo, "amadan.net/"), "/", "__")+".git")
157}
158
159// Repos is everything the agent reaches: the agent-wide credential
160// covers granted repositories too (the file forge's Repos does the same).
161func (f *localForge) Repos() []string {
162 f.mu.Lock()
163 defer f.mu.Unlock()
164 out := append(slices.Clone(f.repos), f.hidden...)
165 slices.Sort(out)
166 return out
167}
168
169func (f *localForge) Reachable(context.Context) []string {
170 f.mu.Lock()
171 out := append(slices.Clone(f.repos), f.hidden...)
172 f.mu.Unlock()
173 slices.Sort(out)
174 return slices.Compact(out)
175}
176
177func (f *localForge) Remote(ctx context.Context, repo string, use thin.Use) (workspace.Remote, error) {
178 if !slices.Contains(f.Reachable(ctx), repo) {
179 return workspace.Remote{}, workspace.ErrGitPassword
180 }
181 return workspace.Remote{URL: f.path(repo)}, nil
182}
183
184func (f *localForge) CreateIn(context.Context) []string { return slices.Clone(f.createIn) }
185
186func (f *localForge) Agent() string { return "equipo-test" }
187
188// Recheck: the local forge is always current.
189func (f *localForge) Recheck() {}
190
191// Merge is the hub's merge API on the local forge: the same refusals
192// (moved, conflicts, already merged) and a merge commit, branch deleted.
193func (f *localForge) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) {
194 if !slices.Contains(f.Reachable(ctx), repo) {
195 return forge.MergeResult{Status: 404, Reason: "not_found"}, nil
196 }
197 f.mu.Lock()
198 hub := forgetest.Hub{CreatesUnbornDefault: f.hubUpdated}
199 f.mu.Unlock()
200 return hub.Merge(ctx, "git", f.path(repo), branch, req)
201}
202
203func (f *localForge) Exists(ctx context.Context, repo string) (bool, error) {
204 return slices.Contains(f.Reachable(ctx), repo), nil
205}
206
207func (f *localForge) Create(ctx context.Context, repo string) error {
208 if !thin.ValidNewRepo(repo) || !slices.Contains(f.createIn, strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/")[0]) {
209 return thin.ErrNoCreate
210 }
211 if out, err := exec.CommandContext(ctx, "git", "init", "-q", "--bare", f.path(repo)).CombinedOutput(); err != nil {
212 return &os.PathError{Op: "init", Path: string(out), Err: err}
213 }
214 f.mu.Lock()
215 f.repos = append(f.repos, repo)
216 f.mu.Unlock()
217 return nil
218}
219
220// keep follows the stream like a client that loses its connection: it
221// reopens at the conversation's cursor whenever the stream ends.
222func (s *session) keep() {
223 s.close()
224 go func() {
225 for s.ctx.Err() == nil {
226 var cursor int64
227 s.conv.Locked(func(c *thintest.Conversation) { cursor = c.Cursor })
228 st, err := s.env.Client.Open(s.ctx, cursor)
229 if err != nil {
230 time.Sleep(time.Second)
231 continue
232 }
233 s.conv.Follow(st)
234 st.Close()
235 }
236 }()
237}
238
239// cards returns the conversation's cards of a kind, for one turn.
240func cards(c *thintest.Conversation, turn, kind string) []wire.Card {
241 var out []wire.Card
242 for _, k := range c.Cards {
243 if k.TurnID == turn && k.Kind == kind {
244 out = append(out, k)
245 }
246 }
247 return out
248}
249
250func (s *session) project(name string) (wire.Project, bool) {
251 var out wire.Project
252 found := false
253 s.conv.Locked(func(c *thintest.Conversation) {
254 for _, p := range c.Projects {
255 if p.Name == name && p.State == wire.ProjectActive {
256 out, found = p, true
257 }
258 }
259 })
260 return out, found
261}
262
263// noRepoQuestion fails if the coordinator asked the person to choose a
264// repository or mentioned a set-up step.
265func noRepoQuestion(t *testing.T, s *session, turn string) {
266 t.Helper()
267 // Only a question about WHERE the work goes fails: a live coordinator
268 // may fairly ask about the change itself (the live README may hold no
269 // typo any more).
270 bad := []string{"set up", "which repository", "which repo", "which project", "which framework", "which one should"}
271 var questions []wire.Card
272 s.conv.Locked(func(c *thintest.Conversation) { questions = cards(c, turn, wire.CardQuestion) })
273 for _, q := range questions {
274 text := strings.ToLower(q.Question)
275 for _, b := range bad {
276 if strings.Contains(text, b) {
277 t.Fatalf("coordinator asked which repository (%q): %+v", b, q)
278 }
279 }
280 }
281 reply := strings.ToLower(s.reply(t, turn).Text)
282 for _, b := range bad {
283 if strings.Contains(reply, b) {
284 t.Fatalf("reply asks the person to choose (%q): %s", b, reply)
285 }
286 }
287}
288
289// Scenario 2 (to the project): "fix the README typo in sample" puts the
290// project in the conversation with an Added card, clones it, and never
291// asks which repository.
292func scenarioProject(t *testing.T, env *Env) {
293 s := open(t, env)
294 s.keep()
295 s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
296 target := "oficina/sample"
297 if env.Live {
298 target = env.Project
299 }
300 // The allowlist arrives with the runner's hello.
301 deadline := time.Now().Add(90 * time.Second)
302 for {
303 list, err := env.Client.Projects(s.ctx)
304 if err == nil && slices.Contains(list.Allowed, "amadan.net/"+target) {
305 break
306 }
307 if time.Now().After(deadline) {
308 t.Fatalf("allowlist never listed %s: %+v %v", target, list, err)
309 }
310 time.Sleep(time.Second)
311 }
312 text := "think Fix the README typo in sample. tool:status\ntool:add_project:oficina/sample"
313 if env.Live {
314 text = "In " + target + ", add a README note saying: Staging suite check " + env.RunID + ". This is a new request for this run."
315 }
316 sent, timing := s.timed(t, "project", text)
317 if err := s.placement(sent.Turn.ID, []string{target}, true); err != nil {
318 t.Fatal(err)
319 }
320 if _, ok := s.project(target); !ok {
321 t.Fatalf("no %s project event", target)
322 }
323 if env.Live {
324 return
325 }
326 noRepoQuestion(t, s, sent.Turn.ID)
327 if timing.Timing == nil || timing.Timing.ResultMs == 0 || timing.Timing.FirstToolMs == 0 || timing.Timing.FirstThinkingMs == 0 {
328 t.Fatalf("turn timing %+v", timing.Timing)
329 }
330 var acts []wire.Activity
331 s.conv.Locked(func(c *thintest.Conversation) { acts = c.Activity[sent.Turn.ID] })
332 kinds := []string{}
333 for _, a := range acts {
334 kinds = append(kinds, a.Kind+":"+a.Tool+":"+a.Label)
335 }
336 want := []string{"thinking::Thinking", "tool:status:Checking your projects…", "tool:add_project:Adding a project…", "tool:add_project:Adding oficina/sample…"}
337 if !slices.Equal(kinds, want) {
338 t.Fatalf("activity %q, want %q", kinds, want)
339 }
340 if r := s.reply(t, sent.Turn.ID).Text; !strings.Contains(r, "[add_project: Added oficina/sample.") || strings.Contains(r, "not cloned") || !strings.Contains(r, `"can_add":["oficina/equipo","oficina/notes","oficina/sample"]`) {
341 t.Fatalf("reply %q", r)
342 }
343 // A second turn in the same project reports "Working in", not Added.
344 again := s.send(t, "tool:add_project:oficina/sample")
345 s.waitTurn(t, again.Turn.ID, wire.TurnReplied)
346 s.wait(t, "working card", 10*time.Second, func(c *thintest.Conversation) bool {
347 k := cards(c, again.Turn.ID, wire.CardProject)
348 return len(k) == 1 && k[0].State == wire.CardWorking
349 })
350}
351
352// Scenario 2b: discovery finds quoted repository references through the
353// index and reads code without asking for placement. A repository outside
354// the allowlist gets one access card.
355func scenarioFindAndRead(t *testing.T, env *Env) {
356 s := open(t, env)
357 s.keep()
358 s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
359 if env.Live {
360 sent := s.send(t, "Investigate the swipe-back gesture in Woodstar for this suite run. Do not create a repository. Ask me if the project is unclear.")
361 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
362 list, err := env.Client.Projects(s.ctx)
363 if err != nil {
364 t.Fatal(err)
365 }
366 var allowed []string
367 for _, repo := range list.Allowed {
368 allowed = append(allowed, strings.TrimPrefix(repo, "amadan.net/"))
369 }
370 if err := s.placement(sent.Turn.ID, allowed, false); err != nil {
371 t.Fatal(err)
372 }
373 return
374 }
375 sent := s.send(t, "In Woodstar, the panes aren't slideable from the edge. tool:find:Woodstar\ntool:search_code:oficina/sample|EdgeSwipe\ntool:read_file:oficina/sample|panes/swipe.go")
376 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
377 r := s.reply(t, sent.Turn.ID).Text
378 for _, want := range []string{"oficina/sample", "calls itself Woodstar", "repository", "panes/swipe.go:3:// EdgeSwipe goes back", "4\tfunc EdgeSwipe() bool { return false }"} {
379 if !strings.Contains(r, want) {
380 t.Fatalf("reply lacks %q: %s", want, r)
381 }
382 }
383 noRepoQuestion(t, s, sent.Turn.ID)
384 // A repository reachable only through the namespace grant is readable.
385 notes := s.send(t, "tool:read_file:oficina/notes|README.md")
386 s.waitTurn(t, notes.Turn.ID, wire.TurnReplied)
387 if r := s.reply(t, notes.Turn.ID).Text; !strings.Contains(r, "1\t# Notes") {
388 t.Fatalf("granted repository not readable: %s", r)
389 }
390 // Path tricks are refused.
391 trick := s.send(t, "tool:read_file:oficina/sample|../../etc/passwd")
392 s.waitTurn(t, trick.Turn.ID, wire.TurnReplied)
393 if r := s.reply(t, trick.Turn.ID).Text; !strings.Contains(r, "Could not read that") {
394 t.Fatalf("path trick: %s", r)
395 }
396 // A repository the person never named, in a namespace Equipo knows
397 // nothing of: it cannot tell whether it exists, so no access card
398 // (#48, review R1); the model is told so.
399 missing := s.send(t, "In Moonbeam, the panes stick. tool:find:moonbeam/app")
400 s.waitTurn(t, missing.Turn.ID, wire.TurnReplied)
401 if r := s.reply(t, missing.Turn.ID).Text; !strings.Contains(r, "moonbeam/app exists") {
402 t.Fatalf("reply %s", r)
403 }
404 snap, err := env.Client.Snapshot(s.ctx)
405 if err != nil {
406 t.Fatal(err)
407 }
408 for _, k := range snap.Cards {
409 if k.TurnID == missing.Turn.ID && k.Kind == wire.CardAccess {
410 t.Fatalf("access card for an unknown namespace: %+v", k)
411 }
412 }
413 // The person names it: the grant card, as before #48.
414 named := s.send(t, "The panes stick in moonbeam/app. tool:find:moonbeam/app")
415 s.waitTurn(t, named.Turn.ID, wire.TurnReplied)
416 s.wait(t, "access card", 10*time.Second, func(c *thintest.Conversation) bool {
417 k := cards(c, named.Turn.ID, wire.CardAccess)
418 return len(k) == 1 && k[0].Question == "moonbeam/app" && k[0].Choice == "equipo-test" && slices.Equal(k[0].Options, []string{"oficina"})
419 })
420 if r := s.reply(t, named.Turn.ID).Text; !strings.Contains(r, `Nothing Equipo's agent can reach matches \"moonbeam/app\"`) && !strings.Contains(r, `matches "moonbeam/app"`) {
421 t.Fatalf("reply %s", r)
422 }
423}
424
425// Scenario 2c: an explicit new-project request creates its repository.
426// Without creation access, the coordinator asks instead of silently choosing
427// an existing project.
428func scenarioNewWork(t *testing.T, env *Env) {
429 s := open(t, env)
430 s.keep()
431 s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
432 text := "Create a new project called oficina/suite-site"
433 if env.Live {
434 text = "Plan a small website introducing the Oficina suite. Use the existing project " + env.Project + " if it fits, otherwise ask me where it should go. Do not create a repository."
435 }
436 sent := s.send(t, text)
437 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
438 if env.Live {
439 if err := s.placement(sent.Turn.ID, []string{env.Project}, false); err != nil {
440 t.Fatal(err)
441 }
442 return
443 }
444 noRepoQuestion(t, s, sent.Turn.ID)
445 s.wait(t, "created card", 10*time.Second, func(c *thintest.Conversation) bool {
446 k := cards(c, sent.Turn.ID, wire.CardProject)
447 return len(k) == 1 && k[0].State == wire.CardCreated && k[0].Name == "oficina/suite-site"
448 })
449 if r := s.reply(t, sent.Turn.ID).Text; !strings.Contains(r, "Created oficina/suite-site.") || strings.Contains(r, "not cloned") {
450 t.Fatalf("reply %s", r)
451 }
452 // Outside the namespaces the agent may create in, it is refused.
453 other := s.send(t, "tool:create_project:carlos/site")
454 s.waitTurn(t, other.Turn.ID, wire.TurnReplied)
455 if r := s.reply(t, other.Turn.ID).Text; !strings.Contains(r, "You cannot create a repository in that namespace") {
456 t.Fatalf("reply %s", r)
457 }
458 // Change points the work at another repository: the answer is the
459 // person's next message, and the card shows what changed.
460 var card wire.Card
461 s.conv.Locked(func(c *thintest.Conversation) { card = cards(c, sent.Turn.ID, wire.CardProject)[0] })
462 ans, err := env.Client.Answer(s.ctx, card.ID, "oficina/equipo", card.Revision)
463 if err != nil || ans.Card.State != wire.CardChanged || ans.Message.Text != "oficina/equipo" {
464 t.Fatalf("change: %+v %v", ans, err)
465 }
466 s.env.Turn(t)
467 s.waitTurn(t, ans.Turn.ID, wire.TurnReplied)
468 // Remove takes the project out; its card says so.
469 p, ok := s.project("oficina/suite-site")
470 if !ok {
471 t.Fatal("no created project")
472 }
473 if _, err := env.Client.RemoveProject(s.ctx, p.ID); err != nil {
474 t.Fatal(err)
475 }
476 s.wait(t, "removed", 10*time.Second, func(c *thintest.Conversation) bool {
477 return c.Projects[p.ID].State == wire.ProjectRemoved && c.Cards[card.ID].State == wire.CardChanged
478 })
479}
480
481// Scenario 2e: with no home for new projects set, status says so (the
482// coordinator then takes the best-fitting repository with Change); the
483// person can ask for a home, only in a namespace the agent creates in.
484func scenarioProjectHome(t *testing.T, env *Env) {
485 if env.Live {
486 t.Skip("driven by the fake CLI")
487 }
488 s := open(t, env)
489 s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
490 step := func(text, want string) {
491 t.Helper()
492 sent := s.send(t, text)
493 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
494 if r := s.reply(t, sent.Turn.ID).Text; !strings.Contains(r, want) {
495 t.Fatalf("%s: reply %s, want %s", text, r, want)
496 }
497 }
498 step("tool:status", `"home":""`)
499 list, err := env.Client.Projects(s.ctx)
500 if err != nil || list.Home != "" {
501 t.Fatalf("unset home: %+v %v", list, err)
502 }
503 // With no home there is nothing to clear; a namespace the agent cannot
504 // create in is refused; anything else is the person's tap.
505 step("tool:set_project_home:", "nothing to clear")
506 step("Put new projects in carlos.\ntool:set_project_home:carlos", "You cannot create a repository in that namespace")
507 sent := s.send(t, "New projects go to oficina.\ntool:set_project_home:oficina")
508 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
509 if r := s.reply(t, sent.Turn.ID).Text; !strings.Contains(r, "Nothing changed yet") {
510 t.Fatalf("set home: %s", r)
511 }
512 var ask wire.Card
513 s.wait(t, "home card", 10*time.Second, func(c *thintest.Conversation) bool {
514 k := cards(c, sent.Turn.ID, wire.CardHome)
515 if len(k) == 1 {
516 ask = k[0]
517 }
518 return len(k) == 1 && k[0].Name == "oficina" && k[0].State == wire.CardHomeAsk
519 })
520 step("tool:status", `"home":""`)
521 if _, err := env.Client.Answer(s.ctx, ask.ID, wire.ChoiceConfirm, ask.Revision); err != nil {
522 t.Fatal(err)
523 }
524 step("tool:status", `"home":"oficina"`)
525 if list, err = env.Client.Projects(s.ctx); err != nil || list.Home != "oficina" {
526 t.Fatalf("home: %+v %v", list, err)
527 }
528}
529
530// Scenario 2d: ask_person shows a question card; a stale answer is a 409
531// carrying the current card; the answer becomes the next message.
532func scenarioQuestion(t *testing.T, env *Env) {
533 if env.Live {
534 t.Skip("the question card is driven by the fake CLI; live runs never steer the model")
535 }
536 s := open(t, env)
537 s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
538 sent := s.send(t, "tool:ask_person:Should the panes slide on iPad too?|Yes|No")
539 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
540 var q wire.Card
541 s.wait(t, "question", 10*time.Second, func(c *thintest.Conversation) bool {
542 k := cards(c, sent.Turn.ID, wire.CardQuestion)
543 if len(k) == 1 {
544 q = k[0]
545 }
546 return len(k) == 1 && slices.Equal(k[0].Options, []string{"Yes", "No"}) && k[0].State == wire.CardOpen
547 })
548 if _, err := env.Client.Answer(s.ctx, q.ID, "Maybe", q.Revision); thintest.Status(err) != 422 {
549 t.Fatalf("choice outside the options: %v", err)
550 }
551 if _, err := env.Client.Answer(s.ctx, q.ID, "Yes", q.Revision+1); thintest.Status(err) != 409 {
552 t.Fatalf("stale revision: %v", err)
553 }
554 ans, err := env.Client.Answer(s.ctx, q.ID, "Yes", q.Revision)
555 if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Choice != "Yes" {
556 t.Fatalf("answer %+v %v", ans, err)
557 }
558 s.env.Turn(t)
559 _, err = env.Client.Answer(s.ctx, q.ID, "No", ans.Card.Revision)
560 var conflict wire.CardConflict
561 if st, ok := err.(*thintest.ErrStatus); !ok || st.Status != 409 || json.Unmarshal(st.Body, &conflict) != nil || conflict.Code != "card_answered" || conflict.Card.Choice != "Yes" {
562 t.Fatalf("second answer: %v", err)
563 }
564 s.waitTurn(t, ans.Turn.ID, wire.TurnReplied)
565}
566
567// turnClock is where one turn's time went, as the client and both ends
568// saw it.
569type turnClock struct {
570 Commit, FirstActivity, FirstDelta, Message time.Duration
571 Timing *wire.TurnTiming
572}
573
574// TurnClocks collects per-turn timing for the report.
575var TurnClocks = map[string]turnClock{}
576
577// timed sends text and records the turn's clock.
578func (s *session) timed(t *testing.T, name, text string) (wire.Sent, turnClock) {
579 t.Helper()
580 start := time.Now()
581 sent := s.send(t, text)
582 clock := turnClock{Commit: time.Since(start)}
583 s.waitTurn(t, sent.Turn.ID, wire.TurnReplied)
584 var reply wire.Message
585 s.wait(t, "reply", 30*time.Second, func(c *thintest.Conversation) bool {
586 for _, m := range c.Replies() {
587 if m.TurnID == sent.Turn.ID {
588 reply = m
589 }
590 }
591 if at, ok := c.FirstActivity[sent.Turn.ID]; ok {
592 clock.FirstActivity = at.Sub(start)
593 }
594 if at, ok := c.FirstDelta[sent.Turn.ID]; ok {
595 clock.FirstDelta = at.Sub(start)
596 }
597 return reply.ID != ""
598 })
599 clock.Message = time.Since(start)
600 turn, err := s.env.Client.Turn(s.ctx, sent.Turn.ID)
601 if err != nil {
602 t.Fatal(err)
603 }
604 clock.Timing = turn.Timing
605 TurnClocks[t.Name()+"/"+name] = clock
606 raw, _ := json.Marshal(clock)
607 t.Logf("turn clock %s: %s", name, raw)
608 return sent, clock
609}
610
611func (s *session) placement(turn string, named []string, required bool) error {
612 var found []wire.Card
613 var tasks []wire.Task
614 s.conv.Locked(func(c *thintest.Conversation) {
615 for _, card := range c.Cards {
616 if card.TurnID == turn {
617 found = append(found, card)
618 }
619 }
620 for _, task := range c.Tasks {
621 if task.TurnID == turn {
622 tasks = append(tasks, task)
623 }
624 }
625 })
626 return stagingtest.Placement(found, tasks, named, required)
627}
628