package pi import ( "amadan.net/oficina/equipo/internal/fakepi" "bufio" "context" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "net" "os" "path/filepath" "slices" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/testci" ) // testKey is the key the tests deliver; the fake refuses any other. const testKey = fakepi.TestKey // toolServer is the runner's end of the attempt's tool socket: Equipo's // step tools over MCP, recording each call. type toolServer struct { path string mu sync.Mutex calls []string } func (s *toolServer) called() []string { s.mu.Lock() defer s.mu.Unlock() return append([]string(nil), s.calls...) } func startToolServer(t *testing.T, root string, tools []string) *toolServer { t.Helper() dir, err := os.MkdirTemp(root, "tool-") if err != nil { t.Fatal(err) } os.Chmod(dir, 0700) s := &toolServer{path: filepath.Join(dir, "equipo.sock")} ln, err := net.Listen("unix", s.path) if err != nil { t.Fatal(err) } os.Chmod(s.path, 0600) t.Cleanup(func() { ln.Close() }) go func() { for { c, err := ln.Accept() if err != nil { return } go s.serve(c, tools) } }() return s } func (s *toolServer) serve(c net.Conn, tools []string) { defer c.Close() r := bufio.NewReader(c) for { line, err := r.ReadBytes('\n') if err != nil { return } var q struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` } `json:"params"` } if json.Unmarshal(line, &q) != nil || len(q.ID) == 0 { continue } var result any switch q.Method { case "initialize": result = map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo", "version": "1"}} case "tools/list": var list []any // Besides the role's tools, one no role pins: Pi must not // declare or call it. for _, name := range append(slices.Clone(tools), "merge_now") { list = append(list, map[string]any{"name": name, "description": "Equipo's " + name, "inputSchema": map[string]any{"type": "object"}}) } result = map[string]any{"tools": list} case "tools/call": s.mu.Lock() s.calls = append(s.calls, q.Params.Name+" "+string(q.Params.Arguments)) s.mu.Unlock() result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "Recorded."}}} default: raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "error": map[string]any{"code": -32601, "message": "no"}}) c.Write(append(raw, '\n')) continue } raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "result": result}) c.Write(append(raw, '\n')) } } // harness runs Pi (the real pinned one, or fakepi) in the real // containment: bubblewrap, the egress relay to api.tensorx.ai only, the // key through the secret pipe. type harness struct { t *testing.T manager *containment.Manager scratch string install Install proxy string keyHome string tensorx *fakepi.TensorX goRoot, moduleCache string } func copyTestBinary(t *testing.T, dir, name string) string { t.Helper() self, err := os.Executable() if err != nil { t.Fatal(err) } raw, err := os.ReadFile(self) if err != nil { t.Fatal(err) } p := filepath.Join(dir, name) if err := os.WriteFile(p, raw, 0755); err != nil { t.Fatal(err) } return p } // realInstall is the pinned Pi this machine has (EQUIPO_PI_ROOT, laid out // as Paths says), or a skip, or on CI a failure. func realInstall(t *testing.T) Install { t.Helper() root := os.Getenv("EQUIPO_PI_ROOT") if root == "" { testci.Absent(t, "the pinned Pi (EQUIPO_PI_ROOT) is absent") } testci.Tools(t, "pi") node, tree := Paths(root) inst, ok := Install{Node: node, Tree: tree}.Pinned() if !ok { t.Skip("no Pi pins for this platform") } return inst } // fakeInstall is fakepi as the Pi CLI, run by a copy of this binary as // Node, with its digests as the pins. func fakeInstall(t *testing.T) Install { t.Helper() dir := t.TempDir() node := copyTestBinary(t, dir, "node") tree := filepath.Join(dir, "pi", "node_modules") cli := filepath.Join(tree, "@earendil-works/pi-coding-agent/dist/bundle/cli.js") if err := os.MkdirAll(filepath.Dir(cli), 0755); err != nil { t.Fatal(err) } if err := os.WriteFile(cli, []byte("// fakepi stands in for Pi\n"), 0644); err != nil { t.Fatal(err) } if err := Seal(tree); err != nil { t.Fatal(err) } t.Cleanup(func() { filepath.Walk(tree, func(p string, info os.FileInfo, err error) error { if err == nil && info.IsDir() { os.Chmod(p, 0755) } return nil }) }) sum, err := TreeSHA256(tree) if err != nil { t.Fatal(err) } raw, _ := os.ReadFile(node) return Install{Node: node, Tree: tree, NodeSHA256: digest(raw), TreeSHA256: sum} } func newHarness(t *testing.T, inst Install) *harness { t.Helper() testci.Tools(t, "bwrap") if _, err := os.Stat("/usr/bin/bwrap"); err != nil { testci.Absent(t, "bubblewrap is absent") } root := t.TempDir() scratch := filepath.Join(root, "s") if err := os.Mkdir(scratch, 0700); err != nil { t.Fatal(err) } self, err := os.Executable() if err != nil { t.Fatal(err) } m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch}) if err != nil { testci.Absent(t, fmt.Sprintf("namespaces are unavailable here: %v", err)) } bin := filepath.Join(root, "bin") os.Mkdir(bin, 0755) keyHome := filepath.Join(root, "tensorx-abcdef012345") if err := os.Mkdir(keyHome, 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(testKey), 0600); err != nil { t.Fatal(err) } h := &harness{t: t, manager: m, scratch: scratch, install: inst, proxy: copyTestBinary(t, bin, "equipo-tool-proxy"), keyHome: keyHome} h.tensorx = fakepi.StartTensorX(t) return h } // run is one launch: Pi opened on the workspace for action, with the // step tools equipo served on its tool socket. type run struct { launcher *Launcher session provider.Session process provider.Process tools *toolServer home string events <-chan provider.Event cleanup func() kill context.CancelFunc host *teeHost } // errors is what Pi wrote on stderr so far. func (r *run) errors() string { time.Sleep(100 * time.Millisecond) return r.host.stderr() } // teeHost keeps what the process writes on stderr. type teeHost struct { host provider.ProcessHost mu sync.Mutex buf []byte } func (h *teeHost) stderr() string { h.mu.Lock() defer h.mu.Unlock() return string(h.buf) } func (h *teeHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { p, err := h.host.Start(ctx, l, argv) if err == nil { go func() { b := make([]byte, 4096) for { n, err := p.Stderr().Read(b) h.mu.Lock() if len(h.buf) < 1<<20 { h.buf = append(h.buf, b[:n]...) } h.mu.Unlock() if err != nil { return } } }() } return p, err } func contextTimeout(d time.Duration) (context.Context, context.CancelFunc) { return context.WithTimeout(context.Background(), d) } // openKept resumes session id from the transcript kept in dir. func (h *harness) openKept(work, action string, equipo []string, id, dir string) *run { return h.openWith(work, action, equipo, id, dir) } func (h *harness) open(work, action string, equipo []string, session string) *run { return h.openWith(work, action, equipo, session, "") } func (h *harness) openWith(work, action string, equipo []string, session, kept string) *run { t := h.t t.Helper() scratch, err := os.MkdirTemp(h.scratch, "policy-") if err != nil { t.Fatal(err) } if session == "" { session = NewSessionID() } in, cleanup, err := Prepare(h.scratch, Run{GoRoot: h.goRoot, ModuleCache: h.moduleCache, Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Scratch: scratch, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", Equipo: equipo, Resume: session, EgressHosts: egressHosts(t), ExtraCA: h.tensorx.CA}) if err != nil { t.Fatal(err) } if kept != "" { if err := RestoreSession(kept, session, in.Home); err != nil { t.Fatal(err) } } policy, err := provider.BuildPiPolicy(in) if err != nil { t.Fatal(err) } tools := startToolServer(t, h.scratch, equipo) host := &teeHost{host: h.manager} l, _ := New(host) launch := provider.Launch{ToolSocket: tools.path, AttemptKey: "test/" + NewSessionID(), Workspace: work, Selection: provider.Selection{ConnectionID: "tensorx-abcdef012345", Provider: "tensorx", Model: "z-ai/glm-5.3", Family: Family("z-ai/glm-5.3")}, Binding: provider.PiBinding("tensorx-abcdef012345", in.Home, h.keyHome), Policy: policy} // The context Open gets is the attempt's lifetime: cancelling it // kills the namespace. ctx, kill := context.WithCancel(context.Background()) sess, err := l.Open(ctx, launch) if err != nil { kill() cleanup() time.Sleep(200 * time.Millisecond) t.Fatalf("open: %v\n%s", err, host.stderr()) } proc, _ := l.Process(sess) events, _ := l.Events(context.Background(), sess) r := &run{launcher: l, session: sess, process: proc, tools: tools, home: in.Home, events: events} r.host = host r.kill = kill r.cleanup = func() { r.stop(t) kill() cleanup() os.RemoveAll(scratch) } t.Cleanup(r.cleanup) return r } func egressHosts(t *testing.T) []string { p, err := egress.ProviderPolicy(provider.NetworkContract{Provider: "tensorx", Harness: "pi"}, false) if err != nil { t.Fatal(err) } return p.Hosts } // prompt sends one prompt and collects its events to its end, answering // every ask with answer. func (r *run) prompt(t *testing.T, text, answer string) []provider.Event { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() if err := r.launcher.StartTurn(ctx, r.session, provider.Turn{ID: NewSessionID(), Prompt: text}); err != nil { t.Fatalf("prompt: %v\n%s", err, r.errors()) } var out []provider.Event for { select { case <-ctx.Done(): t.Fatalf("no end; events %v", kinds(out)) case e, ok := <-r.events: if !ok { t.Fatalf("Pi ended; events %v\n%s", kinds(out), r.errors()) } out = append(out, e) if e.Kind == KindAsk { if err := r.launcher.Respond(ctx, r.session, provider.Answer{RequestID: e.RequestID, Behavior: answer}); err != nil { t.Fatal(err) } } if e.Kind == KindDone { return out } } } } // stop closes Pi's stdin, kills the namespace and waits for its proof. func (r *run) stop(t *testing.T) error { if r.process == nil { return nil } r.launcher.Close(context.Background(), r.session) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if c, ok := r.process.(interface{ Contain(context.Context) error }); ok { c.Contain(ctx) } _, err := r.process.Wait(ctx) r.process = nil return err } func digest(raw []byte) string { sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]) }