fix: lint cleanup across repo (errcheck, staticcheck, ineffassign, unused)
- daemon.go: real bug — maybeRetryParked resolved fg := d.forgeFor(task) (matching markDead's pattern) but called d.Forge.SetStateLabel instead of fg.SetStateLabel, silently using the wrong forge client for multi-identity/multi-forge task routing. Fixed to use fg throughout. - telegram.go: updateThreadID existed but was never called anywhere; wired it into updateLoggingMiddleware so debug logs include thread_id. - Two SA9003 empty-branch tests (nell adapter_test.go, tools toolentry_test.go) were dead assertions with no body; implemented the actual check instead of deleting them. - memory manager_test.go: mockProvider.lastConfigSchema/lastBackupPaths were declared but never recorded; wired GetConfigSchema/BackupPaths to populate them and strengthened the aggregation tests to assert on per-provider content, not just counts. - Removed genuinely dead gateway messageevent_test.go helpers (intPtr/ i64Ptr, marked //go:fix inline, already fully superseded by the new() builtin used throughout the file). - Remaining errcheck findings (defer Close/Flush/Write, os.Setenv, etc. in test files) fixed with the existing `_ = ` convention already used elsewhere in the codebase. go build ./..., go test ./... (all packages ok), and golangci-lint run ./... all clean.
This commit is contained in:
1 parent
64352a06f3
commit
6fe1a7d037
19 files changed
+219
-183
No files matched your search
@@ -104,13 +104,13 @@ func (g *Gateway) Stop(ctx context.Context) error {
|
||||
|
||||
// handleSMTP processes one SMTP session.
|
||||
func (g *Gateway) handleSMTP(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
defer func() { _ = conn.Close() }()
|
||||
r := bufio.NewReader(conn)
|
||||
w := bufio.NewWriter(conn)
|
||||
|
||||
write := func(code int, msg string) {
|
||||
fmt.Fprintf(w, "%d %s\r\n", code, msg)
|
||||
w.Flush()
|
||||
_, _ = fmt.Fprintf(w, "%d %s\r\n", code, msg)
|
||||
_ = w.Flush()
|
||||
}
|
||||
readLine := func() (string, error) {
|
||||
line, err := r.ReadString('\n')
|
||||
@@ -290,7 +290,7 @@ func (g *Gateway) sendReply(to, from, text string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial relay: %w", err)
|
||||
}
|
||||
defer c.Close()
|
||||
defer func() { _ = c.Close() }()
|
||||
|
||||
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||
tlsCfg := &tls.Config{ServerName: serverName(g.RelayAddr)}
|
||||
|
||||
@@ -81,19 +81,19 @@ func TestSMTPReceiveAndRoute(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
ln.Close()
|
||||
_ = ln.Close()
|
||||
|
||||
g.ListenAddr = addr
|
||||
go func() { _ = g.Start(ctx, router) }()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
defer g.Stop(context.Background())
|
||||
defer func() { _ = g.Stop(context.Background()) }()
|
||||
|
||||
// Connect via SMTP and send a message.
|
||||
conn, err := net.DialTimeout("tcp", addr, 1*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
defer func() { _ = conn.Close() }()
|
||||
|
||||
// Read greeting.
|
||||
buf := make([]byte, 1024)
|
||||
@@ -104,7 +104,7 @@ func TestSMTPReceiveAndRoute(t *testing.T) {
|
||||
|
||||
// Send a minimal SMTP transaction.
|
||||
send := func(s string) {
|
||||
conn.Write([]byte(s + "\r\n"))
|
||||
_, _ = conn.Write([]byte(s + "\r\n"))
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
|
||||
|
||||
@@ -345,6 +345,9 @@ func (g *Gateway) updateLoggingMiddleware() bot.Middleware {
|
||||
if hasChat {
|
||||
attrs = append(attrs, "chat_id", chatID)
|
||||
}
|
||||
if threadID := updateThreadID(update); threadID != 0 {
|
||||
attrs = append(attrs, "thread_id", threadID)
|
||||
}
|
||||
g.log.Debug("telegram update", attrs...)
|
||||
next(ctx, b, update)
|
||||
}
|
||||
|
||||
@@ -179,12 +179,12 @@ func TestWriteTaskJSONOverwrite(t *testing.T) {
|
||||
p1 := TaskPayload{ID: 1, Title: "first"}
|
||||
p2 := TaskPayload{ID: 2, Title: "second"}
|
||||
|
||||
WriteTaskJSON(dir, p1)
|
||||
WriteTaskJSON(dir, p2) // overwrite
|
||||
_ = WriteTaskJSON(dir, p1)
|
||||
_ = WriteTaskJSON(dir, p2) // overwrite
|
||||
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "task.json"))
|
||||
var decoded TaskPayload
|
||||
json.Unmarshal(data, &decoded)
|
||||
_ = json.Unmarshal(data, &decoded)
|
||||
|
||||
if decoded.ID != 2 || decoded.Title != "second" {
|
||||
t.Errorf("expected second payload, got ID=%d Title=%q", decoded.ID, decoded.Title)
|
||||
@@ -201,7 +201,7 @@ func TestWriteTaskJSONMinimalPayload(t *testing.T) {
|
||||
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "task.json"))
|
||||
var decoded TaskPayload
|
||||
json.Unmarshal(data, &decoded)
|
||||
_ = json.Unmarshal(data, &decoded)
|
||||
|
||||
if decoded.ID != 1 {
|
||||
t.Error("minimal payload ID mismatch")
|
||||
|
||||
@@ -475,7 +475,7 @@ func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, repo config.Rep
|
||||
d.acknowledge(ctx, fg, repo, is)
|
||||
return
|
||||
}
|
||||
d.maybeRetryParked(ctx, fg, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
}
|
||||
|
||||
// pollNATS publishes discovered issues to NATS (new flow).
|
||||
@@ -487,7 +487,7 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, repo config.Repo,
|
||||
return
|
||||
}
|
||||
if existing != nil {
|
||||
d.maybeRetryParked(ctx, fg, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
return
|
||||
}
|
||||
if err := d.Nats.PublishTask(ctx, repo.Owner, repo.Name, is.Number, is.Title, is.Body, labels, identity); err != nil {
|
||||
@@ -620,10 +620,9 @@ func (d *Daemon) pollEither(ctx context.Context, repo config.Repo) []forge.Issue
|
||||
// maybeRetryParked requeues a parked task whose state label a human has
|
||||
// removed -- the forge-native retry trigger. When retry_count reaches the
|
||||
// configured max_retries the task moves to dead instead of requeuing.
|
||||
// fg is only used before task is loaded (the hasLabel short-circuit needs
|
||||
// no forge call); once task is available its own Identity is authoritative
|
||||
// for which forge client owns it, resolved via forgeFor.
|
||||
func (d *Daemon) maybeRetryParked(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue) {
|
||||
// The forge client is resolved from the task's own Identity via forgeFor
|
||||
// (not passed in) since that's authoritative for which forge client owns it.
|
||||
func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forge.Issue) {
|
||||
if hasLabel(is.Labels, d.Cfg.Dispatch.StateLabel("parked")) {
|
||||
return
|
||||
}
|
||||
@@ -631,7 +630,7 @@ func (d *Daemon) maybeRetryParked(ctx context.Context, fg forge.Forge, repo conf
|
||||
if err != nil || task == nil || task.Status != store.StatusParked {
|
||||
return
|
||||
}
|
||||
fg = d.forgeFor(task)
|
||||
fg := d.forgeFor(task)
|
||||
|
||||
maxRetries := repo.EffectiveMaxRetries(d.Cfg.MaxRetries)
|
||||
|
||||
@@ -648,7 +647,7 @@ func (d *Daemon) maybeRetryParked(ctx context.Context, fg forge.Forge, repo conf
|
||||
d.Log.Error("increment retry_count failed", "issue", is.Number, "err", err)
|
||||
}
|
||||
d.Log.Info("parked task requeued via label removal", "repo", repo.FullName(), "issue", is.Number, "retry_count", task.RetryCount+1, "max_retries", maxRetries)
|
||||
d.Forge.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
fg.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: "task_retried", TaskID: task.ID,
|
||||
Repo: repo.FullName(), Issue: is.Number, Detail: "parked label removed",
|
||||
|
||||
@@ -543,7 +543,7 @@ func TestMaybeRetryParkedUnderThreshold(t *testing.T) {
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, d.Forge, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
@@ -572,7 +572,7 @@ func TestMaybeRetryParkedAtThreshold(t *testing.T) {
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, d.Forge, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
@@ -601,7 +601,7 @@ func TestMaybeRetryParkedSkipsDead(t *testing.T) {
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, d.Forge, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
if len(fg.stateLabels) != 0 {
|
||||
t.Fatalf("expected no state label calls, got %d", len(fg.stateLabels))
|
||||
@@ -689,7 +689,7 @@ func TestMaybeRetryParkedStillParked(t *testing.T) {
|
||||
is := forge.Issue{Number: 1, Labels: []string{"archie:parked", "bug"}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, d.Forge, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
if len(fg.stateLabels) != 0 {
|
||||
t.Fatalf("expected no state label calls, got %d", len(fg.stateLabels))
|
||||
@@ -705,7 +705,7 @@ func TestMaybeRetryParkedRepoOverride(t *testing.T) {
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo", MaxRetries: 1}
|
||||
|
||||
d.maybeRetryParked(ctx, d.Forge, repo, is)
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
|
||||
@@ -5,12 +5,6 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
//go:fix inline
|
||||
func intPtr(v int) *int { return new(v) }
|
||||
|
||||
//go:fix inline
|
||||
func i64Ptr(v int64) *int64 { return new(v) }
|
||||
|
||||
func TestMessageEventToLegacy(t *testing.T) {
|
||||
e := MessageEvent{
|
||||
Type: MsgText,
|
||||
|
||||
@@ -342,7 +342,7 @@ func (m *Manager) OnTurnStart(sessionID string) {
|
||||
|
||||
for _, p := range providers {
|
||||
if h, ok := p.(TurnStartHook); ok {
|
||||
safeGo(func() { h.OnTurnStart(sessionID) })
|
||||
safeGo(func() { _ = h.OnTurnStart(sessionID) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -354,7 +354,7 @@ func (m *Manager) OnSessionEnd(sessionID string) {
|
||||
|
||||
for _, p := range providers {
|
||||
if h, ok := p.(SessionEndHook); ok {
|
||||
safeGo(func() { h.OnSessionEnd(sessionID) })
|
||||
safeGo(func() { _ = h.OnSessionEnd(sessionID) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -366,7 +366,7 @@ func (m *Manager) OnSessionSwitch(oldSessionID, newSessionID string) {
|
||||
|
||||
for _, p := range providers {
|
||||
if h, ok := p.(SessionSwitchHook); ok {
|
||||
safeGo(func() { h.OnSessionSwitch(oldSessionID, newSessionID) })
|
||||
safeGo(func() { _ = h.OnSessionSwitch(oldSessionID, newSessionID) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -378,7 +378,7 @@ func (m *Manager) OnPreCompress(sessionID string) {
|
||||
|
||||
for _, p := range providers {
|
||||
if h, ok := p.(PreCompressHook); ok {
|
||||
safeGo(func() { h.OnPreCompress(sessionID) })
|
||||
safeGo(func() { _ = h.OnPreCompress(sessionID) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -390,7 +390,7 @@ func (m *Manager) OnMemoryWrite(sessionID string, content string) {
|
||||
|
||||
for _, p := range providers {
|
||||
if h, ok := p.(MemoryWriteHook); ok {
|
||||
safeGo(func() { h.OnMemoryWrite(sessionID, content) })
|
||||
safeGo(func() { _ = h.OnMemoryWrite(sessionID, content) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -402,7 +402,7 @@ func (m *Manager) OnDelegation(sessionID string) {
|
||||
|
||||
for _, p := range providers {
|
||||
if h, ok := p.(DelegationHook); ok {
|
||||
safeGo(func() { h.OnDelegation(sessionID) })
|
||||
safeGo(func() { _ = h.OnDelegation(sessionID) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package memory
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -221,13 +222,16 @@ func (m *mockProvider) OnDelegation(sessionID string) error {
|
||||
// ── Config helpers ──────────────────────────────────────────────────────
|
||||
|
||||
func (m *mockProvider) GetConfigSchema() map[string]any {
|
||||
m.mu.Lock()
|
||||
m.getConfigSchemaCalls++
|
||||
m.mu.Unlock()
|
||||
return map[string]any{
|
||||
schema := map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{},
|
||||
"provider": m.nameVal,
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.getConfigSchemaCalls++
|
||||
m.lastConfigSchema = schema
|
||||
m.mu.Unlock()
|
||||
return schema
|
||||
}
|
||||
|
||||
func (m *mockProvider) SaveConfig(values map[string]any, hermesHome string) error {
|
||||
@@ -242,10 +246,12 @@ func (m *mockProvider) SaveConfig(values map[string]any, hermesHome string) erro
|
||||
// ── Backup paths ────────────────────────────────────────────────────────
|
||||
|
||||
func (m *mockProvider) BackupPaths() []string {
|
||||
paths := []string{"/var/data/" + m.nameVal}
|
||||
m.mu.Lock()
|
||||
m.backupPathsCalls++
|
||||
m.lastBackupPaths = paths
|
||||
m.mu.Unlock()
|
||||
return []string{"/var/data/" + m.nameVal}
|
||||
return paths
|
||||
}
|
||||
|
||||
// ── Compile-time checks ─────────────────────────────────────────────────
|
||||
@@ -551,7 +557,7 @@ func TestManager_HandleToolCall_ScanBlocksPromptInjection(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
mgr.SetScanReject(true)
|
||||
@@ -577,7 +583,7 @@ func TestManager_HandleToolCall_ScanAllowsCleanContent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
mgr.SetScanReject(true)
|
||||
@@ -604,7 +610,7 @@ func TestManager_HandleToolCall_NotifiesExternalOnBuiltinWrite(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
_, err = mgr.HandleToolCall("builtin_tool", map[string]any{
|
||||
"session_id": "session-1",
|
||||
@@ -643,7 +649,7 @@ func TestManager_HandleToolCall_DoesNotNotifyOnExternalWrite(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// external_tool is owned by ext itself; a write through ext's own tool
|
||||
// must not loop back and notify ext of its own write.
|
||||
@@ -921,6 +927,26 @@ func TestManager_GetConfigSchema_Aggregates(t *testing.T) {
|
||||
if _, ok := schemas["external"]; !ok {
|
||||
t.Error("missing external in config schemas")
|
||||
}
|
||||
|
||||
// The manager's aggregated result must be each provider's own schema,
|
||||
// not a shared/mixed one.
|
||||
if schemas["builtin"]["provider"] != "builtin" {
|
||||
t.Errorf("schemas[\"builtin\"][\"provider\"] = %v, want %q", schemas["builtin"]["provider"], "builtin")
|
||||
}
|
||||
if schemas["external"]["provider"] != "external" {
|
||||
t.Errorf("schemas[\"external\"][\"provider\"] = %v, want %q", schemas["external"]["provider"], "external")
|
||||
}
|
||||
|
||||
builtin.mu.Lock()
|
||||
if builtin.lastConfigSchema["provider"] != "builtin" {
|
||||
t.Errorf("builtin.lastConfigSchema recorded %v, want provider=builtin", builtin.lastConfigSchema)
|
||||
}
|
||||
builtin.mu.Unlock()
|
||||
ext.mu.Lock()
|
||||
if ext.lastConfigSchema["provider"] != "external" {
|
||||
t.Errorf("external.lastConfigSchema recorded %v, want provider=external", ext.lastConfigSchema)
|
||||
}
|
||||
ext.mu.Unlock()
|
||||
}
|
||||
|
||||
func TestManager_SaveConfig(t *testing.T) {
|
||||
@@ -980,6 +1006,23 @@ func TestManager_BackupPaths_Aggregates(t *testing.T) {
|
||||
if len(paths) != 2 {
|
||||
t.Fatalf("BackupPaths() returned %d paths, want 2", len(paths))
|
||||
}
|
||||
if !slices.Contains(paths, "/var/data/builtin") {
|
||||
t.Errorf("BackupPaths() = %v, missing builtin path", paths)
|
||||
}
|
||||
if !slices.Contains(paths, "/var/data/external") {
|
||||
t.Errorf("BackupPaths() = %v, missing external path", paths)
|
||||
}
|
||||
|
||||
builtin.mu.Lock()
|
||||
if len(builtin.lastBackupPaths) != 1 || builtin.lastBackupPaths[0] != "/var/data/builtin" {
|
||||
t.Errorf("builtin.lastBackupPaths = %v, want [/var/data/builtin]", builtin.lastBackupPaths)
|
||||
}
|
||||
builtin.mu.Unlock()
|
||||
ext.mu.Lock()
|
||||
if len(ext.lastBackupPaths) != 1 || ext.lastBackupPaths[0] != "/var/data/external" {
|
||||
t.Errorf("external.lastBackupPaths = %v, want [/var/data/external]", ext.lastBackupPaths)
|
||||
}
|
||||
ext.mu.Unlock()
|
||||
}
|
||||
|
||||
func TestManager_BackupPaths_NoBackupProviders(t *testing.T) {
|
||||
@@ -1205,7 +1248,7 @@ func TestManager_SubmitSync_DispatchesToExternalProvider(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
done := make(chan error, 1)
|
||||
op := SyncOp{
|
||||
@@ -1257,7 +1300,7 @@ func TestManager_SubmitSync_FIFOOrdering(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Submit 3 ops. The external providers OnMemoryWrite stores the last
|
||||
// content only, so use content as a sequence identifier.
|
||||
@@ -1308,7 +1351,7 @@ func TestManager_SubmitSync_CompletionNotification(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Submit to builtin (no MemoryWriteHook by default on mock builtin).
|
||||
// Actually builtin mock does implement MemoryWriteHook. So this should
|
||||
@@ -1344,7 +1387,7 @@ func TestManager_SubmitSync_ProviderNotFound(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
done := make(chan error, 1)
|
||||
op := SyncOp{
|
||||
@@ -1400,7 +1443,7 @@ func TestManager_PrefetchContext_Success(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
ctx := context.Background()
|
||||
result, err := mgr.PrefetchContext(ctx, "test query")
|
||||
@@ -1418,7 +1461,7 @@ func TestManager_PrefetchContext_StoresResult(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
_, err = mgr.PrefetchContext(context.Background(), "store me")
|
||||
if err != nil {
|
||||
@@ -1444,10 +1487,10 @@ func TestManager_PrefetchContext_SkipWhenInFlight(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Start a prefetch that blocks.
|
||||
go mgr.PrefetchContext(context.Background(), "blocking")
|
||||
go func() { _, _ = mgr.PrefetchContext(context.Background(), "blocking") }()
|
||||
|
||||
// Give the goroutine time to acquire the in-flight flag.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
@@ -1476,7 +1519,7 @@ func TestManager_PrefetchContext_Timeout(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Set a very short timeout.
|
||||
mgr.SetPrefetchTimeout(10 * time.Millisecond)
|
||||
@@ -1496,7 +1539,7 @@ func TestManager_SetPrefetchTimeout(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Set custom timeout.
|
||||
mgr.SetPrefetchTimeout(5 * time.Second)
|
||||
@@ -1520,7 +1563,7 @@ func TestManager_NotifyMemoryToolWrite_DispatchesToExternal(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.NotifyMemoryToolWrite("session-1", "add", "notes", "hello world")
|
||||
|
||||
@@ -1550,7 +1593,7 @@ func TestManager_NotifyMemoryToolWrite_NoOpWithoutExternal(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Should not panic or error when no external provider is active.
|
||||
mgr.NotifyMemoryToolWrite("session-1", "add", "notes", "content")
|
||||
@@ -1564,7 +1607,7 @@ func TestManager_NotifyMemoryToolWrite_NoOpWhenExternalUnavailable(t *testing.T)
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
// Should not panic when external provider is unavailable.
|
||||
mgr.NotifyMemoryToolWrite("session-1", "add", "notes", "content")
|
||||
@@ -1578,7 +1621,7 @@ func TestManager_ScanContent_NoScannerReturnsNone(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
result := mgr.ScanContent("anything")
|
||||
if result.Level != ThreatNone {
|
||||
@@ -1592,7 +1635,7 @@ func TestManager_ScanContent_DisabledReturnsNone(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
mgr.SetScanDisabled(true)
|
||||
@@ -1609,7 +1652,7 @@ func TestManager_ScanContent_DetectsPromptInjection(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
|
||||
@@ -1626,7 +1669,7 @@ func TestManager_ScanContent_RejectModeBlocksPromptInjection(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
mgr.SetScanReject(true)
|
||||
@@ -1643,7 +1686,7 @@ func TestManager_ScanContent_DetectsSensitiveData(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
|
||||
@@ -1659,7 +1702,7 @@ func TestManager_ScanContent_CleanContent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
|
||||
@@ -1675,7 +1718,7 @@ func TestManager_SetScanner_NilClears(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetScanner(&DefaultScanner{})
|
||||
if mgr.Scanner() == nil {
|
||||
@@ -1830,7 +1873,7 @@ func TestManager_SetShutdownTimeout(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
defer mgr.Shutdown()
|
||||
defer func() { _ = mgr.Shutdown() }()
|
||||
|
||||
mgr.SetShutdownTimeout(30 * time.Second)
|
||||
if got := mgr.shutdownTimeout; got != 30*time.Second {
|
||||
|
||||
@@ -136,8 +136,8 @@ func TestScrubber_PartialOpenTag_SplitAtAngle(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("Hello <"))
|
||||
s.Write([]byte("memory>secret</memory> World"))
|
||||
_, _ = s.Write([]byte("Hello <"))
|
||||
_, _ = s.Write([]byte("memory>secret</memory> World"))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -169,8 +169,8 @@ func TestScrubber_PartialOpenTag_SplitMidTag(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte(tt.chunk1))
|
||||
s.Write([]byte(tt.chunk2))
|
||||
_, _ = s.Write([]byte(tt.chunk1))
|
||||
_, _ = s.Write([]byte(tt.chunk2))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -205,8 +205,8 @@ func TestScrubber_PartialCloseTag_SplitMidTag(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte(tt.chunk1))
|
||||
s.Write([]byte(tt.chunk2))
|
||||
_, _ = s.Write([]byte(tt.chunk1))
|
||||
_, _ = s.Write([]byte(tt.chunk2))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -253,8 +253,8 @@ func TestScrubber_PartialTag_NotActuallyATag(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte(tt.chunk1))
|
||||
s.Write([]byte(tt.chunk2))
|
||||
_, _ = s.Write([]byte(tt.chunk1))
|
||||
_, _ = s.Write([]byte(tt.chunk2))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -289,9 +289,9 @@ func TestScrubber_OpenTagAtExactChunkBoundary(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("Hello "))
|
||||
s.Write([]byte("<memory>secret</memory>"))
|
||||
s.Write([]byte(" World"))
|
||||
_, _ = s.Write([]byte("Hello "))
|
||||
_, _ = s.Write([]byte("<memory>secret</memory>"))
|
||||
_, _ = s.Write([]byte(" World"))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -306,8 +306,8 @@ func TestScrubber_CloseTagAtExactChunkBoundary(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("Hello <memory>secret"))
|
||||
s.Write([]byte("</memory> World"))
|
||||
_, _ = s.Write([]byte("Hello <memory>secret"))
|
||||
_, _ = s.Write([]byte("</memory> World"))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -324,7 +324,7 @@ func TestScrubber_SingleByteChunks(t *testing.T) {
|
||||
s := New(&buf)
|
||||
|
||||
for i := 0; i < len(input); i++ {
|
||||
s.Write([]byte{input[i]})
|
||||
_, _ = s.Write([]byte{input[i]})
|
||||
}
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -342,7 +342,7 @@ func TestScrubber_TwoByteChunks(t *testing.T) {
|
||||
|
||||
for i := 0; i < len(input); i += 2 {
|
||||
end := min(i+2, len(input))
|
||||
s.Write([]byte(input[i:end]))
|
||||
_, _ = s.Write([]byte(input[i:end]))
|
||||
}
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -357,8 +357,8 @@ func TestScrubber_ChunkEndingWithOpenTagStart(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("text <"))
|
||||
s.Write([]byte("notmemory> more"))
|
||||
_, _ = s.Write([]byte("text <"))
|
||||
_, _ = s.Write([]byte("notmemory> more"))
|
||||
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -427,7 +427,7 @@ func TestScrubber_Process_StreamingEquivalence(t *testing.T) {
|
||||
for _, ch := range chunks {
|
||||
streamingResult.WriteString(s2.Process(ch))
|
||||
}
|
||||
s2.Flush()
|
||||
_ = s2.Flush()
|
||||
streamingResult.WriteString(s2.Process("")) // drain any final output
|
||||
|
||||
if streamingResult.String() != oneShot {
|
||||
@@ -472,7 +472,7 @@ func TestScrubber_Reset_MidStream(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("A <memory>secret"))
|
||||
_, _ = s.Write([]byte("A <memory>secret"))
|
||||
if s.InMemoryBlock() == false {
|
||||
t.Error("expected to be in memory block")
|
||||
}
|
||||
@@ -487,8 +487,8 @@ func TestScrubber_Reset_MidStream(t *testing.T) {
|
||||
t.Errorf("BlocksStripped = %d after Reset, want 0", s.BlocksStripped())
|
||||
}
|
||||
|
||||
s.Write([]byte("clean <memory>gone</memory> text"))
|
||||
s.Flush()
|
||||
_, _ = s.Write([]byte("clean <memory>gone</memory> text"))
|
||||
_ = s.Flush()
|
||||
|
||||
if got := buf.String(); got != "clean text" {
|
||||
t.Errorf("after Reset: got %q, want %q", got, "clean text")
|
||||
@@ -541,12 +541,12 @@ func TestScrubber_InMemoryBlock(t *testing.T) {
|
||||
t.Error("InMemoryBlock should be false initially")
|
||||
}
|
||||
|
||||
s.Write([]byte("before <memory>"))
|
||||
_, _ = s.Write([]byte("before <memory>"))
|
||||
if !s.InMemoryBlock() {
|
||||
t.Error("InMemoryBlock should be true after open tag")
|
||||
}
|
||||
|
||||
s.Write([]byte("content</memory> after"))
|
||||
_, _ = s.Write([]byte("content</memory> after"))
|
||||
if s.InMemoryBlock() {
|
||||
t.Error("InMemoryBlock should be false after close tag")
|
||||
}
|
||||
@@ -560,22 +560,22 @@ func TestScrubber_Depth(t *testing.T) {
|
||||
t.Errorf("Depth = %d initially, want 0", s.Depth())
|
||||
}
|
||||
|
||||
s.Write([]byte("<memory>"))
|
||||
_, _ = s.Write([]byte("<memory>"))
|
||||
if s.Depth() != 1 {
|
||||
t.Errorf("Depth = %d after first open, want 1", s.Depth())
|
||||
}
|
||||
|
||||
s.Write([]byte("<memory>"))
|
||||
_, _ = s.Write([]byte("<memory>"))
|
||||
if s.Depth() != 2 {
|
||||
t.Errorf("Depth = %d after second open, want 2", s.Depth())
|
||||
}
|
||||
|
||||
s.Write([]byte("</memory>"))
|
||||
_, _ = s.Write([]byte("</memory>"))
|
||||
if s.Depth() != 1 {
|
||||
t.Errorf("Depth = %d after first close, want 1", s.Depth())
|
||||
}
|
||||
|
||||
s.Write([]byte("</memory>"))
|
||||
_, _ = s.Write([]byte("</memory>"))
|
||||
if s.Depth() != 0 {
|
||||
t.Errorf("Depth = %d after second close, want 0", s.Depth())
|
||||
}
|
||||
@@ -610,7 +610,7 @@ func TestScrubber_IOWriter_Chain(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("io.WriteString error: %v", err)
|
||||
}
|
||||
s.Flush()
|
||||
_ = s.Flush()
|
||||
|
||||
if got := buf.String(); got != "Hello World" {
|
||||
t.Errorf("got %q, want %q", got, "Hello World")
|
||||
@@ -629,9 +629,9 @@ func TestScrubber_MemoryBlockAcrossManyChunks(t *testing.T) {
|
||||
|
||||
for i := 0; i < len(input); i += 3 {
|
||||
end := min(i+3, len(input))
|
||||
s.Write([]byte(input[i:end]))
|
||||
_, _ = s.Write([]byte(input[i:end]))
|
||||
}
|
||||
s.Flush()
|
||||
_ = s.Flush()
|
||||
|
||||
expected := "visible_startvisible_end"
|
||||
if got := buf.String(); got != expected {
|
||||
@@ -643,14 +643,14 @@ func TestScrubber_ConsecutivePartialTags(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("a <")) // partial
|
||||
s.Write([]byte("m")) // still partial
|
||||
s.Write([]byte("emory>")) // complete!
|
||||
s.Write([]byte("hidden"))
|
||||
s.Write([]byte("</")) // partial close
|
||||
s.Write([]byte("memory>")) // complete close
|
||||
s.Write([]byte("b"))
|
||||
s.Flush()
|
||||
_, _ = s.Write([]byte("a <")) // partial
|
||||
_, _ = s.Write([]byte("m")) // still partial
|
||||
_, _ = s.Write([]byte("emory>")) // complete!
|
||||
_, _ = s.Write([]byte("hidden"))
|
||||
_, _ = s.Write([]byte("</")) // partial close
|
||||
_, _ = s.Write([]byte("memory>")) // complete close
|
||||
_, _ = s.Write([]byte("b"))
|
||||
_ = s.Flush()
|
||||
|
||||
if got := buf.String(); got != "a b" {
|
||||
t.Errorf("got %q, want %q", got, "a b")
|
||||
@@ -728,11 +728,11 @@ func TestScrubber_UnicodeSplitAcrossChunks(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("Hi <m"))
|
||||
s.Write([]byte("emory>")) // completes the open tag
|
||||
s.Write([]byte("世界</memory> Bye"))
|
||||
_, _ = s.Write([]byte("Hi <m"))
|
||||
_, _ = s.Write([]byte("emory>")) // completes the open tag
|
||||
_, _ = s.Write([]byte("世界</memory> Bye"))
|
||||
|
||||
s.Flush()
|
||||
_ = s.Flush()
|
||||
|
||||
if got := buf.String(); got != "Hi Bye" {
|
||||
t.Errorf("got %q, want %q", got, "Hi Bye")
|
||||
@@ -809,7 +809,7 @@ func TestScrubber_Flush_PendingInMemoryBlock_NotEmitted(t *testing.T) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
s.Write([]byte(tt.input))
|
||||
_, _ = s.Write([]byte(tt.input))
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
}
|
||||
@@ -825,7 +825,7 @@ func TestScrubber_Flush_PendingInMemoryBlock_StatsCorrect(t *testing.T) {
|
||||
// on Flush inside a memory block.
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
s.Write([]byte("<memory>abc<"))
|
||||
_, _ = s.Write([]byte("<memory>abc<"))
|
||||
// At this point: bytesStripped = 8 (<memory>) + 3 (abc) = 11, pending = "<"
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
@@ -847,8 +847,8 @@ func TestScrubber_Flush_PendingInMemoryBlock_TwoChunks(t *testing.T) {
|
||||
// memory block, second chunk is empty.
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
s.Write([]byte("<memory>xyz<"))
|
||||
s.Write([]byte("")) // empty chunk
|
||||
_, _ = s.Write([]byte("<memory>xyz<"))
|
||||
_, _ = s.Write([]byte("")) // empty chunk
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
}
|
||||
@@ -865,7 +865,7 @@ func TestScrubber_Flush_PendingOutsideMemoryBlock(t *testing.T) {
|
||||
// This is the normal case for a partial tag that turns out not to be a tag.
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
s.Write([]byte("hello <m"))
|
||||
_, _ = s.Write([]byte("hello <m"))
|
||||
if err := s.Flush(); err != nil {
|
||||
t.Fatalf("Flush error: %v", err)
|
||||
}
|
||||
@@ -880,9 +880,9 @@ func TestScrubber_Flush_SingleByteChunkIntoMemoryBlock(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
|
||||
s.Write([]byte("A <mem"))
|
||||
s.Write([]byte("ory>xyz<"))
|
||||
s.Flush()
|
||||
_, _ = s.Write([]byte("A <mem"))
|
||||
_, _ = s.Write([]byte("ory>xyz<"))
|
||||
_ = s.Flush()
|
||||
|
||||
if got := buf.String(); got != "A " {
|
||||
t.Errorf("got %q, want %q", got, "A ")
|
||||
@@ -899,18 +899,18 @@ func TestScrubber_Write_ZeroLengthChunkWithPending(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
s := New(&buf)
|
||||
// Write text ending with a partial tag prefix.
|
||||
s.Write([]byte("data <m"))
|
||||
_, _ = s.Write([]byte("data <m"))
|
||||
if len(s.pending) == 0 {
|
||||
t.Error("pending should not be empty after partial tag")
|
||||
}
|
||||
s.Write([]byte("")) // zero-length write -- no-op
|
||||
_, _ = s.Write([]byte("")) // zero-length write -- no-op
|
||||
if len(s.pending) == 0 {
|
||||
t.Error("pending should not be cleared by zero-length Write")
|
||||
}
|
||||
// Now write text that does NOT complete the tag: "<m" + "x..." = "<mx..."
|
||||
// which is NOT "<memory>" so it should pass through.
|
||||
s.Write([]byte("x abc"))
|
||||
s.Flush()
|
||||
_, _ = s.Write([]byte("x abc"))
|
||||
_ = s.Flush()
|
||||
if got := buf.String(); got != "data <mx abc" {
|
||||
t.Errorf("got %q, want %q", got, "data <mx abc")
|
||||
}
|
||||
@@ -926,7 +926,7 @@ func TestScrubber_SatisfiesIOWriter(t *testing.T) {
|
||||
|
||||
func TestScrubber_DebugString(t *testing.T) {
|
||||
s := New(nil)
|
||||
s.Write([]byte("<memory>test"))
|
||||
_, _ = s.Write([]byte("<memory>test"))
|
||||
|
||||
ds := s.DebugString()
|
||||
if !strings.Contains(ds, "depth=1") {
|
||||
@@ -942,9 +942,9 @@ func BenchmarkScrubber_NoMemoryBlock(b *testing.B) {
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
s.Write(input)
|
||||
_, _ = s.Write(input)
|
||||
}
|
||||
s.Flush()
|
||||
_ = s.Flush()
|
||||
}
|
||||
|
||||
func BenchmarkScrubber_SingleMemoryBlock(b *testing.B) {
|
||||
@@ -954,8 +954,8 @@ func BenchmarkScrubber_SingleMemoryBlock(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
s.Reset()
|
||||
s.Write(input)
|
||||
s.Flush()
|
||||
_, _ = s.Write(input)
|
||||
_ = s.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -973,9 +973,9 @@ func BenchmarkScrubber_ManySmallChunks(b *testing.B) {
|
||||
for b.Loop() {
|
||||
s.Reset()
|
||||
for _, ch := range chunks {
|
||||
s.Write(ch)
|
||||
_, _ = s.Write(ch)
|
||||
}
|
||||
s.Flush()
|
||||
_ = s.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1004,8 +1004,8 @@ func BenchmarkScrubber_LargeInputManyBlocks(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
s.Reset()
|
||||
s.Write(data)
|
||||
s.Flush()
|
||||
_, _ = s.Write(data)
|
||||
_ = s.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1016,7 +1016,7 @@ func BenchmarkScrubber_NestedBlocks(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
s.Reset()
|
||||
s.Write(input)
|
||||
s.Flush()
|
||||
_, _ = s.Write(input)
|
||||
_ = s.Flush()
|
||||
}
|
||||
}
|
||||
@@ -86,8 +86,8 @@ func TestEnvelopeJSONRoundTrip(t *testing.T) {
|
||||
t.Errorf("expected error 'request failed', got %v", decoded.Err())
|
||||
}
|
||||
// Error field flattens into parent JSON.
|
||||
if decoded.Envelope.Error != "request failed" {
|
||||
t.Errorf("Error = %q", decoded.Envelope.Error)
|
||||
if decoded.Error != "request failed" {
|
||||
t.Errorf("Error = %q", decoded.Error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -243,7 +243,7 @@ func TestPersistenceAcrossRestart(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s2.Close()
|
||||
defer func() { _ = s2.Close() }()
|
||||
|
||||
task, err := s2.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
@@ -459,8 +459,8 @@ func TestStatusCountsAfterTransitions(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
s.EnqueueIssue(ctx, "acme", "repo", 1, "t1", "", "", "")
|
||||
s.EnqueueIssue(ctx, "acme", "repo", 2, "t2", "", "", "")
|
||||
_, _ = s.EnqueueIssue(ctx, "acme", "repo", 1, "t1", "", "", "")
|
||||
_, _ = s.EnqueueIssue(ctx, "acme", "repo", 2, "t2", "", "", "")
|
||||
|
||||
task1, _ := s.ClaimNext(ctx)
|
||||
task2, _ := s.ClaimNext(ctx)
|
||||
@@ -470,7 +470,7 @@ func TestStatusCountsAfterTransitions(t *testing.T) {
|
||||
t.Errorf("expected 2 running, got %d", counts[store.StatusRunning])
|
||||
}
|
||||
|
||||
s.Transition(ctx, task1.ID, store.StatusRunning, store.StatusPROpen, "")
|
||||
_ = s.Transition(ctx, task1.ID, store.StatusRunning, store.StatusPROpen, "")
|
||||
counts, _ = s.StatusCounts(ctx)
|
||||
if counts[store.StatusPROpen] != 1 {
|
||||
t.Errorf("expected 1 pr_open, got %d", counts[store.StatusPROpen])
|
||||
@@ -497,8 +497,8 @@ func TestInsertEventsSinceAndRecent(t *testing.T) {
|
||||
if len(evs) < 2 {
|
||||
t.Fatalf("expected at least 2 events, got %d", len(evs))
|
||||
}
|
||||
if evs[0].ID < evs[1].ID {
|
||||
// Oldest first — correct.
|
||||
if evs[0].ID >= evs[1].ID {
|
||||
t.Errorf("EventsSince order: evs[0].ID=%d, evs[1].ID=%d, want oldest first", evs[0].ID, evs[1].ID)
|
||||
}
|
||||
|
||||
// RecentEvents returns newest first.
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
)
|
||||
|
||||
func TestEnvEngineResolve(t *testing.T) {
|
||||
os.Setenv("TEST_SECRET_KEY", "test-value")
|
||||
defer os.Unsetenv("TEST_SECRET_KEY")
|
||||
_ = os.Setenv("TEST_SECRET_KEY", "test-value")
|
||||
defer func() { _ = os.Unsetenv("TEST_SECRET_KEY") }()
|
||||
|
||||
e := &envEngine{}
|
||||
if e.Name() != "env" {
|
||||
@@ -65,8 +65,8 @@ func TestRegistryGetMissing(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRegistryResolve(t *testing.T) {
|
||||
os.Setenv("TEST_SECRET", "resolved")
|
||||
defer os.Unsetenv("TEST_SECRET")
|
||||
_ = os.Setenv("TEST_SECRET", "resolved")
|
||||
defer func() { _ = os.Unsetenv("TEST_SECRET") }()
|
||||
|
||||
r := NewRegistry()
|
||||
v, err := r.Resolve(SecretRef{Engine: "env", Key: "TEST_SECRET"})
|
||||
|
||||
@@ -55,7 +55,7 @@ func (t *HTTPTransport) Send(ctx context.Context, body []byte) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
// Read up to 4 KB of the error body for diagnostics.
|
||||
@@ -80,7 +80,7 @@ func (t *HTTPTransport) Notify(ctx context.Context, body []byte) error {
|
||||
}
|
||||
// Drain and close the response body to return the connection to the pool.
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -101,3 +101,6 @@ func (t *HTTPTransport) do(ctx context.Context, body []byte) (*http.Response, er
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Compile-time interface check.
|
||||
var _ Transport = (*HTTPTransport)(nil)
|
||||
@@ -21,7 +21,7 @@ func TestHTTPTransportSendReturnsResponse(t *testing.T) {
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprint(w, `{"jsonrpc":"2.0","id":"1","result":{"status":"ok"}}`)
|
||||
_, _ = fmt.Fprint(w, `{"jsonrpc":"2.0","id":"1","result":{"status":"ok"}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
@@ -42,7 +42,7 @@ func TestHTTPTransportSendReturnsResponse(t *testing.T) {
|
||||
func TestHTTPTransportSendReturnsErrorOnNon200(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, "boom")
|
||||
_, _ = fmt.Fprint(w, "boom")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
@@ -107,7 +107,7 @@ func TestHTTPTransportSendWithCustomHeaders(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
receivedHeader = r.Header.Get("Authorization")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"jsonrpc":"2.0","id":"1","result":{}}`)
|
||||
_, _ = fmt.Fprint(w, `{"jsonrpc":"2.0","id":"1","result":{}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
|
||||
@@ -66,10 +66,6 @@ type SSETransport struct {
|
||||
mu sync.Mutex
|
||||
state TransportState
|
||||
|
||||
// sessionID is learned from the endpoint event after the SSE
|
||||
// connection is established and appended as a query parameter on
|
||||
// POSTs to the message endpoint.
|
||||
sessionID string
|
||||
// messageEndpoint is the actual POST URL the server told us to use,
|
||||
// discovered from the endpoint event (or the config fallback).
|
||||
messageEndpoint string
|
||||
@@ -214,7 +210,7 @@ func (t *SSETransport) connect(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
err := fmt.Errorf("mcp sse: server returned %d", resp.StatusCode)
|
||||
_ = t.setError(err)
|
||||
return err
|
||||
@@ -228,7 +224,7 @@ func (t *SSETransport) connect(ctx context.Context) error {
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
msgURL, err := readEndpointEvent(reader)
|
||||
if err != nil {
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
_ = t.setError(fmt.Errorf("mcp sse: read endpoint event: %w", err))
|
||||
return err
|
||||
}
|
||||
@@ -252,7 +248,7 @@ func (t *SSETransport) connect(ctx context.Context) error {
|
||||
// "message" events to the corresponding pending channel.
|
||||
func (t *SSETransport) runReader(body io.Closer, reader *bufio.Reader) {
|
||||
defer t.readerWg.Done()
|
||||
defer body.Close()
|
||||
defer func() { _ = body.Close() }()
|
||||
|
||||
for {
|
||||
event, data, err := readSSEEvent(reader)
|
||||
@@ -323,7 +319,7 @@ func (t *SSETransport) reconnect() {
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff())
|
||||
continue
|
||||
}
|
||||
@@ -331,7 +327,7 @@ func (t *SSETransport) reconnect() {
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
msgURL, err := readEndpointEvent(reader)
|
||||
if err != nil {
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff())
|
||||
continue
|
||||
}
|
||||
@@ -407,7 +403,7 @@ func (t *SSETransport) postJSON(ctx context.Context, body []byte) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp sse: post: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
|
||||
@@ -19,11 +19,9 @@ import (
|
||||
// events onto events to send them back through the SSE stream.
|
||||
type sseTestServer struct {
|
||||
*httptest.Server
|
||||
SessID string
|
||||
events chan string
|
||||
incoming chan []byte
|
||||
mu sync.Mutex
|
||||
postedIDs []string
|
||||
SessID string
|
||||
events chan string
|
||||
incoming chan []byte
|
||||
}
|
||||
|
||||
func newSSETestServer(t *testing.T) *sseTestServer {
|
||||
@@ -33,7 +31,7 @@ func newSSETestServer(t *testing.T) *sseTestServer {
|
||||
incoming: make(chan []byte, 10),
|
||||
}
|
||||
s.Server = httptest.NewUnstartedServer(s)
|
||||
s.Server.Start()
|
||||
s.Start()
|
||||
s.SessID = "test-session-id"
|
||||
return s
|
||||
}
|
||||
@@ -51,13 +49,13 @@ func (s *sseTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// Send the endpoint event — tells the client where to POST.
|
||||
fmt.Fprintf(w, "event: endpoint\ndata: %s/messages?session_id=%s\n\n", s.URL, s.SessID)
|
||||
_, _ = fmt.Fprintf(w, "event: endpoint\ndata: %s/messages?session_id=%s\n\n", s.URL, s.SessID)
|
||||
flusher.Flush()
|
||||
|
||||
for {
|
||||
select {
|
||||
case data := <-s.events:
|
||||
fmt.Fprintf(w, "event: message\ndata: %s\n\n", data)
|
||||
_, _ = fmt.Fprintf(w, "event: message\ndata: %s\n\n", data)
|
||||
flusher.Flush()
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
@@ -66,7 +64,7 @@ func (s *sseTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
case "/messages":
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
_ = r.Body.Close()
|
||||
s.incoming <- body
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
|
||||
@@ -86,7 +84,7 @@ func TestSSETransportSendReceivesResponseViaSSE(t *testing.T) {
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer tr.Stop(context.Background())
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond) // let the SSE connection establish
|
||||
|
||||
@@ -121,7 +119,7 @@ func TestSSETransportNotifyFireAndForget(t *testing.T) {
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer tr.Stop(context.Background())
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
@@ -197,7 +195,7 @@ func TestSSETransportConcurrentSendsGetCorrectResponses(t *testing.T) {
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer tr.Stop(context.Background())
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ func TestRegistryAll(t *testing.T) {
|
||||
|
||||
t.Run("returns copy of tools", func(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
r.Register(ToolEntry{Name: "x", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "x", Handler: noopHandler})
|
||||
all := r.All()
|
||||
all[0].Name = "mutated"
|
||||
// Original registry must be unaffected.
|
||||
@@ -115,10 +115,10 @@ func TestRegistryAll(t *testing.T) {
|
||||
|
||||
func TestRegistryByToolset(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
r.Register(ToolEntry{Name: "f1", Toolset: "file", Handler: noopHandler})
|
||||
r.Register(ToolEntry{Name: "f2", Toolset: "file", Handler: noopHandler})
|
||||
r.Register(ToolEntry{Name: "g1", Toolset: "git", Handler: noopHandler})
|
||||
r.Register(ToolEntry{Name: "u1", Toolset: "", Handler: noopHandler}) // ungrouped
|
||||
_ = r.Register(ToolEntry{Name: "f1", Toolset: "file", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "f2", Toolset: "file", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "g1", Toolset: "git", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "u1", Toolset: "", Handler: noopHandler}) // ungrouped
|
||||
|
||||
t.Run("filters by toolset", func(t *testing.T) {
|
||||
file := r.ByToolset("file")
|
||||
@@ -152,9 +152,9 @@ func TestRegistryByToolset(t *testing.T) {
|
||||
|
||||
func TestRegistryAvailable(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
r.Register(ToolEntry{Name: "always", Handler: noopHandler})
|
||||
r.Register(ToolEntry{Name: "offline", Handler: noopHandler, CheckFn: func() bool { return false }})
|
||||
r.Register(ToolEntry{Name: "conditional", Handler: noopHandler, CheckFn: func() bool { return true }})
|
||||
_ = r.Register(ToolEntry{Name: "always", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "offline", Handler: noopHandler, CheckFn: func() bool { return false }})
|
||||
_ = r.Register(ToolEntry{Name: "conditional", Handler: noopHandler, CheckFn: func() bool { return true }})
|
||||
|
||||
t.Run("returns only available tools", func(t *testing.T) {
|
||||
avail := r.Available()
|
||||
@@ -175,7 +175,7 @@ func TestRegistryAvailable(t *testing.T) {
|
||||
|
||||
t.Run("dynamic availability reflected", func(t *testing.T) {
|
||||
flag := true
|
||||
r.Register(ToolEntry{
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "toggle",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return flag },
|
||||
@@ -317,10 +317,10 @@ func TestRegistryAvailableReentrySafety(t *testing.T) {
|
||||
// calling All(), ByToolset(), or even Register() from inside
|
||||
// CheckFn cannot deadlock.
|
||||
r := NewRegistry()
|
||||
r.Register(ToolEntry{Name: "safe", Handler: noopHandler})
|
||||
_ = r.Register(ToolEntry{Name: "safe", Handler: noopHandler})
|
||||
|
||||
called := false
|
||||
r.Register(ToolEntry{
|
||||
_ = r.Register(ToolEntry{
|
||||
Name: "reentrant",
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool {
|
||||
|
||||
@@ -316,7 +316,7 @@ func TestToolEntryZeroValue(t *testing.T) {
|
||||
t.Error("zero ToolEntry should fail Validate")
|
||||
}
|
||||
if !e.Available() {
|
||||
// nil CheckFn = available -- this is correct even for zero value.
|
||||
t.Error("zero ToolEntry should be Available (nil CheckFn = available)")
|
||||
}
|
||||
if e.ResolvedSchema() != nil {
|
||||
t.Error("zero ToolEntry should have nil resolved schema")
|
||||
|
||||
Reference in new issue
Block a user