xonecas.io
6119
My

mysis / commit a07363b

refactor: add golangci-lint and fix all linting issues

- Add comprehensive .golangci.yml v2 configuration with strict linters
- Add lint target to Makefile with auto-install of golangci-lint
- Fix all errcheck violations by checking deferred Close() calls
- Fix all gosec violations with proper nolint directives for false positives
- Replace switch statements where appropriate instead of if-else chains
- Pre-allocate slices where size is known for better performance
- Fix directory permissions from 0755 to 0750 for security
- Add error handling for all io operations and HTTP response bodies
- Update AGENTS.md with lint command documentation

All code now passes golangci-lint with 0 issues.

xonecas2026-02-11 a07363bd3092a0b059c7247f429105ee2793612c parent 7f9ec14

22 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.golangci.yml+58−0
@@ -0,0 +1,58 @@
1+# golangci-lint v2 configuration
2+version: "2"
3+
4+run:
5+ timeout: 5m
6+ tests: true
7+
8+# Use recommended defaults + a few extras
9+linters:
10+ enable:
11+ - errcheck
12+ - govet
13+ - staticcheck
14+ - unused
15+ - ineffassign
16+ - gocritic
17+ - gosec
18+ - misspell
19+ - unconvert
20+ - unparam
21+ - prealloc
22+
23+formatters:
24+ enable:
25+ - gofmt
26+ - goimports
27+
28+linters-settings:
29+ errcheck:
30+ check-type-assertions: true
31+
32+ govet:
33+ enable:
34+ - shadow
35+
36+ gosec:
37+ excludes:
38+ - G104
39+
40+ gocritic:
41+ enabled-tags:
42+ - diagnostic
43+ - performance
44+
45+issues:
46+ max-issues-per-linter: 50
47+ max-same-issues: 3
48+
49+ exclude-rules:
50+ - path: _test\.go
51+ linters:
52+ - errcheck
53+ - gosec
54+
55+output:
56+ formats:
57+ colored-line-number:
58+ path: stdout
AGENTS.md+2−0
@@ -14,3 +14,5 @@ Keep documentation concise and factual. No documentation file should be more tha
1414 - The app config is in `./config.toml`.
1515 - `cmd/main.go` is the orchestrator and entrypoint. It can then run in interactive mode with TUI or non-interactive mode with cli.
1616 - Project has a strict rule of separation of concerns. Shared functionality and data access is shared no matter what display mode the app is using. Ex: `llm/loop.go` is one core functionaly shared by both displays.
17+- Makefile commands: `lint`, `test`, `run`, `build`. Always prefer these to lint, test, run and build the app.
18+- Linter: golangci-lint with strict config. Must pass with 0 issues.
Makefile+8−1
@@ -1,4 +1,4 @@
1-.PHONY: fmt build run test test-integration install clean db-reset-accounts check-upstream-version mcp_client backup-credentials
1+.PHONY: fmt build run test lint install clean backup-credentials
22
33 VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
44 LDFLAGS := -ldflags "-X main.Version=$(VERSION)"
@@ -25,6 +25,13 @@ test:
2525 @echo "package coverage:"
2626 @go tool cover -func=coverage.out | grep "^total:"
2727
28+lint:
29+ @if ! command -v golangci-lint >/dev/null 2>&1; then \
30+ echo "Installing golangci-lint..."; \
31+ curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $$(go env GOPATH)/bin latest; \
32+ fi
33+ $$(go env GOPATH)/bin/golangci-lint run ./...
34+
2835 clean:
2936 rm -rf bin/ coverage.out
3037
cmd/mysis/main.go+15−3
@@ -73,7 +73,11 @@ func run() error {
7373 if err != nil {
7474 return fmt.Errorf("failed to open database: %w", err)
7575 }
76- defer db.Close()
76+ defer func() {
77+ if err := db.Close(); err != nil {
78+ log.Error().Err(err).Msg("Failed to close database")
79+ }
80+ }()
7781
7882 // Create session manager
7983 sessionMgr := session.NewManager(db)
@@ -117,7 +121,11 @@ func run() error {
117121 if err != nil {
118122 return fmt.Errorf("failed to create provider: %w", err)
119123 }
120- defer prov.Close()
124+ defer func() {
125+ if err := prov.Close(); err != nil {
126+ log.Error().Err(err).Msg("Failed to close provider")
127+ }
128+ }()
121129
122130 log.Info().
123131 Str("provider", selectedProvider).
@@ -133,7 +141,11 @@ func run() error {
133141 } else {
134142 log.Info().Str("upstream", cfg.MCP.Upstream).Msg("MCP proxy initialized")
135143 }
136- defer proxy.Close()
144+ defer func() {
145+ if err := proxy.Close(); err != nil {
146+ log.Error().Err(err).Msg("Failed to close MCP proxy")
147+ }
148+ }()
137149
138150 // Initialize or resume session
139151 sessionResult, err := sessionMgr.Initialize(flags.SessionName, selectedProvider, selectedModel)
internal/config/config.go+1−1
@@ -150,7 +150,7 @@ func EnsureDataDir() (string, error) {
150150 if err != nil {
151151 return "", err
152152 }
153- if err := os.MkdirAll(dir, 0755); err != nil {
153+ if err := os.MkdirAll(dir, 0750); err != nil {
154154 return "", err
155155 }
156156 return dir, nil
internal/config/credentials.go+1−0
@@ -27,6 +27,7 @@ func LoadCredentials() (*Credentials, error) {
2727 Providers: make(map[string]ProviderCredentials),
2828 }
2929
30+ //nolint:gosec // G304: Path from validated config file
3031 data, err := os.ReadFile(path)
3132 if os.IsNotExist(err) {
3233 return creds, nil
internal/features/app.go+8−4
@@ -21,12 +21,13 @@ func InitializeProviders(cfg *config.Config, creds *config.Credentials) *provide
2121
2222 for name, provCfg := range cfg.Providers {
2323 // Detect provider type based on endpoint
24- if strings.Contains(provCfg.Endpoint, "localhost:11434") || strings.Contains(provCfg.Endpoint, "/ollama") {
24+ switch {
25+ case strings.Contains(provCfg.Endpoint, "localhost:11434"), strings.Contains(provCfg.Endpoint, "/ollama"):
2526 // Ollama provider
2627 factory := provider.NewOllamaFactory(name, provCfg.Endpoint)
2728 registry.RegisterFactory(name, factory)
2829 log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered Ollama provider")
29- } else if strings.Contains(provCfg.Endpoint, "opencode.ai") {
30+ case strings.Contains(provCfg.Endpoint, "opencode.ai"):
3031 // OpenCode Zen provider
3132 keyName := provCfg.APIKeyName
3233 if keyName == "" {
@@ -40,7 +41,7 @@ func InitializeProviders(cfg *config.Config, creds *config.Credentials) *provide
4041 factory := provider.NewOpenCodeFactory(name, provCfg.Endpoint, apiKey)
4142 registry.RegisterFactory(name, factory)
4243 log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered OpenCode provider")
43- } else {
44+ default:
4445 log.Warn().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Unknown provider type")
4546 }
4647 }
@@ -55,6 +56,7 @@ func LoadSystemPromptFromFile(path string) (string, error) {
5556 return "", fmt.Errorf("system prompt file must be markdown (.md or .markdown): %s", path)
5657 }
5758
59+ //nolint:gosec // G304: Path from validated config file
5860 data, err := os.ReadFile(path)
5961 if err != nil {
6062 return "", fmt.Errorf("read system prompt file: %w", err)
@@ -95,12 +97,13 @@ func SetupFileLogging(debug bool) error {
9597
9698 // Create logs directory
9799 logDir := filepath.Join(dataDir, "logs")
98- if err := os.MkdirAll(logDir, 0755); err != nil {
100+ if err := os.MkdirAll(logDir, 0750); err != nil {
99101 return fmt.Errorf("create logs directory: %w", err)
100102 }
101103
102104 // Create log file
103105 logFile := filepath.Join(logDir, "mysis.log")
106+ //nolint:gosec // G304: Path from validated config file
104107 file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
105108 if err != nil {
106109 return fmt.Errorf("open log file: %w", err)
@@ -115,6 +118,7 @@ func SetupFileLogging(debug bool) error {
115118 // In debug mode, also write human-readable logs to a separate debug file
116119 if debug {
117120 debugFile := filepath.Join(logDir, "mysis-debug.log")
121+ //nolint:gosec // G304: Debug log file path is constructed from validated data directory
118122 debugFileWriter, err := os.OpenFile(debugFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
119123 if err != nil {
120124 return fmt.Errorf("open debug log file: %w", err)
internal/llm/loop.go+4−7
@@ -118,10 +118,7 @@ func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error {
118118 }
119119
120120 // Execute each tool call and update history
121- toolResults, err := executeToolCalls(ctx, opts.Proxy, resp.ToolCalls, opts.OnMessage, opts.SuppressOutput)
122- if err != nil {
123- return err
124- }
121+ toolResults := executeToolCalls(ctx, opts.Proxy, resp.ToolCalls, opts.OnMessage, opts.SuppressOutput)
125122 opts.History = append(opts.History, toolResults...)
126123
127124 // Continue loop to let LLM process tool results
@@ -146,8 +143,8 @@ func displayReasoning(reasoning string) {
146143
147144 // executeToolCalls executes a list of tool calls and adds results to history.
148145 // Returns the list of tool result messages that were added.
149-func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provider.ToolCall, onMessage MessageCallback, suppressOutput bool) ([]provider.Message, error) {
150- var toolResults []provider.Message
146+func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provider.ToolCall, onMessage MessageCallback, suppressOutput bool) []provider.Message {
147+ toolResults := make([]provider.Message, 0, len(toolCalls))
151148
152149 for _, toolCall := range toolCalls {
153150 if !suppressOutput {
@@ -220,7 +217,7 @@ func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provide
220217 toolResults = append(toolResults, toolMsg)
221218 }
222219
223- return toolResults, nil
220+ return toolResults
224221 }
225222
226223 // displayToolArguments shows tool arguments in a truncated format.
internal/mcp/client.go+12−2
@@ -11,6 +11,8 @@ import (
1111 "strings"
1212 "sync/atomic"
1313 "time"
14+
15+ "github.com/rs/zerolog/log"
1416 )
1517
1618 // Client is an MCP client that communicates with an upstream server.
@@ -78,7 +80,11 @@ func (c *Client) send(ctx context.Context, req *Request) (*Response, error) {
7880 if err != nil {
7981 return nil, fmt.Errorf("http request: %w", err)
8082 }
81- defer httpResp.Body.Close()
83+ defer func() {
84+ if err := httpResp.Body.Close(); err != nil {
85+ log.Warn().Err(err).Msg("Failed to close response body")
86+ }
87+ }()
8288
8389 if httpResp.StatusCode != http.StatusOK {
8490 respBody, _ := io.ReadAll(httpResp.Body)
@@ -312,7 +318,11 @@ func (c *Client) Notify(ctx context.Context, method string, params interface{})
312318 if err != nil {
313319 return fmt.Errorf("http request: %w", err)
314320 }
315- defer httpResp.Body.Close()
321+ defer func() {
322+ if err := httpResp.Body.Close(); err != nil {
323+ log.Warn().Err(err).Msg("Failed to close response body")
324+ }
325+ }()
316326
317327 // Capture session ID from response if present
318328 if sessionID := httpResp.Header.Get("Mcp-Session-Id"); sessionID != "" {
internal/mcp/client_test.go+16−14
@@ -12,9 +12,10 @@ import (
1212 func TestClientInitialize(t *testing.T) {
1313 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1414 var req Request
15- json.NewDecoder(r.Body).Decode(&req)
15+ _ = json.NewDecoder(r.Body).Decode(&req)
1616
17- if req.Method == "initialize" {
17+ switch req.Method {
18+ case "initialize":
1819 result := map[string]interface{}{
1920 "protocolVersion": "2024-11-05",
2021 "capabilities": map[string]interface{}{},
@@ -26,12 +27,12 @@ func TestClientInitialize(t *testing.T) {
2627 ID: req.ID,
2728 Result: data,
2829 }
29- json.NewEncoder(w).Encode(resp)
30- } else if req.Method == "notifications/initialized" {
30+ _ = json.NewEncoder(w).Encode(resp)
31+ case "notifications/initialized":
3132 w.WriteHeader(http.StatusNoContent)
32- } else {
33+ default:
3334 resp := NewErrorResponse(req.ID, 0, "not implemented")
34- json.NewEncoder(w).Encode(resp)
35+ _ = json.NewEncoder(w).Encode(resp)
3536 }
3637 }))
3738 defer server.Close()
@@ -47,7 +48,7 @@ func TestClientNotify(t *testing.T) {
4748 received := false
4849 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
4950 var req Request
50- json.NewDecoder(r.Body).Decode(&req)
51+ _ = json.NewDecoder(r.Body).Decode(&req)
5152 if req.Method == "notifications/initialized" {
5253 received = true
5354 }
@@ -105,16 +106,16 @@ func TestClientParseSSEResponseLargePayload(t *testing.T) {
105106 func TestClientCallToolErrorReturnsToolResult(t *testing.T) {
106107 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
107108 var req Request
108- json.NewDecoder(r.Body).Decode(&req)
109+ _ = json.NewDecoder(r.Body).Decode(&req)
109110
110111 if req.Method != "tools/call" {
111112 resp := NewErrorResponse(req.ID, 0, "unexpected method")
112- json.NewEncoder(w).Encode(resp)
113+ _ = json.NewEncoder(w).Encode(resp)
113114 return
114115 }
115116
116117 resp := NewErrorResponse(req.ID, 42, "insufficient_items: Not enough Iron Ore")
117- json.NewEncoder(w).Encode(resp)
118+ _ = json.NewEncoder(w).Encode(resp)
118119 }))
119120 defer server.Close()
120121
@@ -159,9 +160,10 @@ func TestClientInitializeRetry(t *testing.T) {
159160
160161 // Succeed on second attempt
161162 var req Request
162- json.NewDecoder(r.Body).Decode(&req)
163+ _ = json.NewDecoder(r.Body).Decode(&req)
163164
164- if req.Method == "initialize" {
165+ switch req.Method {
166+ case "initialize":
165167 result := map[string]interface{}{
166168 "protocolVersion": "2024-11-05",
167169 "capabilities": map[string]interface{}{},
@@ -173,8 +175,8 @@ func TestClientInitializeRetry(t *testing.T) {
173175 ID: req.ID,
174176 Result: data,
175177 }
176- json.NewEncoder(w).Encode(resp)
177- } else if req.Method == "notifications/initialized" {
178+ _ = json.NewEncoder(w).Encode(resp)
179+ case "notifications/initialized":
178180 w.WriteHeader(http.StatusNoContent)
179181 }
180182 }))
internal/mcp/tools_test.go+5−5
@@ -107,7 +107,7 @@ func TestGetCredentialsTool(t *testing.T) {
107107
108108 t.Run("credentials exist", func(t *testing.T) {
109109 // Save credentials first
110- store.SaveCredentials(sessionID, "player2", "pass456")
110+ _ = store.SaveCredentials(sessionID, "player2", "pass456")
111111
112112 result, err := handler(context.Background(), json.RawMessage("{}"))
113113 if err != nil {
@@ -183,19 +183,19 @@ func TestSessionIsolation(t *testing.T) {
183183 session1 := "session-1"
184184 handler1 := MakeSaveCredentialsHandler(store, session1)
185185 args1, _ := json.Marshal(SaveCredentialsArgs{Username: "user1", Password: "pass1"})
186- handler1(context.Background(), args1)
186+ _, _ = handler1(context.Background(), args1)
187187
188188 // Session 2
189189 session2 := "session-2"
190190 handler2 := MakeSaveCredentialsHandler(store, session2)
191191 args2, _ := json.Marshal(SaveCredentialsArgs{Username: "user2", Password: "pass2"})
192- handler2(context.Background(), args2)
192+ _, _ = handler2(context.Background(), args2)
193193
194194 // Verify session 1 credentials
195195 getHandler1 := MakeGetCredentialsHandler(store, session1)
196196 result1, _ := getHandler1(context.Background(), json.RawMessage("{}"))
197197 var creds1 GetCredentialsResult
198- json.Unmarshal([]byte(result1.Content[0].Text), &creds1)
198+ _ = json.Unmarshal([]byte(result1.Content[0].Text), &creds1)
199199
200200 if creds1.Username != "user1" {
201201 t.Errorf("Session 1: Username = %q, want %q", creds1.Username, "user1")
@@ -205,7 +205,7 @@ func TestSessionIsolation(t *testing.T) {
205205 getHandler2 := MakeGetCredentialsHandler(store, session2)
206206 result2, _ := getHandler2(context.Background(), json.RawMessage("{}"))
207207 var creds2 GetCredentialsResult
208- json.Unmarshal([]byte(result2.Content[0].Text), &creds2)
208+ _ = json.Unmarshal([]byte(result2.Content[0].Text), &creds2)
209209
210210 if creds2.Username != "user2" {
211211 t.Errorf("Session 2: Username = %q, want %q", creds2.Username, "user2")
internal/provider/ollama.go+17−7
@@ -247,7 +247,9 @@ func (p *OllamaProvider) createChatCompletion(ctx context.Context, req ollamaCha
247247 if resp.StatusCode == 429 || resp.StatusCode == 500 || resp.StatusCode == 502 ||
248248 resp.StatusCode == 503 || resp.StatusCode == 504 {
249249 payload, _ := io.ReadAll(resp.Body)
250- resp.Body.Close()
250+ if err := resp.Body.Close(); err != nil {
251+ log.Warn().Err(err).Msg("Failed to close response body")
252+ }
251253 lastErr = fmt.Errorf("chat completion status %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
252254
253255 log.Warn().
@@ -261,7 +263,9 @@ func (p *OllamaProvider) createChatCompletion(ctx context.Context, req ollamaCha
261263
262264 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
263265 payload, _ := io.ReadAll(resp.Body)
264- resp.Body.Close()
266+ if err := resp.Body.Close(); err != nil {
267+ log.Warn().Err(err).Msg("Failed to close response body")
268+ }
265269
266270 log.Error().
267271 Str("provider", "ollama").
@@ -272,10 +276,12 @@ func (p *OllamaProvider) createChatCompletion(ctx context.Context, req ollamaCha
272276 return nil, fmt.Errorf("chat completion status %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
273277 }
274278
275- bodyBytes, err := io.ReadAll(resp.Body)
276- resp.Body.Close()
277- if err != nil {
278- return nil, fmt.Errorf("read response body: %w", err)
279+ bodyBytes, readErr := io.ReadAll(resp.Body)
280+ if err := resp.Body.Close(); err != nil {
281+ log.Warn().Err(err).Msg("Failed to close response body")
282+ }
283+ if readErr != nil {
284+ return nil, fmt.Errorf("read response body: %w", readErr)
279285 }
280286
281287 var decoded chatCompletionResponse
@@ -318,7 +324,11 @@ func (p *OllamaProvider) Stream(ctx context.Context, messages []Message) (<-chan
318324 ch := make(chan StreamChunk)
319325 go func() {
320326 defer close(ch)
321- defer stream.Close()
327+ defer func() {
328+ if err := stream.Close(); err != nil {
329+ log.Warn().Err(err).Msg("Failed to close stream")
330+ }
331+ }()
322332
323333 for {
324334 resp, err := stream.Recv()
internal/provider/ollama_test.go+31−30
@@ -53,7 +53,7 @@ func TestOllama_SystemMessagesAnywhere(t *testing.T) {
5353 }
5454
5555 w.Header().Set("Content-Type", "application/json")
56- json.NewEncoder(w).Encode(map[string]interface{}{
56+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
5757 "choices": []map[string]interface{}{
5858 {
5959 "message": map[string]interface{}{
@@ -72,13 +72,14 @@ func TestOllama_SystemMessagesAnywhere(t *testing.T) {
7272 ctx := context.Background()
7373
7474 // System messages at different positions, including consecutive ones
75- messages := []Message{
76- {Role: "system", Content: "You are a helpful assistant."},
77- {Role: "user", Content: "Hello"},
78- {Role: "system", Content: "Be concise in your responses."},
79- {Role: "system", Content: "Use simple language."},
80- {Role: "assistant", Content: "Hi there!"},
81- }
75+ messages := make([]Message, 0, 5)
76+ messages = append(messages,
77+ Message{Role: "system", Content: "You are a helpful assistant."},
78+ Message{Role: "user", Content: "Hello"},
79+ Message{Role: "system", Content: "Be concise in your responses."},
80+ Message{Role: "system", Content: "Use simple language."},
81+ Message{Role: "assistant", Content: "Hi there!"},
82+ )
8283
8384 _, err := provider.Chat(ctx, messages)
8485 if err != nil {
@@ -132,7 +133,7 @@ func TestOllama_ConsecutiveSystemMessagesMerge(t *testing.T) {
132133 }
133134
134135 w.Header().Set("Content-Type", "application/json")
135- json.NewEncoder(w).Encode(map[string]interface{}{
136+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
136137 "choices": []map[string]interface{}{
137138 {
138139 "message": map[string]interface{}{
@@ -150,12 +151,13 @@ func TestOllama_ConsecutiveSystemMessagesMerge(t *testing.T) {
150151 ctx := context.Background()
151152
152153 // Three consecutive system messages followed by user message
153- messages := []Message{
154- {Role: "system", Content: "This is instruction one."},
155- {Role: "system", Content: "This is instruction two."},
156- {Role: "system", Content: "This is instruction three."},
157- {Role: "user", Content: "Hello"},
158- }
154+ messages := make([]Message, 0, 4)
155+ messages = append(messages,
156+ Message{Role: "system", Content: "This is instruction one."},
157+ Message{Role: "system", Content: "This is instruction two."},
158+ Message{Role: "system", Content: "This is instruction three."},
159+ Message{Role: "user", Content: "Hello"},
160+ )
159161
160162 _, err := provider.Chat(ctx, messages)
161163 if err != nil {
@@ -204,7 +206,7 @@ func TestOllama_ToolCalls(t *testing.T) {
204206 t.Errorf("expected tool type=function, got %v", tool["type"])
205207 }
206208
207- json.NewEncoder(w).Encode(map[string]interface{}{
209+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
208210 "choices": []map[string]interface{}{
209211 {
210212 "message": map[string]interface{}{
@@ -242,7 +244,7 @@ func TestOllama_ToolCalls(t *testing.T) {
242244 t.Error("expected tool result message in second request")
243245 }
244246
245- json.NewEncoder(w).Encode(map[string]interface{}{
247+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
246248 "choices": []map[string]interface{}{
247249 {
248250 "message": map[string]interface{}{
@@ -269,9 +271,8 @@ func TestOllama_ToolCalls(t *testing.T) {
269271 },
270272 }
271273
272- messages := []Message{
273- {Role: "user", Content: "What is 5 plus 3?"},
274- }
274+ messages := make([]Message, 0, 1)
275+ messages = append(messages, Message{Role: "user", Content: "What is 5 plus 3?"})
275276
276277 resp1, err := provider.ChatWithTools(ctx, messages, tools)
277278 if err != nil {
@@ -346,7 +347,7 @@ func TestOllama_ReasoningField(t *testing.T) {
346347 },
347348 }
348349
349- json.NewEncoder(w).Encode(response)
350+ _ = json.NewEncoder(w).Encode(response)
350351 }))
351352 defer server.Close()
352353
@@ -354,9 +355,8 @@ func TestOllama_ReasoningField(t *testing.T) {
354355 provider := NewOllama(baseURL, "test-model")
355356 ctx := context.Background()
356357
357- messages := []Message{
358- {Role: "user", Content: "Question?"},
359- }
358+ messages := make([]Message, 0, 1)
359+ messages = append(messages, Message{Role: "user", Content: "Question?"})
360360
361361 tools := []Tool{
362362 {Name: "dummy", Description: "Dummy tool"},
@@ -398,7 +398,7 @@ func TestOllama_SystemMessagesAtEnd(t *testing.T) {
398398 }
399399
400400 w.Header().Set("Content-Type", "application/json")
401- json.NewEncoder(w).Encode(map[string]interface{}{
401+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
402402 "choices": []map[string]interface{}{
403403 {
404404 "message": map[string]interface{}{
@@ -416,11 +416,12 @@ func TestOllama_SystemMessagesAtEnd(t *testing.T) {
416416 ctx := context.Background()
417417
418418 // System message at the end
419- messages := []Message{
420- {Role: "user", Content: "Hello"},
421- {Role: "assistant", Content: "Hi!"},
422- {Role: "system", Content: "Here's a final instruction."},
423- }
419+ messages := make([]Message, 0, 3)
420+ messages = append(messages,
421+ Message{Role: "user", Content: "Hello"},
422+ Message{Role: "assistant", Content: "Hi!"},
423+ Message{Role: "system", Content: "Here's a final instruction."},
424+ )
424425
425426 resp, err := provider.Chat(ctx, messages)
426427 if err != nil {
internal/provider/opencode.go+14−4
@@ -234,8 +234,6 @@ func (p *OpenCodeProvider) createChatCompletion(ctx context.Context, req openai.
234234 lastErr = err
235235 continue // Network error - retry
236236 }
237- defer resp.Body.Close()
238-
239237 log.Debug().
240238 Str("provider", p.name).
241239 Str("url", url).
@@ -247,6 +245,9 @@ func (p *OpenCodeProvider) createChatCompletion(ctx context.Context, req openai.
247245 if resp.StatusCode == 429 || resp.StatusCode == 500 || resp.StatusCode == 502 ||
248246 resp.StatusCode == 503 || resp.StatusCode == 504 {
249247 payload, _ := io.ReadAll(resp.Body)
248+ if err := resp.Body.Close(); err != nil {
249+ log.Warn().Err(err).Msg("Failed to close response body")
250+ }
250251 lastErr = fmt.Errorf("chat completion status %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
251252
252253 log.Warn().
@@ -256,13 +257,15 @@ func (p *OpenCodeProvider) createChatCompletion(ctx context.Context, req openai.
256257 Str("body", string(payload)).
257258 Msg("OpenCode retryable error")
258259
259- resp.Body.Close()
260260 continue // Retry on transient server errors and rate limits
261261 }
262262
263263 // Non-retryable client error (4xx except 429)
264264 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
265265 payload, _ := io.ReadAll(resp.Body)
266+ if err := resp.Body.Close(); err != nil {
267+ log.Warn().Err(err).Msg("Failed to close response body")
268+ }
266269 log.Error().
267270 Str("provider", p.name).
268271 Int("status", resp.StatusCode).
@@ -273,6 +276,9 @@ func (p *OpenCodeProvider) createChatCompletion(ctx context.Context, req openai.
273276
274277 // Success - read and decode body
275278 bodyBytes, err := io.ReadAll(resp.Body)
279+ if closeErr := resp.Body.Close(); closeErr != nil {
280+ log.Warn().Err(closeErr).Msg("Failed to close response body")
281+ }
276282 if err != nil {
277283 log.Error().
278284 Str("provider", p.name).
@@ -338,7 +344,11 @@ func (p *OpenCodeProvider) Stream(ctx context.Context, messages []Message) (<-ch
338344 ch := make(chan StreamChunk)
339345 go func() {
340346 defer close(ch)
341- defer stream.Close()
347+ defer func() {
348+ if err := stream.Close(); err != nil {
349+ log.Warn().Err(err).Msg("Failed to close stream")
350+ }
351+ }()
342352
343353 for {
344354 resp, err := stream.Recv()
internal/provider/opencode_test.go+32−34
@@ -45,7 +45,7 @@ func TestOpenCode_SystemPromptOnly(t *testing.T) {
4545
4646 // Return mock response
4747 w.Header().Set("Content-Type", "application/json")
48- json.NewEncoder(w).Encode(map[string]interface{}{
48+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
4949 "choices": []map[string]interface{}{
5050 {
5151 "message": map[string]interface{}{
@@ -62,9 +62,8 @@ func TestOpenCode_SystemPromptOnly(t *testing.T) {
6262 provider := NewOpenCode(server.URL, "test-model", "test-key")
6363
6464 // Send only system messages
65- messages := []Message{
66- {Role: "system", Content: "You are a helpful assistant."},
67- }
65+ messages := make([]Message, 0, 1)
66+ messages = append(messages, Message{Role: "system", Content: "You are a helpful assistant."})
6867
6968 ctx := context.Background()
7069 response, err := provider.Chat(ctx, messages)
@@ -114,7 +113,7 @@ func TestOpenCode_ToolCallsAndResults(t *testing.T) {
114113 }
115114
116115 // Return tool call response
117- json.NewEncoder(w).Encode(map[string]interface{}{
116+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
118117 "choices": []map[string]interface{}{
119118 {
120119 "message": map[string]interface{}{
@@ -153,7 +152,7 @@ func TestOpenCode_ToolCallsAndResults(t *testing.T) {
153152 }
154153
155154 // Return final response
156- json.NewEncoder(w).Encode(map[string]interface{}{
155+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
157156 "choices": []map[string]interface{}{
158157 {
159158 "message": map[string]interface{}{
@@ -179,9 +178,8 @@ func TestOpenCode_ToolCallsAndResults(t *testing.T) {
179178 },
180179 }
181180
182- messages := []Message{
183- {Role: "user", Content: "What's the weather in NYC?"},
184- }
181+ messages := make([]Message, 0, 1)
182+ messages = append(messages, Message{Role: "user", Content: "What's the weather in NYC?"})
185183
186184 resp1, err := provider.ChatWithTools(ctx, messages, tools)
187185 if err != nil {
@@ -242,9 +240,8 @@ func TestOpenCode_InvalidToolSchema(t *testing.T) {
242240 },
243241 }
244242
245- messages := []Message{
246- {Role: "user", Content: "Do something"},
247- }
243+ messages := make([]Message, 0, 1)
244+ messages = append(messages, Message{Role: "user", Content: "Do something"})
248245
249246 _, err := provider.ChatWithTools(ctx, messages, tools)
250247 if err == nil {
@@ -298,7 +295,7 @@ func TestOpenCode_MultipleSystemMessages(t *testing.T) {
298295 }
299296
300297 w.Header().Set("Content-Type", "application/json")
301- json.NewEncoder(w).Encode(map[string]interface{}{
298+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
302299 "choices": []map[string]interface{}{
303300 {
304301 "message": map[string]interface{}{
@@ -315,12 +312,13 @@ func TestOpenCode_MultipleSystemMessages(t *testing.T) {
315312 ctx := context.Background()
316313
317314 // Send multiple system messages scattered in conversation
318- messages := []Message{
319- {Role: "system", Content: "You are a helpful assistant."},
320- {Role: "user", Content: "Hello"},
321- {Role: "system", Content: "Be concise in your responses."},
322- {Role: "assistant", Content: "Hi"},
323- }
315+ messages := make([]Message, 0, 4)
316+ messages = append(messages,
317+ Message{Role: "system", Content: "You are a helpful assistant."},
318+ Message{Role: "user", Content: "Hello"},
319+ Message{Role: "system", Content: "Be concise in your responses."},
320+ Message{Role: "assistant", Content: "Hi"},
321+ )
324322
325323 _, err := provider.Chat(ctx, messages)
326324 if err != nil {
@@ -347,7 +345,7 @@ func TestOpenCode_PreservesConversationHistory(t *testing.T) {
347345 } `json:"messages"`
348346 Stream bool `json:"stream"`
349347 }
350- json.NewDecoder(r.Body).Decode(&req)
348+ _ = json.NewDecoder(r.Body).Decode(&req)
351349
352350 // Verify Stream is false
353351 if req.Stream {
@@ -378,7 +376,7 @@ func TestOpenCode_PreservesConversationHistory(t *testing.T) {
378376
379377 // Return valid response
380378 w.Header().Set("Content-Type", "application/json")
381- json.NewEncoder(w).Encode(map[string]interface{}{
379+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
382380 "choices": []map[string]interface{}{
383381 {
384382 "message": map[string]interface{}{
@@ -395,14 +393,15 @@ func TestOpenCode_PreservesConversationHistory(t *testing.T) {
395393 provider := NewOpenCodeWithTemp("opencode_zen", server.URL, "test-model", "test-key", 0.7)
396394
397395 // Create messages simulating the failure scenario
398- messages := []Message{
399- {Role: "system", Content: "System prompt 1"},
400- {Role: "user", Content: "User message 1"},
401- {Role: "assistant", Content: "Assistant response 1"},
402- {Role: "system", Content: "Context update 1"},
403- {Role: "user", Content: "User message 2"},
404- {Role: "assistant", Content: "Assistant response 2"},
405- }
396+ messages := make([]Message, 0, 6)
397+ messages = append(messages,
398+ Message{Role: "system", Content: "System prompt 1"},
399+ Message{Role: "user", Content: "User message 1"},
400+ Message{Role: "assistant", Content: "Assistant response 1"},
401+ Message{Role: "system", Content: "Context update 1"},
402+ Message{Role: "user", Content: "User message 2"},
403+ Message{Role: "assistant", Content: "Assistant response 2"},
404+ )
406405
407406 // Call Chat
408407 _, err := provider.Chat(context.Background(), messages)
@@ -420,7 +419,7 @@ func TestOpenCode_StreamParameterSetCorrectly(t *testing.T) {
420419 var req struct {
421420 Stream bool `json:"stream"`
422421 }
423- json.NewDecoder(r.Body).Decode(&req)
422+ _ = json.NewDecoder(r.Body).Decode(&req)
424423
425424 // THIS IS THE CRITICAL TEST
426425 if req.Stream {
@@ -428,7 +427,7 @@ func TestOpenCode_StreamParameterSetCorrectly(t *testing.T) {
428427 }
429428
430429 w.Header().Set("Content-Type", "application/json")
431- json.NewEncoder(w).Encode(map[string]interface{}{
430+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
432431 "choices": []map[string]interface{}{
433432 {"message": map[string]interface{}{"role": "assistant", "content": "ok"}},
434433 },
@@ -438,9 +437,8 @@ func TestOpenCode_StreamParameterSetCorrectly(t *testing.T) {
438437
439438 provider := NewOpenCodeWithTemp("opencode_zen", server.URL, "test-model", "test-key", 0.7)
440439
441- messages := []Message{
442- {Role: "user", Content: "Test"},
443- }
440+ messages := make([]Message, 0, 1)
441+ messages = append(messages, Message{Role: "user", Content: "Test"})
444442
445443 _, err := provider.Chat(context.Background(), messages)
446444 if err != nil {
internal/provider/provider_test.go+51−35
@@ -42,7 +42,8 @@ func TestMockProviderChat(t *testing.T) {
4242 mock := NewMock("test", "Hello, World!")
4343
4444 ctx := context.Background()
45- messages := []Message{{Role: "user", Content: "Hi"}}
45+ messages := make([]Message, 0, 1)
46+ messages = append(messages, Message{Role: "user", Content: "Hi"})
4647
4748 response, err := mock.Chat(ctx, messages)
4849 if err != nil {
@@ -58,7 +59,8 @@ func TestMockProviderChatDelay(t *testing.T) {
5859 mock := NewMock("test", "ok").SetDelay(delay)
5960
6061 ctx := context.Background()
61- messages := []Message{{Role: "user", Content: "Hi"}}
62+ messages := make([]Message, 0, 1)
63+ messages = append(messages, Message{Role: "user", Content: "Hi"})
6264
6365 start := time.Now()
6466 _, err := mock.Chat(ctx, messages)
@@ -76,7 +78,8 @@ func TestMockProviderChatWithToolsDelay(t *testing.T) {
7678 mock := NewMock("test", "ok").SetDelay(delay)
7779
7880 ctx := context.Background()
79- messages := []Message{{Role: "user", Content: "Hi"}}
81+ messages := make([]Message, 0, 1)
82+ messages = append(messages, Message{Role: "user", Content: "Hi"})
8083
8184 start := time.Now()
8285 _, err := mock.ChatWithTools(ctx, messages, nil)
@@ -95,7 +98,8 @@ func TestMockProviderChatDelayContextCancel(t *testing.T) {
9598 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
9699 defer cancel()
97100
98- messages := []Message{{Role: "user", Content: "Hi"}}
101+ messages := make([]Message, 0, 1)
102+ messages = append(messages, Message{Role: "user", Content: "Hi"})
99103 _, err := mock.Chat(ctx, messages)
100104 if err == nil {
101105 t.Fatal("expected context deadline error")
@@ -107,7 +111,8 @@ func TestMockProviderChatError(t *testing.T) {
107111 mock := NewMock("test", "").WithChatError(expectedErr)
108112
109113 ctx := context.Background()
110- messages := []Message{{Role: "user", Content: "Hi"}}
114+ messages := make([]Message, 0, 1)
115+ messages = append(messages, Message{Role: "user", Content: "Hi"})
111116
112117 _, err := mock.Chat(ctx, messages)
113118 if !errors.Is(err, expectedErr) {
@@ -119,7 +124,8 @@ func TestMockProviderStream(t *testing.T) {
119124 mock := NewMock("test", "Streamed response")
120125
121126 ctx := context.Background()
122- messages := []Message{{Role: "user", Content: "Hi"}}
127+ messages := make([]Message, 0, 1)
128+ messages = append(messages, Message{Role: "user", Content: "Hi"})
123129
124130 ch, err := mock.Stream(ctx, messages)
125131 if err != nil {
@@ -152,7 +158,8 @@ func TestMockProviderStreamError(t *testing.T) {
152158 mock := NewMock("test", "").WithStreamError(expectedErr)
153159
154160 ctx := context.Background()
155- messages := []Message{{Role: "user", Content: "Hi"}}
161+ messages := make([]Message, 0, 1)
162+ messages = append(messages, Message{Role: "user", Content: "Hi"})
156163
157164 _, err := mock.Stream(ctx, messages)
158165 if !errors.Is(err, expectedErr) {
@@ -175,11 +182,12 @@ func TestOpenCodeProviderName(t *testing.T) {
175182 }
176183
177184 func TestToOpenAIMessages(t *testing.T) {
178- messages := []Message{
179- {Role: "system", Content: "You are helpful."},
180- {Role: "user", Content: "Hello"},
181- {Role: "assistant", Content: "Hi there!"},
182- }
185+ messages := make([]Message, 0, 3)
186+ messages = append(messages,
187+ Message{Role: "system", Content: "You are helpful."},
188+ Message{Role: "user", Content: "Hello"},
189+ Message{Role: "assistant", Content: "Hi there!"},
190+ )
183191
184192 result := toOpenAIMessages(messages)
185193
@@ -195,17 +203,18 @@ func TestToOpenAIMessages(t *testing.T) {
195203 }
196204
197205 func TestToOpenAIMessagesWithToolCalls(t *testing.T) {
198- messages := []Message{
199- {Role: "user", Content: "What's the weather?"},
200- {
206+ messages := make([]Message, 0, 3)
207+ messages = append(messages,
208+ Message{Role: "user", Content: "What's the weather?"},
209+ Message{
201210 Role: "assistant",
202211 Content: "",
203212 ToolCalls: []ToolCall{
204213 {ID: "call_123", Name: "get_weather", Arguments: json.RawMessage(`{"location":"NYC"}`)},
205214 },
206215 },
207- {Role: "tool", Content: `{"temp": 72}`, ToolCallID: "call_123"},
208- }
216+ Message{Role: "tool", Content: `{"temp": 72}`, ToolCallID: "call_123"},
217+ )
209218
210219 result := toOpenAIMessages(messages)
211220
@@ -239,7 +248,8 @@ func TestMockProviderChatWithTools(t *testing.T) {
239248 mock := NewMock("test", "thinking...").WithToolCalls(toolCalls)
240249
241250 ctx := context.Background()
242- messages := []Message{{Role: "user", Content: "Do something"}}
251+ messages := make([]Message, 0, 1)
252+ messages = append(messages, Message{Role: "user", Content: "Do something"})
243253 tools := []Tool{{Name: "test_tool", Description: "A test tool"}}
244254
245255 resp, err := mock.ChatWithTools(ctx, messages, tools)
@@ -263,7 +273,8 @@ func TestMockProviderChatWithToolsError(t *testing.T) {
263273 mock := NewMock("test", "").WithChatError(expectedErr)
264274
265275 ctx := context.Background()
266- messages := []Message{{Role: "user", Content: "Do something"}}
276+ messages := make([]Message, 0, 1)
277+ messages = append(messages, Message{Role: "user", Content: "Do something"})
267278 tools := []Tool{{Name: "test_tool", Description: "A test tool"}}
268279
269280 _, err := mock.ChatWithTools(ctx, messages, tools)
@@ -276,7 +287,8 @@ func TestMockProviderWithResponse(t *testing.T) {
276287 mock := NewMock("test", "initial")
277288
278289 ctx := context.Background()
279- messages := []Message{{Role: "user", Content: "Hi"}}
290+ messages := make([]Message, 0, 1)
291+ messages = append(messages, Message{Role: "user", Content: "Hi"})
280292
281293 // Initial response
282294 resp, _ := mock.Chat(ctx, messages)
@@ -297,7 +309,8 @@ func TestMockProviderWithReasoning(t *testing.T) {
297309 mock := NewMock("test", "response").WithReasoning(reasoning)
298310
299311 ctx := context.Background()
300- messages := []Message{{Role: "user", Content: "Hi"}}
312+ messages := make([]Message, 0, 1)
313+ messages = append(messages, Message{Role: "user", Content: "Hi"})
301314 tools := []Tool{{Name: "test_tool", Description: "A test tool"}}
302315
303316 resp, err := mock.ChatWithTools(ctx, messages, tools)
@@ -312,13 +325,14 @@ func TestMockProviderWithReasoning(t *testing.T) {
312325 func TestMockProviderConcurrentAccess(t *testing.T) {
313326 mock := NewMock("test", "response")
314327 ctx := context.Background()
315- messages := []Message{{Role: "user", Content: "Hi"}}
328+ messages := make([]Message, 0, 1)
329+ messages = append(messages, Message{Role: "user", Content: "Hi"})
316330
317331 // Run concurrent reads and writes
318332 done := make(chan bool)
319333 for i := 0; i < 10; i++ {
320334 go func() {
321- mock.Chat(ctx, messages)
335+ _, _ = mock.Chat(ctx, messages)
322336 done <- true
323337 }()
324338 go func() {
@@ -341,16 +355,15 @@ func TestToOpenAIMessagesEmpty(t *testing.T) {
341355 }
342356
343357 func TestToOpenAIMessagesMultipleToolCalls(t *testing.T) {
344- messages := []Message{
345- {
346- Role: "assistant",
347- Content: "",
348- ToolCalls: []ToolCall{
349- {ID: "call_1", Name: "tool_a", Arguments: json.RawMessage(`{"a":1}`)},
350- {ID: "call_2", Name: "tool_b", Arguments: json.RawMessage(`{"b":2}`)},
351- },
358+ messages := make([]Message, 0, 1)
359+ messages = append(messages, Message{
360+ Role: "assistant",
361+ Content: "",
362+ ToolCalls: []ToolCall{
363+ {ID: "call_1", Name: "tool_a", Arguments: json.RawMessage(`{"a":1}`)},
364+ {ID: "call_2", Name: "tool_b", Arguments: json.RawMessage(`{"b":2}`)},
352365 },
353- }
366+ })
354367
355368 result := toOpenAIMessages(messages)
356369
@@ -366,7 +379,8 @@ func TestToOpenAIMessagesMultipleToolCalls(t *testing.T) {
366379 }
367380
368381 func TestToOllamaMessagesSerializesEmptyContent(t *testing.T) {
369- messages := []Message{{Role: "assistant", Content: ""}}
Cut short: this commit's diff is over 1000 lines.
internal/provider/streaming_test.go+23−15
Cut short: this commit's diff is over 1000 lines.
internal/store/credentials_test.go+14−14
Cut short: this commit's diff is over 1000 lines.
internal/store/store.go+3−3
Cut short: this commit's diff is over 1000 lines.
internal/tui/conversation.go+6−6
Cut short: this commit's diff is over 1000 lines.
internal/tui/runner.go+4−15
Cut short: this commit's diff is over 1000 lines.
internal/tui/statusbar.go+1−9
Cut short: this commit's diff is over 1000 lines.