package thin import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "image" "image/png" "net/netip" "os" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/webread" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/specialist" "amadan.net/oficina/equipo/internal/websource" "amadan.net/oficina/equipo/internal/wire" ) // researchRig is a primary with one healthy Claude connection of the // person's, a fetch phase that writes the bundles a test gives it (never // the network), a model that makes the tool calls a test scripts (no // containment), and a clock the test moves. type researchRig struct { t *testing.T dir string cfg runner.Config state *State e *Engineer mu sync.Mutex // passes are the bundles the fetch phase writes, one per launch. passes []func(p webread.Plan) ([]testFile, []webread.Entry) plans []webread.Plan cfgs []webread.LaunchConfig at []time.Duration // calls the model makes, in order, and what each tool answered. calls []testCall answers []testAnswer spec specialistRun ran int // workspace is what the model's /workspace held when it ran. workspace []string // clock and the waits the step asked for. now time.Time start time.Time sleeps []time.Duration // passTime is how long each fetch pass takes on the clock. passTime time.Duration } type testFile struct { source string text string png []byte } type testCall struct { name string args string } type testAnswer struct { text string isError bool } func newResearchRig(t *testing.T) *researchRig { t.Helper() dir := t.TempDir() for _, d := range []string{"state", "work", "scratch", "config"} { if err := os.MkdirAll(filepath.Join(dir, d), 0700); err != nil { t.Fatal(err) } } state, err := OpenState(context.Background(), filepath.Join(dir, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) home := filepath.Join(dir, "accounts", "claude-1") if err := os.MkdirAll(home, 0700); err != nil { t.Fatal(err) } identity := map[string]string{"account_id": "c1@example.com", "home_id": "h-1", "provider_version": "1"} raw, _ := json.Marshal([]map[string]any{{"id": "claude-1", "local_id": "claude-1", "label": "claude-1", "person_id": connPerson, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": "c1@example.com", "provider_home": home, "kind": "subscription", "expected_identity": identity}}) bindings := filepath.Join(dir, "config", "bindings.json") if err := os.WriteFile(bindings, raw, 0600); err != nil { t.Fatal(err) } cfg := runner.Config{Origin: "https://equipo.example.com", StateDir: filepath.Join(dir, "state"), WorkspaceRoot: filepath.Join(dir, "work"), ScratchRoot: filepath.Join(dir, "scratch"), AccountBindingsPath: bindings, BwrapPath: "/usr/bin/bwrap", Executable: "/usr/local/bin/equipo-runner", ClaudePath: "/bin/true", CodexPath: "/bin/true"} conns := &Conns{Runner: cfg, State: state} conns.Validated("claude-1") g := &researchRig{t: t, dir: dir, cfg: cfg, state: state, now: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)} g.start = g.now g.e = &Engineer{O: ClaudeOptions{Runner: cfg, State: state}, Conns: conns, Owners: []string{connPerson}} g.e.rh = researchHooks{ launch: g.launch, run: g.model, addrs: func() ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("81.2.69.160")}, nil }, now: func() time.Time { g.mu.Lock(); defer g.mu.Unlock(); return g.now }, sleep: func(ctx context.Context, d time.Duration) error { g.mu.Lock() defer g.mu.Unlock() g.sleeps = append(g.sleeps, d) g.now = g.now.Add(d) return ctx.Err() }, } return g } // launch writes the next pass's bundle into the output directory. func (g *researchRig) launch(_ context.Context, cfg webread.LaunchConfig, p webread.Plan) error { g.mu.Lock() n := len(g.plans) g.plans = append(g.plans, p) g.cfgs = append(g.cfgs, cfg) g.at = append(g.at, g.now.Sub(g.start)) g.now = g.now.Add(g.passTime) g.mu.Unlock() if err := checkPrivateEmpty(cfg.OutDir); err != nil { g.t.Errorf("pass %d output directory: %v", n, err) } if n >= len(g.passes) { return errors.New("no more passes") } files, log := g.passes[n](p) used := webread.Spent{Requests: len(log), Bytes: 10} if p.Spent != nil { used.Requests += p.Spent.Requests used.Bytes += p.Spent.Bytes } writeTestBundle(g.t, cfg.OutDir, files, log, used) return nil } func checkPrivateEmpty(dir string) error { st, err := os.Lstat(dir) if err != nil { return err } if !st.IsDir() || st.Mode().Perm() != 0700 { return fmt.Errorf("mode %v", st.Mode()) } names, _ := os.ReadDir(dir) if len(names) != 0 { return fmt.Errorf("not empty") } return nil } // writeTestBundle writes a bundle as the fetcher does: generated names, // a manifest with sizes and hashes, a log naming each file. func writeTestBundle(t *testing.T, dir string, files []testFile, log []webread.Entry, used webread.Spent) { t.Helper() m := webread.Manifest{Version: 1, Files: []webread.File{}, Log: log, Used: used} for i, f := range files { f := f var data []byte file := webread.File{Source: f.source} if f.png != nil { data = f.png c, err := png.DecodeConfig(bytes.NewReader(data)) if err != nil { t.Fatal(err) } file.Name, file.Kind, file.Type, file.Width, file.Height = fmt.Sprintf("s%03d.png", i+1), webread.KindImage, "image/png", c.Width, c.Height } else { data = []byte(f.text) file.Name, file.Kind, file.Type = fmt.Sprintf("s%03d.txt", i+1), webread.KindText, "text/html" } sum := sha256.Sum256(data) file.Size, file.SHA256 = int64(len(data)), hex.EncodeToString(sum[:]) m.Files = append(m.Files, file) for j := range m.Log { if m.Log[j].Source == f.source && m.Log[j].File == "" && m.Log[j].Reason == "" { m.Log[j].File = file.Name break } } if err := os.WriteFile(filepath.Join(dir, file.Name), data, 0600); err != nil { t.Fatal(err) } } raw, _ := json.Marshal(m) if err := os.WriteFile(filepath.Join(dir, webread.ManifestName), raw, 0600); err != nil { t.Fatal(err) } } // model plays the Research model: it makes the scripted tool calls // through the step's own tool function, as the socket would. func (g *researchRig) model(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { g.mu.Lock() g.ran++ g.spec = spec calls := slices.Clone(g.calls) g.mu.Unlock() entries, err := os.ReadDir(tree.Dir) if err != nil { g.t.Errorf("workspace: %v", err) } for _, e := range entries { g.workspace = append(g.workspace, e.Name()) } if !strings.HasPrefix(tree.Dir, g.cfg.WorkspaceRoot+string(os.PathSeparator)) { g.t.Errorf("workspace %s is not under the workspace root", tree.Dir) } for _, c := range calls { text, isError := spec.call(ctx, c.name, "toolu_1", json.RawMessage(c.args)) g.answers = append(g.answers, testAnswer{text, isError}) } return stepResult{terminated: true, summary: "Done.", tokens: []wire.Usage{{InputTokens: i64(10), OutputTokens: i64(5), Complete: true}}} } func pngBytes(t *testing.T, w, h int) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, w, h)) for i := range img.Pix { img.Pix[i] = byte(i * 7) } var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } func researchRow() stepRow { return stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "s_r1", Attempt: 1, Specialist: wire.SpecialistResearch, Title: "Shop colours", Brief: "Match the shop's colours on the site.", Findings: []wire.Finding{}, Research: &wire.ResearchDispatch{Question: "Colours and logo?", PersonWords: []string{"Use https://shop.example.com/ for the colours"}, SpecialistBrief: "Look up the shop's public pages for its colours, logo and opening hours.", SpecialistRevision: 2, Sources: []wire.ResearchSource{{ID: "s1", URL: "https://shop.example.com/", Origin: wire.ResearchOriginPerson}, {ID: "s2", URL: "https://shop.example.com/about", Origin: wire.ResearchOriginProposed}}, Inventory: []string{"81.2.69.160/32"}}}} } // page is pass one of the happy path: s1 a page, its logo e1 expanded // from it, s2 a page. func (g *researchRig) page(logo []byte) func(webread.Plan) ([]testFile, []webread.Entry) { return func(webread.Plan) ([]testFile, []webread.Entry) { return []testFile{{source: "s1", text: "Shop. Colours: teal and sand."}, {source: "s1.1", png: logo}, {source: "s2", text: "About the shop."}}, []webread.Entry{ {Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Hops: []webread.Hop{{URL: "https://shop.example.com/", Address: "151.101.1.1", Status: 200}}, Address: "151.101.1.1", Status: 200, Type: "text/html", Bytes: 30, SHA256: strings.Repeat("a", 64), Millis: 12}, {Source: "s2", Origin: webread.OriginProposed, URL: "https://shop.example.com/about", Address: "151.101.1.1", Status: 200, Type: "text/html", Bytes: 15, SHA256: strings.Repeat("b", 64), Millis: 9}, {Source: "s1.1", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://shop.example.com/logo.png", Address: "151.101.1.1", Status: 200, Type: "image/png", Bytes: int64(len(logo)), SHA256: strings.Repeat("c", 64), Millis: 5}, {Source: "s1.2", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://cdn.example.net/a.css", Reason: webread.ReasonNotPublic, Millis: 1}, } } } func (g *researchRig) exec(r stepRow) wire.StepReport { g.t.Helper() return g.e.Exec(context.Background(), r, func(wire.StepReport) {}) } func refusedNothingRan(t *testing.T, g *researchRig, name string, rep wire.StepReport) { t.Helper() if rep.State != wire.StepFailed || rep.Reason != "policy_rejected" || !rep.Termination || rep.Research != nil { t.Errorf("%s: %+v", name, rep) } if len(g.plans) != 0 || g.ran != 0 { t.Errorf("%s: %d fetch passes, %d model runs", name, len(g.plans), g.ran) } } // TestResearchRefusesARepositoryDispatch: a Research step names no // repository, branch or commit; one that does never fetches or runs. func TestResearchRefusesARepositoryDispatch(t *testing.T) { for name, change := range map[string]func(*stepRow){ "a repository": func(r *stepRow) { r.Repo = "amadan.net/oficina/sample" }, "a branch": func(r *stepRow) { r.Branch = "equipo/t-1" }, "a base": func(r *stepRow) { r.BaseSHA = strings.Repeat("a", 40) }, "a candidate": func(r *stepRow) { r.CandidateSHA = strings.Repeat("b", 40) }, "no research": func(r *stepRow) { r.Research = nil }, "not an owner": func(r *stepRow) { r.Person = "other@example.com" }, } { g := newResearchRig(t) r := researchRow() change(&r) refusedNothingRan(t, g, name, g.exec(r)) } } // TestResearchRefusesBadSourcesAndInventory: every source parses under // the one URL contract with a runner-shaped id, and the inventory is // there and well formed. func TestResearchRefusesBadSourcesAndInventory(t *testing.T) { for name, change := range map[string]func(*wire.ResearchDispatch){ "no sources": func(d *wire.ResearchDispatch) { d.Sources = nil }, "an ip literal": func(d *wire.ResearchDispatch) { d.Sources[0].URL = "https://10.0.0.1/" }, "a local name": func(d *wire.ResearchDispatch) { d.Sources[0].URL = "https://printer.local/" }, "not canonical": func(d *wire.ResearchDispatch) { d.Sources[0].URL = "https://SHOP.example.com/" }, "a proposal query": func(d *wire.ResearchDispatch) { d.Sources[1].URL = "https://shop.example.com/?q=1" }, "an unknown origin": func(d *wire.ResearchDispatch) { d.Sources[0].Origin = "expanded" }, "an upper-case id": func(d *wire.ResearchDispatch) { d.Sources[0].ID = "S1" }, "a dotted id": func(d *wire.ResearchDispatch) { d.Sources[0].ID = "s1.1" }, "a repeated id": func(d *wire.ResearchDispatch) { d.Sources[1].ID = "s1" }, "empty inventory": func(d *wire.ResearchDispatch) { d.Inventory = nil }, "unparsable inventory": func(d *wire.ResearchDispatch) { d.Inventory = []string{"81.2.69.160/33"} }, "an unmasked prefix": func(d *wire.ResearchDispatch) { d.Inventory = []string{"81.2.69.160/24"} }, "a bare address": func(d *wire.ResearchDispatch) { d.Inventory = []string{"81.2.69.160"} }, "no specialist brief": func(d *wire.ResearchDispatch) { d.SpecialistBrief = "" }, "a brief too long": func(d *wire.ResearchDispatch) { d.SpecialistBrief = strings.Repeat("b", specialist.MaxBrief+1) }, "a brief not UTF-8": func(d *wire.ResearchDispatch) { d.SpecialistBrief = "colours \xff" }, "no brief revision": func(d *wire.ResearchDispatch) { d.SpecialistRevision = 0 }, } { g := newResearchRig(t) // No public address here: only the dispatch's own checks refuse. g.e.rh.addrs = func() ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("10.0.0.4")}, nil } r := researchRow() change(r.Research) refusedNothingRan(t, g, name, g.exec(r)) } // The happy dispatch itself parses: the refusals above are the guards. for _, s := range researchRow().Research.Sources { if _, err := websource.Parse(s.URL); err != nil { t.Fatal(err) } } } // TestResearchRefusesAnAddressOutsideTheInventory: the step reads this // machine's addresses at its start; one outside the confirmed inventory, // or a list it cannot read, refuses the step (fail closed). Private and // shared addresses never matter: the fetcher refuses them anyway. func TestResearchRefusesAnAddressOutsideTheInventory(t *testing.T) { for name, c := range map[string]struct { addrs []string err error ok bool }{ "inside": {addrs: []string{"81.2.69.160"}, ok: true}, "inside an ipv6 /64": {addrs: []string{"81.2.69.160", "2a01:4f8:1:2::5"}, ok: true}, "private ignored": {addrs: []string{"81.2.69.160", "10.0.0.4", "100.100.1.2", "fd00::1"}, ok: true}, "outside": {addrs: []string{"81.2.69.160", "81.2.69.161"}}, "ipv6 outside": {addrs: []string{"81.2.69.160", "2a01:4f8:1:3::5"}}, "unreadable": {err: errors.New("no interfaces")}, } { g := newResearchRig(t) g.passes = append(g.passes, g.page(pngBytes(t, 4, 4))) g.e.rh.addrs = func() ([]netip.Addr, error) { var out []netip.Addr for _, a := range c.addrs { out = append(out, netip.MustParseAddr(a)) } return out, c.err } r := researchRow() r.Research.Inventory = []string{"81.2.69.160/32", "2a01:4f8:1:2::/64"} rep := g.exec(r) if c.ok { if rep.State != wire.StepDone || len(g.plans) != 1 { t.Errorf("%s: %+v", name, rep) } continue } refusedNothingRan(t, g, name, rep) } } // TestResearchStepReportsFindingsAndKeptImages is the whole step: the // fetch phase's plan, the model's inputs on an empty workspace, a kept // image copied for later steps, and a report whose image bytes go out // as research_file frames before the final report. func TestResearchStepReportsFindingsAndKeptImages(t *testing.T) { g := newResearchRig(t) logo := pngBytes(t, 64, 32) g.passes = append(g.passes, g.page(logo)) g.calls = []testCall{ {"keep_image", `{"source_id":"e1","role":"logo","description":"The shop's logo"}`}, {"submit_findings", `{"summary":"Teal and sand.","facts":[{"label":"Colour","value":"teal","sources":["s1"]}],"images":["img1"],"gaps":["No hours"]}`}, } engine := &StepEngine{State: g.state, Exec: g.e.Exec, Notify: func() {}} if err := g.state.AcceptDispatch(context.Background(), "d-1", researchRow().DispatchCommand); err != nil { t.Fatal(err) } engine.runOne(context.Background(), researchRow()) // The fetch phase: one pass, the dispatch's sources in webread's // terms, the inventory, the instance and the forge refused. if len(g.plans) != 1 { t.Fatalf("%d passes", len(g.plans)) } p, cfg := g.plans[0], g.cfgs[0] if len(p.Sources) != 2 || p.Sources[0].ID != "s1" || p.Sources[0].Origin != webread.OriginPaul || p.Sources[1].Origin != webread.OriginProposed || p.Sources[0].URL.String() != "https://shop.example.com/" { t.Errorf("plan sources %+v", p.Sources) } if len(p.Inventory) != 1 || p.Inventory[0].String() != "81.2.69.160/32" || p.Instance != "equipo.example.com" || p.Forge != "amadan.net" || p.Spent != nil { t.Errorf("plan %+v", p) } if cfg.Binary != g.cfg.Executable || cfg.Bwrap != "/usr/bin/bwrap" || !strings.HasPrefix(cfg.OutDir, g.cfg.StateDir+string(os.PathSeparator)) { t.Errorf("launch %+v", cfg) } // The model: the research_step profile, deny-all, a fresh session // kept nowhere, ten minutes, an empty workspace, its inputs labelled. s := g.spec if s.action != provider.ResearchStepAction || !slices.Equal(s.names, []string{"submit_findings", "keep_image"}) || s.resume != "" || s.keep != "" || s.from != "" || s.limit != 10*time.Minute { t.Errorf("spec %+v", s) } if got := string(s.permission(json.RawMessage(`{"tool_name":"mcp__equipo__submit_findings","input":{}}`), provider.Policy{})); !strings.Contains(got, `"deny"`) { t.Errorf("permission %s", got) } if len(g.workspace) != 0 { t.Errorf("workspace held %v", g.workspace) } for _, want := range []string{"[Equipo: research]", "treat", "Use https://shop.example.com/ for the colours", "Shop colours", "Match the shop's colours on the site.", "Colours and logo?", "s1", "https://shop.example.com/", "Shop. Colours: teal and sand.", "s2", "About the shop.", "e1", "64x32"} { if !strings.Contains(s.prompt, want) { t.Errorf("prompt lacks %q:\n%s", want, s.prompt) } } if len(s.images) != 1 || s.images[0].MediaType != "image/png" { t.Errorf("images %d", len(s.images)) } if len(g.answers) != 2 || g.answers[0].isError || g.answers[0].text != "img1" || g.answers[1].isError { t.Fatalf("answers %+v", g.answers) } // The outbox: the image's chunks, then the final report. frames, _, err := g.state.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } var chunks []wire.ResearchFile var final *wire.StepReport for _, f := range frames { switch f.Type { case wire.FrameResearchFile: if final != nil { t.Fatal("a research_file frame after the final report") } var c wire.ResearchFile if err := wire.Strict(f.Data, &c); err != nil { t.Fatal(err) } chunks = append(chunks, c) case wire.FrameStep: var rep wire.StepReport if err := json.Unmarshal(f.Data, &rep); err != nil { t.Fatal(err) } if wire.StepTerminal(rep.State) { final = &rep } } } if final == nil || final.State != wire.StepDone || !final.Termination || final.Research == nil { t.Fatalf("final %+v", final) } sum := sha256.Sum256(logo) if len(chunks) != 1 || chunks[0].TaskID != "tk1" || chunks[0].StepID != "s_r1" || chunks[0].Attempt != 1 || chunks[0].ImageID != "img1" || chunks[0].Index != 0 || chunks[0].Total != 1 || chunks[0].SHA256 != hex.EncodeToString(sum[:]) || chunks[0].Size != int64(len(logo)) { t.Fatalf("chunks %+v", chunks) } if data, err := base64.StdEncoding.DecodeString(chunks[0].Data); err != nil || !bytes.Equal(data, logo) { t.Fatalf("chunk data %v", err) } res := final.Research f, err := wire.DecodeFindings(res.Findings, map[string]bool{"s1": true}, map[string]bool{"img1": true}) if err != nil || f.Summary != "Teal and sand." || len(f.Facts) != 1 || f.Images[0] != "img1" || f.Gaps[0] != "No hours" { t.Fatalf("findings %s %v", res.Findings, err) } if len(res.Images) != 1 || !wire.ValidResearchImage(res.Images[0]) || res.Images[0].SourceID != "e1" || res.Images[0].Role != "logo" || res.Images[0].Width != 64 || res.Images[0].Height != 32 || res.Images[0].SHA256 != chunks[0].SHA256 { t.Fatalf("images %+v", res.Images) } want := []wire.ResearchFetch{ {SourceID: "s1", Origin: wire.ResearchOriginPerson, URL: "https://shop.example.com/", Address: "151.101.1.1", Status: 200, Type: "text/html", Bytes: 30, SHA256: strings.Repeat("a", 64), Millis: 12}, {SourceID: "s2", Origin: wire.ResearchOriginProposed, URL: "https://shop.example.com/about", Address: "151.101.1.1", Status: 200, Type: "text/html", Bytes: 15, SHA256: strings.Repeat("b", 64), Millis: 9}, {SourceID: "e1", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://shop.example.com/logo.png", Address: "151.101.1.1", Status: 200, Type: "image/png", Bytes: int64(len(logo)), SHA256: strings.Repeat("c", 64), Millis: 5}, {SourceID: "e2", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://cdn.example.net/a.css", Reason: webread.ReasonNotPublic, Millis: 1}, } got, _ := json.Marshal(res.Fetches) wantRaw, _ := json.Marshal(want) if !bytes.Equal(got, wantRaw) { t.Fatalf("fetches\n%s\nwant\n%s", got, wantRaw) } if len(final.Usage) != 1 || final.Family != "claude" || final.Account != "claude-1" { t.Errorf("usage %+v family %q", final.Usage, final.Family) } // The kept image stays for the task's later steps: a generated name // under research//, its hash in the state. kept, err := g.state.researchImages(context.Background(), "tk1") if err != nil || len(kept) != 1 || kept[0].ImageID != "img1" || kept[0].SHA256 != chunks[0].SHA256 || kept[0].StepID != "s_r1" { t.Fatalf("kept %+v %v", kept, err) } path := g.e.researchImagePath(kept[0]) if filepath.Dir(path) != filepath.Join(g.cfg.StateDir, "research", "tk1") { t.Fatalf("kept at %s", path) } if data, err := os.ReadFile(path); err != nil || !bytes.Equal(data, logo) { t.Fatalf("kept file: %v", err) } // The attempt's own directories are gone. if left, _ := filepath.Glob(filepath.Join(g.cfg.WorkspaceRoot, "*")); len(left) != 0 { t.Errorf("workspace root keeps %v", left) } if left, _ := filepath.Glob(filepath.Join(g.cfg.StateDir, researchWork, "*")); len(left) != 0 { t.Errorf("attempt dirs left %v", left) } // An attempt the runner stopped in (recovered failed) keeps nothing; // the done one keeps its image. stopped := researchRow() stopped.StepID = "s_r0" if err := g.state.AcceptDispatch(context.Background(), "d-0", stopped.DispatchCommand); err != nil { t.Fatal(err) } if err := g.e.keepResearchImage(context.Background(), stopped, wire.ResearchImage{ID: "img1", SourceID: "e1", Role: "logo", SHA256: chunks[0].SHA256, Size: int64(len(logo)), Width: 64, Height: 32}, logo); err != nil { t.Fatal(err) } if err := g.state.RecoverSteps(context.Background(), nil); err != nil { t.Fatal(err) } g.e.Sweep(context.Background(), g.state) if kept, _ := g.state.researchImages(context.Background(), "tk1"); len(kept) != 1 || kept[0].StepID != "s_r1" { t.Fatalf("after the sweep %+v", kept) } if left, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "*")); len(left) != 1 || left[0] != path { t.Fatalf("files after the sweep %v", left) } // The task ends: its kept images go with it. if _, err := g.state.ForgetTask(context.Background(), "f-1", wire.ForgetTaskCommand{Person: connPerson, TaskID: "tk1"}); err != nil { t.Fatal(err) } g.e.Sweep(context.Background(), g.state) if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) { t.Fatalf("the task's research directory stays: %v", err) } } // TestResearchKeepImageGuards: only an image of this attempt's bundle, // a known role, a short description, strict arguments, and at most eight. func TestResearchKeepImageGuards(t *testing.T) { g := newResearchRig(t) var files []testFile log := []webread.Entry{{Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Status: 200, Type: "text/html"}} files = append(files, testFile{source: "s1", text: "page"}) for i := 1; i <= 9; i++ { id := fmt.Sprintf("s1.%d", i) files = append(files, testFile{source: id, png: pngBytes(t, 2+i, 2)}) log = append(log, webread.Entry{Source: id, Origin: webread.OriginExpanded, Parent: "s1", URL: fmt.Sprintf("https://shop.example.com/%d.png", i), Status: 200, Type: "image/png"}) } g.passes = append(g.passes, func(webread.Plan) ([]testFile, []webread.Entry) { return files, log }) refused := []testCall{ {"keep_image", `{"source_id":"s9","role":"logo","description":"x"}`}, {"keep_image", `{"source_id":"s1","role":"logo","description":"a page, not an image"}`}, {"keep_image", `{"source_id":"e1","role":"banner","description":"x"}`}, {"keep_image", `{"source_id":"e1","role":"logo","description":"` + strings.Repeat("x", 201) + `"}`}, {"keep_image", `{"source_id":"e1","role":"logo","description":"x","path":"/etc/passwd"}`}, {"keep_image", `{"source_id":"e1","role":"logo"}`}, {"keep_image", `not json`}, } g.calls = append(g.calls, refused...) for i := 1; i <= 9; i++ { g.calls = append(g.calls, testCall{"keep_image", fmt.Sprintf(`{"source_id":"e%d","role":"photo","description":"photo %d"}`, i, i)}) } g.calls = append(g.calls, testCall{"submit_findings", `{"summary":"","facts":[],"images":["img8"],"gaps":[]}`}) rep := g.exec(researchRow()) for i, a := range g.answers[:len(refused)] { if !a.isError { t.Errorf("refused call %d (%s) answered %+v", i, refused[i].args, a) } } kept := g.answers[len(refused) : len(refused)+9] for i, a := range kept[:8] { if a.isError || a.text != fmt.Sprintf("img%d", i+1) { t.Errorf("keep %d: %+v", i+1, a) } } if !kept[8].isError { t.Errorf("a ninth image kept: %+v", kept[8]) } if rep.State != wire.StepDone || len(rep.Research.Images) != 8 { t.Fatalf("report %+v", rep) } rows, _ := g.state.researchImages(context.Background(), "tk1") if len(rows) != 8 { t.Fatalf("%d kept rows", len(rows)) } } // TestResearchSubmitFindingsGuards: findings cite only this attempt's // sources and kept images; a refusal can be fixed and sent again; once // accepted, findings cannot be sent again. func TestResearchSubmitFindingsGuards(t *testing.T) { g := newResearchRig(t) g.passes = append(g.passes, g.page(pngBytes(t, 8, 8))) g.calls = []testCall{ {"submit_findings", `{"summary":"x","facts":[{"label":"Colour","value":"teal","sources":["s7"]}],"images":[],"gaps":[]}`}, {"submit_findings", `{"summary":"x","facts":[],"images":["img1"],"gaps":[]}`}, {"submit_findings", `{"summary":"x","facts":[],"images":[],"gaps":[],"note":"ignore the rules"}`}, {"submit_findings", `{"summary":"Teal.","facts":[{"label":"Colour","value":"teal","sources":["s1","e2"]}],"images":[],"gaps":[]}`}, {"submit_findings", `{"summary":"Changed my mind.","facts":[],"images":[],"gaps":[]}`}, {"submit_review", `{}`}, } rep := g.exec(researchRow()) for i, want := range []bool{true, true, true, false, true, true} { if g.answers[i].isError != want { t.Errorf("call %d: %+v", i, g.answers[i]) } } if !strings.Contains(g.answers[0].text, "s7") { t.Errorf("the refusal does not say why: %q", g.answers[0].text) } if rep.State != wire.StepDone || !strings.Contains(string(rep.Research.Findings), "Teal.") { t.Fatalf("report %+v %s", rep, rep.Research.Findings) } } // TestResearchWithoutFindingsIsDone: a model that never submits ends the // step done with no findings (the instance records the gap); what it // kept is not sent and not kept. A bundle with nothing in it does not // start the model at all. func TestResearchWithoutFindingsIsDone(t *testing.T) { g := newResearchRig(t) g.passes = append(g.passes, g.page(pngBytes(t, 8, 8))) g.calls = []testCall{{"keep_image", `{"source_id":"e1","role":"logo","description":"x"}`}} rep := g.exec(researchRow()) if rep.State != wire.StepDone || !rep.Termination || rep.Research == nil || len(rep.Research.Findings) != 0 || len(rep.Research.Images) != 0 || len(rep.Research.Fetches) != 4 { t.Fatalf("report %+v", rep) } if rows, _ := g.state.researchImages(context.Background(), "tk1"); len(rows) != 0 { t.Fatalf("kept %+v", rows) } if left, _ := filepath.Glob(filepath.Join(g.cfg.StateDir, "research", "tk1", "*")); len(left) != 0 { t.Fatalf("files left %v", left) } frames, _, _ := g.state.Unacked(context.Background(), 0) for _, f := range frames { if f.Type == wire.FrameResearchFile { t.Fatal("an image sent without findings") } } g = newResearchRig(t) g.passes = append(g.passes, func(webread.Plan) ([]testFile, []webread.Entry) { return nil, []webread.Entry{{Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Reason: webread.ReasonStatus, Status: 404}, {Source: "s2", Origin: webread.OriginProposed, URL: "https://shop.example.com/about", Reason: webread.ReasonHostRefused}} }) rep = g.exec(researchRow()) if rep.State != wire.StepDone || g.ran != 0 || len(rep.Research.Fetches) != 2 || len(rep.Research.Findings) != 0 { t.Fatalf("nothing read: %+v, %d runs", rep, g.ran) } } // TestResearchRetriesOnAFixedSchedule: a source that failed for a // transient reason is fetched again 30 s and 2 min into the phase, never // more than twice, sharing the phase's budget; the model has no part in // it. Permanent failures are never retried, and a retry that would not // fit in the three minutes does not start. func TestResearchRetriesOnAFixedSchedule(t *testing.T) { g := newResearchRig(t) fail := func(reason string, status int) func(webread.Plan) ([]testFile, []webread.Entry) { return func(p webread.Plan) ([]testFile, []webread.Entry) { var log []webread.Entry for _, s := range p.Sources { log = append(log, webread.Entry{Source: s.ID, Origin: s.Origin, URL: s.URL.String(), Reason: reason, Status: status}) } return nil, log } } first := func(webread.Plan) ([]testFile, []webread.Entry) { return []testFile{{source: "s1", text: "ok"}}, []webread.Entry{ {Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Status: 200, Type: "text/html"}, {Source: "s2", Origin: webread.OriginProposed, URL: "https://shop.example.com/about", Reason: webread.ReasonTimeout}, {Source: "s3", Origin: webread.OriginPaul, URL: "https://shop.example.com/gone", Reason: webread.ReasonStatus, Status: 404}, {Source: "s4", Origin: webread.OriginPaul, URL: "https://shop.example.com/busy", Reason: webread.ReasonStatus, Status: 503}, {Source: "s1.1", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://shop.example.com/x.css", Reason: webread.ReasonConnect}, } } g.passes = append(g.passes, first, fail(webread.ReasonConnect, 0), fail(webread.ReasonLookup, 0), fail(webread.ReasonLookup, 0)) r := researchRow() r.Research.Sources = append(r.Research.Sources, wire.ResearchSource{ID: "s3", URL: "https://shop.example.com/gone", Origin: wire.ResearchOriginPerson}, wire.ResearchSource{ID: "s4", URL: "https://shop.example.com/busy", Origin: wire.ResearchOriginPerson}) g.calls = []testCall{{"submit_findings", `{"summary":"","facts":[],"images":[],"gaps":[]}`}} rep := g.exec(r) if len(g.plans) != 3 || !slices.Equal(g.at, []time.Duration{0, 30 * time.Second, 2 * time.Minute}) { t.Fatalf("passes at %v", g.at) } for i, p := range g.plans[1:] { var ids []string for _, s := range p.Sources { ids = append(ids, s.ID) } if !slices.Equal(ids, []string{"s2", "s4"}) || p.Spent == nil || p.Spent.Requests != 5+2*i { t.Errorf("retry %d: %v spent %+v", i+1, ids, p.Spent) } } if rep.State != wire.StepDone || len(rep.Research.Fetches) != 9 || g.ran != 1 { t.Fatalf("report %+v (%d fetch lines)", rep, len(rep.Research.Fetches)) } // A first pass that took most of the phase leaves no room for a retry. g = newResearchRig(t) g.passTime = 2*time.Minute + 50*time.Second g.passes = append(g.passes, first, fail(webread.ReasonConnect, 0)) g.exec(r) if len(g.plans) != 1 { t.Fatalf("a retry past the phase: %v", g.at) } } // TestResearchCapabilityAddresses: the hello reports the public global // unicast addresses, canonical and bounded; an error leaves it out. func TestResearchCapabilityAddresses(t *testing.T) { list := func(addrs ...string) func() ([]netip.Addr, error) { return func() ([]netip.Addr, error) { var out []netip.Addr for _, a := range addrs { out = append(out, netip.MustParseAddr(a)) } return out, nil } } c := researchCapability(list("2a01:4f8:1:2::5", "81.2.69.160", "10.0.0.4", "100.100.1.2", "fd00::1", "81.2.69.160")) if c == nil || !slices.Equal(c.Addresses, []string{"81.2.69.160", "2a01:4f8:1:2::5"}) { t.Fatalf("addresses %+v", c) } for _, a := range c.Addresses { if !wire.ValidResearchAddress(a) { t.Fatalf("%s", a) } } if c := researchCapability(list()); c == nil || c.Addresses == nil || len(c.Addresses) != 0 { t.Fatalf("none: %+v", c) } if c := researchCapability(func() ([]netip.Addr, error) { return nil, errors.New("no") }); c != nil { t.Fatalf("an error reported %+v", c) } // A Linux primary's capability report carries them. if c := linuxCapabilities(runner.Config{}, func() *wire.PreviewHost { return nil }, nil, nil, nil)(context.Background()); c.Research == nil { t.Fatal("the Linux report has no Research addresses") } var many []string for i := range 40 { many = append(many, fmt.Sprintf("81.2.69.%d", i+1)) } if c := researchCapability(list(many...)); len(c.Addresses) != wire.MaxResearchAddresses || wire.ValidCapabilities(wire.Capabilities{Research: c}) != nil { t.Fatalf("bounded: %d", len(c.Addresses)) } } // TestHandshakeHelloWithholdsResearch: the first hello goes out before // the instance says its protocol, so it never carries the Research // addresses; after a protocol 13 welcome the next hello, sent at once, // does; at 11 none ever does. func TestHandshakeHelloWithholdsResearch(t *testing.T) { hello := func() wire.Hello { return wire.Hello{Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}, Capabilities: &wire.Capabilities{Tags: []string{wire.TagLinux}, Simulators: []wire.Simulator{}, Research: &wire.ResearchCapability{Addresses: []string{"81.2.69.160"}}}} } for _, protocol := range []int{wire.ProtocolPreviewHost, wire.ProtocolResearch} { inst := newFakeInstance(t) link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) c := <-inst.conns _, raw := read(t, c, wire.FrameHello) if strings.Contains(string(raw), `"research"`) || !strings.Contains(string(raw), `"linux"`) { t.Fatalf("handshake hello: %s", raw) } welcome, _ := json.Marshal(wire.Frame{ID: "w-r", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":` + itoa(int64(protocol)) + `,"role":"primary"}`)}) write(t, c, welcome) read(t, c, wire.FrameSync) if protocol < wire.ProtocolResearch { link.HelloSoon() } _, raw = read(t, c, wire.FrameHello) if got := strings.Contains(string(raw), `"research":{"addresses":["81.2.69.160"]}`); got != (protocol >= wire.ProtocolResearch) { t.Fatalf("protocol %d hello: %s", protocol, raw) } } } // TestResearchAuthorizedRightBeforeFetching (Astra security finding 3): // the start authorization comes immediately before the fetch phase, // after a connection is chosen: a step deferred for want of a connection // was never authorized (the instance can still cancel it as queued), a // resume asks again, and so does every retry pass. A refused start // fetches nothing. func TestResearchAuthorizedRightBeforeFetching(t *testing.T) { g := newResearchRig(t) var asked int var passesWhenAsked []int g.e.AuthorizeStep = func(context.Context, string, int64) error { asked++ return nil } g.e.Conns.Limit("claude-1", connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) if rep := g.exec(researchRow()); rep.State != stepDeferred || asked != 0 || len(g.plans) != 0 { t.Fatalf("deferred: %+v, %d authorizations, %d passes", rep, asked, len(g.plans)) } // The resume, with a connection again. auth := g.e.AuthorizeStep g = newResearchRig(t) g.e.AuthorizeStep = func(ctx context.Context, step string, attempt int64) error { g.mu.Lock() passes := len(g.plans) g.mu.Unlock() passesWhenAsked = append(passesWhenAsked, passes) return auth(ctx, step, attempt) } passesWhenAsked = nil fail := func(p webread.Plan) ([]testFile, []webread.Entry) { var log []webread.Entry for _, s := range p.Sources { log = append(log, webread.Entry{Source: s.ID, Origin: s.Origin, URL: s.URL.String(), Reason: webread.ReasonConnect}) } return nil, log } g.passes = append(g.passes, fail, fail, fail) g.exec(researchRow()) if len(g.plans) != 3 || !slices.Equal(passesWhenAsked, []int{0, 1, 2}) { t.Fatalf("authorized before passes %v, %d passes", passesWhenAsked, len(g.plans)) } // Refused before the first pass: nothing is fetched. g = newResearchRig(t) g.e.AuthorizeStep = func(context.Context, string, int64) error { return ErrWithdrawn } if rep := g.exec(researchRow()); rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || len(g.plans) != 0 || g.ran != 0 { t.Fatalf("refused start: %+v, %d passes", rep, len(g.plans)) } // Refused before a retry pass: no further pass; what was read goes on. g = newResearchRig(t) n := 0 g.e.AuthorizeStep = func(context.Context, string, int64) error { n++ if n > 1 { return ErrWithdrawn } return nil } g.passes = append(g.passes, fail, fail) if rep := g.exec(researchRow()); len(g.plans) != 1 || rep.State != wire.StepCancelled || rep.Reason != "withdrawn" { t.Fatalf("refused retry: %+v, %d passes", rep, len(g.plans)) } } // TestResearchKeepsTheRedirectChain (Astra security finding 5): the // fetcher's hops start with the request to the source's own URL; the // report keeps every redirect after it, a full chain of // wire.MaxResearchHops, each with its address and status. func TestResearchKeepsTheRedirectChain(t *testing.T) { g := newResearchRig(t) hops := []webread.Hop{{URL: "https://shop.example.com/", Address: "151.101.1.1", Status: 301}} var want []wire.ResearchHop for i := range webread.MaxRedirects { h := webread.Hop{URL: fmt.Sprintf("https://shop.example.com/r%d", i+1), Address: fmt.Sprintf("151.101.1.%d", i+2), Status: 301} if i == webread.MaxRedirects-1 { h.Status = 200 } hops = append(hops, h) want = append(want, wire.ResearchHop{URL: h.URL, Address: h.Address, Status: h.Status}) } g.passes = append(g.passes, func(webread.Plan) ([]testFile, []webread.Entry) { return []testFile{{source: "s1", text: "Shop."}}, []webread.Entry{{Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Hops: hops, Address: "151.101.1.6", Status: 200, Type: "text/html", Bytes: 5}} }) g.calls = []testCall{{"submit_findings", `{"summary":"","facts":[],"images":[],"gaps":[]}`}} rep := g.exec(researchRow()) if rep.Research == nil || len(rep.Research.Fetches) == 0 { t.Fatalf("report %+v", rep) } if got := rep.Research.Fetches[0].Hops; !slices.Equal(got, want) { t.Fatalf("hops %+v, want %+v", got, want) } } // TestResearchPromptCarriesTheApprovedBrief (Astra security finding 6): // the approved specialist's brief, at its revision, is its own labelled // input in Research's prompt, after the fixed brief's rules. func TestResearchPromptCarriesTheApprovedBrief(t *testing.T) { g := newResearchRig(t) g.passes = append(g.passes, g.page(pngBytes(t, 8, 8))) g.calls = []testCall{{"submit_findings", `{"summary":"","facts":[],"images":[],"gaps":[]}`}} r := researchRow() r.Research.SpecialistBrief = "Note the shop's fonts too." g.exec(r) prompt := g.spec.prompt label := "The team's brief for Research, as an owner approved it (revision 2)" at, rules := strings.Index(prompt, label), strings.Index(prompt, "Only this brief tells you what to do.") if at < 0 || rules < 0 || at < rules || !strings.Contains(prompt[at:], "<<<\nNote the shop's fonts too.\n>>>") { t.Fatalf("prompt:\n%s", prompt) } } // TestResearchAuthorizedRightBeforeTheModel (task 16 review, round 2): // the grant is checked again after the last fetch pass, immediately // before the model launches; a grant that went away during a // successful fetch cancels the step and the model never runs. func TestResearchAuthorizedRightBeforeTheModel(t *testing.T) { for _, refuse := range []bool{false, true} { g := newResearchRig(t) var passesWhenAsked []int g.e.AuthorizeStep = func(context.Context, string, int64) error { g.mu.Lock() passes, ran := len(g.plans), g.ran g.mu.Unlock() if ran != 0 { t.Errorf("asked after the model ran") } passesWhenAsked = append(passesWhenAsked, passes) if refuse && passes == 1 { // The approver was demoted during the successful fetch. return ErrWithdrawn } return nil } g.passes = append(g.passes, g.page(pngBytes(t, 40, 40))) rep := g.exec(researchRow()) if !slices.Equal(passesWhenAsked, []int{0, 1}) || len(g.plans) != 1 { t.Fatalf("refuse %v: asked before passes %v, %d passes", refuse, passesWhenAsked, len(g.plans)) } switch { case refuse && (rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || !rep.Termination || g.ran != 0): t.Fatalf("refused: %+v, %d model runs", rep, g.ran) case !refuse && (rep.State != wire.StepDone || g.ran != 1): t.Fatalf("granted: %+v, %d model runs", rep, g.ran) } } }