From 757e1da3230425fee97607a57bc12953ca3a6aad Mon Sep 17 00:00:00 2001 From: sisantaChhatoi Date: Thu, 3 Dec 2026 02:08:01 +0530 Subject: [PATCH] refactor(notify): use modern Go idioms Mechanical modernization of notify, chatbridge, sidequestion, report, archivestore, config, enrich and llmrec with the gopls/go fix modernizers: range over int, strings.SplitSeq, strings.Cut / CutPrefix, slices.Contains / Sort / Backward, maps.Copy, min / max, sync.WaitGroup.Go and t.Context in tests. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- archivestore/s3.go | 2 +- chatbridge/router.go | 8 ++------ chatbridge/router_test.go | 4 ++-- config/config.go | 8 ++------ enrich/coverage_test.go | 6 ++---- llmrec/context_telemetry.go | 5 +---- notify/channels_test.go | 8 ++++---- notify/email.go | 13 +++++-------- notify/email_test.go | 5 ++--- notify/limits_test.go | 2 +- notify/mask.go | 5 ++--- notify/pack_test.go | 4 ++-- notify/render.go | 5 +---- notify/webhook_template_test.go | 2 +- report/quality.go | 2 +- report/report_test.go | 2 +- sidequestion/context.go | 13 +++++++------ sidequestion/sidequestion_test.go | 4 ++-- 18 files changed, 39 insertions(+), 59 deletions(-) diff --git a/archivestore/s3.go b/archivestore/s3.go index 5761a838..65e93288 100644 --- a/archivestore/s3.go +++ b/archivestore/s3.go @@ -277,7 +277,7 @@ const ( func (s *Store) readArchiveChunk(ctx context.Context, key, etag string, start, end, total int64) ([]byte, error) { var lastErr error - for attempt := 0; attempt < archiveReadAttempts; attempt++ { + for attempt := range archiveReadAttempts { if err := ctx.Err(); err != nil { return nil, err } diff --git a/chatbridge/router.go b/chatbridge/router.go index 07266625..d35d0e08 100644 --- a/chatbridge/router.go +++ b/chatbridge/router.go @@ -3,6 +3,7 @@ package chatbridge import ( "context" "fmt" + "slices" "sort" "strings" "sync" @@ -267,10 +268,5 @@ func parseCommand(text, botUserName string) (name, args string, forOther bool) { } func contains(list []string, v string) bool { - for _, s := range list { - if s == v { - return true - } - } - return false + return slices.Contains(list, v) } diff --git a/chatbridge/router_test.go b/chatbridge/router_test.go index fce6212a..fcc34f36 100644 --- a/chatbridge/router_test.go +++ b/chatbridge/router_test.go @@ -51,7 +51,7 @@ func TestRouteUnknownChatRefusedOnceThenMuted(t *testing.T) { if strings.Contains(reply, "echo") { t.Fatalf("refusal must not run the command: %q", reply) } - for i := 0; i < 3; i++ { + for i := range 3 { if d, reply := r.Route(context.Background(), KindTelegram, Access{Chats: []string{"100"}}, msg("555", "hello?")); d != DecisionMuted || reply != "" { t.Fatalf("repeat %d: got %v %q", i, d, reply) } @@ -67,7 +67,7 @@ func TestRouteEmptyAllowlistRefusesEveryone(t *testing.T) { func TestRouteRefusalMemoryIsBounded(t *testing.T) { r := testRouter() - for i := 0; i < maxRefusedChats; i++ { + for i := range maxRefusedChats { r.Route(context.Background(), KindTelegram, Access{}, msg("c"+itoa(i), "hi")) } // Past the cap the memory starts over: a new chat (it may be the diff --git a/config/config.go b/config/config.go index 9e01878f..dc9272ef 100644 --- a/config/config.go +++ b/config/config.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "strconv" "strings" ) @@ -81,12 +82,7 @@ func isGoRunDir(dir string) bool { return true } } - for _, seg := range strings.Split(filepath.ToSlash(dir), "/") { - if seg == "go-build" { - return true - } - } - return false + return slices.Contains(strings.Split(filepath.ToSlash(dir), "/"), "go-build") } // Path returns the config file path. Resolution order: diff --git a/enrich/coverage_test.go b/enrich/coverage_test.go index 2f96c22a..a2e6d7fc 100644 --- a/enrich/coverage_test.go +++ b/enrich/coverage_test.go @@ -590,11 +590,9 @@ func TestWorkerStopsOnClose(t *testing.T) { } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { e.worker() - }() + }) e.Close() diff --git a/llmrec/context_telemetry.go b/llmrec/context_telemetry.go index b4e14533..39b0d3aa 100644 --- a/llmrec/context_telemetry.go +++ b/llmrec/context_telemetry.go @@ -71,10 +71,7 @@ func MeasureContext(req llm.CompletionRequest) ContextMetrics { // 1. System prompt bytes (split at DynamicBoundary when > 0, else single static block). if len(req.System) > 0 { if req.DynamicBoundary > 0 { - b := req.DynamicBoundary - if b > len(req.System) { - b = len(req.System) - } + b := min(req.DynamicBoundary, len(req.System)) m.SystemStaticBytes = joinedSegmentBytes(req.System[:b]) m.SystemDynamicBytes = joinedSegmentBytes(req.System[b:]) } else { diff --git a/notify/channels_test.go b/notify/channels_test.go index bdc84bd6..96a25db1 100644 --- a/notify/channels_test.go +++ b/notify/channels_test.go @@ -34,7 +34,7 @@ func singleMsg() Message { // batchMsg builds a batch digest message. func batchMsg(n int) Message { m := Message{Batch: true, WindowMinutes: 30, HomeURL: "https://artex.local/function/findings"} - for i := 0; i < n; i++ { + for i := range n { m.Items = append(m.Items, Item{ FindingID: int64(i + 1), Name: "vuln" + itoa(i+1), @@ -405,9 +405,9 @@ func TestEmailEscapesStructuralInjection(t *testing.T) { func mustExtractHeader(t *testing.T, msg, name string) string { t.Helper() - for _, line := range strings.Split(msg, "\r\n") { - if strings.HasPrefix(line, name+": ") { - return strings.TrimPrefix(line, name+": ") + for line := range strings.SplitSeq(msg, "\r\n") { + if after, ok := strings.CutPrefix(line, name+": "); ok { + return after } } t.Fatalf("header %s not found", name) diff --git a/notify/email.go b/notify/email.go index a3113fec..22fd26a5 100644 --- a/notify/email.go +++ b/notify/email.go @@ -11,6 +11,7 @@ import ( "net" "net/mail" "net/smtp" + "slices" "strconv" "strings" "time" @@ -59,10 +60,8 @@ func (emailChannel) Validate(cfg map[string]any) error { if len(cfgStrings(cfg, "to")) == 0 { return errors.New("at least one recipient address is required") } - for _, rcpt := range cfgStrings(cfg, "to") { - if hasLineBreak(rcpt) { - return errors.New("recipient address must not contain line breaks") - } + if slices.ContainsFunc(cfgStrings(cfg, "to"), hasLineBreak) { + return errors.New("recipient address must not contain line breaks") } if _, err := senderAddress(cfgString(cfg, "from")); err != nil { return err @@ -236,10 +235,8 @@ func buildEmailMessage(from string, to []string, m Message) (string, error) { if hasLineBreak(from) { return "", errors.New("sender address must not contain line breaks") } - for _, rcpt := range to { - if hasLineBreak(rcpt) { - return "", errors.New("recipient address must not contain line breaks") - } + if slices.ContainsFunc(to, hasLineBreak) { + return "", errors.New("recipient address must not contain line breaks") } var b strings.Builder fmt.Fprintf(&b, "From: %s\r\n", from) diff --git a/notify/email_test.go b/notify/email_test.go index d1b77dfa..aa61d82b 100644 --- a/notify/email_test.go +++ b/notify/email_test.go @@ -3,6 +3,7 @@ package notify import ( "bufio" "context" + "maps" "net" "net/mail" @@ -151,9 +152,7 @@ func emailCfg(t *testing.T, f *fakeSMTP, extra map[string]any) map[string]any { "from": "artex@example.com", "to": []any{"a@example.com", "b@example.com"}, } - for k, v := range extra { - cfg[k] = v - } + maps.Copy(cfg, extra) return cfg } diff --git a/notify/limits_test.go b/notify/limits_test.go index 19b9697b..f3fb465a 100644 --- a/notify/limits_test.go +++ b/notify/limits_test.go @@ -139,7 +139,7 @@ func TestFeishuUntruncatedItemStaysWithinBodyLimit(t *testing.T) { // 36000 bytes of CJK: also checks that the cut lands on a character boundary. huge.Summary = strings.Repeat("漏洞摘要", 3000) huge.Assets = nil - for i := 0; i < 1500; i++ { + for i := range 1500 { huge.Assets = append(huge.Assets, "host"+itoa(i+1)+".example.com") } diff --git a/notify/mask.go b/notify/mask.go index b9179462..5fcf5028 100644 --- a/notify/mask.go +++ b/notify/mask.go @@ -3,6 +3,7 @@ package notify import ( "encoding/json" "fmt" + "maps" "strings" ) @@ -275,9 +276,7 @@ func isBlankConfigValue(v any) bool { // provided" from "provided empty", but the UI does not use that distinction). func MergeConfig(stored, incoming map[string]any) map[string]any { out := make(map[string]any, len(stored)+len(incoming)) - for k, v := range stored { - out[k] = v - } + maps.Copy(out, stored) for k, v := range incoming { if s, ok := v.(string); ok { if IsMasked(s) { diff --git a/notify/pack_test.go b/notify/pack_test.go index d59303a7..2df96466 100644 --- a/notify/pack_test.go +++ b/notify/pack_test.go @@ -42,7 +42,7 @@ func TestMarkdownBodyPacksWholeItemsWithinByteLimit(t *testing.T) { t.Fatalf("the header should state how many items are not included in this message:\n%s", body[:minInt(400, len(body))]) } // Only the first kept items should be included. - for i := 0; i < kept; i++ { + for i := range kept { if !strings.Contains(body, "vuln"+itoa(i+1)) { t.Fatalf("item %d should be in this message:\n%s", i+1, body) } @@ -121,7 +121,7 @@ func TestTelegramPackingCountsEscapedText(t *testing.T) { if kept <= 0 || kept >= len(m.Items) { t.Fatalf("only a part should fit, got %d", kept) } - for i := 0; i < kept; i++ { + for i := range kept { if !strings.Contains(text, "vuln"+itoa(i+1)+" end") { t.Fatalf("item %d of %d reported as kept is not whole in the message:\n...%s", i+1, kept, text[max(0, len(text)-300):]) } diff --git a/notify/render.go b/notify/render.go index 7d565376..1d3dc851 100644 --- a/notify/render.go +++ b/notify/render.go @@ -128,10 +128,7 @@ func packItemCount(items []Item, maxSize, reserve int, footer string, size func( if maxSize <= 0 { return len(items) } - budget := maxSize - reserve - size(footer) - if budget < 0 { - budget = 0 - } + budget := max(maxSize-reserve-size(footer), 0) used := 0 for i, it := range items { used += size(render(it, i)) diff --git a/notify/webhook_template_test.go b/notify/webhook_template_test.go index e09b109b..eb6ced72 100644 --- a/notify/webhook_template_test.go +++ b/notify/webhook_template_test.go @@ -32,7 +32,7 @@ func TestTemplateContextHasNoMethods(t *testing.T) { typ := reflect.TypeOf(v) if n := typ.NumMethod(); n != 0 { var names []string - for i := 0; i < n; i++ { + for i := range n { names = append(names, typ.Method(i).Name) } t.Fatalf("%s exposes %d methods (%s): text/template can call them, "+ diff --git a/report/quality.go b/report/quality.go index 38ba6ff7..430cd169 100644 --- a/report/quality.go +++ b/report/quality.go @@ -215,7 +215,7 @@ func detailedReportLimit(body, heading string, limit int) string { // closing fence both count, which is exactly what a Markdown renderer pairs up. func unbalancedFence(s string) bool { fences := 0 - for _, line := range strings.Split(s, "\n") { + for line := range strings.SplitSeq(s, "\n") { if strings.HasPrefix(strings.TrimLeft(line, " \t"), "```") { fences++ } diff --git a/report/report_test.go b/report/report_test.go index d22a137e..f89b9a1c 100644 --- a/report/report_test.go +++ b/report/report_test.go @@ -41,7 +41,7 @@ func TestMarkdownCoverageGaps(t *testing.T) { // The report lists at most reportMaxGaps gaps, then a count line. func TestMarkdownCoverageGapsCap(t *testing.T) { var entries []db.CoverageEntry - for i := 0; i < reportMaxGaps+30; i++ { + for range reportMaxGaps + 30 { entries = append(entries, db.CoverageEntry{Surface: "/p", RiskArea: "xss", Outcome: db.OutcomeNeedsFollowUp}) } md := Markdown(Input{Title: "t", Coverage: db.BuildCoverageLedger(entries, nil, db.CoverageCompleteness{})}) diff --git a/sidequestion/context.go b/sidequestion/context.go index ea3f170d..a502c66e 100644 --- a/sidequestion/context.go +++ b/sidequestion/context.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "strings" "unicode/utf8" @@ -214,13 +215,13 @@ func (b *contextBuilder) compactSnapshot(ctx context.Context, base []llm.Message b.progress("compressing_snapshot") groups := messageGroups(base) start, used := len(base), 0 - for i := len(groups) - 1; i >= 0; i-- { - cost := EstimateInputTokens(llm.CompletionRequest{Messages: groups[i]}) + for _, group := range slices.Backward(groups) { + cost := EstimateInputTokens(llm.CompletionRequest{Messages: group}) if used+cost > keepTokens { break } used += cost - start -= len(groups[i]) + start -= len(group) } // A provider-reported overflow must change the actual request even when // our estimate considers all messages small enough to retain. @@ -267,8 +268,8 @@ func (b *contextBuilder) prepare(ctx context.Context, snapshot Snapshot, questio // crowd all primary evidence out. Both count and token limits are enforced. historyLimit := min(16000, max(0, limit/4)) count, cost := 0, 0 - for i := len(b.recent) - 1; i >= 0; i-- { - cost += EstimateInputTokens(llm.CompletionRequest{Messages: exchangeMessages(b.recent[i])}) + for i, v := range slices.Backward(b.recent) { + cost += EstimateInputTokens(llm.CompletionRequest{Messages: exchangeMessages(v)}) if cost > historyLimit { count = i + 1 break @@ -344,7 +345,7 @@ func (s SideQuestionService) Respond(ctx context.Context, snapshot Snapshot, que return } previousSize := 0 - for attempt := 0; attempt < 2; attempt++ { + for attempt := range 2 { var req llm.CompletionRequest req, err = b.prepare(ctx, snapshot, question, options, attempt > 0) if err != nil { diff --git a/sidequestion/sidequestion_test.go b/sidequestion/sidequestion_test.go index b25e1d8c..37294726 100644 --- a/sidequestion/sidequestion_test.go +++ b/sidequestion/sidequestion_test.go @@ -128,7 +128,7 @@ func TestBuildRequestCompactionToolPairingAndBudget(t *testing.T) { s := Snapshot{Request: fixture(), Model: Model{WindowTokens: 100000}} s.Request.Messages = append(s.Request.Messages, llm.BoundaryMessage(llm.BoundaryMeta{Trigger: "auto"}), llm.UserText("compressed summary"), s.Request.Messages[3]) history := []Exchange{} - for i := 0; i < 25; i++ { + for range 25 { history = append(history, Exchange{Question: strings.Repeat("q", 100), Answer: "answer", Status: "completed"}) } r, err := BuildRequest(s, history, "current question") @@ -226,7 +226,7 @@ func TestMainSideConcurrencyAndIndependentCancellation(t *testing.T) { } }() go func() { a, _ := (SideQuestionService{bound}).Answer(sideCtx, fixture(), true, nil); sideDone <- a }() - for i := 0; i < 2; i++ { + for range 2 { select { case <-started: case <-time.After(time.Second):