Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

Fix lint violations: extract helpers, use defer, prealloc slices

Martin Vogelb5aded4eedf6
diff --git a/cmd/codebase-memory-mcp/main.go b/cmd/codebase-memory-mcp/main.go
index 120e14355..874a2c4b1 100644
--- a/cmd/codebase-memory-mcp/main.go
+++ b/cmd/codebase-memory-mcp/main.go
@@ -186,16 +186,18 @@ func printArraySummary(toolName string, arr []any, dbPath string) {
}
fmt.Printf("%d project(s) indexed:\n", len(arr))
for _, item := range arr {
- if m, ok := item.(map[string]any); ok {
- name, _ := m["name"].(string)
- nodes := jsonInt(m["nodes"])
- edges := jsonInt(m["edges"])
- indexedAt, _ := m["indexed_at"].(string)
- rootPath, _ := m["root_path"].(string)
- fmt.Printf(" %-30s %d nodes, %d edges (indexed %s)\n", name, nodes, edges, indexedAt)
- if rootPath != "" {
- fmt.Printf(" %-30s %s\n", "", rootPath)
- }
+ m, ok := item.(map[string]any)
+ if !ok {
+ continue
+ }
+ name, _ := m["name"].(string)
+ nodes := jsonInt(m["nodes"])
+ edges := jsonInt(m["edges"])
+ indexedAt, _ := m["indexed_at"].(string)
+ rootPath, _ := m["root_path"].(string)
+ fmt.Printf(" %-30s %d nodes, %d edges (indexed %s)\n", name, nodes, edges, indexedAt)
+ if rootPath != "" {
+ fmt.Printf(" %-30s %s\n", "", rootPath)
}
}
fmt.Printf("\n db: %s\n", dbPath)
@@ -228,17 +230,19 @@ func printSearchGraphSummary(data map[string]any) {
fmt.Println()
for _, r := range results {
- if m, ok := r.(map[string]any); ok {
- name, _ := m["name"].(string)
- label, _ := m["label"].(string)
- filePath, _ := m["file_path"].(string)
- startLine := jsonInt(m["start_line"])
- fmt.Printf(" [%s] %s", label, name)
- if filePath != "" {
- fmt.Printf(" %s:%d", filePath, startLine)
- }
- fmt.Println()
+ m, ok := r.(map[string]any)
+ if !ok {
+ continue
+ }
+ name, _ := m["name"].(string)
+ label, _ := m["label"].(string)
+ filePath, _ := m["file_path"].(string)
+ startLine := jsonInt(m["start_line"])
+ fmt.Printf(" [%s] %s", label, name)
+ if filePath != "" {
+ fmt.Printf(" %s:%d", filePath, startLine)
}
+ fmt.Println()
}
}
diff --git a/internal/cypher/executor.go b/internal/cypher/executor.go
index 0b9b37f25..3a3d4a93c 100644
--- a/internal/cypher/executor.go
+++ b/internal/cypher/executor.go
@@ -78,6 +78,7 @@ func (e *Executor) executePlan(plan *Plan) (*Result, error) {
return e.projectResults(allBindings, plan.ReturnSpec)
}
+//nolint:gocognit // step dispatch with fusion/push-down is inherently branchy
func (e *Executor) executeStepsForProject(project string, steps []PlanStep) ([]binding, error) {
var bindings []binding
diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go
index b3f2dd515..ec5fd85c8 100644
--- a/internal/pipeline/pipeline.go
+++ b/internal/pipeline/pipeline.go
@@ -569,7 +569,7 @@ func (p *Pipeline) passDefinitions(files []discover.FileInfo) {
slog.Info("pass2.definitions")
// Separate JSON files (processed sequentially, they're fast and few)
- var parseableFiles []discover.FileInfo
+ parseableFiles := make([]discover.FileInfo, 0, len(files))
for _, f := range files {
if f.Language == lang.JSON {
if err := p.processJSONFile(f); err != nil {
@@ -1079,7 +1079,7 @@ func (p *Pipeline) resolveFileCalls(relPath string, cached *cachedAST) []resolve
// processFileCalls is the legacy sequential entry point for incremental re-indexing.
// It resolves calls for a single file and writes edges to DB immediately.
-func (p *Pipeline) processFileCalls(relPath string, cached *cachedAST, spec *lang.LanguageSpec) {
+func (p *Pipeline) processFileCalls(relPath string, cached *cachedAST, _ *lang.LanguageSpec) {
edges := p.resolveFileCalls(relPath, cached)
for _, re := range edges {
callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.CallerQN)
diff --git a/internal/store/nodes.go b/internal/store/nodes.go
index 5cd35e8c3..30d0e48f3 100644
--- a/internal/store/nodes.go
+++ b/internal/store/nodes.go
@@ -233,21 +233,22 @@ func (s *Store) resolveNodeIDs(project string, qns []string, idMap map[string]in
query := fmt.Sprintf("SELECT id, qualified_name FROM nodes WHERE project = ? AND qualified_name IN (%s)",
strings.Join(placeholders, ","))
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return fmt.Errorf("resolve node IDs: %w", err)
- }
- for rows.Next() {
- var id int64
- var qn string
- if err := rows.Scan(&id, &qn); err != nil {
- rows.Close()
- return err
+ if err := func() error {
+ rows, err := s.q.Query(query, args...)
+ if err != nil {
+ return fmt.Errorf("resolve node IDs: %w", err)
}
- idMap[qn] = id
- }
- rows.Close()
- if err := rows.Err(); err != nil {
+ defer rows.Close()
+ for rows.Next() {
+ var id int64
+ var qn string
+ if err := rows.Scan(&id, &qn); err != nil {
+ return err
+ }
+ idMap[qn] = id
+ }
+ return rows.Err()
+ }(); err != nil {
return err
}
}
diff --git a/internal/store/schema.go b/internal/store/schema.go
index a77a8253c..368df7018 100644
--- a/internal/store/schema.go
+++ b/internal/store/schema.go
@@ -31,83 +31,103 @@ type TypeCount struct {
func (s *Store) GetSchema(project string) (*SchemaInfo, error) {
info := &SchemaInfo{}
- // Node label counts
+ var err error
+ if info.NodeLabels, err = s.schemaNodeLabels(project); err != nil {
+ return nil, err
+ }
+ if info.RelationshipTypes, err = s.schemaEdgeTypes(project); err != nil {
+ return nil, err
+ }
+ if info.RelationshipPatterns, err = s.schemaRelPatterns(project); err != nil {
+ return nil, err
+ }
+ if info.SampleFunctionNames, err = s.schemaSampleNames(project, "Function", 30); err != nil {
+ return nil, err
+ }
+ if info.SampleClassNames, err = s.schemaSampleNames(project, "Class", 20); err != nil {
+ return nil, err
+ }
+ if info.SampleQualifiedNames, err = s.schemaSampleQNs(project); err != nil {
+ return nil, err
+ }
+ return info, nil
+}
+
+func (s *Store) schemaNodeLabels(project string) ([]LabelCount, error) {
rows, err := s.q.Query("SELECT label, COUNT(*) as cnt FROM nodes WHERE project=? GROUP BY label ORDER BY cnt DESC", project)
if err != nil {
return nil, fmt.Errorf("schema labels: %w", err)
}
defer rows.Close()
+ var labels []LabelCount
for rows.Next() {
var lc LabelCount
if err := rows.Scan(&lc.Label, &lc.Count); err != nil {
return nil, err
}
- info.NodeLabels = append(info.NodeLabels, lc)
- }
- if err := rows.Err(); err != nil {
- return nil, err
+ labels = append(labels, lc)
}
+ return labels, rows.Err()
+}
- // Edge type counts
- rows2, err := s.q.Query("SELECT type, COUNT(*) as cnt FROM edges WHERE project=? GROUP BY type ORDER BY cnt DESC", project)
+func (s *Store) schemaEdgeTypes(project string) ([]TypeCount, error) {
+ rows, err := s.q.Query("SELECT type, COUNT(*) as cnt FROM edges WHERE project=? GROUP BY type ORDER BY cnt DESC", project)
if err != nil {
return nil, fmt.Errorf("schema edge types: %w", err)
}
- defer rows2.Close()
- for rows2.Next() {
+ defer rows.Close()
+ var types []TypeCount
+ for rows.Next() {
var tc TypeCount
- if err := rows2.Scan(&tc.Type, &tc.Count); err != nil {
+ if err := rows.Scan(&tc.Type, &tc.Count); err != nil {
return nil, err
}
- info.RelationshipTypes = append(info.RelationshipTypes, tc)
- }
- if err := rows2.Err(); err != nil {
- return nil, err
+ types = append(types, tc)
}
+ return types, rows.Err()
+}
- // Relationship patterns: build id→label map, then scan edges and aggregate in Go.
- // This replaces a 3-way JOIN (O(edges × 2 lookups)) with two sequential scans.
+// schemaRelPatterns builds relationship patterns via id→label map + edge scan.
+// This replaces a 3-way JOIN (O(edges × 2 lookups)) with two sequential scans.
+func (s *Store) schemaRelPatterns(project string) ([]string, error) {
idLabel := make(map[int64]string, 4096)
- rows3, err := s.q.Query("SELECT id, label FROM nodes WHERE project=?", project)
+ rows, err := s.q.Query("SELECT id, label FROM nodes WHERE project=?", project)
if err != nil {
return nil, fmt.Errorf("schema id-label: %w", err)
}
- for rows3.Next() {
+ defer rows.Close()
+ for rows.Next() {
var id int64
var label string
- if err := rows3.Scan(&id, &label); err != nil {
- rows3.Close()
+ if err := rows.Scan(&id, &label); err != nil {
return nil, err
}
idLabel[id] = label
}
- rows3.Close()
- if err := rows3.Err(); err != nil {
+ if err := rows.Err(); err != nil {
return nil, err
}
type patternKey struct{ src, rel, tgt string }
patternCounts := make(map[patternKey]int)
- rows3b, err := s.q.Query("SELECT source_id, target_id, type FROM edges WHERE project=?", project)
+ rows2, err := s.q.Query("SELECT source_id, target_id, type FROM edges WHERE project=?", project)
if err != nil {
return nil, fmt.Errorf("schema edge scan: %w", err)
}
- for rows3b.Next() {
+ defer rows2.Close()
+ for rows2.Next() {
var srcID, tgtID int64
var edgeType string
- if err := rows3b.Scan(&srcID, &tgtID, &edgeType); err != nil {
- rows3b.Close()
+ if err := rows2.Scan(&srcID, &tgtID, &edgeType); err != nil {
return nil, err
}
pk := patternKey{src: idLabel[srcID], rel: edgeType, tgt: idLabel[tgtID]}
patternCounts[pk]++
}
- rows3b.Close()
- if err := rows3b.Err(); err != nil {
+ if err := rows2.Err(); err != nil {
return nil, err
}
- // Sort by count descending, take top 25
type patternEntry struct {
key patternKey
cnt int
@@ -120,61 +140,43 @@ func (s *Store) GetSchema(project string) (*SchemaInfo, error) {
if len(entries) > 25 {
entries = entries[:25]
}
+ patterns := make([]string, 0, len(entries))
for _, e := range entries {
- info.RelationshipPatterns = append(info.RelationshipPatterns,
- fmt.Sprintf("(:%s)-[:%s]->(:%s) [%dx]", e.key.src, e.key.rel, e.key.tgt, e.cnt))
- }
-
- // Sample function names
- rows4, err := s.q.Query("SELECT name FROM nodes WHERE project=? AND label='Function' ORDER BY name LIMIT 30", project)
- if err != nil {
- return nil, fmt.Errorf("schema sample funcs: %w", err)
- }
- defer rows4.Close()
- for rows4.Next() {
- var name string
- if err := rows4.Scan(&name); err != nil {
- return nil, err
- }
- info.SampleFunctionNames = append(info.SampleFunctionNames, name)
- }
- if err := rows4.Err(); err != nil {
- return nil, err
+ patterns = append(patterns, fmt.Sprintf("(:%s)-[:%s]->(:%s) [%dx]", e.key.src, e.key.rel, e.key.tgt, e.cnt))
}
+ return patterns, nil
+}
- // Sample class names
- rows5, err := s.q.Query("SELECT name FROM nodes WHERE project=? AND label='Class' ORDER BY name LIMIT 20", project)
+func (s *Store) schemaSampleNames(project, label string, limit int) ([]string, error) {
+ rows, err := s.q.Query("SELECT name FROM nodes WHERE project=? AND label=? ORDER BY name LIMIT ?", project, label, limit)
if err != nil {
- return nil, fmt.Errorf("schema sample classes: %w", err)
+ return nil, fmt.Errorf("schema sample %s: %w", label, err)
}
- defer rows5.Close()
- for rows5.Next() {
+ defer rows.Close()
+ var names []string
+ for rows.Next() {
var name string
- if err := rows5.Scan(&name); err != nil {
+ if err := rows.Scan(&name); err != nil {
return nil, err
}
- info.SampleClassNames = append(info.SampleClassNames, name)
- }
- if err := rows5.Err(); err != nil {
- return nil, err
+ names = append(names, name)
}
+ return names, rows.Err()
+}
- // Sample qualified names
- rows6, err := s.q.Query("SELECT qualified_name FROM nodes WHERE project=? LIMIT 5", project)
+func (s *Store) schemaSampleQNs(project string) ([]string, error) {
+ rows, err := s.q.Query("SELECT qualified_name FROM nodes WHERE project=? LIMIT 5", project)
if err != nil {
return nil, fmt.Errorf("schema sample qns: %w", err)
}
- defer rows6.Close()
- for rows6.Next() {
+ defer rows.Close()
+ var qns []string
+ for rows.Next() {
var qn string
- if err := rows6.Scan(&qn); err != nil {
+ if err := rows.Scan(&qn); err != nil {
return nil, err
}
- info.SampleQualifiedNames = append(info.SampleQualifiedNames, qn)
- }
- if err := rows6.Err(); err != nil {
- return nil, err
+ qns = append(qns, qn)
}
-
- return info, nil
+ return qns, rows.Err()
}
diff --git a/internal/store/search.go b/internal/store/search.go
index 651d5cc6a..c1c2cc4a4 100644
--- a/internal/store/search.go
+++ b/internal/store/search.go
@@ -249,28 +249,15 @@ func (s *Store) batchCountDegrees(nodeIDs []int64, relationship string) (map[int
var inQueryArgs []any
if relationship != "" {
inQuery = fmt.Sprintf("SELECT target_id, COUNT(*) FROM edges WHERE target_id IN (%s) AND type=? GROUP BY target_id", inClause)
- inQueryArgs = append(inArgs, relationship)
+ inQueryArgs = append(append([]any{}, inArgs...), relationship)
} else {
inQuery = fmt.Sprintf("SELECT target_id, COUNT(*) FROM edges WHERE target_id IN (%s) GROUP BY target_id", inClause)
inQueryArgs = inArgs
}
- rows, err := s.q.Query(inQuery, inQueryArgs...)
- if err != nil {
+ if err := s.scanDegrees(inQuery, inQueryArgs, result, true); err != nil {
return nil, fmt.Errorf("batch count in-degree: %w", err)
}
- for rows.Next() {
- var id int64
- var count int
- if err := rows.Scan(&id, &count); err != nil {
- rows.Close()
- return nil, err
- }
- dp := result[id]
- dp.InDegree = count
- result[id] = dp
- }
- rows.Close()
// Count outbound (source_id)
var outQuery string
@@ -283,27 +270,39 @@ func (s *Store) batchCountDegrees(nodeIDs []int64, relationship string) (map[int
outQueryArgs = inArgs
}
- rows, err = s.q.Query(outQuery, outQueryArgs...)
- if err != nil {
+ if err := s.scanDegrees(outQuery, outQueryArgs, result, false); err != nil {
return nil, fmt.Errorf("batch count out-degree: %w", err)
}
- for rows.Next() {
- var id int64
- var count int
- if err := rows.Scan(&id, &count); err != nil {
- rows.Close()
- return nil, err
- }
- dp := result[id]
- dp.OutDegree = count
- result[id] = dp
- }
- rows.Close()
}
return result, nil
}
+// scanDegrees runs a degree-count query and populates the result map.
+// If inbound is true, sets InDegree; otherwise sets OutDegree.
+func (s *Store) scanDegrees(query string, args []any, result map[int64]degreePair, inbound bool) error {
+ rows, err := s.q.Query(query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id int64
+ var count int
+ if err := rows.Scan(&id, &count); err != nil {
+ return err
+ }
+ dp := result[id]
+ if inbound {
+ dp.InDegree = count
+ } else {
+ dp.OutDegree = count
+ }
+ result[id] = dp
+ }
+ return rows.Err()
+}
+
// buildFilteredResults applies degree, direction, and entry-point filters to nodes,
// counts degrees, and loads connected names for each qualifying result.
func (s *Store) buildFilteredResults(nodes []*Node, params *SearchParams) ([]*SearchResult, error) {
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index 58fe95999..8b051c62f 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -360,12 +360,12 @@ func TestExtractLikeHints(t *testing.T) {
{".*Order.*Handler.*", []string{"Order", "Handler"}},
{"handler", []string{"handler"}},
{"^handleRequest$", []string{"handleRequest"}},
- {".*", nil}, // no literal >= 3 chars
- {".*ab.*", nil}, // "ab" is only 2 chars, below threshold
- {".*abc.*", []string{"abc"}}, // exactly 3 chars, included
- {".*foo|.*bar", nil}, // alternation → bail out
+ {".*", nil}, // no literal >= 3 chars
+ {".*ab.*", nil}, // "ab" is only 2 chars, below threshold
+ {".*abc.*", []string{"abc"}}, // exactly 3 chars, included
+ {".*foo|.*bar", nil}, // alternation → bail out
{".*Order.*|.*Handler.*", nil}, // alternation → bail out
- {"\\.", nil}, // escaped dot is ".", only 1 char
+ {"\\.", nil}, // escaped dot is ".", only 1 char
{".*test_.*helper.*", []string{"test_", "helper"}},
}
for _, tt := range tests {
@@ -469,9 +469,9 @@ func TestPragmaSettings(t *testing.T) {
pragma string
want string
}{
- {"synchronous", "0"}, // OFF for in-memory
- {"temp_store", "2"}, // MEMORY
- {"foreign_keys", "1"}, // ON
+ {"synchronous", "0"}, // OFF for in-memory
+ {"temp_store", "2"}, // MEMORY
+ {"foreign_keys", "1"}, // ON
}
for _, tt := range tests {
var val string
@@ -739,10 +739,10 @@ func TestBatchCountDegrees(t *testing.T) {
idB, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
idC, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "C", QualifiedName: "test.C"})
- s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "CALLS"})
- s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idC, Type: "CALLS"})
- s.InsertEdge(&Edge{Project: "test", SourceID: idB, TargetID: idC, Type: "CALLS"})
- s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idC, Type: "USAGE"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idC, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idB, TargetID: idC, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idC, Type: "USAGE"})
// Batch count all types
degrees, err := s.batchCountDegrees([]int64{idA, idB, idC}, "")