package headless import ( "amadan.net/oficina/equipo/internal/thintest" "bytes" "database/sql" "io/fs" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" _ "modernc.org/sqlite" ) // A coordinator whose init frame differs from the launch policy, or that // answers under another session, is stopped and the turn fails visibly; // the next message gets a fresh, valid process. func TestHeadlessPolicyGuards(t *testing.T) { env, _, r := localEnv(t) r.start(t) s := open(t, env) for _, word := range []string{"badinit", "othersession"} { bad := s.send(t, "please "+word) turn := s.waitTurn(t, bad.Turn.ID, wire.TurnFailed, wire.TurnReplied) if turn.State != wire.TurnFailed || turn.Reason != "policy_rejected" { t.Fatalf("%s: turn %s/%s, want failed/policy_rejected", word, turn.State, turn.Reason) } ok := s.send(t, "hello again") s.waitTurn(t, ok.Turn.ID, wire.TurnReplied) } } // Copies cannot refresh, so with a turn cap that leaves no room the // process is rotated before every turn and the session resumes each time. // The source home's lock is held only while refreshing and staging. func TestHeadlessCopyRotation(t *testing.T) { env, _, r := localEnv(t) r.opts.Claude.MaxTurn = 25*time.Minute - 2*time.Second r.opts.Claude.Margin = time.Second r.start(t) s := open(t, env) var last wire.Sent for i := range 3 { last = s.send(t, "turn "+string(rune('a'+i))) s.waitTurn(t, last.Turn.ID, wire.TurnReplied) time.Sleep(1100 * time.Millisecond) } if text := s.reply(t, last.Turn.ID).Text; !strings.Contains(text, "Turn 3, resumed session, process turn 1.") { t.Fatalf("not rotated onto a fresh copy with the same session: %q", text) } // While a coordinator process is up, nobody holds the source lock. bs, err := os.ReadFile(r.cfg.AccountBindingsPath) if err != nil { t.Fatal(err) } home := filepath.Join(filepath.Dir(filepath.Dir(r.cfg.AccountBindingsPath)), "accounts", "claude-1") if !bytes.Contains(bs, []byte(home)) { t.Fatal("unexpected bindings layout") } f, err := os.Open(home) if err != nil { t.Fatal(err) } defer f.Close() // A background rotation (this cap leaves the copy about two seconds) // holds the lock for a moment to refresh and stage; held for the // session, it would never come free. deadline := time.Now().Add(3 * time.Second) for err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil; err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) { if time.Now().After(deadline) { t.Fatalf("source home still locked during the session: %v", err) } time.Sleep(20 * time.Millisecond) } unix.Flock(int(f.Fd()), unix.LOCK_UN) } // No credential bytes reach a frame, an event, the instance database or // the runner's own state, and no runtime copy outlives its process. // TestHeadlessPrewarm: when the copy stops covering a turn between // messages, the runner rotates it in the background, so the next message // starts on a fresh process that is already up (not cold) and resumes the // session. func TestHeadlessPrewarm(t *testing.T) { env, _, r := localEnv(t) r.opts.Claude.MaxTurn = 25*time.Minute - 5*time.Second r.opts.Claude.Margin = time.Second r.start(t) s := open(t, env) first := s.send(t, "hello") s.waitTurn(t, first.Turn.ID, wire.TurnReplied) time.Sleep(6 * time.Second) second := s.send(t, "again") s.waitTurn(t, second.Turn.ID, wire.TurnReplied) turn, err := env.Client.Turn(s.ctx, second.Turn.ID) if err != nil || turn.Timing == nil { t.Fatalf("turn %+v %v", turn, err) } if turn.Timing.Cold { t.Fatalf("the second turn started cold: %+v", turn.Timing) } if text := s.reply(t, second.Turn.ID).Text; !strings.Contains(text, "Turn 2, resumed session, process turn 1.") { t.Fatalf("not a rotated process on the same session: %q", text) } } // TestHeadlessNewHouseRuleStartsFresh: a session started under an older // house rule is not resumed, so a changed rule reaches the coordinator. func TestHeadlessNewHouseRuleStartsFresh(t *testing.T) { env, _, r := localEnv(t) r.start(t) s := open(t, env) first := s.send(t, "hello") s.waitTurn(t, first.Turn.ID, wire.TurnReplied) r.stop(t) db, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db")) if err != nil { t.Fatal(err) } if _, err = db.Exec("UPDATE sessions_lane SET account = 'claude-1'"); err != nil { t.Fatal(err) } db.Close() r.start(t) second := s.send(t, "again") s.waitTurn(t, second.Turn.ID, wire.TurnReplied) if text := s.reply(t, second.Turn.ID).Text; !strings.Contains(text, "fresh session") { t.Fatalf("an old-rule session was resumed: %q", text) } } func TestHeadlessNoCredentialLeaks(t *testing.T) { env, inst, r := localEnv(t) r.start(t) s := open(t, env) sent := s.send(t, "hello") s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) r.stop(t) secrets := [][]byte{[]byte("fake-access"), []byte("fake-refresh"), []byte(".credentials.json"), []byte("claudeAiOauth")} check := func(where string, raw []byte) { for _, secret := range secrets { if bytes.Contains(raw, secret) { t.Fatalf("%s contains %q", where, secret) } } } for _, table := range []string{"chat_events", "chat_messages", "chat_turns", "runner_commands", "runner_sessions"} { rows, err := inst.DB.Writer().Query("SELECT * FROM " + table) if err != nil { t.Fatal(err) } cols, _ := rows.Columns() for rows.Next() { values := make([]sql.RawBytes, len(cols)) ptrs := make([]any, len(cols)) for i := range values { ptrs[i] = &values[i] } if err = rows.Scan(ptrs...); err != nil { t.Fatal(err) } for _, v := range values { check(table, v) } } rows.Close() } db, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db")) if err != nil { t.Fatal(err) } defer db.Close() for _, table := range []string{"outbox", "runs", "sessions", "meta", "inbox"} { rows, err := db.Query("SELECT * FROM " + table) if err != nil { t.Fatal(err) } cols, _ := rows.Columns() for rows.Next() { values := make([]sql.RawBytes, len(cols)) ptrs := make([]any, len(cols)) for i := range values { ptrs[i] = &values[i] } rows.Scan(ptrs...) for _, v := range values { check("runner "+table, v) } } rows.Close() } // Session homes hold transcripts only. root := filepath.Join(filepath.Dir(r.cfg.StateDir), "sessions") filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err == nil && !d.IsDir() && !strings.HasSuffix(path, ".jsonl") { t.Fatalf("non-transcript in session home: %s", path) } return nil }) // Runtime copies, namespace records and scratch are released when // their process exits. homes, _ := os.ReadDir(filepath.Join(r.cfg.ScratchRoot, "homes")) for _, h := range homes { t.Fatalf("runtime home left behind: %s", h.Name()) } left, _ := os.ReadDir(r.cfg.ScratchRoot) for _, e := range left { if e.Name() != "homes" && !strings.HasPrefix(e.Name(), ".equipo-root-owner") { t.Fatalf("scratch left behind: %s", e.Name()) } } } // A runner killed outright leaves its credential copy behind; the next // runner process removes it at start, before anything else runs. func TestHeadlessRunnerKillLeavesNoCopies(t *testing.T) { env, _, r := localEnv(t) r.subprocess = true r.start(t) s := open(t, env) sent := s.send(t, "take a while sleep:3000") s.wait(t, "streaming", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[sent.Turn.ID] != "" }) copies := func() (n int) { entries, _ := os.ReadDir(filepath.Join(r.cfg.ScratchRoot, "homes")) for _, e := range entries { if strings.HasPrefix(e.Name(), "account-") { n++ } } return n } if copies() == 0 { t.Fatal("no credential copy while a turn runs") } r.kill(t) if copies() == 0 { t.Fatal("expected the killed process to leave its copy") } r.start(t) turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) if turn.Attempt != 2 { t.Fatalf("attempt %d after a kill, want 2", turn.Attempt) } r.stop(t) if n := copies(); n != 0 { t.Fatalf("%d credential copies outlived their processes", n) } left, _ := os.ReadDir(r.cfg.ScratchRoot) for _, e := range left { if e.Name() != "homes" && !strings.HasPrefix(e.Name(), ".equipo-root-owner") { t.Fatalf("scratch left behind: %s", e.Name()) } } }