package headless import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "image" "image/color" "image/png" "net/netip" "os" "os/exec" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/webread" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // Research end to end (Research spec §2 to §5, slices R3 and R4): the // real instance and runner, real bubblewrap, the fake CLI, and a fetch // phase that writes its bundle without the network. The coordinator adds // Research (an owner's Add), records a task naming the shop's pages, // requests Research and starts the task; the owner confirms the site // inventory; Research runs contained, keeps the logo and submits // findings; the instance stores them; Engineering gets the findings // block and the logo read-only at /research/ (it copies the logo into // the repository, and its writes to /research are refused by the // filesystem); Review's dispatch carries the findings and its three // checks. // headlessLogo is the shop's logo as the fetcher would keep it. func headlessLogo(t *testing.T) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, 24, 16)) for x := range 24 { for y := range 16 { img.Set(x, y, color.RGBA{27, 42, uint8(74 + x), 255}) } } var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } func hexSum(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } // researchPage is the shop's page text: what it says, and the words that // steer the fake Research model (as page text steers a gullible one). const researchPage = "Shop on Main Street. Navy and cream.\n" + "keep:s2|logo|The shop's logo.\n" + "summary:A barber shop on Main Street, navy and cream.\n" + "fact:Colours|Navy and cream|s1\n" + "image:$kept\n" + "gap:No opening hours on the page.\n" // fakeFetch is the fetch phase without the network: for each approved // source a log line, a page for a page and the logo for an image, in // the bundle format the fetcher writes. func fakeFetch(t *testing.T, logo []byte, plans *[]webread.Plan, mu *sync.Mutex) func(context.Context, webread.LaunchConfig, webread.Plan) error { return func(_ context.Context, cfg webread.LaunchConfig, p webread.Plan) error { mu.Lock() *plans = append(*plans, p) mu.Unlock() m := webread.Manifest{Version: 1, Files: []webread.File{}, Log: []webread.Entry{}} for i, s := range p.Sources { var data []byte f := webread.File{Source: s.ID} if strings.HasSuffix(s.URL.String(), ".png") { data = logo f.Name, f.Kind, f.Type, f.Width, f.Height = fmt.Sprintf("s%03d.png", i+1), webread.KindImage, "image/png", 24, 16 } else { data = []byte(researchPage) f.Name, f.Kind, f.Type = fmt.Sprintf("s%03d.txt", i+1), webread.KindText, "text/html" } f.Size, f.SHA256 = int64(len(data)), hexSum(data) m.Files = append(m.Files, f) m.Log = append(m.Log, webread.Entry{Source: s.ID, Origin: s.Origin, URL: s.URL.String(), Address: "81.2.69.50", Status: 200, Type: f.Type, Bytes: f.Size, SHA256: f.SHA256, Millis: 12, File: f.Name}) if err := os.WriteFile(filepath.Join(cfg.OutDir, f.Name), data, 0600); err != nil { return err } } m.Used = webread.Spent{Requests: len(p.Sources), Bytes: 1000} raw, _ := json.Marshal(m) return os.WriteFile(filepath.Join(cfg.OutDir, webread.ManifestName), raw, 0600) } } // openCard waits for an open card of kind. func (s *session) openCard(t *testing.T, kind string) wire.Card { t.Helper() var out wire.Card s.wait(t, "an open "+kind+" card", 3*time.Minute, func(c *thintest.Conversation) bool { for _, k := range c.Cards { if k.Kind == kind && k.State == wire.CardOpen { out = k return true } } return false }) return out } // specialistStep waits for the task's newest step of specialist to end. func (s *session) specialistStep(t *testing.T, task, specialist string, timeout time.Duration) wire.Step { t.Helper() var out wire.Step s.wait(t, specialist+" step ended", timeout, func(c *thintest.Conversation) bool { var last *wire.Step for i := range c.Tasks[task].Steps { if c.Tasks[task].Steps[i].Specialist == specialist { last = &c.Tasks[task].Steps[i] } } if last == nil { return false } out = c.Steps[last.ID] if out.ID == "" || out.Revision < last.Revision { out = *last } return wire.StepTerminal(out.State) }) return out } // dispatchOf is the newest dispatch the instance sent for the task's // step of specialist. func dispatchOf(t *testing.T, inst *thintest.Instance, task, specialist string) wire.DispatchCommand { t.Helper() rows, err := inst.DB.Writer().Query("SELECT body FROM runner_commands WHERE kind = ? ORDER BY seq", wire.FrameDispatch) if err != nil { t.Fatal(err) } defer rows.Close() var out wire.DispatchCommand for rows.Next() { var body string var d wire.DispatchCommand if rows.Scan(&body) != nil || json.Unmarshal([]byte(body), &d) != nil { continue } if d.TaskID == task && d.Specialist == specialist { out = d } } if out.StepID == "" { t.Fatalf("no %s dispatch for %s", specialist, task) } return out } func TestHeadlessResearchHandoff(t *testing.T) { env, inst, r := localEnv(t) logo := headlessLogo(t) var mu sync.Mutex var plans []webread.Plan r.opts.ResearchFetch = fakeFetch(t, logo, &plans, &mu) r.opts.ResearchAddresses = func() ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("81.2.69.160")}, nil } // Engineering's words: copy the kept logo into the repository, then // try to write to /research (an existing file and a new one). r.opts.StepNote = "\ncopy:/research/img1-logo.png|assets/logo.png\nrowrite:/research/img1-logo.png\nrowrite:/research/planted.png\n" r.start(t) s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) // Research joins the team: proposed, then the owner's Add. s.send(t, "Add Research to the team.\ntool:propose_specialist:Reads the shop's pages for its colours and logo.") card := s.openCard(t, wire.CardSpecialist) if _, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil { t.Fatal(err) } // The task names the shop's page and logo in the person's own words. sent := s.send(t, "Make a page for the shop at https://shop.example.com/ with its logo https://shop.example.com/logo.png.\n"+ "tool:record_task:oficina/sample|Shop page|A page for the shop.|separate\n"+ "tool:research:$task|Its colours and logo.|\n"+ "tool:start_task:$task|Make the page.") id := s.taskOf(t, sent.Turn.ID) // The site inventory: the runner's detected address, confirmed once. inv := s.openCard(t, wire.CardResearchInventory) if _, err := env.Client.Answer(s.ctx, inv.ID, wire.ChoiceConfirm, inv.Revision); err != nil { t.Fatal(err) } if d := dispatchOf(t, inst, id, wire.SpecialistResearch); d.Research == nil || len(d.Research.Inventory) == 0 || d.Repo != "" || d.Branch != "" { t.Fatalf("research dispatch %+v", d) } // Research runs contained, keeps the logo and submits findings. rs := s.specialistStep(t, id, wire.SpecialistResearch, 5*time.Minute) if rs.State != wire.StepDone { t.Fatalf("Research %s %s: %s %s", rs.State, rs.Reason, rs.Summary, rs.LogTail) } mu.Lock() fetched := len(plans) var sources []string if fetched > 0 { for _, src := range plans[0].Sources { sources = append(sources, src.ID+"="+src.URL.String()) } } mu.Unlock() if fetched != 1 || strings.Join(sources, " ") != "s1=https://shop.example.com/ s2=https://shop.example.com/logo.png" { t.Fatalf("fetch passes %d, sources %v", fetched, sources) } var stored string if err := inst.DB.Writer().QueryRow("SELECT findings FROM chat_research WHERE task_id = ?", id).Scan(&stored); err != nil { t.Fatalf("no stored findings: %v", err) } var f wire.ResearchFindings if err := json.Unmarshal([]byte(stored), &f); err != nil || f.Summary != "A barber shop on Main Street, navy and cream." || len(f.Facts) != 1 || f.Facts[0].Value != "Navy and cream" || len(f.Images) != 1 || f.Images[0] != "img1" { t.Fatalf("stored findings %s %v", stored, err) } var keptSHA string if err := inst.DB.Writer().QueryRow("SELECT sha256 FROM chat_task_files WHERE task_id = ? AND kept = 1 AND complete = 1 AND image_id = 'img1'", id).Scan(&keptSHA); err != nil || keptSHA != hexSum(logo) { t.Fatalf("kept image %s %v", keptSHA, err) } // Engineering: the findings block, the logo read-only at /research/. eng := dispatchOf(t, inst, id, wire.SpecialistEngineering) if eng.ResearchNote == nil || len(eng.ResearchNote.Images) != 1 || eng.ResearchNote.Images[0].SHA256 != hexSum(logo) { t.Fatalf("Engineering's dispatch %+v", eng.ResearchNote) } step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed, wire.StepCancelled) if step.State != wire.StepDone || !step.Pushed || len(step.CandidateSHA) != 40 { t.Fatalf("Engineering %s %s: %s %s", step.State, step.Reason, step.Summary, step.LogTail) } for _, want := range []string{"Copied /research/img1-logo.png to assets/logo.png.", "Writing /research/img1-logo.png failed (errno 30).", "Writing /research/planted.png failed (errno 30)."} { if !strings.Contains(step.Summary, want) { t.Fatalf("Engineering's summary lacks %q: %s", want, step.Summary) } } out, err := exec.Command("git", "--git-dir="+env.ForgePath("oficina/sample"), "cat-file", "blob", step.CandidateSHA+":assets/logo.png").Output() if err != nil || !bytes.Equal(out, logo) { t.Fatalf("the committed logo is not the kept one (%d bytes): %v", len(out), err) } // Review: the same findings, and the three checks in its brief. s.wait(t, "the review dispatch", 5*time.Minute, func(*thintest.Conversation) bool { var n int inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ? AND body LIKE ?", wire.FrameDispatch, `%"specialist":"review"%`, `%"task_id":"`+id+`"%`).Scan(&n) return n > 0 }) rv := dispatchOf(t, inst, id, wire.SpecialistReview) if rv.ResearchNote == nil || !bytes.Equal(rv.ResearchNote.Findings, eng.ResearchNote.Findings) || len(rv.ResearchNote.Images) != 1 { t.Fatalf("Review's dispatch %+v", rv.ResearchNote) } for _, want := range []string{"the change matches the findings", "it adds no request to a host outside the findings' sources", "it puts no repository secret, environment file or unrelated repository text into its output"} { if !strings.Contains(rv.Brief, want) { t.Fatalf("Review's brief lacks %q: %s", want, rv.Brief) } } review := s.specialistStep(t, id, wire.SpecialistReview, 5*time.Minute) if review.State != wire.StepDone { t.Fatalf("Review %s %s: %s", review.State, review.Reason, review.Summary) } // No attempt's /research directory outlives it. if left, _ := filepath.Glob(filepath.Join(r.cfg.StateDir, "research-work", "handoff-*")); len(left) != 0 { t.Fatalf("hand-off directories left: %v", left) } }