| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "image" |
| 11 | "image/color" |
| 12 | "image/png" |
| 13 | "net/netip" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "path/filepath" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "amadan.net/oficina/equipo/internal/runner/webread" |
| 23 | "amadan.net/oficina/equipo/internal/thintest" |
| 24 | "amadan.net/oficina/equipo/internal/wire" |
| 25 | ) |
| 26 | |
| 27 | // Research end to end (Research spec §2 to §5, slices R3 and R4): the |
| 28 | // real instance and runner, real bubblewrap, the fake CLI, and a fetch |
| 29 | // phase that writes its bundle without the network. The coordinator adds |
| 30 | // Research (an owner's Add), records a task naming the shop's pages, |
| 31 | // requests Research and starts the task; the owner confirms the site |
| 32 | // inventory; Research runs contained, keeps the logo and submits |
| 33 | // findings; the instance stores them; Engineering gets the findings |
| 34 | // block and the logo read-only at /research/ (it copies the logo into |
| 35 | // the repository, and its writes to /research are refused by the |
| 36 | // filesystem); Review's dispatch carries the findings and its three |
| 37 | // checks. |
| 38 | |
| 39 | // headlessLogo is the shop's logo as the fetcher would keep it. |
| 40 | func headlessLogo(t *testing.T) []byte { |
| 41 | t.Helper() |
| 42 | img := image.NewRGBA(image.Rect(0, 0, 24, 16)) |
| 43 | for x := range 24 { |
| 44 | for y := range 16 { |
| 45 | img.Set(x, y, color.RGBA{27, 42, uint8(74 + x), 255}) |
| 46 | } |
| 47 | } |
| 48 | var b bytes.Buffer |
| 49 | if err := png.Encode(&b, img); err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | return b.Bytes() |
| 53 | } |
| 54 | |
| 55 | func hexSum(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } |
| 56 | |
| 57 | // researchPage is the shop's page text: what it says, and the words that |
| 58 | // steer the fake Research model (as page text steers a gullible one). |
| 59 | const researchPage = "Shop on Main Street. Navy and cream.\n" + |
| 60 | "keep:s2|logo|The shop's logo.\n" + |
| 61 | "summary:A barber shop on Main Street, navy and cream.\n" + |
| 62 | "fact:Colours|Navy and cream|s1\n" + |
| 63 | "image:$kept\n" + |
| 64 | "gap:No opening hours on the page.\n" |
| 65 | |
| 66 | // fakeFetch is the fetch phase without the network: for each approved |
| 67 | // source a log line, a page for a page and the logo for an image, in |
| 68 | // the bundle format the fetcher writes. |
| 69 | func fakeFetch(t *testing.T, logo []byte, plans *[]webread.Plan, mu *sync.Mutex) func(context.Context, webread.LaunchConfig, webread.Plan) error { |
| 70 | return func(_ context.Context, cfg webread.LaunchConfig, p webread.Plan) error { |
| 71 | mu.Lock() |
| 72 | *plans = append(*plans, p) |
| 73 | mu.Unlock() |
| 74 | m := webread.Manifest{Version: 1, Files: []webread.File{}, Log: []webread.Entry{}} |
| 75 | for i, s := range p.Sources { |
| 76 | var data []byte |
| 77 | f := webread.File{Source: s.ID} |
| 78 | if strings.HasSuffix(s.URL.String(), ".png") { |
| 79 | data = logo |
| 80 | f.Name, f.Kind, f.Type, f.Width, f.Height = fmt.Sprintf("s%03d.png", i+1), webread.KindImage, "image/png", 24, 16 |
| 81 | } else { |
| 82 | data = []byte(researchPage) |
| 83 | f.Name, f.Kind, f.Type = fmt.Sprintf("s%03d.txt", i+1), webread.KindText, "text/html" |
| 84 | } |
| 85 | f.Size, f.SHA256 = int64(len(data)), hexSum(data) |
| 86 | m.Files = append(m.Files, f) |
| 87 | 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}) |
| 88 | if err := os.WriteFile(filepath.Join(cfg.OutDir, f.Name), data, 0600); err != nil { |
| 89 | return err |
| 90 | } |
| 91 | } |
| 92 | m.Used = webread.Spent{Requests: len(p.Sources), Bytes: 1000} |
| 93 | raw, _ := json.Marshal(m) |
| 94 | return os.WriteFile(filepath.Join(cfg.OutDir, webread.ManifestName), raw, 0600) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // openCard waits for an open card of kind. |
| 99 | func (s *session) openCard(t *testing.T, kind string) wire.Card { |
| 100 | t.Helper() |
| 101 | var out wire.Card |
| 102 | s.wait(t, "an open "+kind+" card", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 103 | for _, k := range c.Cards { |
| 104 | if k.Kind == kind && k.State == wire.CardOpen { |
| 105 | out = k |
| 106 | return true |
| 107 | } |
| 108 | } |
| 109 | return false |
| 110 | }) |
| 111 | return out |
| 112 | } |
| 113 | |
| 114 | // specialistStep waits for the task's newest step of specialist to end. |
| 115 | func (s *session) specialistStep(t *testing.T, task, specialist string, timeout time.Duration) wire.Step { |
| 116 | t.Helper() |
| 117 | var out wire.Step |
| 118 | s.wait(t, specialist+" step ended", timeout, func(c *thintest.Conversation) bool { |
| 119 | var last *wire.Step |
| 120 | for i := range c.Tasks[task].Steps { |
| 121 | if c.Tasks[task].Steps[i].Specialist == specialist { |
| 122 | last = &c.Tasks[task].Steps[i] |
| 123 | } |
| 124 | } |
| 125 | if last == nil { |
| 126 | return false |
| 127 | } |
| 128 | out = c.Steps[last.ID] |
| 129 | if out.ID == "" || out.Revision < last.Revision { |
| 130 | out = *last |
| 131 | } |
| 132 | return wire.StepTerminal(out.State) |
| 133 | }) |
| 134 | return out |
| 135 | } |
| 136 | |
| 137 | // dispatchOf is the newest dispatch the instance sent for the task's |
| 138 | // step of specialist. |
| 139 | func dispatchOf(t *testing.T, inst *thintest.Instance, task, specialist string) wire.DispatchCommand { |
| 140 | t.Helper() |
| 141 | rows, err := inst.DB.Writer().Query("SELECT body FROM runner_commands WHERE kind = ? ORDER BY seq", wire.FrameDispatch) |
| 142 | if err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | defer rows.Close() |
| 146 | var out wire.DispatchCommand |
| 147 | for rows.Next() { |
| 148 | var body string |
| 149 | var d wire.DispatchCommand |
| 150 | if rows.Scan(&body) != nil || json.Unmarshal([]byte(body), &d) != nil { |
| 151 | continue |
| 152 | } |
| 153 | if d.TaskID == task && d.Specialist == specialist { |
| 154 | out = d |
| 155 | } |
| 156 | } |
| 157 | if out.StepID == "" { |
| 158 | t.Fatalf("no %s dispatch for %s", specialist, task) |
| 159 | } |
| 160 | return out |
| 161 | } |
| 162 | |
| 163 | func TestHeadlessResearchHandoff(t *testing.T) { |
| 164 | env, inst, r := localEnv(t) |
| 165 | logo := headlessLogo(t) |
| 166 | var mu sync.Mutex |
| 167 | var plans []webread.Plan |
| 168 | r.opts.ResearchFetch = fakeFetch(t, logo, &plans, &mu) |
| 169 | r.opts.ResearchAddresses = func() ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("81.2.69.160")}, nil } |
| 170 | // Engineering's words: copy the kept logo into the repository, then |
| 171 | // try to write to /research (an existing file and a new one). |
| 172 | r.opts.StepNote = "\ncopy:/research/img1-logo.png|assets/logo.png\nrowrite:/research/img1-logo.png\nrowrite:/research/planted.png\n" |
| 173 | r.start(t) |
| 174 | s := open(t, env) |
| 175 | s.keep() |
| 176 | s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) |
| 177 | |
| 178 | // Research joins the team: proposed, then the owner's Add. |
| 179 | s.send(t, "Add Research to the team.\ntool:propose_specialist:Reads the shop's pages for its colours and logo.") |
| 180 | card := s.openCard(t, wire.CardSpecialist) |
| 181 | if _, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | |
| 185 | // The task names the shop's page and logo in the person's own words. |
| 186 | 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"+ |
| 187 | "tool:record_task:oficina/sample|Shop page|A page for the shop.|separate\n"+ |
| 188 | "tool:research:$task|Its colours and logo.|\n"+ |
| 189 | "tool:start_task:$task|Make the page.") |
| 190 | id := s.taskOf(t, sent.Turn.ID) |
| 191 | |
| 192 | // The site inventory: the runner's detected address, confirmed once. |
| 193 | inv := s.openCard(t, wire.CardResearchInventory) |
| 194 | if _, err := env.Client.Answer(s.ctx, inv.ID, wire.ChoiceConfirm, inv.Revision); err != nil { |
| 195 | t.Fatal(err) |
| 196 | } |
| 197 | if d := dispatchOf(t, inst, id, wire.SpecialistResearch); d.Research == nil || len(d.Research.Inventory) == 0 || d.Repo != "" || d.Branch != "" { |
| 198 | t.Fatalf("research dispatch %+v", d) |
| 199 | } |
| 200 | |
| 201 | // Research runs contained, keeps the logo and submits findings. |
| 202 | rs := s.specialistStep(t, id, wire.SpecialistResearch, 5*time.Minute) |
| 203 | if rs.State != wire.StepDone { |
| 204 | t.Fatalf("Research %s %s: %s %s", rs.State, rs.Reason, rs.Summary, rs.LogTail) |
| 205 | } |
| 206 | mu.Lock() |
| 207 | fetched := len(plans) |
| 208 | var sources []string |
| 209 | if fetched > 0 { |
| 210 | for _, src := range plans[0].Sources { |
| 211 | sources = append(sources, src.ID+"="+src.URL.String()) |
| 212 | } |
| 213 | } |
| 214 | mu.Unlock() |
| 215 | if fetched != 1 || strings.Join(sources, " ") != "s1=https://shop.example.com/ s2=https://shop.example.com/logo.png" { |
| 216 | t.Fatalf("fetch passes %d, sources %v", fetched, sources) |
| 217 | } |
| 218 | var stored string |
| 219 | if err := inst.DB.Writer().QueryRow("SELECT findings FROM chat_research WHERE task_id = ?", id).Scan(&stored); err != nil { |
| 220 | t.Fatalf("no stored findings: %v", err) |
| 221 | } |
| 222 | var f wire.ResearchFindings |
| 223 | 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" { |
| 224 | t.Fatalf("stored findings %s %v", stored, err) |
| 225 | } |
| 226 | var keptSHA string |
| 227 | 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) { |
| 228 | t.Fatalf("kept image %s %v", keptSHA, err) |
| 229 | } |
| 230 | |
| 231 | // Engineering: the findings block, the logo read-only at /research/. |
| 232 | eng := dispatchOf(t, inst, id, wire.SpecialistEngineering) |
| 233 | if eng.ResearchNote == nil || len(eng.ResearchNote.Images) != 1 || eng.ResearchNote.Images[0].SHA256 != hexSum(logo) { |
| 234 | t.Fatalf("Engineering's dispatch %+v", eng.ResearchNote) |
| 235 | } |
| 236 | step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed, wire.StepCancelled) |
| 237 | if step.State != wire.StepDone || !step.Pushed || len(step.CandidateSHA) != 40 { |
| 238 | t.Fatalf("Engineering %s %s: %s %s", step.State, step.Reason, step.Summary, step.LogTail) |
| 239 | } |
| 240 | 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)."} { |
| 241 | if !strings.Contains(step.Summary, want) { |
| 242 | t.Fatalf("Engineering's summary lacks %q: %s", want, step.Summary) |
| 243 | } |
| 244 | } |
| 245 | out, err := exec.Command("git", "--git-dir="+env.ForgePath("oficina/sample"), "cat-file", "blob", step.CandidateSHA+":assets/logo.png").Output() |
| 246 | if err != nil || !bytes.Equal(out, logo) { |
| 247 | t.Fatalf("the committed logo is not the kept one (%d bytes): %v", len(out), err) |
| 248 | } |
| 249 | |
| 250 | // Review: the same findings, and the three checks in its brief. |
| 251 | s.wait(t, "the review dispatch", 5*time.Minute, func(*thintest.Conversation) bool { |
| 252 | var n int |
| 253 | 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) |
| 254 | return n > 0 |
| 255 | }) |
| 256 | rv := dispatchOf(t, inst, id, wire.SpecialistReview) |
| 257 | if rv.ResearchNote == nil || !bytes.Equal(rv.ResearchNote.Findings, eng.ResearchNote.Findings) || len(rv.ResearchNote.Images) != 1 { |
| 258 | t.Fatalf("Review's dispatch %+v", rv.ResearchNote) |
| 259 | } |
| 260 | 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"} { |
| 261 | if !strings.Contains(rv.Brief, want) { |
| 262 | t.Fatalf("Review's brief lacks %q: %s", want, rv.Brief) |
| 263 | } |
| 264 | } |
| 265 | review := s.specialistStep(t, id, wire.SpecialistReview, 5*time.Minute) |
| 266 | if review.State != wire.StepDone { |
| 267 | t.Fatalf("Review %s %s: %s", review.State, review.Reason, review.Summary) |
| 268 | } |
| 269 | // No attempt's /research directory outlives it. |
| 270 | if left, _ := filepath.Glob(filepath.Join(r.cfg.StateDir, "research-work", "handoff-*")); len(left) != 0 { |
| 271 | t.Fatalf("hand-off directories left: %v", left) |
| 272 | } |
| 273 | } |
| 274 | |