oficina / equipo Public

M8 harness: build the older release, frame tap, runner setup split

TestMixedVersions builds the protocol 1 release's headless test binary
from git history (its runner mode is the real older runner; an overlay
adds an older-instance mode) and drives both pairs. The instance gains
a frame tap for tests; localEnv's runner files move to runnerSetup.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9b3df02d3888f0c10a4e571bfeea50fa8df2d2ad parent 1477a64
4 files changed, +362 −32
  • internal/equipo/chat/store.go +6 −0
  • internal/equipo/chat/stream.go +3 −0
  • internal/headless/env_test.go +49 −32
  • internal/headless/m8_test.go +304 −0
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 8b865f41..768831d3 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"strings"
+ "sync/atomic"
"time"
"unicode/utf8"
@@ -69,8 +70,13 @@ type Store struct {
hub *Hub
now func() time.Time
process string
+ tap atomic.Pointer[func(runner string, raw []byte)]
}
+// SetFrameTap sees every frame the instance sends a runner, as sent
+// (tests: what a protocol 1 runner receives).
+func (s *Store) SetFrameTap(f func(runner string, raw []byte)) { s.tap.Store(&f) }
+
func NewStore(d *db.DB, a Authority, hub *Hub) *Store {
if hub == nil {
hub = NewHub()
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index e0f0110d..18924e51 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -77,6 +77,9 @@ func (rc *runnerConn) send(ctx context.Context, f wire.Frame) error {
if err != nil {
return err
}
+ if tap := rc.h.Store.tap.Load(); tap != nil && *tap != nil {
+ (*tap)(rc.principal.RunnerID, raw)
+ }
wctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
return rc.c.Write(wctx, websocket.MessageText, raw)
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go
index 9e9bb7c8..bc4fa981 100644
--- a/internal/headless/env_test.go
+++ b/internal/headless/env_test.go
@@ -23,6 +23,7 @@ import (
"amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/oficina/equipo/internal/runner/thin"
+ "amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/thintest"
"amadan.net/oficina/equipo/internal/toolproxy"
"amadan.net/rastrillo/rastrillo/budget"
@@ -123,6 +124,9 @@ type localRunner struct {
// runnerID scopes the connection wait to this runner (several runners
// share one instance).
runnerID string
+ // binary runs the runner process from another build (M8: the slice 4
+ // test binary), not this one.
+ binary string
inst *thintest.Instance
root string
cmd *exec.Cmd
@@ -242,38 +246,9 @@ func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) {
inst := thintest.StartInstance(t)
token := inst.DeviceToken(t)
cred := inst.EnrolRunner(t)
- root, err := os.MkdirTemp("", "eqh-")
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { os.RemoveAll(root) })
- private(t, root)
- bin := private(t, filepath.Join(root, "bin"))
- digest := copyExecutable(t, filepath.Join(bin, "claude"))
- copyExecutable(t, filepath.Join(bin, "equipo-tool-proxy"))
- state := private(t, filepath.Join(root, "state"))
- if err = thintest.WriteRunnerCredential(state, cred); err != nil {
- t.Fatal(err)
- }
- home := private(t, filepath.Join(root, "accounts", "claude-1"))
- identity := map[string]string{"account_id": thintest.Owner, "home_id": rand.Text(), "provider_version": fakeclaude.Version}
- writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity)
- writeJSON(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{"emailAddress": thintest.Owner}})
- if err = fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil {
- t.Fatal(err)
- }
- config := private(t, filepath.Join(root, "config"))
- bindings := filepath.Join(config, "bindings.json")
- writeJSON(t, bindings, []map[string]any{{"id": "claude-1", "local_id": "claude-1", "label": "claude-1", "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": thintest.Owner, "provider_home": home, "kind": "subscription", "expected_identity": identity}})
- self, _ := os.Executable()
- cfg := runner.Config{Origin: inst.URL, InstanceID: inst.TeamID, StateDir: state, AccountBindingsPath: bindings, AmadanCredentialPath: filepath.Join(config, "amadan.json"), ClaudePath: filepath.Join(bin, "claude"), CodexPath: filepath.Join(bin, "claude"), CodexCodeModeHostPath: filepath.Join(bin, "claude"), BwrapPath: "/usr/bin/bwrap", GoRoot: filepath.Join(root, "go"), GoBinary: filepath.Join(root, "go", "bin", "go"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: filepath.Join(bin, "claude"), ToolProxyPath: filepath.Join(bin, "equipo-tool-proxy"), Executable: self}
- logger := slog.New(slog.NewTextHandler(io.Discard, nil))
- if testing.Verbose() {
- logger = slog.New(slog.NewTextHandler(os.Stderr, nil))
- }
- forge := newLocalForge(t, root)
- // Moving in is on only for the scenarios about it (2b_*).
- r := &localRunner{inst: inst, root: root, cfg: cfg, opts: thin.Options{Version: "test", Logger: logger, Forge: forge, NoMoveIn: true, MergeEvery: time.Second, Claude: thin.ClaudeOptions{Digest: digest, Idle: time.Minute, LockWait: 5 * time.Second}}}
+ r, forge := runnerSetup(t, inst.URL, inst.TeamID, cred)
+ r.inst = inst
+ cfg, state, root := r.cfg, r.cfg.StateDir, r.root
t.Cleanup(func() { r.stop(t) })
turns := 0
env := &Env{
@@ -438,6 +413,9 @@ func (r *localRunner) startProcess(t *testing.T) {
}
defer log.Close()
self, _ := os.Executable()
+ if r.binary != "" {
+ self = r.binary
+ }
cmd := exec.Command(self)
cmd.Env = append(os.Environ(), "EQUIPO_HEADLESS_RUNNER="+path)
cmd.Stdout, cmd.Stderr = log, log
@@ -480,3 +458,42 @@ func (r *localRunner) kill(t *testing.T) {
}
r.endProcess(t, syscall.SIGKILL)
}
+
+// runnerSetup makes a runner's files (fake Claude home, bindings, roots,
+// a local forge) for an instance at origin, enrolled as cred.
+func runnerSetup(t *testing.T, origin, teamID string, cred runnerproto.RunnerCredential) (*localRunner, *localForge) {
+ t.Helper()
+ root, err := os.MkdirTemp("", "eqh-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(root) })
+ private(t, root)
+ bin := private(t, filepath.Join(root, "bin"))
+ digest := copyExecutable(t, filepath.Join(bin, "claude"))
+ copyExecutable(t, filepath.Join(bin, "equipo-tool-proxy"))
+ state := private(t, filepath.Join(root, "state"))
+ if err = thintest.WriteRunnerCredential(state, cred); err != nil {
+ t.Fatal(err)
+ }
+ home := private(t, filepath.Join(root, "accounts", "claude-1"))
+ identity := map[string]string{"account_id": thintest.Owner, "home_id": rand.Text(), "provider_version": fakeclaude.Version}
+ writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity)
+ writeJSON(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{"emailAddress": thintest.Owner}})
+ if err = fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ config := private(t, filepath.Join(root, "config"))
+ bindings := filepath.Join(config, "bindings.json")
+ writeJSON(t, bindings, []map[string]any{{"id": "claude-1", "local_id": "claude-1", "label": "claude-1", "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": thintest.Owner, "provider_home": home, "kind": "subscription", "expected_identity": identity}})
+ self, _ := os.Executable()
+ cfg := runner.Config{Origin: origin, InstanceID: teamID, StateDir: state, AccountBindingsPath: bindings, AmadanCredentialPath: filepath.Join(config, "amadan.json"), ClaudePath: filepath.Join(bin, "claude"), CodexPath: filepath.Join(bin, "claude"), CodexCodeModeHostPath: filepath.Join(bin, "claude"), BwrapPath: "/usr/bin/bwrap", GoRoot: filepath.Join(root, "go"), GoBinary: filepath.Join(root, "go", "bin", "go"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: filepath.Join(bin, "claude"), ToolProxyPath: filepath.Join(bin, "equipo-tool-proxy"), Executable: self}
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ if testing.Verbose() {
+ logger = slog.New(slog.NewTextHandler(os.Stderr, nil))
+ }
+ forge := newLocalForge(t, root)
+ // Moving in is on only for the scenarios about it (2b_*).
+ r := &localRunner{root: root, cfg: cfg, opts: thin.Options{Version: "test", Logger: logger, Forge: forge, NoMoveIn: true, MergeEvery: time.Second, Claude: thin.ClaudeOptions{Digest: digest, Idle: time.Minute, LockWait: 5 * time.Second}}}
+ return r, forge
+}
diff --git a/internal/headless/m8_test.go b/internal/headless/m8_test.go
new file mode 100644
index 00000000..fdf17b9b
--- /dev/null
+++ b/internal/headless/m8_test.go
@@ -0,0 +1,304 @@
+package headless
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/thintest"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// slice4 is the protocol 1 release the mixed-version tests run against:
+// thin v1 slice 4c, the release staging serves and this branch starts
+// from. (The spec names ca0a65c, slice 4 itself; its wire predates the
+// 4b and 4c frame fields, a skew that release already has.)
+const slice4 = "2d1edaf08eedce9c1add0d6de584cdd7debddff0"
+
+// oldInstanceTest is added to the slice 4 tree when its test binary is
+// built: an instance of that release, in its own process, until stdin
+// closes.
+const oldInstanceTest = `package headless
+
+import (
+ "encoding/json"
+ "io"
+ "os"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/thintest"
+)
+
+func TestM8OldInstance(t *testing.T) {
+ out := os.Getenv("EQUIPO_M8_OUT")
+ if out == "" {
+ t.Skip("M8 only")
+ }
+ inst := thintest.StartInstance(t)
+ token := inst.DeviceToken(t)
+ cred := inst.EnrolRunner(t)
+ raw, _ := json.Marshal(map[string]any{"url": inst.URL, "team": inst.TeamID, "token": token, "db": inst.Path, "credential": cred})
+ if err := os.WriteFile(out+".tmp", raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(out+".tmp", out); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = io.Copy(io.Discard, os.Stdin)
+}
+`
+
+var oldOnce sync.Mutex
+
+// oldBinary is the slice 4 headless test binary (the real slice 4 runner
+// and, with the overlay above, instance), built from git history once
+// and kept in the user cache (EQUIPO_M8_CACHE overrides; a read-only
+// cache falls back to the test's own directory).
+func oldBinary(t *testing.T) string {
+ t.Helper()
+ oldOnce.Lock()
+ defer oldOnce.Unlock()
+ cache := os.Getenv("EQUIPO_M8_CACHE")
+ if cache == "" {
+ if dir, err := os.UserCacheDir(); err == nil {
+ cache = filepath.Join(dir, "equipo-m8")
+ }
+ }
+ if cache == "" || os.MkdirAll(filepath.Join(cache, slice4), 0700) != nil {
+ cache = t.TempDir()
+ }
+ bin := filepath.Join(cache, slice4, "headless.test")
+ if info, err := os.Stat(bin); err == nil && info.Mode().IsRegular() {
+ return bin
+ }
+ if err := os.MkdirAll(filepath.Dir(bin), 0700); err != nil {
+ bin = filepath.Join(t.TempDir(), "headless.test")
+ }
+ top, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
+ if err != nil {
+ t.Fatalf("M8 needs the repository's history: %v", err)
+ }
+ src := t.TempDir()
+ archive := exec.Command("git", "-C", strings.TrimSpace(string(top)), "archive", "--format=tar", slice4)
+ untar := exec.Command("tar", "-x", "-C", src)
+ pipe, _ := archive.StdoutPipe()
+ untar.Stdin = pipe
+ if err := untar.Start(); err != nil {
+ t.Fatal(err)
+ }
+ if err := archive.Run(); err != nil {
+ t.Fatalf("M8 needs commit %s in the repository's history: %v", slice4, err)
+ }
+ if err := untar.Wait(); err != nil {
+ t.Fatal(err)
+ }
+ extra := filepath.Join(t.TempDir(), "m8_old_instance_test.go")
+ if err := os.WriteFile(extra, []byte(oldInstanceTest), 0600); err != nil {
+ t.Fatal(err)
+ }
+ overlay := filepath.Join(t.TempDir(), "overlay.json")
+ raw, _ := json.Marshal(map[string]any{"Replace": map[string]string{filepath.Join(src, "internal", "headless", "m8_old_instance_test.go"): extra}})
+ if err := os.WriteFile(overlay, raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ build := exec.Command("go", "test", "-c", "-overlay", overlay, "-o", bin+".tmp", "./internal/headless")
+ build.Dir = src
+ build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOFLAGS=-mod=readonly")
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("building slice 4 at %s: %v %s", slice4, err, out)
+ }
+ if err := os.Rename(bin+".tmp", bin); err != nil {
+ t.Fatal(err)
+ }
+ return bin
+}
+
+// sampleToReady sends the typo fix on oficina/sample and waits until the
+// task is ready to merge or done.
+func sampleToReady(t *testing.T, env *Env, title string) wire.Task {
+ t.Helper()
+ s := open(t, env)
+ s.keep()
+ s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
+ sent := s.send(t, "tool:record_task:oficina/sample|"+title+"|The README says teh panes.\ntool:start_task:$task|edit:README.md|teh panes|the panes")
+ id := s.taskOf(t, sent.Turn.ID)
+ k := s.settled(t, id, 3*time.Minute)
+ if k.Stage != wire.StageReadyToMerge && k.Stage != wire.StageDone {
+ t.Fatalf("not ready: %+v", k)
+ }
+ if k.Checks != wire.ChecksPassed || k.Verdict != wire.VerdictApprove {
+ t.Fatalf("judged %+v", k)
+ }
+ return k
+}
+
+// M8: mixed versions with the real slice 4 code.
+func TestMixedVersions(t *testing.T) {
+ if testing.Short() {
+ t.Skip("builds slice 4")
+ }
+ old := oldBinary(t)
+
+ // The slice 4 runner against this instance: it speaks protocol 1,
+ // runs the sample scenario to ready, and is never sent anything
+ // protocol 1 lacks (no blob, no needs, nothing new in welcome).
+ t.Run("old runner, new instance", func(t *testing.T) {
+ env, inst, r := localEnv(t)
+ var mu sync.Mutex
+ var sent [][]byte
+ inst.Store.Chat().SetFrameTap(func(_ string, raw []byte) {
+ mu.Lock()
+ sent = append(sent, append([]byte(nil), raw...))
+ mu.Unlock()
+ })
+ r.subprocess, r.binary = true, old
+ r.start(t)
+ k := sampleToReady(t, env, "Fix the panes typo")
+ var protocol int
+ if err := inst.DB.Writer().QueryRow("SELECT protocol FROM runner_sessions").Scan(&protocol); err != nil || protocol != wire.Protocol1 {
+ t.Fatalf("protocol %d %v", protocol, err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ kinds := map[string]int{}
+ for _, raw := range sent {
+ f, _, err := wire.ParseFrame(raw)
+ if err != nil {
+ t.Fatalf("unparsable frame %s", raw)
+ }
+ kinds[f.Type]++
+ if !wire.Speaks(wire.Protocol1, f.Type) {
+ t.Fatalf("protocol 1 runner sent %s", raw)
+ }
+ for _, field := range []string{`"needs"`, `"runner_id":"`, `"protocol"`, `"role"`, `"release"`, `"step_id":"","attempt"`} {
+ if f.Type != wire.FrameWelcome && field == `"runner_id":"` {
+ if f.Type == wire.FrameDispatch && bytes.Contains(f.Data, []byte(field)) {
+ t.Fatalf("dispatch with runner_id at protocol 1: %s", raw)
+ }
+ continue
+ }
+ if f.Type != wire.FrameWelcome && field != `"needs"` {
+ continue
+ }
+ if bytes.Contains(f.Data, []byte(field)) && field != `"runner_id":"` {
+ t.Fatalf("protocol 2 field %s at protocol 1: %s", field, raw)
+ }
+ }
+ }
+ if kinds[wire.FrameDispatch] < 3 || kinds[wire.FrameWelcome] < 1 {
+ t.Fatalf("frames sent %v", kinds)
+ }
+ t.Logf("slice 4 runner: task %s %s on %s; frames %v", k.ID, k.Stage, k.CandidateSHA[:7], kinds)
+ })
+
+ // This runner against the slice 4 instance: its protocol 2 hello is
+ // refused once, it says hello at protocol 1, logs it, and runs the same
+ // scenario. A worker enrolling with that instance is refused with a
+ // clear diagnostic and nothing is created or lost.
+ t.Run("new runner, old instance", func(t *testing.T) {
+ out := filepath.Join(t.TempDir(), "instance.json")
+ cmd := exec.Command(old, "-test.run", "^TestM8OldInstance$", "-test.timeout", "20m")
+ cmd.Env = append(os.Environ(), "EQUIPO_M8_OUT="+out)
+ stdin, _ := cmd.StdinPipe()
+ var logs bytes.Buffer
+ cmd.Stdout, cmd.Stderr = &logs, &logs
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ stdin.Close()
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ select {
+ case <-done:
+ case <-time.After(30 * time.Second):
+ cmd.Process.Kill()
+ <-done
+ }
+ })
+ var info struct {
+ URL, Team, Token, DB string
+ Credential runnerproto.RunnerCredential
+ }
+ deadline := time.Now().Add(2 * time.Minute)
+ for {
+ raw, err := os.ReadFile(out)
+ if err == nil && json.Unmarshal(raw, &info) == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("slice 4 instance did not start: %s", logs.String())
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ r, _ := runnerSetup(t, info.URL, info.Team, info.Credential)
+ t.Cleanup(func() { r.stop(t) })
+ runnerLog := &lockedBuffer{}
+ r.opts.Logger = slog.New(slog.NewTextHandler(runnerLog, nil))
+ turns := 0
+ env := &Env{Client: thintest.NewClient(info.URL, info.Token), turns: &turns, ForgePath: r.opts.Forge.(*localForge).path}
+ r.start(t)
+ k := sampleToReady(t, env, "Fix the panes typo")
+ if !strings.Contains(runnerLog.String(), "the instance is older: speaking protocol 1") {
+ t.Fatalf("no fallback line: %s", runnerLog.String())
+ }
+ t.Logf("against slice 4: task %s %s on %s", k.ID, k.Stage, k.CandidateSHA[:7])
+
+ // A worker cannot enrol there.
+ worker := runner.Config{Origin: info.URL, InstanceID: info.Team, StateDir: filepath.Join(t.TempDir(), "worker"), WorkerOnly: true}
+ var printed bytes.Buffer
+ err := runner.Enrol(context.Background(), worker, &printed)
+ if code, _ := runner.Diagnostic(err); code != "runner.instance_older_than_worker" {
+ t.Fatalf("worker enrolment with slice 4: %q %v", code, err)
+ }
+ d, err := sql.Open("sqlite", "file:"+info.DB+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ var runners, enrolments int
+ d.QueryRow("SELECT count(*) FROM runners").Scan(&runners)
+ d.QueryRow("SELECT count(*) FROM runner_enrolments").Scan(&enrolments)
+ if runners != 1 || enrolments != 1 {
+ t.Fatalf("the refused worker left %d runners, %d enrolments", runners, enrolments)
+ }
+ // Nothing lost: the primary still serves the person.
+ s := open(t, env)
+ sent := s.send(t, "Still there?")
+ if turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied); turn.State != wire.TurnReplied {
+ t.Fatalf("after the refused worker: %+v", turn)
+ }
+ })
+}
+
+// lockedBuffer is a log sink read while the runner writes.
+type lockedBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (l *lockedBuffer) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.Write(p)
+}
+
+func (l *lockedBuffer) String() string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.String()
+}
+
+var _ = io.Discard