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 <noreply@anthropic.com>
This commit is contained in:
sisantaChhatoi 2026-12-03 02:08:01 +05:30
parent 9ae08ed457
commit 757e1da323
18 changed files with 39 additions and 59 deletions

View file

@ -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
}

View file

@ -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)
}

View file

@ -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

View file

@ -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:

View file

@ -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()

View file

@ -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 {

View file

@ -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)

View file

@ -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)

View file

@ -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
}

View file

@ -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")
}

View file

@ -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) {

View file

@ -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):])
}

View file

@ -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))

View file

@ -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, "+

View file

@ -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++
}

View file

@ -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{})})

View file

@ -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 {

View file

@ -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):