| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "image" |
| 13 | "image/png" |
| 14 | "net/netip" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "slices" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "testing" |
| 21 | "time" |
| 22 | |
| 23 | "amadan.net/oficina/equipo/internal/runner" |
| 24 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 25 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 26 | "amadan.net/oficina/equipo/internal/runner/webread" |
| 27 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 28 | "amadan.net/oficina/equipo/internal/specialist" |
| 29 | "amadan.net/oficina/equipo/internal/websource" |
| 30 | "amadan.net/oficina/equipo/internal/wire" |
| 31 | ) |
| 32 | |
| 33 | // researchRig is a primary with one healthy Claude connection of the |
| 34 | // person's, a fetch phase that writes the bundles a test gives it (never |
| 35 | // the network), a model that makes the tool calls a test scripts (no |
| 36 | // containment), and a clock the test moves. |
| 37 | type researchRig struct { |
| 38 | t *testing.T |
| 39 | dir string |
| 40 | cfg runner.Config |
| 41 | state *State |
| 42 | e *Engineer |
| 43 | |
| 44 | mu sync.Mutex |
| 45 | // passes are the bundles the fetch phase writes, one per launch. |
| 46 | passes []func(p webread.Plan) ([]testFile, []webread.Entry) |
| 47 | plans []webread.Plan |
| 48 | cfgs []webread.LaunchConfig |
| 49 | at []time.Duration |
| 50 | // calls the model makes, in order, and what each tool answered. |
| 51 | calls []testCall |
| 52 | answers []testAnswer |
| 53 | spec specialistRun |
| 54 | ran int |
| 55 | // workspace is what the model's /workspace held when it ran. |
| 56 | workspace []string |
| 57 | // clock and the waits the step asked for. |
| 58 | now time.Time |
| 59 | start time.Time |
| 60 | sleeps []time.Duration |
| 61 | // passTime is how long each fetch pass takes on the clock. |
| 62 | passTime time.Duration |
| 63 | } |
| 64 | |
| 65 | type testFile struct { |
| 66 | source string |
| 67 | text string |
| 68 | png []byte |
| 69 | } |
| 70 | |
| 71 | type testCall struct { |
| 72 | name string |
| 73 | args string |
| 74 | } |
| 75 | |
| 76 | type testAnswer struct { |
| 77 | text string |
| 78 | isError bool |
| 79 | } |
| 80 | |
| 81 | func newResearchRig(t *testing.T) *researchRig { |
| 82 | t.Helper() |
| 83 | dir := t.TempDir() |
| 84 | for _, d := range []string{"state", "work", "scratch", "config"} { |
| 85 | if err := os.MkdirAll(filepath.Join(dir, d), 0700); err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | } |
| 89 | state, err := OpenState(context.Background(), filepath.Join(dir, "state")) |
| 90 | if err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | t.Cleanup(func() { state.Close() }) |
| 94 | home := filepath.Join(dir, "accounts", "claude-1") |
| 95 | if err := os.MkdirAll(home, 0700); err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | identity := map[string]string{"account_id": "c1@example.com", "home_id": "h-1", "provider_version": "1"} |
| 99 | 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}}) |
| 100 | bindings := filepath.Join(dir, "config", "bindings.json") |
| 101 | if err := os.WriteFile(bindings, raw, 0600); err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | 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"} |
| 105 | conns := &Conns{Runner: cfg, State: state} |
| 106 | conns.Validated("claude-1") |
| 107 | g := &researchRig{t: t, dir: dir, cfg: cfg, state: state, now: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)} |
| 108 | g.start = g.now |
| 109 | g.e = &Engineer{O: ClaudeOptions{Runner: cfg, State: state}, Conns: conns, Owners: []string{connPerson}} |
| 110 | g.e.rh = researchHooks{ |
| 111 | launch: g.launch, |
| 112 | run: g.model, |
| 113 | addrs: func() ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("81.2.69.160")}, nil }, |
| 114 | now: func() time.Time { g.mu.Lock(); defer g.mu.Unlock(); return g.now }, |
| 115 | sleep: func(ctx context.Context, d time.Duration) error { |
| 116 | g.mu.Lock() |
| 117 | defer g.mu.Unlock() |
| 118 | g.sleeps = append(g.sleeps, d) |
| 119 | g.now = g.now.Add(d) |
| 120 | return ctx.Err() |
| 121 | }, |
| 122 | } |
| 123 | return g |
| 124 | } |
| 125 | |
| 126 | // launch writes the next pass's bundle into the output directory. |
| 127 | func (g *researchRig) launch(_ context.Context, cfg webread.LaunchConfig, p webread.Plan) error { |
| 128 | g.mu.Lock() |
| 129 | n := len(g.plans) |
| 130 | g.plans = append(g.plans, p) |
| 131 | g.cfgs = append(g.cfgs, cfg) |
| 132 | g.at = append(g.at, g.now.Sub(g.start)) |
| 133 | g.now = g.now.Add(g.passTime) |
| 134 | g.mu.Unlock() |
| 135 | if err := checkPrivateEmpty(cfg.OutDir); err != nil { |
| 136 | g.t.Errorf("pass %d output directory: %v", n, err) |
| 137 | } |
| 138 | if n >= len(g.passes) { |
| 139 | return errors.New("no more passes") |
| 140 | } |
| 141 | files, log := g.passes[n](p) |
| 142 | used := webread.Spent{Requests: len(log), Bytes: 10} |
| 143 | if p.Spent != nil { |
| 144 | used.Requests += p.Spent.Requests |
| 145 | used.Bytes += p.Spent.Bytes |
| 146 | } |
| 147 | writeTestBundle(g.t, cfg.OutDir, files, log, used) |
| 148 | return nil |
| 149 | } |
| 150 | |
| 151 | func checkPrivateEmpty(dir string) error { |
| 152 | st, err := os.Lstat(dir) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | if !st.IsDir() || st.Mode().Perm() != 0700 { |
| 157 | return fmt.Errorf("mode %v", st.Mode()) |
| 158 | } |
| 159 | names, _ := os.ReadDir(dir) |
| 160 | if len(names) != 0 { |
| 161 | return fmt.Errorf("not empty") |
| 162 | } |
| 163 | return nil |
| 164 | } |
| 165 | |
| 166 | // writeTestBundle writes a bundle as the fetcher does: generated names, |
| 167 | // a manifest with sizes and hashes, a log naming each file. |
| 168 | func writeTestBundle(t *testing.T, dir string, files []testFile, log []webread.Entry, used webread.Spent) { |
| 169 | t.Helper() |
| 170 | m := webread.Manifest{Version: 1, Files: []webread.File{}, Log: log, Used: used} |
| 171 | for i, f := range files { |
| 172 | f := f |
| 173 | var data []byte |
| 174 | file := webread.File{Source: f.source} |
| 175 | if f.png != nil { |
| 176 | data = f.png |
| 177 | c, err := png.DecodeConfig(bytes.NewReader(data)) |
| 178 | if err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | 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 |
| 182 | } else { |
| 183 | data = []byte(f.text) |
| 184 | file.Name, file.Kind, file.Type = fmt.Sprintf("s%03d.txt", i+1), webread.KindText, "text/html" |
| 185 | } |
| 186 | sum := sha256.Sum256(data) |
| 187 | file.Size, file.SHA256 = int64(len(data)), hex.EncodeToString(sum[:]) |
| 188 | m.Files = append(m.Files, file) |
| 189 | for j := range m.Log { |
| 190 | if m.Log[j].Source == f.source && m.Log[j].File == "" && m.Log[j].Reason == "" { |
| 191 | m.Log[j].File = file.Name |
| 192 | break |
| 193 | } |
| 194 | } |
| 195 | if err := os.WriteFile(filepath.Join(dir, file.Name), data, 0600); err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | } |
| 199 | raw, _ := json.Marshal(m) |
| 200 | if err := os.WriteFile(filepath.Join(dir, webread.ManifestName), raw, 0600); err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | // model plays the Research model: it makes the scripted tool calls |
| 206 | // through the step's own tool function, as the socket would. |
| 207 | func (g *researchRig) model(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { |
| 208 | g.mu.Lock() |
| 209 | g.ran++ |
| 210 | g.spec = spec |
| 211 | calls := slices.Clone(g.calls) |
| 212 | g.mu.Unlock() |
| 213 | entries, err := os.ReadDir(tree.Dir) |
| 214 | if err != nil { |
| 215 | g.t.Errorf("workspace: %v", err) |
| 216 | } |
| 217 | for _, e := range entries { |
| 218 | g.workspace = append(g.workspace, e.Name()) |
| 219 | } |
| 220 | if !strings.HasPrefix(tree.Dir, g.cfg.WorkspaceRoot+string(os.PathSeparator)) { |
| 221 | g.t.Errorf("workspace %s is not under the workspace root", tree.Dir) |
| 222 | } |
| 223 | for _, c := range calls { |
| 224 | text, isError := spec.call(ctx, c.name, "toolu_1", json.RawMessage(c.args)) |
| 225 | g.answers = append(g.answers, testAnswer{text, isError}) |
| 226 | } |
| 227 | return stepResult{terminated: true, summary: "Done.", tokens: []wire.Usage{{InputTokens: i64(10), OutputTokens: i64(5), Complete: true}}} |
| 228 | } |
| 229 | |
| 230 | func pngBytes(t *testing.T, w, h int) []byte { |
| 231 | t.Helper() |
| 232 | img := image.NewRGBA(image.Rect(0, 0, w, h)) |
| 233 | for i := range img.Pix { |
| 234 | img.Pix[i] = byte(i * 7) |
| 235 | } |
| 236 | var b bytes.Buffer |
| 237 | if err := png.Encode(&b, img); err != nil { |
| 238 | t.Fatal(err) |
| 239 | } |
| 240 | return b.Bytes() |
| 241 | } |
| 242 | |
| 243 | func researchRow() stepRow { |
| 244 | 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{}, |
| 245 | 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, |
| 246 | Sources: []wire.ResearchSource{{ID: "s1", URL: "https://shop.example.com/", Origin: wire.ResearchOriginPerson}, {ID: "s2", URL: "https://shop.example.com/about", Origin: wire.ResearchOriginProposed}}, |
| 247 | Inventory: []string{"81.2.69.160/32"}}}} |
| 248 | } |
| 249 | |
| 250 | // page is pass one of the happy path: s1 a page, its logo e1 expanded |
| 251 | // from it, s2 a page. |
| 252 | func (g *researchRig) page(logo []byte) func(webread.Plan) ([]testFile, []webread.Entry) { |
| 253 | return func(webread.Plan) ([]testFile, []webread.Entry) { |
| 254 | return []testFile{{source: "s1", text: "Shop. Colours: teal and sand."}, {source: "s1.1", png: logo}, {source: "s2", text: "About the shop."}}, |
| 255 | []webread.Entry{ |
| 256 | {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}, |
| 257 | {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}, |
| 258 | {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}, |
| 259 | {Source: "s1.2", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://cdn.example.net/a.css", Reason: webread.ReasonNotPublic, Millis: 1}, |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | func (g *researchRig) exec(r stepRow) wire.StepReport { |
| 265 | g.t.Helper() |
| 266 | return g.e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| 267 | } |
| 268 | |
| 269 | func refusedNothingRan(t *testing.T, g *researchRig, name string, rep wire.StepReport) { |
| 270 | t.Helper() |
| 271 | if rep.State != wire.StepFailed || rep.Reason != "policy_rejected" || !rep.Termination || rep.Research != nil { |
| 272 | t.Errorf("%s: %+v", name, rep) |
| 273 | } |
| 274 | if len(g.plans) != 0 || g.ran != 0 { |
| 275 | t.Errorf("%s: %d fetch passes, %d model runs", name, len(g.plans), g.ran) |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // TestResearchRefusesARepositoryDispatch: a Research step names no |
| 280 | // repository, branch or commit; one that does never fetches or runs. |
| 281 | func TestResearchRefusesARepositoryDispatch(t *testing.T) { |
| 282 | for name, change := range map[string]func(*stepRow){ |
| 283 | "a repository": func(r *stepRow) { r.Repo = "amadan.net/oficina/sample" }, |
| 284 | "a branch": func(r *stepRow) { r.Branch = "equipo/t-1" }, |
| 285 | "a base": func(r *stepRow) { r.BaseSHA = strings.Repeat("a", 40) }, |
| 286 | "a candidate": func(r *stepRow) { r.CandidateSHA = strings.Repeat("b", 40) }, |
| 287 | "no research": func(r *stepRow) { r.Research = nil }, |
| 288 | "not an owner": func(r *stepRow) { r.Person = "other@example.com" }, |
| 289 | } { |
| 290 | g := newResearchRig(t) |
| 291 | r := researchRow() |
| 292 | change(&r) |
| 293 | refusedNothingRan(t, g, name, g.exec(r)) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | // TestResearchRefusesBadSourcesAndInventory: every source parses under |
| 298 | // the one URL contract with a runner-shaped id, and the inventory is |
| 299 | // there and well formed. |
| 300 | func TestResearchRefusesBadSourcesAndInventory(t *testing.T) { |
| 301 | for name, change := range map[string]func(*wire.ResearchDispatch){ |
| 302 | "no sources": func(d *wire.ResearchDispatch) { d.Sources = nil }, |
| 303 | "an ip literal": func(d *wire.ResearchDispatch) { d.Sources[0].URL = "https://10.0.0.1/" }, |
| 304 | "a local name": func(d *wire.ResearchDispatch) { d.Sources[0].URL = "https://printer.local/" }, |
| 305 | "not canonical": func(d *wire.ResearchDispatch) { d.Sources[0].URL = "https://SHOP.example.com/" }, |
| 306 | "a proposal query": func(d *wire.ResearchDispatch) { d.Sources[1].URL = "https://shop.example.com/?q=1" }, |
| 307 | "an unknown origin": func(d *wire.ResearchDispatch) { d.Sources[0].Origin = "expanded" }, |
| 308 | "an upper-case id": func(d *wire.ResearchDispatch) { d.Sources[0].ID = "S1" }, |
| 309 | "a dotted id": func(d *wire.ResearchDispatch) { d.Sources[0].ID = "s1.1" }, |
| 310 | "a repeated id": func(d *wire.ResearchDispatch) { d.Sources[1].ID = "s1" }, |
| 311 | "empty inventory": func(d *wire.ResearchDispatch) { d.Inventory = nil }, |
| 312 | "unparsable inventory": func(d *wire.ResearchDispatch) { d.Inventory = []string{"81.2.69.160/33"} }, |
| 313 | "an unmasked prefix": func(d *wire.ResearchDispatch) { d.Inventory = []string{"81.2.69.160/24"} }, |
| 314 | "a bare address": func(d *wire.ResearchDispatch) { d.Inventory = []string{"81.2.69.160"} }, |
| 315 | "no specialist brief": func(d *wire.ResearchDispatch) { d.SpecialistBrief = "" }, |
| 316 | "a brief too long": func(d *wire.ResearchDispatch) { d.SpecialistBrief = strings.Repeat("b", specialist.MaxBrief+1) }, |
| 317 | "a brief not UTF-8": func(d *wire.ResearchDispatch) { d.SpecialistBrief = "colours \xff" }, |
| 318 | "no brief revision": func(d *wire.ResearchDispatch) { d.SpecialistRevision = 0 }, |
| 319 | } { |
| 320 | g := newResearchRig(t) |
| 321 | // No public address here: only the dispatch's own checks refuse. |
| 322 | g.e.rh.addrs = func() ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("10.0.0.4")}, nil } |
| 323 | r := researchRow() |
| 324 | change(r.Research) |
| 325 | refusedNothingRan(t, g, name, g.exec(r)) |
| 326 | } |
| 327 | // The happy dispatch itself parses: the refusals above are the guards. |
| 328 | for _, s := range researchRow().Research.Sources { |
| 329 | if _, err := websource.Parse(s.URL); err != nil { |
| 330 | t.Fatal(err) |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | // TestResearchRefusesAnAddressOutsideTheInventory: the step reads this |
| 336 | // machine's addresses at its start; one outside the confirmed inventory, |
| 337 | // or a list it cannot read, refuses the step (fail closed). Private and |
| 338 | // shared addresses never matter: the fetcher refuses them anyway. |
| 339 | func TestResearchRefusesAnAddressOutsideTheInventory(t *testing.T) { |
| 340 | for name, c := range map[string]struct { |
| 341 | addrs []string |
| 342 | err error |
| 343 | ok bool |
| 344 | }{ |
| 345 | "inside": {addrs: []string{"81.2.69.160"}, ok: true}, |
| 346 | "inside an ipv6 /64": {addrs: []string{"81.2.69.160", "2a01:4f8:1:2::5"}, ok: true}, |
| 347 | "private ignored": {addrs: []string{"81.2.69.160", "10.0.0.4", "100.100.1.2", "fd00::1"}, ok: true}, |
| 348 | "outside": {addrs: []string{"81.2.69.160", "81.2.69.161"}}, |
| 349 | "ipv6 outside": {addrs: []string{"81.2.69.160", "2a01:4f8:1:3::5"}}, |
| 350 | "unreadable": {err: errors.New("no interfaces")}, |
| 351 | } { |
| 352 | g := newResearchRig(t) |
| 353 | g.passes = append(g.passes, g.page(pngBytes(t, 4, 4))) |
| 354 | g.e.rh.addrs = func() ([]netip.Addr, error) { |
| 355 | var out []netip.Addr |
| 356 | for _, a := range c.addrs { |
| 357 | out = append(out, netip.MustParseAddr(a)) |
| 358 | } |
| 359 | return out, c.err |
| 360 | } |
| 361 | r := researchRow() |
| 362 | r.Research.Inventory = []string{"81.2.69.160/32", "2a01:4f8:1:2::/64"} |
| 363 | rep := g.exec(r) |
| 364 | if c.ok { |
| 365 | if rep.State != wire.StepDone || len(g.plans) != 1 { |
| 366 | t.Errorf("%s: %+v", name, rep) |
| 367 | } |
| 368 | continue |
| 369 | } |
| 370 | refusedNothingRan(t, g, name, rep) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | // TestResearchStepReportsFindingsAndKeptImages is the whole step: the |
| 375 | // fetch phase's plan, the model's inputs on an empty workspace, a kept |
| 376 | // image copied for later steps, and a report whose image bytes go out |
| 377 | // as research_file frames before the final report. |
| 378 | func TestResearchStepReportsFindingsAndKeptImages(t *testing.T) { |
| 379 | g := newResearchRig(t) |
| 380 | logo := pngBytes(t, 64, 32) |
| 381 | g.passes = append(g.passes, g.page(logo)) |
| 382 | g.calls = []testCall{ |
| 383 | {"keep_image", `{"source_id":"e1","role":"logo","description":"The shop's logo"}`}, |
| 384 | {"submit_findings", `{"summary":"Teal and sand.","facts":[{"label":"Colour","value":"teal","sources":["s1"]}],"images":["img1"],"gaps":["No hours"]}`}, |
| 385 | } |
| 386 | engine := &StepEngine{State: g.state, Exec: g.e.Exec, Notify: func() {}} |
| 387 | if err := g.state.AcceptDispatch(context.Background(), "d-1", researchRow().DispatchCommand); err != nil { |
| 388 | t.Fatal(err) |
| 389 | } |
| 390 | engine.runOne(context.Background(), researchRow()) |
| 391 | |
| 392 | // The fetch phase: one pass, the dispatch's sources in webread's |
| 393 | // terms, the inventory, the instance and the forge refused. |
| 394 | if len(g.plans) != 1 { |
| 395 | t.Fatalf("%d passes", len(g.plans)) |
| 396 | } |
| 397 | p, cfg := g.plans[0], g.cfgs[0] |
| 398 | 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/" { |
| 399 | t.Errorf("plan sources %+v", p.Sources) |
| 400 | } |
| 401 | 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 { |
| 402 | t.Errorf("plan %+v", p) |
| 403 | } |
| 404 | if cfg.Binary != g.cfg.Executable || cfg.Bwrap != "/usr/bin/bwrap" || !strings.HasPrefix(cfg.OutDir, g.cfg.StateDir+string(os.PathSeparator)) { |
| 405 | t.Errorf("launch %+v", cfg) |
| 406 | } |
| 407 | |
| 408 | // The model: the research_step profile, deny-all, a fresh session |
| 409 | // kept nowhere, ten minutes, an empty workspace, its inputs labelled. |
| 410 | s := g.spec |
| 411 | 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 { |
| 412 | t.Errorf("spec %+v", s) |
| 413 | } |
| 414 | if got := string(s.permission(json.RawMessage(`{"tool_name":"mcp__equipo__submit_findings","input":{}}`), provider.Policy{})); !strings.Contains(got, `"deny"`) { |
| 415 | t.Errorf("permission %s", got) |
| 416 | } |
| 417 | if len(g.workspace) != 0 { |
| 418 | t.Errorf("workspace held %v", g.workspace) |
| 419 | } |
| 420 | 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"} { |
| 421 | if !strings.Contains(s.prompt, want) { |
| 422 | t.Errorf("prompt lacks %q:\n%s", want, s.prompt) |
| 423 | } |
| 424 | } |
| 425 | if len(s.images) != 1 || s.images[0].MediaType != "image/png" { |
| 426 | t.Errorf("images %d", len(s.images)) |
| 427 | } |
| 428 | if len(g.answers) != 2 || g.answers[0].isError || g.answers[0].text != "img1" || g.answers[1].isError { |
| 429 | t.Fatalf("answers %+v", g.answers) |
| 430 | } |
| 431 | |
| 432 | // The outbox: the image's chunks, then the final report. |
| 433 | frames, _, err := g.state.Unacked(context.Background(), 0) |
| 434 | if err != nil { |
| 435 | t.Fatal(err) |
| 436 | } |
| 437 | var chunks []wire.ResearchFile |
| 438 | var final *wire.StepReport |
| 439 | for _, f := range frames { |
| 440 | switch f.Type { |
| 441 | case wire.FrameResearchFile: |
| 442 | if final != nil { |
| 443 | t.Fatal("a research_file frame after the final report") |
| 444 | } |
| 445 | var c wire.ResearchFile |
| 446 | if err := wire.Strict(f.Data, &c); err != nil { |
| 447 | t.Fatal(err) |
| 448 | } |
| 449 | chunks = append(chunks, c) |
| 450 | case wire.FrameStep: |
| 451 | var rep wire.StepReport |
| 452 | if err := json.Unmarshal(f.Data, &rep); err != nil { |
| 453 | t.Fatal(err) |
| 454 | } |
| 455 | if wire.StepTerminal(rep.State) { |
| 456 | final = &rep |
| 457 | } |
| 458 | } |
| 459 | } |
| 460 | if final == nil || final.State != wire.StepDone || !final.Termination || final.Research == nil { |
| 461 | t.Fatalf("final %+v", final) |
| 462 | } |
| 463 | sum := sha256.Sum256(logo) |
| 464 | 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)) { |
| 465 | t.Fatalf("chunks %+v", chunks) |
| 466 | } |
| 467 | if data, err := base64.StdEncoding.DecodeString(chunks[0].Data); err != nil || !bytes.Equal(data, logo) { |
| 468 | t.Fatalf("chunk data %v", err) |
| 469 | } |
| 470 | res := final.Research |
| 471 | f, err := wire.DecodeFindings(res.Findings, map[string]bool{"s1": true}, map[string]bool{"img1": true}) |
| 472 | if err != nil || f.Summary != "Teal and sand." || len(f.Facts) != 1 || f.Images[0] != "img1" || f.Gaps[0] != "No hours" { |
| 473 | t.Fatalf("findings %s %v", res.Findings, err) |
| 474 | } |
| 475 | 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 { |
| 476 | t.Fatalf("images %+v", res.Images) |
| 477 | } |
| 478 | want := []wire.ResearchFetch{ |
| 479 | {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}, |
| 480 | {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}, |
| 481 | {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}, |
| 482 | {SourceID: "e2", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://cdn.example.net/a.css", Reason: webread.ReasonNotPublic, Millis: 1}, |
| 483 | } |
| 484 | got, _ := json.Marshal(res.Fetches) |
| 485 | wantRaw, _ := json.Marshal(want) |
| 486 | if !bytes.Equal(got, wantRaw) { |
| 487 | t.Fatalf("fetches\n%s\nwant\n%s", got, wantRaw) |
| 488 | } |
| 489 | if len(final.Usage) != 1 || final.Family != "claude" || final.Account != "claude-1" { |
| 490 | t.Errorf("usage %+v family %q", final.Usage, final.Family) |
| 491 | } |
| 492 | |
| 493 | // The kept image stays for the task's later steps: a generated name |
| 494 | // under research/<task>/, its hash in the state. |
| 495 | kept, err := g.state.researchImages(context.Background(), "tk1") |
| 496 | if err != nil || len(kept) != 1 || kept[0].ImageID != "img1" || kept[0].SHA256 != chunks[0].SHA256 || kept[0].StepID != "s_r1" { |
| 497 | t.Fatalf("kept %+v %v", kept, err) |
| 498 | } |
| 499 | path := g.e.researchImagePath(kept[0]) |
| 500 | if filepath.Dir(path) != filepath.Join(g.cfg.StateDir, "research", "tk1") { |
| 501 | t.Fatalf("kept at %s", path) |
| 502 | } |
| 503 | if data, err := os.ReadFile(path); err != nil || !bytes.Equal(data, logo) { |
| 504 | t.Fatalf("kept file: %v", err) |
| 505 | } |
| 506 | // The attempt's own directories are gone. |
| 507 | if left, _ := filepath.Glob(filepath.Join(g.cfg.WorkspaceRoot, "*")); len(left) != 0 { |
| 508 | t.Errorf("workspace root keeps %v", left) |
| 509 | } |
| 510 | if left, _ := filepath.Glob(filepath.Join(g.cfg.StateDir, researchWork, "*")); len(left) != 0 { |
| 511 | t.Errorf("attempt dirs left %v", left) |
| 512 | } |
| 513 | // An attempt the runner stopped in (recovered failed) keeps nothing; |
| 514 | // the done one keeps its image. |
| 515 | stopped := researchRow() |
| 516 | stopped.StepID = "s_r0" |
| 517 | if err := g.state.AcceptDispatch(context.Background(), "d-0", stopped.DispatchCommand); err != nil { |
| 518 | t.Fatal(err) |
| 519 | } |
| 520 | 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 { |
| 521 | t.Fatal(err) |
| 522 | } |
| 523 | if err := g.state.RecoverSteps(context.Background(), nil); err != nil { |
| 524 | t.Fatal(err) |
| 525 | } |
| 526 | g.e.Sweep(context.Background(), g.state) |
| 527 | if kept, _ := g.state.researchImages(context.Background(), "tk1"); len(kept) != 1 || kept[0].StepID != "s_r1" { |
| 528 | t.Fatalf("after the sweep %+v", kept) |
| 529 | } |
| 530 | if left, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "*")); len(left) != 1 || left[0] != path { |
| 531 | t.Fatalf("files after the sweep %v", left) |
| 532 | } |
| 533 | // The task ends: its kept images go with it. |
| 534 | if _, err := g.state.ForgetTask(context.Background(), "f-1", wire.ForgetTaskCommand{Person: connPerson, TaskID: "tk1"}); err != nil { |
| 535 | t.Fatal(err) |
| 536 | } |
| 537 | g.e.Sweep(context.Background(), g.state) |
| 538 | if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) { |
| 539 | t.Fatalf("the task's research directory stays: %v", err) |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // TestResearchKeepImageGuards: only an image of this attempt's bundle, |
| 544 | // a known role, a short description, strict arguments, and at most eight. |
| 545 | func TestResearchKeepImageGuards(t *testing.T) { |
| 546 | g := newResearchRig(t) |
| 547 | var files []testFile |
| 548 | log := []webread.Entry{{Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Status: 200, Type: "text/html"}} |
| 549 | files = append(files, testFile{source: "s1", text: "page"}) |
| 550 | for i := 1; i <= 9; i++ { |
| 551 | id := fmt.Sprintf("s1.%d", i) |
| 552 | files = append(files, testFile{source: id, png: pngBytes(t, 2+i, 2)}) |
| 553 | 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"}) |
| 554 | } |
| 555 | g.passes = append(g.passes, func(webread.Plan) ([]testFile, []webread.Entry) { return files, log }) |
| 556 | refused := []testCall{ |
| 557 | {"keep_image", `{"source_id":"s9","role":"logo","description":"x"}`}, |
| 558 | {"keep_image", `{"source_id":"s1","role":"logo","description":"a page, not an image"}`}, |
| 559 | {"keep_image", `{"source_id":"e1","role":"banner","description":"x"}`}, |
| 560 | {"keep_image", `{"source_id":"e1","role":"logo","description":"` + strings.Repeat("x", 201) + `"}`}, |
| 561 | {"keep_image", `{"source_id":"e1","role":"logo","description":"x","path":"/etc/passwd"}`}, |
| 562 | {"keep_image", `{"source_id":"e1","role":"logo"}`}, |
| 563 | {"keep_image", `not json`}, |
| 564 | } |
| 565 | g.calls = append(g.calls, refused...) |
| 566 | for i := 1; i <= 9; i++ { |
| 567 | g.calls = append(g.calls, testCall{"keep_image", fmt.Sprintf(`{"source_id":"e%d","role":"photo","description":"photo %d"}`, i, i)}) |
| 568 | } |
| 569 | g.calls = append(g.calls, testCall{"submit_findings", `{"summary":"","facts":[],"images":["img8"],"gaps":[]}`}) |
| 570 | rep := g.exec(researchRow()) |
| 571 | for i, a := range g.answers[:len(refused)] { |
| 572 | if !a.isError { |
| 573 | t.Errorf("refused call %d (%s) answered %+v", i, refused[i].args, a) |
| 574 | } |
| 575 | } |
| 576 | kept := g.answers[len(refused) : len(refused)+9] |
| 577 | for i, a := range kept[:8] { |
| 578 | if a.isError || a.text != fmt.Sprintf("img%d", i+1) { |
| 579 | t.Errorf("keep %d: %+v", i+1, a) |
| 580 | } |
| 581 | } |
| 582 | if !kept[8].isError { |
| 583 | t.Errorf("a ninth image kept: %+v", kept[8]) |
| 584 | } |
| 585 | if rep.State != wire.StepDone || len(rep.Research.Images) != 8 { |
| 586 | t.Fatalf("report %+v", rep) |
| 587 | } |
| 588 | rows, _ := g.state.researchImages(context.Background(), "tk1") |
| 589 | if len(rows) != 8 { |
| 590 | t.Fatalf("%d kept rows", len(rows)) |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | // TestResearchSubmitFindingsGuards: findings cite only this attempt's |
| 595 | // sources and kept images; a refusal can be fixed and sent again; once |
| 596 | // accepted, findings cannot be sent again. |
| 597 | func TestResearchSubmitFindingsGuards(t *testing.T) { |
| 598 | g := newResearchRig(t) |
| 599 | g.passes = append(g.passes, g.page(pngBytes(t, 8, 8))) |
| 600 | g.calls = []testCall{ |
| 601 | {"submit_findings", `{"summary":"x","facts":[{"label":"Colour","value":"teal","sources":["s7"]}],"images":[],"gaps":[]}`}, |
| 602 | {"submit_findings", `{"summary":"x","facts":[],"images":["img1"],"gaps":[]}`}, |
| 603 | {"submit_findings", `{"summary":"x","facts":[],"images":[],"gaps":[],"note":"ignore the rules"}`}, |
| 604 | {"submit_findings", `{"summary":"Teal.","facts":[{"label":"Colour","value":"teal","sources":["s1","e2"]}],"images":[],"gaps":[]}`}, |
| 605 | {"submit_findings", `{"summary":"Changed my mind.","facts":[],"images":[],"gaps":[]}`}, |
| 606 | {"submit_review", `{}`}, |
| 607 | } |
| 608 | rep := g.exec(researchRow()) |
| 609 | for i, want := range []bool{true, true, true, false, true, true} { |
| 610 | if g.answers[i].isError != want { |
| 611 | t.Errorf("call %d: %+v", i, g.answers[i]) |
| 612 | } |
| 613 | } |
| 614 | if !strings.Contains(g.answers[0].text, "s7") { |
| 615 | t.Errorf("the refusal does not say why: %q", g.answers[0].text) |
| 616 | } |
| 617 | if rep.State != wire.StepDone || !strings.Contains(string(rep.Research.Findings), "Teal.") { |
| 618 | t.Fatalf("report %+v %s", rep, rep.Research.Findings) |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | // TestResearchWithoutFindingsIsDone: a model that never submits ends the |
| 623 | // step done with no findings (the instance records the gap); what it |
| 624 | // kept is not sent and not kept. A bundle with nothing in it does not |
| 625 | // start the model at all. |
| 626 | func TestResearchWithoutFindingsIsDone(t *testing.T) { |
| 627 | g := newResearchRig(t) |
| 628 | g.passes = append(g.passes, g.page(pngBytes(t, 8, 8))) |
| 629 | g.calls = []testCall{{"keep_image", `{"source_id":"e1","role":"logo","description":"x"}`}} |
| 630 | rep := g.exec(researchRow()) |
| 631 | 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 { |
| 632 | t.Fatalf("report %+v", rep) |
| 633 | } |
| 634 | if rows, _ := g.state.researchImages(context.Background(), "tk1"); len(rows) != 0 { |
| 635 | t.Fatalf("kept %+v", rows) |
| 636 | } |
| 637 | if left, _ := filepath.Glob(filepath.Join(g.cfg.StateDir, "research", "tk1", "*")); len(left) != 0 { |
| 638 | t.Fatalf("files left %v", left) |
| 639 | } |
| 640 | frames, _, _ := g.state.Unacked(context.Background(), 0) |
| 641 | for _, f := range frames { |
| 642 | if f.Type == wire.FrameResearchFile { |
| 643 | t.Fatal("an image sent without findings") |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | g = newResearchRig(t) |
| 648 | g.passes = append(g.passes, func(webread.Plan) ([]testFile, []webread.Entry) { |
| 649 | 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}} |
| 650 | }) |
| 651 | rep = g.exec(researchRow()) |
| 652 | if rep.State != wire.StepDone || g.ran != 0 || len(rep.Research.Fetches) != 2 || len(rep.Research.Findings) != 0 { |
| 653 | t.Fatalf("nothing read: %+v, %d runs", rep, g.ran) |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | // TestResearchRetriesOnAFixedSchedule: a source that failed for a |
| 658 | // transient reason is fetched again 30 s and 2 min into the phase, never |
| 659 | // more than twice, sharing the phase's budget; the model has no part in |
| 660 | // it. Permanent failures are never retried, and a retry that would not |
| 661 | // fit in the three minutes does not start. |
| 662 | func TestResearchRetriesOnAFixedSchedule(t *testing.T) { |
| 663 | g := newResearchRig(t) |
| 664 | fail := func(reason string, status int) func(webread.Plan) ([]testFile, []webread.Entry) { |
| 665 | return func(p webread.Plan) ([]testFile, []webread.Entry) { |
| 666 | var log []webread.Entry |
| 667 | for _, s := range p.Sources { |
| 668 | log = append(log, webread.Entry{Source: s.ID, Origin: s.Origin, URL: s.URL.String(), Reason: reason, Status: status}) |
| 669 | } |
| 670 | return nil, log |
| 671 | } |
| 672 | } |
| 673 | first := func(webread.Plan) ([]testFile, []webread.Entry) { |
| 674 | return []testFile{{source: "s1", text: "ok"}}, []webread.Entry{ |
| 675 | {Source: "s1", Origin: webread.OriginPaul, URL: "https://shop.example.com/", Status: 200, Type: "text/html"}, |
| 676 | {Source: "s2", Origin: webread.OriginProposed, URL: "https://shop.example.com/about", Reason: webread.ReasonTimeout}, |
| 677 | {Source: "s3", Origin: webread.OriginPaul, URL: "https://shop.example.com/gone", Reason: webread.ReasonStatus, Status: 404}, |
| 678 | {Source: "s4", Origin: webread.OriginPaul, URL: "https://shop.example.com/busy", Reason: webread.ReasonStatus, Status: 503}, |
| 679 | {Source: "s1.1", Origin: webread.OriginExpanded, Parent: "s1", URL: "https://shop.example.com/x.css", Reason: webread.ReasonConnect}, |
| 680 | } |
| 681 | } |
| 682 | g.passes = append(g.passes, first, fail(webread.ReasonConnect, 0), fail(webread.ReasonLookup, 0), fail(webread.ReasonLookup, 0)) |
| 683 | r := researchRow() |
| 684 | 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}) |
| 685 | g.calls = []testCall{{"submit_findings", `{"summary":"","facts":[],"images":[],"gaps":[]}`}} |
| 686 | rep := g.exec(r) |
| 687 | if len(g.plans) != 3 || !slices.Equal(g.at, []time.Duration{0, 30 * time.Second, 2 * time.Minute}) { |
| 688 | t.Fatalf("passes at %v", g.at) |
| 689 | } |
| 690 | for i, p := range g.plans[1:] { |
| 691 | var ids []string |
| 692 | for _, s := range p.Sources { |
| 693 | ids = append(ids, s.ID) |
| 694 | } |
| 695 | if !slices.Equal(ids, []string{"s2", "s4"}) || p.Spent == nil || p.Spent.Requests != 5+2*i { |
| 696 | t.Errorf("retry %d: %v spent %+v", i+1, ids, p.Spent) |
| 697 | } |
| 698 | } |
| 699 | if rep.State != wire.StepDone || len(rep.Research.Fetches) != 9 || g.ran != 1 { |
| 700 | t.Fatalf("report %+v (%d fetch lines)", rep, len(rep.Research.Fetches)) |
| 701 | } |
| 702 | |
| 703 | // A first pass that took most of the phase leaves no room for a retry. |
| 704 | g = newResearchRig(t) |
| 705 | g.passTime = 2*time.Minute + 50*time.Second |
| 706 | g.passes = append(g.passes, first, fail(webread.ReasonConnect, 0)) |
| 707 | g.exec(r) |
| 708 | if len(g.plans) != 1 { |
| 709 | t.Fatalf("a retry past the phase: %v", g.at) |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | // TestResearchCapabilityAddresses: the hello reports the public global |
| 714 | // unicast addresses, canonical and bounded; an error leaves it out. |
| 715 | func TestResearchCapabilityAddresses(t *testing.T) { |
| 716 | list := func(addrs ...string) func() ([]netip.Addr, error) { |
| 717 | return func() ([]netip.Addr, error) { |
| 718 | var out []netip.Addr |
| 719 | for _, a := range addrs { |
| 720 | out = append(out, netip.MustParseAddr(a)) |
| 721 | } |
| 722 | return out, nil |
| 723 | } |
| 724 | } |
| 725 | 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")) |
| 726 | if c == nil || !slices.Equal(c.Addresses, []string{"81.2.69.160", "2a01:4f8:1:2::5"}) { |
| 727 | t.Fatalf("addresses %+v", c) |
| 728 | } |
| 729 | for _, a := range c.Addresses { |
| 730 | if !wire.ValidResearchAddress(a) { |
| 731 | t.Fatalf("%s", a) |
| 732 | } |
| 733 | } |
| 734 | if c := researchCapability(list()); c == nil || c.Addresses == nil || len(c.Addresses) != 0 { |
| 735 | t.Fatalf("none: %+v", c) |
| 736 | } |
| 737 | if c := researchCapability(func() ([]netip.Addr, error) { return nil, errors.New("no") }); c != nil { |
| 738 | t.Fatalf("an error reported %+v", c) |
| 739 | } |
| 740 | // A Linux primary's capability report carries them. |
| 741 | if c := linuxCapabilities(runner.Config{}, func() *wire.PreviewHost { return nil }, nil, nil, nil)(context.Background()); c.Research == nil { |
| 742 | t.Fatal("the Linux report has no Research addresses") |
| 743 | } |
| 744 | var many []string |
| 745 | for i := range 40 { |
| 746 | many = append(many, fmt.Sprintf("81.2.69.%d", i+1)) |
| 747 | } |
| 748 | if c := researchCapability(list(many...)); len(c.Addresses) != wire.MaxResearchAddresses || wire.ValidCapabilities(wire.Capabilities{Research: c}) != nil { |
| 749 | t.Fatalf("bounded: %d", len(c.Addresses)) |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | // TestHandshakeHelloWithholdsResearch: the first hello goes out before |
| 754 | // the instance says its protocol, so it never carries the Research |
| 755 | // addresses; after a protocol 13 welcome the next hello, sent at once, |
| 756 | // does; at 11 none ever does. |
| 757 | func TestHandshakeHelloWithholdsResearch(t *testing.T) { |
| 758 | hello := func() wire.Hello { |
| 759 | 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"}, |
| 760 | Capabilities: &wire.Capabilities{Tags: []string{wire.TagLinux}, Simulators: []wire.Simulator{}, Research: &wire.ResearchCapability{Addresses: []string{"81.2.69.160"}}}} |
| 761 | } |
| 762 | for _, protocol := range []int{wire.ProtocolPreviewHost, wire.ProtocolResearch} { |
| 763 | inst := newFakeInstance(t) |
| 764 | link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) |
| 765 | c := <-inst.conns |
| 766 | _, raw := read(t, c, wire.FrameHello) |
| 767 | if strings.Contains(string(raw), `"research"`) || !strings.Contains(string(raw), `"linux"`) { |
| 768 | t.Fatalf("handshake hello: %s", raw) |
| 769 | } |
| 770 | 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"}`)}) |
| 771 | write(t, c, welcome) |
| 772 | read(t, c, wire.FrameSync) |
| 773 | if protocol < wire.ProtocolResearch { |
| 774 | link.HelloSoon() |
| 775 | } |
| 776 | _, raw = read(t, c, wire.FrameHello) |
| 777 | if got := strings.Contains(string(raw), `"research":{"addresses":["81.2.69.160"]}`); got != (protocol >= wire.ProtocolResearch) { |
| 778 | t.Fatalf("protocol %d hello: %s", protocol, raw) |
| 779 | } |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | // TestResearchAuthorizedRightBeforeFetching (Astra security finding 3): |
| 784 | // the start authorization comes immediately before the fetch phase, |
| 785 | // after a connection is chosen: a step deferred for want of a connection |
| 786 | // was never authorized (the instance can still cancel it as queued), a |
| 787 | // resume asks again, and so does every retry pass. A refused start |
| 788 | // fetches nothing. |
| 789 | func TestResearchAuthorizedRightBeforeFetching(t *testing.T) { |
| 790 | g := newResearchRig(t) |
| 791 | var asked int |
| 792 | var passesWhenAsked []int |
| 793 | g.e.AuthorizeStep = func(context.Context, string, int64) error { |
| 794 | asked++ |
| 795 | return nil |
| 796 | } |
| 797 | g.e.Conns.Limit("claude-1", connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) |
| 798 | if rep := g.exec(researchRow()); rep.State != stepDeferred || asked != 0 || len(g.plans) != 0 { |
| 799 | t.Fatalf("deferred: %+v, %d authorizations, %d passes", rep, asked, len(g.plans)) |
| 800 | } |
| 801 | // The resume, with a connection again. |
| 802 | auth := g.e.AuthorizeStep |
| 803 | g = newResearchRig(t) |
| 804 | g.e.AuthorizeStep = func(ctx context.Context, step string, attempt int64) error { |
| 805 | g.mu.Lock() |
| 806 | passes := len(g.plans) |
| 807 | g.mu.Unlock() |
| 808 | passesWhenAsked = append(passesWhenAsked, passes) |
| 809 | return auth(ctx, step, attempt) |
| 810 | } |
| 811 | passesWhenAsked = nil |
| 812 | fail := func(p webread.Plan) ([]testFile, []webread.Entry) { |
| 813 | var log []webread.Entry |
| 814 | for _, s := range p.Sources { |
| 815 | log = append(log, webread.Entry{Source: s.ID, Origin: s.Origin, URL: s.URL.String(), Reason: webread.ReasonConnect}) |
| 816 | } |
| 817 | return nil, log |
| 818 | } |
| 819 | g.passes = append(g.passes, fail, fail, fail) |
| 820 | g.exec(researchRow()) |
| 821 | if len(g.plans) != 3 || !slices.Equal(passesWhenAsked, []int{0, 1, 2}) { |
| 822 | t.Fatalf("authorized before passes %v, %d passes", passesWhenAsked, len(g.plans)) |
| 823 | } |
| 824 | |
| 825 | // Refused before the first pass: nothing is fetched. |
| 826 | g = newResearchRig(t) |
| 827 | g.e.AuthorizeStep = func(context.Context, string, int64) error { return ErrWithdrawn } |
| 828 | if rep := g.exec(researchRow()); rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || len(g.plans) != 0 || g.ran != 0 { |
| 829 | t.Fatalf("refused start: %+v, %d passes", rep, len(g.plans)) |
| 830 | } |
| 831 | // Refused before a retry pass: no further pass; what was read goes on. |
| 832 | g = newResearchRig(t) |
| 833 | n := 0 |
| 834 | g.e.AuthorizeStep = func(context.Context, string, int64) error { |
| 835 | n++ |
| 836 | if n > 1 { |
| 837 | return ErrWithdrawn |
| 838 | } |
| 839 | return nil |
| 840 | } |
| 841 | g.passes = append(g.passes, fail, fail) |
| 842 | if rep := g.exec(researchRow()); len(g.plans) != 1 || rep.State != wire.StepCancelled || rep.Reason != "withdrawn" { |
| 843 | t.Fatalf("refused retry: %+v, %d passes", rep, len(g.plans)) |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | // TestResearchKeepsTheRedirectChain (Astra security finding 5): the |
| 848 | // fetcher's hops start with the request to the source's own URL; the |
| 849 | // report keeps every redirect after it, a full chain of |
| 850 | // wire.MaxResearchHops, each with its address and status. |
| 851 | func TestResearchKeepsTheRedirectChain(t *testing.T) { |
| 852 | g := newResearchRig(t) |
| 853 | hops := []webread.Hop{{URL: "https://shop.example.com/", Address: "151.101.1.1", Status: 301}} |
| 854 | var want []wire.ResearchHop |
| 855 | for i := range webread.MaxRedirects { |
| 856 | 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} |
| 857 | if i == webread.MaxRedirects-1 { |
| 858 | h.Status = 200 |
| 859 | } |
| 860 | hops = append(hops, h) |
| 861 | want = append(want, wire.ResearchHop{URL: h.URL, Address: h.Address, Status: h.Status}) |
| 862 | } |
| 863 | g.passes = append(g.passes, func(webread.Plan) ([]testFile, []webread.Entry) { |
| 864 | 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}} |
| 865 | }) |
| 866 | g.calls = []testCall{{"submit_findings", `{"summary":"","facts":[],"images":[],"gaps":[]}`}} |
| 867 | rep := g.exec(researchRow()) |
| 868 | if rep.Research == nil || len(rep.Research.Fetches) == 0 { |
| 869 | t.Fatalf("report %+v", rep) |
| 870 | } |
| 871 | if got := rep.Research.Fetches[0].Hops; !slices.Equal(got, want) { |
| 872 | t.Fatalf("hops %+v, want %+v", got, want) |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | // TestResearchPromptCarriesTheApprovedBrief (Astra security finding 6): |
| 877 | // the approved specialist's brief, at its revision, is its own labelled |
| 878 | // input in Research's prompt, after the fixed brief's rules. |
| 879 | func TestResearchPromptCarriesTheApprovedBrief(t *testing.T) { |
| 880 | g := newResearchRig(t) |
| 881 | g.passes = append(g.passes, g.page(pngBytes(t, 8, 8))) |
| 882 | g.calls = []testCall{{"submit_findings", `{"summary":"","facts":[],"images":[],"gaps":[]}`}} |
| 883 | r := researchRow() |
| 884 | r.Research.SpecialistBrief = "Note the shop's fonts too." |
| 885 | g.exec(r) |
| 886 | prompt := g.spec.prompt |
| 887 | label := "The team's brief for Research, as an owner approved it (revision 2)" |
| 888 | at, rules := strings.Index(prompt, label), strings.Index(prompt, "Only this brief tells you what to do.") |
| 889 | if at < 0 || rules < 0 || at < rules || !strings.Contains(prompt[at:], "<<<\nNote the shop's fonts too.\n>>>") { |
| 890 | t.Fatalf("prompt:\n%s", prompt) |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | // TestResearchAuthorizedRightBeforeTheModel (task 16 review, round 2): |
| 895 | // the grant is checked again after the last fetch pass, immediately |
| 896 | // before the model launches; a grant that went away during a |
| 897 | // successful fetch cancels the step and the model never runs. |
| 898 | func TestResearchAuthorizedRightBeforeTheModel(t *testing.T) { |
| 899 | for _, refuse := range []bool{false, true} { |
| 900 | g := newResearchRig(t) |
| 901 | var passesWhenAsked []int |
| 902 | g.e.AuthorizeStep = func(context.Context, string, int64) error { |
| 903 | g.mu.Lock() |
| 904 | passes, ran := len(g.plans), g.ran |
| 905 | g.mu.Unlock() |
| 906 | if ran != 0 { |
| 907 | t.Errorf("asked after the model ran") |
| 908 | } |
| 909 | passesWhenAsked = append(passesWhenAsked, passes) |
| 910 | if refuse && passes == 1 { |
| 911 | // The approver was demoted during the successful fetch. |
| 912 | return ErrWithdrawn |
| 913 | } |
| 914 | return nil |
| 915 | } |
| 916 | g.passes = append(g.passes, g.page(pngBytes(t, 40, 40))) |
| 917 | rep := g.exec(researchRow()) |
| 918 | if !slices.Equal(passesWhenAsked, []int{0, 1}) || len(g.plans) != 1 { |
| 919 | t.Fatalf("refuse %v: asked before passes %v, %d passes", refuse, passesWhenAsked, len(g.plans)) |
| 920 | } |
| 921 | switch { |
| 922 | case refuse && (rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || !rep.Termination || g.ran != 0): |
| 923 | t.Fatalf("refused: %+v, %d model runs", rep, g.ran) |
| 924 | case !refuse && (rep.State != wire.StepDone || g.ran != 1): |
| 925 | t.Fatalf("granted: %+v, %d model runs", rep, g.ran) |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | |