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.

Resolve Gin route handler references and cross-file group prefixes

Martin Vogelf55a029ca418
diff --git a/internal/httplink/httplink.go b/internal/httplink/httplink.go
index 5f945e48b..6233fb02f 100644
--- a/internal/httplink/httplink.go
+++ b/internal/httplink/httplink.go
@@ -19,6 +19,7 @@ type RouteHandler struct {
Method string
FunctionName string
QualifiedName string
+ HandlerRef string // resolved handler function reference (e.g. "h.CreateOrder")
}
// HTTPCallSite represents a discovered HTTP call site.
@@ -40,8 +41,9 @@ type HTTPLink struct {
// Linker discovers cross-service HTTP calls and creates HTTP_CALLS edges.
type Linker struct {
- store *store.Store
- project string
+ store *store.Store
+ project string
+ routesByFunc map[string][]int // funcQN → indices into routes slice
}
// New creates a new HTTP Linker.
@@ -60,6 +62,10 @@ var (
// Go gin group: .Group("/prefix")
goGroupRe = regexp.MustCompile(`(\w+)\s*(?::=|=)\s*\w+\.Group\(\s*["']([^"']+)["']`)
+ // Go gin route handler reference: captures the last argument (handler, not middleware)
+ // .POST("/path", h.CreateOrder) or .POST("/path", middleware, h.CreateOrder)
+ goRouteHandlerRe = regexp.MustCompile(`\.(GET|POST|PUT|DELETE|PATCH)\s*\(\s*"[^"]*"\s*(?:,\s*[\w.]+)*,\s*([\w.]+)\s*\)`)
+
// Express.js routes: app.get("/path", router.post("/path"
expressRouteRe = regexp.MustCompile(`\w+\.(get|post|put|delete|patch)\(\s*["'` + "`" + `]([^"'` + "`" + `]+)["'` + "`" + `]`)
@@ -91,12 +97,24 @@ func (l *Linker) Run() ([]HTTPLink, error) {
}
rootPath := proj.RootPath
+ l.routesByFunc = make(map[string][]int)
routes := l.discoverRoutes(rootPath)
slog.Info("httplink.routes", "count", len(routes))
+ // Build routesByFunc index
+ for i, rh := range routes {
+ l.routesByFunc[rh.QualifiedName] = append(l.routesByFunc[rh.QualifiedName], i)
+ }
+
+ // Resolve cross-file group prefixes before inserting Route nodes
+ l.resolveCrossFileGroupPrefixes(routes, rootPath)
+
// Insert Route nodes and HANDLES edges
l.insertRouteNodes(routes)
+ // Create CALLS edges for route handler references (e.g. .POST("/path", h.Handler))
+ l.createRegistrationCallEdges(routes)
+
callSites := l.discoverCallSites(rootPath)
slog.Info("httplink.callsites", "count", len(callSites))
@@ -275,11 +293,19 @@ func extractGoRoutes(f *store.Node, source string) []RouteHandler {
}
}
+ // Capture handler reference (last argument) for CALLS edge creation
+ var handlerRef string
+ hm := goRouteHandlerRe.FindStringSubmatch(line)
+ if hm != nil {
+ handlerRef = hm[2]
+ }
+
routes = append(routes, RouteHandler{
Path: path,
Method: method,
FunctionName: f.Name,
QualifiedName: f.QualifiedName,
+ HandlerRef: handlerRef,
})
}
@@ -958,6 +984,133 @@ func sameService(qn1, qn2 string) bool {
return dir1 == dir2
}
+// crossFileGroupRe matches patterns like: funcName(something.Group("/prefix"))
+// Captures the function name being called and the group prefix.
+var crossFileGroupRe = regexp.MustCompile(`(\w+)\s*\(\s*\w+\.Group\s*\(\s*"([^"]+)"\s*\)`)
+
+// crossFileGroupVarRe matches the variable-based pattern:
+// varName := something.Group("/prefix")
+// ... (next line)
+// funcName(varName)
+var crossFileGroupVarRe = regexp.MustCompile(`(\w+)\s*:?=\s*\w+\.Group\s*\(\s*"([^"]+)"\s*\)`)
+
+// resolveCrossFileGroupPrefixes resolves Group() prefixes from caller functions
+// for routes that were registered without a group prefix within their own function.
+func (l *Linker) resolveCrossFileGroupPrefixes(routes []RouteHandler, rootPath string) {
+ // For each function that registered routes, check if callers pass a Group() result
+ for funcQN, indices := range l.routesByFunc {
+ funcNode, _ := l.store.FindNodeByQN(l.project, funcQN)
+ if funcNode == nil {
+ continue
+ }
+
+ // Find inbound CALLS edges to this function
+ callerEdges, _ := l.store.FindEdgesByTargetAndType(funcNode.ID, "CALLS")
+ if len(callerEdges) == 0 {
+ continue
+ }
+
+ // Check each caller's source for Group() prefix passing
+ for _, edge := range callerEdges {
+ callerNode, _ := l.store.FindNodeByID(edge.SourceID)
+ if callerNode == nil || callerNode.FilePath == "" || callerNode.StartLine <= 0 {
+ continue
+ }
+
+ callerSource := readSourceLines(rootPath, callerNode.FilePath, callerNode.StartLine, callerNode.EndLine)
+ if callerSource == "" {
+ continue
+ }
+
+ // Pattern 1: direct — RegisterRoutes(router.Group("/api"))
+ for _, m := range crossFileGroupRe.FindAllStringSubmatch(callerSource, -1) {
+ calledFunc := m[1]
+ prefix := m[2]
+ if calledFunc == funcNode.Name {
+ l.prependPrefixToRoutes(routes, indices, prefix)
+ break
+ }
+ }
+
+ // Pattern 2: variable-based — v1 := router.Group("/api"); RegisterRoutes(v1)
+ varPrefixes := map[string]string{}
+ for _, m := range crossFileGroupVarRe.FindAllStringSubmatch(callerSource, -1) {
+ varPrefixes[m[1]] = m[2]
+ }
+ if len(varPrefixes) > 0 {
+ // Look for funcName(varName) calls
+ callRe := regexp.MustCompile(regexp.QuoteMeta(funcNode.Name) + `\s*\(\s*(\w+)`)
+ for _, cm := range callRe.FindAllStringSubmatch(callerSource, -1) {
+ argName := cm[1]
+ if prefix, ok := varPrefixes[argName]; ok {
+ l.prependPrefixToRoutes(routes, indices, prefix)
+ break
+ }
+ }
+ }
+ }
+ }
+}
+
+// prependPrefixToRoutes prepends a group prefix to routes at the given indices,
+// but only if the route path doesn't already start with the prefix.
+func (l *Linker) prependPrefixToRoutes(routes []RouteHandler, indices []int, prefix string) {
+ for _, idx := range indices {
+ rh := &routes[idx]
+ normalizedPrefix := strings.TrimRight(prefix, "/")
+ if !strings.HasPrefix(rh.Path, normalizedPrefix) {
+ rh.Path = normalizedPrefix + "/" + strings.TrimLeft(rh.Path, "/")
+ }
+ }
+ slog.Info("httplink.cross_file_prefix", "prefix", prefix, "routes", len(indices))
+}
+
+// createRegistrationCallEdges creates CALLS edges from route-registering functions
+// to the handler functions they reference (e.g. .POST("/path", h.CreateOrder)).
+func (l *Linker) createRegistrationCallEdges(routes []RouteHandler) {
+ count := 0
+ for _, rh := range routes {
+ if rh.HandlerRef == "" {
+ continue
+ }
+
+ // Find the registering function node
+ registrar, _ := l.store.FindNodeByQN(l.project, rh.QualifiedName)
+ if registrar == nil {
+ continue
+ }
+
+ // Resolve handler reference — try method name (strip receiver prefix like "h.")
+ handlerName := rh.HandlerRef
+ if idx := strings.LastIndex(handlerName, "."); idx >= 0 {
+ handlerName = handlerName[idx+1:]
+ }
+
+ // Search for the handler function/method by name
+ handlerNodes, _ := l.store.FindNodesByName(l.project, handlerName)
+ if len(handlerNodes) == 0 {
+ continue
+ }
+
+ // Use the first match (typically unique within a project)
+ handler := handlerNodes[0]
+
+ _, _ = l.store.InsertEdge(&store.Edge{
+ Project: l.project,
+ SourceID: registrar.ID,
+ TargetID: handler.ID,
+ Type: "CALLS",
+ Properties: map[string]any{
+ "via": "route_registration",
+ },
+ })
+ count++
+ }
+ if count > 0 {
+ slog.Info("httplink.registration_edges", "count", count)
+ }
+}
+
// readSourceLines reads specific lines from a file on disk.
func readSourceLines(rootPath, relPath string, startLine, endLine int) string {
absPath := filepath.Join(rootPath, relPath)
diff --git a/internal/httplink/httplink_test.go b/internal/httplink/httplink_test.go
index 07bd1108c..01b173684 100644
--- a/internal/httplink/httplink_test.go
+++ b/internal/httplink/httplink_test.go
@@ -469,6 +469,262 @@ func TestRouteNodesCreated(t *testing.T) {
}
}
+func TestCrossFileGroupPrefix(t *testing.T) {
+ dir, err := os.MkdirTemp("", "httplink-crossfile-*")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(dir)
+
+ // Write a two-file Go project: main.go calls RegisterRoutes(v1.Group("/api"))
+ if err := os.MkdirAll(filepath.Join(dir, "cmd"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Join(dir, "routes"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := os.WriteFile(filepath.Join(dir, "cmd", "main.go"), []byte(`package main
+
+func setup(r *gin.Engine) {
+ RegisterRoutes(r.Group("/api"))
+}
+`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := os.WriteFile(filepath.Join(dir, "routes", "routes.go"), []byte(`package routes
+
+func RegisterRoutes(rg *gin.RouterGroup) {
+ rg.GET("/orders", ListOrders)
+ rg.POST("/orders", CreateOrder)
+}
+`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ project := "testproj"
+ if err := s.UpsertProject(project, dir); err != nil {
+ t.Fatal(err)
+ }
+
+ // Create function nodes that simulate what the pipeline would create
+ setupID, _ := s.UpsertNode(&store.Node{
+ Project: project,
+ Label: "Function",
+ Name: "setup",
+ QualifiedName: "testproj.cmd.main.setup",
+ FilePath: "cmd/main.go",
+ StartLine: 3,
+ EndLine: 5,
+ })
+
+ regID, _ := s.UpsertNode(&store.Node{
+ Project: project,
+ Label: "Function",
+ Name: "RegisterRoutes",
+ QualifiedName: "testproj.routes.routes.RegisterRoutes",
+ FilePath: "routes/routes.go",
+ StartLine: 3,
+ EndLine: 6,
+ })
+
+ // Create CALLS edge: setup -> RegisterRoutes (as pipeline pass3 would)
+ s.InsertEdge(&store.Edge{
+ Project: project,
+ SourceID: setupID,
+ TargetID: regID,
+ Type: "CALLS",
+ })
+
+ linker := New(s, project)
+ _, err = linker.Run()
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+
+ // Verify Route nodes have the cross-file prefix /api prepended
+ routeNodes, _ := s.FindNodesByLabel(project, "Route")
+ if len(routeNodes) != 2 {
+ t.Fatalf("expected 2 Route nodes, got %d", len(routeNodes))
+ }
+
+ foundPaths := map[string]bool{}
+ for _, rn := range routeNodes {
+ path, _ := rn.Properties["path"].(string)
+ foundPaths[path] = true
+ t.Logf("Route: %s (path=%s)", rn.Name, path)
+ }
+
+ if !foundPaths["/api/orders"] {
+ t.Error("expected route path /api/orders with cross-file prefix")
+ }
+}
+
+func TestCrossFileGroupPrefixVariable(t *testing.T) {
+ dir, err := os.MkdirTemp("", "httplink-crossfile-var-*")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(dir)
+
+ if err := os.MkdirAll(filepath.Join(dir, "cmd"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Join(dir, "routes"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ // Variable-based pattern: v1 := r.Group("/api"); RegisterRoutes(v1)
+ if err := os.WriteFile(filepath.Join(dir, "cmd", "main.go"), []byte(`package main
+
+func setup(r *gin.Engine) {
+ v1 := r.Group("/api")
+ RegisterRoutes(v1)
+}
+`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := os.WriteFile(filepath.Join(dir, "routes", "routes.go"), []byte(`package routes
+
+func RegisterRoutes(rg *gin.RouterGroup) {
+ rg.GET("/items", ListItems)
+}
+`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ project := "testproj"
+ s.UpsertProject(project, dir)
+
+ setupID, _ := s.UpsertNode(&store.Node{
+ Project: project, Label: "Function", Name: "setup",
+ QualifiedName: "testproj.cmd.main.setup",
+ FilePath: "cmd/main.go", StartLine: 3, EndLine: 6,
+ })
+
+ regID, _ := s.UpsertNode(&store.Node{
+ Project: project, Label: "Function", Name: "RegisterRoutes",
+ QualifiedName: "testproj.routes.routes.RegisterRoutes",
+ FilePath: "routes/routes.go", StartLine: 3, EndLine: 5,
+ })
+
+ s.InsertEdge(&store.Edge{
+ Project: project, SourceID: setupID, TargetID: regID, Type: "CALLS",
+ })
+
+ linker := New(s, project)
+ linker.Run()
+
+ routeNodes, _ := s.FindNodesByLabel(project, "Route")
+ if len(routeNodes) != 1 {
+ t.Fatalf("expected 1 Route node, got %d", len(routeNodes))
+ }
+
+ path, _ := routeNodes[0].Properties["path"].(string)
+ if path != "/api/items" {
+ t.Errorf("expected /api/items, got %s", path)
+ }
+}
+
+func TestRouteRegistrationCallEdges(t *testing.T) {
+ dir, err := os.MkdirTemp("", "httplink-reg-edges-*")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(dir)
+
+ if err := os.MkdirAll(filepath.Join(dir, "routes"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := os.WriteFile(filepath.Join(dir, "routes", "routes.go"), []byte(`package routes
+
+func RegisterRoutes(rg *gin.RouterGroup) {
+ rg.POST("/orders", h.CreateOrder)
+ rg.GET("/orders/:id", h.GetOrder)
+}
+`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ project := "testproj"
+ s.UpsertProject(project, dir)
+
+ // Create the registering function
+ s.UpsertNode(&store.Node{
+ Project: project, Label: "Function", Name: "RegisterRoutes",
+ QualifiedName: "testproj.routes.routes.RegisterRoutes",
+ FilePath: "routes/routes.go", StartLine: 3, EndLine: 6,
+ })
+
+ // Create handler functions (as pipeline would)
+ s.UpsertNode(&store.Node{
+ Project: project, Label: "Method", Name: "CreateOrder",
+ QualifiedName: "testproj.handlers.handler.CreateOrder",
+ FilePath: "handlers/handler.go", StartLine: 10, EndLine: 30,
+ })
+ s.UpsertNode(&store.Node{
+ Project: project, Label: "Method", Name: "GetOrder",
+ QualifiedName: "testproj.handlers.handler.GetOrder",
+ FilePath: "handlers/handler.go", StartLine: 32, EndLine: 50,
+ })
+
+ linker := New(s, project)
+ linker.Run()
+
+ // Verify CALLS edges from RegisterRoutes to handlers
+ regNode, _ := s.FindNodeByQN(project, "testproj.routes.routes.RegisterRoutes")
+ if regNode == nil {
+ t.Fatal("RegisterRoutes node not found")
+ }
+
+ edges, _ := s.FindEdgesBySourceAndType(regNode.ID, "CALLS")
+ if len(edges) < 2 {
+ t.Errorf("expected at least 2 CALLS edges from RegisterRoutes, got %d", len(edges))
+ }
+
+ // Verify that CreateOrder is a target
+ createNode, _ := s.FindNodeByQN(project, "testproj.handlers.handler.CreateOrder")
+ if createNode == nil {
+ t.Fatal("CreateOrder not found")
+ }
+ foundCreate := false
+ for _, e := range edges {
+ if e.TargetID == createNode.ID {
+ foundCreate = true
+ // Check the via property
+ if via, ok := e.Properties["via"]; ok {
+ if via != "route_registration" {
+ t.Errorf("expected via=route_registration, got %v", via)
+ }
+ }
+ }
+ }
+ if !foundCreate {
+ t.Error("expected CALLS edge from RegisterRoutes to CreateOrder")
+ }
+}
+
func TestLinkerSkipsSameService(t *testing.T) {
s, err := store.OpenMemory()
if err != nil {