package runner import ( "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runnerproto" ) func toolRequestFixture(s *AttemptSocket, b ToolBinding) toolRequest { return toolRequest{Capability: s.capability.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: "round1", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Which?"}`)} } func TestToolSocketRenewedLease(t *testing.T) { base, b := toolFixture(t) b.LeaseDeadline = time.Now().Add(300 * time.Millisecond) root := filepath.Dir(filepath.Dir(filepath.Dir(base.SocketPath))) s, err := NewAttemptSocket(context.Background(), root, b) mustJournal(t, err) defer s.Cleanup(context.Background(), func(context.Context) error { return nil }) renewal, ok := any(s).(interface { RenewLease(context.Context, time.Time) error }) if !ok { t.Fatal("socket has no trusted lease renewal") } deadline := time.Now().Add(time.Second) mustJournal(t, renewal.RenewLease(context.Background(), deadline)) mustJournal(t, renewal.RenewLease(context.Background(), b.LeaseDeadline)) time.Sleep(time.Until(b.LeaseDeadline) + 50*time.Millisecond) input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask_person","arguments":{"request_id":"renewed","question":"Which?"}}}` + "\n" var out strings.Builder mustJournal(t, ServeTools(context.Background(), strings.NewReader(input), &out, s.SocketPath, s.CapabilityPath)) if strings.Contains(out.String(), `"error"`) { t.Fatal("renewed lease tool failed", out.String()) } rows, err := b.Journal.ToolSubmissions(context.Background(), 10) mustJournal(t, err) if len(rows) != 1 { t.Fatal("renewed lease lost submission") } select { case <-s.done: t.Fatal("renewal did not extend timer") default: } select { case <-s.done: case <-time.After(time.Until(deadline) + time.Second): t.Fatal("lost lease did not invalidate idle socket") } if renewal.RenewLease(context.Background(), time.Now().Add(time.Minute)) == nil { t.Fatal("lost lease revived") } if callToolSocket(context.Background(), s.SocketPath, toolRequestFixture(s, b)) == nil { t.Fatal("lost lease accepted tool") } } func TestToolSocketUnauthenticatedCannotInvalidate(t *testing.T) { s, b := toolFixture(t) calls := 0 s.mu.Lock() s.binding.Current = func(context.Context) error { calls++; return runnerproto.ErrInvalid } s.mu.Unlock() q := toolRequestFixture(s, b) q.Capability = "wrong" if callToolSocket(context.Background(), s.SocketPath, q) == nil { t.Fatal("unauthenticated call accepted") } s.mu.Lock() invalid := s.invalid checked := calls s.binding.Current = func(context.Context) error { return nil } s.mu.Unlock() if invalid || checked != 0 { t.Fatal("unauthenticated frame checked authority or closed socket") } q.Capability = s.capability.Secret mustJournal(t, callToolSocket(context.Background(), s.SocketPath, q)) } func TestAgentToolJournalCapacity(t *testing.T) { s, b := toolFixture(t) q := toolRequestFixture(s, b) b.Journal.maxBytes = 1 if s.submit(context.Background(), q) == nil { t.Fatal("full journal accepted tool") } mustJournal(t, b.Journal.AdmissionAllowed(context.Background())) b.Journal.maxBytes = 128 << 20 mustJournal(t, s.submit(context.Background(), q)) } func TestAgentToolAttemptCapacity(t *testing.T) { s, b := toolFixture(t) q := toolRequestFixture(s, b) appendRaw := func() error { return b.Journal.appendTool(context.Background(), ToolSubmission{InstanceID: b.InstanceID, TaskID: q.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: q.RequestID, Name: q.Name, Arguments: q.Arguments, Agent: b.Agent, Isolation: b.Isolation}, runnerproto.EventHash(q.Arguments)) } for i := 0; i < 128; i++ { q.RequestID = fmt.Sprint(i) mustJournal(t, appendRaw()) } q.RequestID = "overflow" if appendRaw() == nil { t.Fatal("attempt exhausted shared journal without a cap") } mustJournal(t, b.Journal.AdmissionAllowed(context.Background())) b.TaskID = "other-task" other, err := NewAttemptSocket(context.Background(), filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath))), b) mustJournal(t, err) defer other.Cleanup(context.Background(), func(context.Context) error { return nil }) mustJournal(t, other.submit(context.Background(), toolRequestFixture(other, b))) rows, err := b.Journal.ToolSubmissions(context.Background(), 1024) mustJournal(t, err) mustJournal(t, b.Journal.AckTool(context.Background(), rows[0])) mustJournal(t, appendRaw()) } func TestAgentToolReproductionFields(t *testing.T) { good := runnerproto.Reproduction{ExpectedSymptom: "wrong value", Files: []runnerproto.CheckFile{{Path: "sub/bug_test.go", Bytes: []byte("test")}}, TestNames: []team.TestIdentity{{Package: "fixture", Name: "TestBug"}}} for _, field := range []string{"valid", "package", "name", "nested_git"} { t.Run(field, func(t *testing.T) { v := good v.Files = append([]runnerproto.CheckFile(nil), good.Files...) v.TestNames = append([]team.TestIdentity(nil), good.TestNames...) switch field { case "package": v.TestNames[0].Package = "" case "name": v.TestNames[0].Name = "" case "nested_git": v.Files[0].Path = "sub/.git/config" } raw, err := json.Marshal(v) mustJournal(t, err) err = validateToolArguments("submit_reproduction", raw) if field == "valid" { mustJournal(t, err) } else if err == nil { t.Fatal("invalid reproduction accepted", field) } }) } } func TestToolSocketCapabilityEncodingFailure(t *testing.T) { s, b := toolFixture(t) root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath))) dir := filepath.Join(root, "encoding-failure") mustJournal(t, os.Mkdir(dir, 0700)) b.LeaseDeadline = time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC) bad, err := ServeAttemptSocket(context.Background(), filepath.Join(dir, "tool.sock"), b) if err == nil { bad.Cleanup(context.Background(), func(context.Context) error { return nil }) t.Fatal("unencodable capability published") } entries, err := os.ReadDir(dir) mustJournal(t, err) if len(entries) != 0 { t.Fatal("encoding failure left authority files") } } func TestAgentToolAttemptByteCapacity(t *testing.T) { s, b := toolFixture(t) b.Journal.maxBytes = 8192 q := toolRequestFixture(s, b) q.Arguments = json.RawMessage(`{"question":"` + strings.Repeat("x", 2048) + `"}`) if s.submit(context.Background(), q) == nil { t.Fatal("attempt exceeded its byte share") } mustJournal(t, b.Journal.AdmissionAllowed(context.Background())) q.Arguments = json.RawMessage(`{"question":"Which?"}`) mustJournal(t, s.submit(context.Background(), q)) }