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.

Remove all Go code — project is now pure C

Martin Vogel6f0910278b33
diff --git a/.golangci.yml b/.golangci.yml
deleted file mode 100644
index 37916383d..000000000
--- a/.golangci.yml
+++ /dev/null
@@ -1,73 +0,0 @@
-version: "2"
-run:
- go: "1.26"
-linters:
- enable:
- - bodyclose
- - cyclop
- - durationcheck
- - funlen
- - gocognit
- - gocritic
- - gosec
- - makezero
- - misspell
- - nestif
- - nilerr
- - noctx
- - prealloc
- - rowserrcheck
- - sqlclosecheck
- - unconvert
- - unparam
- settings:
- cyclop:
- max-complexity: 25
- errcheck:
- check-type-assertions: true
- funlen:
- lines: 120
- statements: 80
- gocognit:
- min-complexity: 30
- gocritic:
- enabled-tags:
- - diagnostic
- - style
- - performance
- gosec:
- excludes:
- - G115
- - G404
- - G704
- - G705
- - G706
- nestif:
- min-complexity: 6
- exclusions:
- generated: lax
- presets:
- - comments
- - common-false-positives
- - legacy
- - std-error-handling
- paths:
- - vendor
- - third_party$
- - builtin$
- - examples$
- - internal/cbm
-issues:
- max-issues-per-linter: 0
- max-same-issues: 0
-formatters:
- enable:
- - gofmt
- - goimports
- exclusions:
- generated: lax
- paths:
- - vendor
- - third_party$
- - builtin$
- - examples$
diff --git a/cmd/codebase-memory-mcp/assets.go b/cmd/codebase-memory-mcp/assets.go
deleted file mode 100644
index 3b763a56b..000000000
--- a/cmd/codebase-memory-mcp/assets.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package main
-
-import "embed"
-
-//go:embed assets/skills/codebase-memory-exploring/SKILL.md
-var skillExploring string
-
-//go:embed assets/skills/codebase-memory-tracing/SKILL.md
-var skillTracing string
-
-//go:embed assets/skills/codebase-memory-quality/SKILL.md
-var skillQuality string
-
-//go:embed assets/skills/codebase-memory-reference/SKILL.md
-var skillReference string
-
-//go:embed assets/codex-instructions.md
-var codexInstructions string
-
-// skillFiles maps skill directory name to embedded content.
-var skillFiles = map[string]string{
- "codebase-memory-exploring": skillExploring,
- "codebase-memory-tracing": skillTracing,
- "codebase-memory-quality": skillQuality,
- "codebase-memory-reference": skillReference,
-}
-
-// Ensure embed import is used.
-var _ embed.FS
diff --git a/cmd/codebase-memory-mcp/cli_test.go b/cmd/codebase-memory-mcp/cli_test.go
deleted file mode 100644
index 61be593e1..000000000
--- a/cmd/codebase-memory-mcp/cli_test.go
+++ /dev/null
@@ -1,288 +0,0 @@
-package main
-
-import (
- "context"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
- "time"
-)
-
-// testBinPath is set in TestMain — persists across all tests in this package.
-var testBinPath string
-
-func TestMain(m *testing.M) {
- // Build the binary once into a temp dir that persists for the full test run.
- tmpDir, err := os.MkdirTemp("", "cmm-cli-test-*")
- if err != nil {
- panic("create temp dir: " + err.Error())
- }
-
- binName := "codebase-memory-mcp"
- if runtime.GOOS == "windows" {
- binName += ".exe"
- }
- binPath := filepath.Join(tmpDir, binName)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
- cmd := exec.CommandContext(ctx, "go", "build", "-o", binPath, "./")
- cmd.Dir = "."
- if out, err := cmd.CombinedOutput(); err != nil {
- cancel()
- os.RemoveAll(tmpDir)
- os.Stderr.Write(out)
- panic("build test binary: " + err.Error())
- }
- cancel()
- testBinPath = binPath
-
- code := m.Run()
- os.RemoveAll(tmpDir)
- os.Exit(code)
-}
-
-func testCmd(t *testing.T, args ...string) *exec.Cmd {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- t.Cleanup(cancel)
- return exec.CommandContext(ctx, testBinPath, args...)
-}
-
-// testEnvWithHome returns env vars with HOME (and USERPROFILE on Windows) set.
-func testEnvWithHome(home string, extra ...string) []string {
- env := append(os.Environ(), "HOME="+home)
- if runtime.GOOS == "windows" {
- env = append(env, "USERPROFILE="+home)
- // On Windows, DLL lookup uses PATH. Tests that replace PATH with an
- // empty dir break DLL resolution for CGo binaries (MSYS2 libgcc etc).
- // Append the original PATH so DLLs remain findable.
- for i, e := range extra {
- if strings.HasPrefix(e, "PATH=") {
- extra[i] = e + string(os.PathListSeparator) + os.Getenv("PATH")
- }
- }
- }
- return append(env, extra...)
-}
-
-func TestCLI_Version(t *testing.T) {
- out, err := testCmd(t, "--version").CombinedOutput()
- if err != nil {
- t.Fatalf("--version failed: %v\n%s", err, out)
- }
- output := strings.TrimSpace(string(out))
- if !strings.HasPrefix(output, "codebase-memory-mcp") {
- t.Fatalf("unexpected --version output: %q", output)
- }
-}
-
-func TestCLI_InstallDryRun(t *testing.T) {
- home := t.TempDir()
- cmd := testCmd(t, "install", "--dry-run")
- cmd.Env = testEnvWithHome(home, "PATH="+t.TempDir())
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("install --dry-run failed: %v\n%s", err, out)
- }
- output := string(out)
- if !strings.Contains(output, "install") {
- t.Fatalf("expected 'install' in output, got: %s", output)
- }
- // Dry run should not create any files
- skillsDir := filepath.Join(home, ".claude", "skills")
- if _, err := os.Stat(skillsDir); !os.IsNotExist(err) {
- t.Fatal("dry-run should not create skills directory")
- }
-}
-
-func TestCLI_UninstallDryRun(t *testing.T) {
- home := t.TempDir()
- cmd := testCmd(t, "uninstall", "--dry-run")
- cmd.Env = testEnvWithHome(home, "PATH="+t.TempDir())
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("uninstall --dry-run failed: %v\n%s", err, out)
- }
- output := string(out)
- if !strings.Contains(output, "uninstall") {
- t.Fatalf("expected 'uninstall' in output, got: %s", output)
- }
-}
-
-func TestCLI_UpdateDryRun(t *testing.T) {
- cmd := testCmd(t, "update", "--dry-run")
- out, _ := cmd.CombinedOutput()
- output := string(out)
- if !strings.Contains(output, "checking for updates") {
- t.Fatalf("expected 'checking for updates' in output, got: %s", output)
- }
-}
-
-func TestCLI_CliHelp(t *testing.T) {
- cmd := testCmd(t, "cli", "--help")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("cli --help failed: %v\n%s", err, out)
- }
- output := string(out)
- if !strings.Contains(output, "Available tools") {
- t.Fatalf("expected 'Available tools' in cli --help output, got: %s", output)
- }
-}
-
-func TestCLI_InstallAndUninstall(t *testing.T) {
- home := t.TempDir()
- emptyPath := t.TempDir()
-
- // Install
- cmd := testCmd(t, "install")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("install failed: %v\n%s", err, out)
- }
-
- // Verify skills were created
- expectedSkills := []string{
- "codebase-memory-exploring",
- "codebase-memory-tracing",
- "codebase-memory-quality",
- "codebase-memory-reference",
- }
- for _, name := range expectedSkills {
- skillFile := filepath.Join(home, ".claude", "skills", name, "SKILL.md")
- if _, err := os.Stat(skillFile); err != nil {
- t.Fatalf("skill %s not found after install: %v", name, err)
- }
- }
-
- // Uninstall
- cmd = testCmd(t, "uninstall")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath)
- out, err = cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("uninstall failed: %v\n%s", err, out)
- }
-
- // Verify skills were removed
- for _, name := range expectedSkills {
- skillDir := filepath.Join(home, ".claude", "skills", name)
- if _, err := os.Stat(skillDir); !os.IsNotExist(err) {
- t.Fatalf("skill dir %s should be removed after uninstall", name)
- }
- }
-}
-
-func TestCLI_InstallRemovesOldSkill(t *testing.T) {
- home := t.TempDir()
- emptyPath := t.TempDir()
-
- oldDir := filepath.Join(home, ".claude", "skills", "codebase-memory-mcp")
- if err := os.MkdirAll(oldDir, 0o750); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(oldDir, "SKILL.md"), []byte("old"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- cmd := testCmd(t, "install")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("install failed: %v\n%s", err, out)
- }
-
- if _, err := os.Stat(oldDir); !os.IsNotExist(err) {
- t.Fatal("old monolithic skill dir should be removed")
- }
- if _, err := os.Stat(filepath.Join(home, ".claude", "skills", "codebase-memory-exploring", "SKILL.md")); err != nil {
- t.Fatal("new exploring skill should exist")
- }
-}
-
-func TestCLI_InstallIdempotent(t *testing.T) {
- home := t.TempDir()
- emptyPath := t.TempDir()
-
- for i := 0; i < 2; i++ {
- cmd := testCmd(t, "install")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("install round %d failed: %v\n%s", i, err, out)
- }
- }
-
- skillFile := filepath.Join(home, ".claude", "skills", "codebase-memory-exploring", "SKILL.md")
- if _, err := os.Stat(skillFile); err != nil {
- t.Fatal("skill missing after idempotent install")
- }
-}
-
-func TestCLI_InstallForceOverwrites(t *testing.T) {
- home := t.TempDir()
- emptyPath := t.TempDir()
-
- cmd := testCmd(t, "install")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- if out, err := cmd.CombinedOutput(); err != nil {
- t.Fatalf("first install failed: %v\n%s", err, out)
- }
-
- skillFile := filepath.Join(home, ".claude", "skills", "codebase-memory-exploring", "SKILL.md")
- if err := os.WriteFile(skillFile, []byte("custom content"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- cmd = testCmd(t, "install")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("second install failed: %v\n%s", err, out)
- }
- data, _ := os.ReadFile(skillFile)
- if string(data) != "custom content" {
- t.Fatal("install without --force should not overwrite customized skills")
- }
-
- cmd = testCmd(t, "install", "--force")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- out, err = cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("force install failed: %v\n%s", err, out)
- }
- data, _ = os.ReadFile(skillFile)
- if string(data) == "custom content" {
- t.Fatal("install --force should overwrite customized skills")
- }
-}
-
-func TestCLI_InstallPATHAppend(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("shell RC PATH append is Unix-specific")
- }
-
- home := t.TempDir()
- emptyPath := t.TempDir()
-
- cmd := testCmd(t, "install")
- cmd.Env = testEnvWithHome(home, "PATH="+emptyPath, "SHELL=/bin/zsh")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("install failed: %v\n%s", err, out)
- }
-
- zshrc := filepath.Join(home, ".zshrc")
- data, err := os.ReadFile(zshrc)
- if err != nil {
- t.Fatalf("expected .zshrc to be created: %v", err)
- }
- if !strings.Contains(string(data), "export PATH=") {
- t.Fatal("expected PATH export in .zshrc")
- }
- if !strings.Contains(string(data), "codebase-memory-mcp install") {
- t.Fatal("expected install comment in .zshrc")
- }
-}
diff --git a/cmd/codebase-memory-mcp/config.go b/cmd/codebase-memory-mcp/config.go
deleted file mode 100644
index b03f8b981..000000000
--- a/cmd/codebase-memory-mcp/config.go
+++ /dev/null
@@ -1,237 +0,0 @@
-package main
-
-import (
- "fmt"
- "os"
- "sort"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// configDefaults documents all known config keys, their defaults, and descriptions.
-var configDefaults = []struct {
- Key string
- Default string
- Description string
-}{
- {store.ConfigAutoIndex, "false", "Enable background auto-indexing on MCP session start"},
- {store.ConfigAutoIndexLimit, "50000", "Max files for auto-indexing new (never-indexed) projects"},
- {store.ConfigMemLimit, "", "GOMEMLIMIT for the server process (e.g. 2G, 512M). Empty = no limit"},
-}
-
-func runConfig(args []string) int {
- if len(args) == 0 {
- printConfigHelp()
- return 0
- }
-
- switch args[0] {
- case "list", "ls":
- return configList()
- case "get":
- if len(args) < 2 {
- fmt.Fprintln(os.Stderr, "Usage: codebase-memory-mcp config get <key>")
- return 1
- }
- return configGet(args[1])
- case "set":
- if len(args) < 3 {
- fmt.Fprintln(os.Stderr, "Usage: codebase-memory-mcp config set <key> <value>")
- return 1
- }
- return configSet(args[1], args[2])
- case "reset":
- if len(args) < 2 {
- fmt.Fprintln(os.Stderr, "Usage: codebase-memory-mcp config reset <key>")
- return 1
- }
- return configReset(args[1])
- case "--help", "-h", "help":
- printConfigHelp()
- return 0
- default:
- fmt.Fprintf(os.Stderr, "Unknown config command: %s\n", args[0])
- printConfigHelp()
- return 1
- }
-}
-
-func configList() int {
- cfg, err := store.OpenConfig()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- defer cfg.Close()
-
- all, err := cfg.All()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
-
- // Merge with defaults to show all known keys
- merged := make(map[string]string)
- for _, d := range configDefaults {
- merged[d.Key] = d.Default
- }
- for k, v := range all {
- merged[k] = v
- }
-
- keys := make([]string, 0, len(merged))
- for k := range merged {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- fmt.Println("Configuration:")
- for _, k := range keys {
- v := merged[k]
- source := "default"
- if _, ok := all[k]; ok {
- source = "set"
- }
- desc := configDescription(k)
- fmt.Printf(" %-25s = %-10s (%s) %s\n", k, v, source, desc)
- }
- return 0
-}
-
-func configGet(key string) int {
- cfg, err := store.OpenConfig()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- defer cfg.Close()
-
- defVal := configDefaultValue(key)
- val := cfg.Get(key, defVal)
- fmt.Println(val)
- return 0
-}
-
-func configSet(key, value string) int {
- // Validate known keys
- if !isKnownConfigKey(key) {
- fmt.Fprintf(os.Stderr, "Unknown config key: %s\n", key)
- fmt.Fprintf(os.Stderr, "Known keys: %s\n", knownConfigKeys())
- return 1
- }
-
- // Validate mem_limit
- if key == store.ConfigMemLimit && value != "" {
- if _, err := parseByteSize(value); err != nil {
- fmt.Fprintf(os.Stderr, "Invalid value for %s: %q (expected size like 2G, 512M, 4096M)\n", key, value)
- return 1
- }
- }
-
- // Validate bool keys
- if key == store.ConfigAutoIndex {
- v := strings.ToLower(value)
- if v != "true" && v != "false" && v != "on" && v != "off" && v != "1" && v != "0" {
- fmt.Fprintf(os.Stderr, "Invalid value for %s: %q (expected true/false)\n", key, value)
- return 1
- }
- // Normalize
- switch v {
- case "on", "1":
- value = "true"
- case "off", "0":
- value = "false"
- default:
- value = v
- }
- }
-
- cfg, err := store.OpenConfig()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- defer cfg.Close()
-
- if err := cfg.Set(key, value); err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- fmt.Printf("%s = %s\n", key, value)
- return 0
-}
-
-func configReset(key string) int {
- cfg, err := store.OpenConfig()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- defer cfg.Close()
-
- if err := cfg.Delete(key); err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- fmt.Printf("%s reset to default (%s)\n", key, configDefaultValue(key))
- return 0
-}
-
-func printConfigHelp() {
- fmt.Fprintf(os.Stderr, `Usage: codebase-memory-mcp config <command> [args]
-
-Commands:
- list Show all config values (with defaults)
- get <key> Get a config value
- set <key> <val> Set a config value
- reset <key> Reset a key to its default
-
-Config keys:
-`)
- for _, d := range configDefaults {
- fmt.Fprintf(os.Stderr, " %-25s default=%-10s %s\n", d.Key, d.Default, d.Description)
- }
- fmt.Fprintf(os.Stderr, `
-Examples:
- codebase-memory-mcp config set auto_index true Enable auto-indexing on session start
- codebase-memory-mcp config set auto_index false Disable auto-indexing (default)
- codebase-memory-mcp config set auto_index_limit 20000
- codebase-memory-mcp config list Show all settings
-`)
-}
-
-func configDefaultValue(key string) string {
- for _, d := range configDefaults {
- if d.Key == key {
- return d.Default
- }
- }
- return ""
-}
-
-func configDescription(key string) string {
- for _, d := range configDefaults {
- if d.Key == key {
- return d.Description
- }
- }
- return ""
-}
-
-func isKnownConfigKey(key string) bool {
- for _, d := range configDefaults {
- if d.Key == key {
- return true
- }
- }
- return false
-}
-
-func knownConfigKeys() string {
- keys := make([]string, len(configDefaults))
- for i, d := range configDefaults {
- keys[i] = d.Key
- }
- return strings.Join(keys, ", ")
-}
diff --git a/cmd/codebase-memory-mcp/install.go b/cmd/codebase-memory-mcp/install.go
deleted file mode 100644
index 4379e0cc0..000000000
--- a/cmd/codebase-memory-mcp/install.go
+++ /dev/null
@@ -1,849 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strings"
- "time"
-)
-
-// installConfig holds settings for the install/uninstall commands.
-type installConfig struct {
- dryRun bool
- force bool
-}
-
-func runInstall(args []string) int {
- cfg := installConfig{}
- for _, a := range args {
- switch a {
- case "--dry-run":
- cfg.dryRun = true
- case "--force":
- cfg.force = true
- }
- }
-
- binaryPath, err := detectBinaryPath()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
-
- fmt.Printf("\ncodebase-memory-mcp %s — install\n", version)
- fmt.Printf("Binary: %s\n\n", binaryPath)
-
- // PATH check
- ensurePATH(binaryPath, cfg)
-
- // Skills (always installed — no CLI dependency)
- installSkills(cfg)
-
- // Claude Code MCP registration
- if claudePath := findCLI("claude"); claudePath != "" {
- fmt.Printf("[Claude Code] detected (%s)\n", claudePath)
- registerClaudeCodeMCP(binaryPath, claudePath, cfg)
- } else {
- fmt.Println("[Claude Code] not found — skipping MCP registration")
- }
-
- fmt.Println()
-
- // Codex CLI
- if codexPath := findCLI("codex"); codexPath != "" {
- fmt.Printf("[Codex CLI] detected (%s)\n", codexPath)
- installCodex(binaryPath, codexPath, cfg)
- } else {
- fmt.Println("[Codex CLI] not found — skipping")
- }
-
- fmt.Println()
-
- // Cursor
- installEditorMCP(binaryPath, cursorConfigPath(), "Cursor", cfg)
-
- // Windsurf
- installEditorMCP(binaryPath, windsurfConfigPath(), "Windsurf", cfg)
-
- // Gemini CLI (same mcpServers format as Cursor/Windsurf)
- installEditorMCP(binaryPath, geminiConfigPath(), "Gemini CLI", cfg)
-
- // VS Code Copilot (uses "servers" key with "type" field)
- installVSCodeMCP(binaryPath, vscodeConfigPath(), cfg)
-
- // Zed (uses "context_servers" key with "source" field)
- installZedMCP(binaryPath, zedConfigPath(), cfg)
-
- fmt.Println("\nDone. Restart your editor/CLI to activate.")
- return 0
-}
-
-func runUninstall(args []string) int {
- cfg := installConfig{}
- for _, a := range args {
- if a == "--dry-run" {
- cfg.dryRun = true
- }
- }
-
- fmt.Printf("\ncodebase-memory-mcp %s — uninstall\n\n", version)
-
- // Remove Claude Code skills
- removeClaudeSkills(cfg)
-
- // Claude Code MCP deregistration
- if claudePath := findCLI("claude"); claudePath != "" {
- fmt.Printf("[Claude Code] detected (%s)\n", claudePath)
- deregisterMCP(claudePath, "claude", cfg)
- }
-
- // Codex CLI MCP deregistration + instructions
- if codexPath := findCLI("codex"); codexPath != "" {
- fmt.Printf("[Codex CLI] detected (%s)\n", codexPath)
- removeCodexMCP(cfg)
- removeCodexInstructions(cfg)
- }
-
- // Cursor
- removeEditorMCP(cursorConfigPath(), "Cursor", cfg)
-
- // Windsurf
- removeEditorMCP(windsurfConfigPath(), "Windsurf", cfg)
-
- // Gemini CLI
- removeEditorMCP(geminiConfigPath(), "Gemini CLI", cfg)
-
- // VS Code Copilot
- removeVSCodeMCP(vscodeConfigPath(), cfg)
-
- // Zed
- removeZedMCP(zedConfigPath(), cfg)
-
- fmt.Println("\nDone. Binary and databases were NOT removed.")
- return 0
-}
-
-// detectBinaryPath resolves the current binary's real path.
-func detectBinaryPath() (string, error) {
- exe, err := os.Executable()
- if err != nil {
- return "", fmt.Errorf("detect binary: %w", err)
- }
- resolved, err := filepath.EvalSymlinks(exe)
- if err != nil {
- return "", fmt.Errorf("resolve symlink: %w", err)
- }
- return resolved, nil
-}
-
-// ensurePATH checks if the binary directory is on PATH and offers to add it.
-func ensurePATH(binaryPath string, cfg installConfig) {
- binDir := filepath.Dir(binaryPath)
- pathDirs := filepath.SplitList(os.Getenv("PATH"))
-
- fmt.Println("[PATH]")
- for _, d := range pathDirs {
- if d == binDir {
- fmt.Printf(" ✓ %s already on PATH\n", binDir)
- return
- }
- }
-
- fmt.Printf(" ⚠ %s is not on PATH\n", binDir)
-
- if runtime.GOOS == "windows" {
- fmt.Printf(" → Add %s to your PATH environment variable manually\n", binDir)
- return
- }
-
- rcFile := detectShellRC()
- if rcFile == "" {
- fmt.Printf(" → Add to your shell profile: export PATH=\"%s:$PATH\"\n", binDir)
- return
- }
-
- line := fmt.Sprintf("export PATH=\"%s:$PATH\"", binDir)
-
- // Check if already present in rc file
- if content, err := os.ReadFile(rcFile); err == nil {
- if strings.Contains(string(content), line) {
- fmt.Printf(" ✓ Already in %s (restart terminal to activate)\n", rcFile)
- return
- }
- }
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would append to %s: %s\n", rcFile, line)
- } else {
- f, err := os.OpenFile(rcFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
- if err != nil {
- fmt.Printf(" ⚠ Could not write to %s: %v\n", rcFile, err)
- fmt.Printf(" → Add manually: %s\n", line)
- return
- }
- defer f.Close()
- fmt.Fprintf(f, "\n# Added by codebase-memory-mcp install\n%s\n", line)
- fmt.Printf(" ✓ Added to %s: %s\n", rcFile, line)
- fmt.Printf(" → Run: source %s (or restart terminal)\n", rcFile)
- }
-}
-
-// detectShellRC returns the appropriate shell rc file path.
-func detectShellRC() string {
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
-
- shell := os.Getenv("SHELL")
- switch {
- case strings.HasSuffix(shell, "/zsh"):
- return filepath.Join(home, ".zshrc")
- case strings.HasSuffix(shell, "/bash"):
- // Prefer .bashrc, fall back to .bash_profile
- bashrc := filepath.Join(home, ".bashrc")
- if _, err := os.Stat(bashrc); err == nil {
- return bashrc
- }
- return filepath.Join(home, ".bash_profile")
- case strings.HasSuffix(shell, "/fish"):
- return filepath.Join(home, ".config", "fish", "config.fish")
- default:
- // Fall back to .profile
- return filepath.Join(home, ".profile")
- }
-}
-
-// installSkills writes the 4 skill files to ~/.claude/skills/ and removes old monolithic skill.
-func installSkills(cfg installConfig) {
- home, err := os.UserHomeDir()
- if err != nil {
- fmt.Printf(" ⚠ Cannot determine home directory: %v\n", err)
- return
- }
-
- fmt.Println("[Skills]")
-
- // Remove old monolithic skill if it exists
- oldSkillDir := filepath.Join(home, ".claude", "skills", "codebase-memory-mcp")
- if info, err := os.Stat(oldSkillDir); err == nil && info.IsDir() {
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove old skill: %s\n", oldSkillDir)
- } else {
- if err := os.RemoveAll(oldSkillDir); err == nil {
- fmt.Printf(" ✓ Removed old monolithic skill: %s\n", oldSkillDir)
- }
- }
- }
-
- // Write 4 skill files
- for name, content := range skillFiles {
- skillDir := filepath.Join(home, ".claude", "skills", name)
- skillFile := filepath.Join(skillDir, "SKILL.md")
-
- if !cfg.force {
- if _, err := os.Stat(skillFile); err == nil {
- fmt.Printf(" ✓ Skill exists (skip): %s\n", skillFile)
- continue
- }
- }
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would write: %s\n", skillFile)
- continue
- }
-
- if err := os.MkdirAll(skillDir, 0o750); err != nil {
- fmt.Printf(" ⚠ mkdir %s: %v\n", skillDir, err)
- continue
- }
- if err := os.WriteFile(skillFile, []byte(content), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", skillFile, err)
- continue
- }
- fmt.Printf(" ✓ Skill: %s\n", skillFile)
- }
-}
-
-// registerClaudeCodeMCP registers the MCP server with Claude Code CLI.
-func registerClaudeCodeMCP(binaryPath, claudePath string, cfg installConfig) {
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would run: %s mcp remove -s user codebase-memory-mcp\n", claudePath)
- fmt.Printf(" [dry-run] Would run: %s mcp add --scope user codebase-memory-mcp -- %s\n", claudePath, binaryPath)
- } else {
- // Silent remove (may fail if not registered — that's fine)
- _ = execCLI(claudePath, "mcp", "remove", "-s", "user", "codebase-memory-mcp")
- if err := execCLI(claudePath, "mcp", "add", "--scope", "user", "codebase-memory-mcp", "--", binaryPath); err != nil {
- fmt.Printf(" ⚠ MCP registration failed: %v\n", err)
- } else {
- fmt.Println(" ✓ MCP server registered (scope: user)")
- }
- }
-}
-
-// installCodex installs MCP registration and instructions for Codex CLI.
-func installCodex(binaryPath, _ string, cfg installConfig) {
- home, err := os.UserHomeDir()
- if err != nil {
- fmt.Printf(" ⚠ Cannot determine home directory: %v\n", err)
- return
- }
-
- // Register MCP server via config.toml
- configFile := filepath.Join(home, ".codex", "config.toml")
- mcpSection := fmt.Sprintf("\n[mcp_servers.codebase-memory-mcp]\ncommand = %q\n", binaryPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would add MCP server to: %s\n", configFile)
- } else {
- if err := os.MkdirAll(filepath.Dir(configFile), 0o750); err != nil {
- fmt.Printf(" ⚠ mkdir %s: %v\n", filepath.Dir(configFile), err)
- } else if err := upsertCodexMCP(configFile, mcpSection, binaryPath); err != nil {
- fmt.Printf(" ⚠ MCP registration failed: %v\n", err)
- } else {
- fmt.Printf(" ✓ MCP server registered: %s\n", configFile)
- }
- }
-
- // Write instructions file
- instrDir := filepath.Join(home, ".codex", "instructions")
- instrFile := filepath.Join(instrDir, "codebase-memory-mcp.md")
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would write: %s\n", instrFile)
- } else {
- if err := os.MkdirAll(instrDir, 0o750); err != nil {
- fmt.Printf(" ⚠ mkdir %s: %v\n", instrDir, err)
- return
- }
- if err := os.WriteFile(instrFile, []byte(codexInstructions), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", instrFile, err)
- return
- }
- fmt.Printf(" ✓ Instructions: %s\n", instrFile)
- }
-}
-
-// upsertCodexMCP adds or updates the codebase-memory-mcp section in config.toml.
-func upsertCodexMCP(configFile, mcpSection, binaryPath string) error {
- content, err := os.ReadFile(configFile)
- if err != nil && !os.IsNotExist(err) {
- return err
- }
-
- text := string(content)
-
- // If section already exists, replace the command line
- const sectionHeader = "[mcp_servers.codebase-memory-mcp]"
- if idx := strings.Index(text, sectionHeader); idx >= 0 {
- // Find the end of this section (next [ or EOF)
- rest := text[idx+len(sectionHeader):]
- endIdx := strings.Index(rest, "\n[")
- if endIdx < 0 {
- endIdx = len(rest)
- }
- newSection := fmt.Sprintf("%s\ncommand = %q\n", sectionHeader, binaryPath)
- text = text[:idx] + newSection + rest[endIdx:]
- } else {
- // Append new section
- text += mcpSection
- }
-
- return os.WriteFile(configFile, []byte(text), 0o600)
-}
-
-// removeClaudeSkills removes all 4 skill directories.
-func removeClaudeSkills(cfg installConfig) {
- home, err := os.UserHomeDir()
- if err != nil {
- return
- }
-
- fmt.Println("[Skills]")
- for name := range skillFiles {
- skillDir := filepath.Join(home, ".claude", "skills", name)
- if _, err := os.Stat(skillDir); os.IsNotExist(err) {
- continue
- }
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove: %s\n", skillDir)
- } else {
- if err := os.RemoveAll(skillDir); err != nil {
- fmt.Printf(" ⚠ remove %s: %v\n", skillDir, err)
- } else {
- fmt.Printf(" ✓ Removed: %s\n", skillDir)
- }
- }
- }
-}
-
-// deregisterMCP removes the MCP server registration from a CLI.
-func deregisterMCP(cliPath, cliName string, cfg installConfig) {
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would run: %s mcp remove -s user codebase-memory-mcp\n", cliPath)
- } else {
- if err := execCLI(cliPath, "mcp", "remove", "-s", "user", "codebase-memory-mcp"); err != nil {
- fmt.Printf(" ⚠ %s MCP deregistration: %v\n", cliName, err)
- } else {
- fmt.Printf(" ✓ %s MCP server deregistered\n", cliName)
- }
- }
-}
-
-// removeCodexMCP removes the codebase-memory-mcp section from Codex config.toml.
-func removeCodexMCP(cfg installConfig) {
- home, err := os.UserHomeDir()
- if err != nil {
- return
- }
- configFile := filepath.Join(home, ".codex", "config.toml")
- content, err := os.ReadFile(configFile)
- if err != nil {
- return
- }
-
- text := string(content)
- const sectionHeader = "[mcp_servers.codebase-memory-mcp]"
- idx := strings.Index(text, sectionHeader)
- if idx < 0 {
- return
- }
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove MCP section from: %s\n", configFile)
- return
- }
-
- // Find end of section (next [ or EOF)
- rest := text[idx+len(sectionHeader):]
- endIdx := strings.Index(rest, "\n[")
- if endIdx < 0 {
- text = strings.TrimRight(text[:idx], "\n")
- } else {
- text = text[:idx] + rest[endIdx+1:]
- }
-
- if err := os.WriteFile(configFile, []byte(text), 0o600); err != nil {
- fmt.Printf(" ⚠ update %s: %v\n", configFile, err)
- } else {
- fmt.Printf(" ✓ Removed MCP section from: %s\n", configFile)
- }
-}
-
-// removeCodexInstructions removes the Codex instructions file.
-func removeCodexInstructions(cfg installConfig) {
- home, err := os.UserHomeDir()
- if err != nil {
- return
- }
- instrFile := filepath.Join(home, ".codex", "instructions", "codebase-memory-mcp.md")
- if _, err := os.Stat(instrFile); os.IsNotExist(err) {
- return
- }
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove: %s\n", instrFile)
- } else {
- if err := os.Remove(instrFile); err != nil {
- fmt.Printf(" ⚠ remove %s: %v\n", instrFile, err)
- } else {
- fmt.Printf(" ✓ Removed: %s\n", instrFile)
- }
- }
-}
-
-// findCLI locates a CLI binary by name.
-func findCLI(name string) string {
- if p, err := exec.LookPath(name); err == nil {
- return p
- }
-
- // Check common install locations
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
-
- candidates := []string{
- "/usr/local/bin/" + name,
- filepath.Join(home, ".npm", "bin", name),
- filepath.Join(home, ".local", "bin", name),
- filepath.Join(home, ".cargo", "bin", name),
- }
- if runtime.GOOS == "darwin" {
- candidates = append(candidates, "/opt/homebrew/bin/"+name)
- }
-
- for _, c := range candidates {
- if _, err := os.Stat(c); err == nil {
- return c
- }
- }
- return ""
-}
-
-// execCLI runs a CLI command and returns any error.
-func execCLI(path string, args ...string) error {
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- cmd := exec.CommandContext(ctx, path, args...)
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- return cmd.Run()
-}
-
-// --- Editor MCP config (Cursor, Windsurf) ---
-
-const mcpServerKey = "codebase-memory-mcp"
-
-// cursorConfigPath returns the Cursor MCP config path.
-func cursorConfigPath() string {
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
- return filepath.Join(home, ".cursor", "mcp.json")
-}
-
-// windsurfConfigPath returns the Windsurf MCP config path.
-func windsurfConfigPath() string {
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
- return filepath.Join(home, ".codeium", "windsurf", "mcp_config.json")
-}
-
-// installEditorMCP upserts our MCP server entry in an editor's JSON config file.
-func installEditorMCP(binaryPath, configPath, editorName string, cfg installConfig) {
- if configPath == "" {
- return
- }
-
- fmt.Printf("[%s] MCP config: %s\n", editorName, configPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would upsert %s in %s\n", mcpServerKey, configPath)
- return
- }
-
- // Read existing config or start fresh
- root := make(map[string]any)
- if data, err := os.ReadFile(configPath); err == nil {
- if jsonErr := json.Unmarshal(data, &root); jsonErr != nil {
- // File exists but is invalid JSON — back up and overwrite
- fmt.Printf(" ⚠ Invalid JSON in %s, overwriting\n", configPath)
- root = make(map[string]any)
- }
- }
-
- // Ensure mcpServers map exists
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- servers = make(map[string]any)
- }
-
- // Upsert our server entry
- servers[mcpServerKey] = map[string]any{
- "command": binaryPath,
- }
- root["mcpServers"] = servers
-
- // Write back
- if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
- fmt.Printf(" ⚠ mkdir %s: %v\n", filepath.Dir(configPath), err)
- return
- }
- out, err := json.MarshalIndent(root, "", " ")
- if err != nil {
- fmt.Printf(" ⚠ marshal JSON: %v\n", err)
- return
- }
- if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
- return
- }
- fmt.Printf(" ✓ MCP server registered in %s\n", configPath)
-}
-
-// removeEditorMCP removes our MCP server entry from an editor's JSON config file.
-func removeEditorMCP(configPath, editorName string, cfg installConfig) {
- if configPath == "" {
- return
- }
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- return // no config file, nothing to remove
- }
-
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- return
- }
-
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- return
- }
- if _, exists := servers[mcpServerKey]; !exists {
- return
- }
-
- fmt.Printf("[%s] MCP config: %s\n", editorName, configPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove %s from %s\n", mcpServerKey, configPath)
- return
- }
-
- delete(servers, mcpServerKey)
- root["mcpServers"] = servers
-
- out, err := json.MarshalIndent(root, "", " ")
- if err != nil {
- fmt.Printf(" ⚠ marshal JSON: %v\n", err)
- return
- }
- if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
- return
- }
- fmt.Printf(" ✓ Removed %s from %s\n", mcpServerKey, configPath)
-}
-
-// --- Gemini CLI ---
-
-// geminiConfigPath returns the Gemini CLI settings path.
-func geminiConfigPath() string {
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
- return filepath.Join(home, ".gemini", "settings.json")
-}
-
-// --- VS Code Copilot ---
-
-// vscodeConfigPath returns the VS Code user-level MCP config path.
-func vscodeConfigPath() string {
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
- switch runtime.GOOS {
- case "darwin":
- return filepath.Join(home, "Library", "Application Support", "Code", "User", "mcp.json")
- case "linux":
- return filepath.Join(home, ".config", "Code", "User", "mcp.json")
- case "windows":
- if appData := os.Getenv("APPDATA"); appData != "" {
- return filepath.Join(appData, "Code", "User", "mcp.json")
- }
- }
- return ""
-}
-
-// installVSCodeMCP upserts our MCP server in VS Code's mcp.json (uses "servers" key).
-func installVSCodeMCP(binaryPath, configPath string, cfg installConfig) {
- if configPath == "" {
- return
- }
-
- fmt.Printf("[VS Code] MCP config: %s\n", configPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would upsert %s in %s\n", mcpServerKey, configPath)
- return
- }
-
- root := make(map[string]any)
- if data, err := os.ReadFile(configPath); err == nil {
- if jsonErr := json.Unmarshal(data, &root); jsonErr != nil {
- fmt.Printf(" ⚠ Invalid JSON in %s, overwriting\n", configPath)
- root = make(map[string]any)
- }
- }
-
- servers, ok := root["servers"].(map[string]any)
- if !ok {
- servers = make(map[string]any)
- }
-
- servers[mcpServerKey] = map[string]any{
- "type": "stdio",
- "command": binaryPath,
- }
- root["servers"] = servers
-
- if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
- fmt.Printf(" ⚠ mkdir %s: %v\n", filepath.Dir(configPath), err)
- return
- }
- out, err := json.MarshalIndent(root, "", " ")
- if err != nil {
- fmt.Printf(" ⚠ marshal JSON: %v\n", err)
- return
- }
- if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
- return
- }
- fmt.Printf(" ✓ MCP server registered in %s\n", configPath)
-}
-
-// removeVSCodeMCP removes our MCP server from VS Code's mcp.json.
-func removeVSCodeMCP(configPath string, cfg installConfig) {
- if configPath == "" {
- return
- }
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- return
- }
-
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- return
- }
-
- servers, ok := root["servers"].(map[string]any)
- if !ok {
- return
- }
- if _, exists := servers[mcpServerKey]; !exists {
- return
- }
-
- fmt.Printf("[VS Code] MCP config: %s\n", configPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove %s from %s\n", mcpServerKey, configPath)
- return
- }
-
- delete(servers, mcpServerKey)
- root["servers"] = servers
-
- out, err := json.MarshalIndent(root, "", " ")
- if err != nil {
- fmt.Printf(" ⚠ marshal JSON: %v\n", err)
- return
- }
- if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
- return
- }
- fmt.Printf(" ✓ Removed %s from %s\n", mcpServerKey, configPath)
-}
-
-// --- Zed ---
-
-// zedConfigPath returns the Zed settings path.
-func zedConfigPath() string {
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
- }
- return filepath.Join(home, ".config", "zed", "settings.json")
-}
-
-// installZedMCP upserts our MCP server in Zed's settings.json under "context_servers".
-func installZedMCP(binaryPath, configPath string, cfg installConfig) {
- if configPath == "" {
- return
- }
-
- fmt.Printf("[Zed] MCP config: %s\n", configPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would upsert %s in %s\n", mcpServerKey, configPath)
- return
- }
-
- root := make(map[string]any)
- if data, err := os.ReadFile(configPath); err == nil {
- if jsonErr := json.Unmarshal(data, &root); jsonErr != nil {
- // Zed settings.json likely has other settings — don't overwrite on bad JSON
- fmt.Printf(" ⚠ Invalid JSON in %s, skipping\n", configPath)
- return
- }
- }
-
- servers, ok := root["context_servers"].(map[string]any)
- if !ok {
- servers = make(map[string]any)
- }
-
- servers[mcpServerKey] = map[string]any{
- "source": "custom",
- "command": binaryPath,
- }
- root["context_servers"] = servers
-
- if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
- fmt.Printf(" ⚠ mkdir %s: %v\n", filepath.Dir(configPath), err)
- return
- }
- out, err := json.MarshalIndent(root, "", " ")
- if err != nil {
- fmt.Printf(" ⚠ marshal JSON: %v\n", err)
- return
- }
- if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
- return
- }
- fmt.Printf(" ✓ MCP server registered in %s\n", configPath)
-}
-
-// removeZedMCP removes our MCP server from Zed's settings.json.
-func removeZedMCP(configPath string, cfg installConfig) {
- if configPath == "" {
- return
- }
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- return
- }
-
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- return
- }
-
- servers, ok := root["context_servers"].(map[string]any)
- if !ok {
- return
- }
- if _, exists := servers[mcpServerKey]; !exists {
- return
- }
-
- fmt.Printf("[Zed] MCP config: %s\n", configPath)
-
- if cfg.dryRun {
- fmt.Printf(" [dry-run] Would remove %s from %s\n", mcpServerKey, configPath)
- return
- }
-
- delete(servers, mcpServerKey)
- root["context_servers"] = servers
-
- out, err := json.MarshalIndent(root, "", " ")
- if err != nil {
- fmt.Printf(" ⚠ marshal JSON: %v\n", err)
- return
- }
- if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
- fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
- return
- }
- fmt.Printf(" ✓ Removed %s from %s\n", mcpServerKey, configPath)
-}
diff --git a/cmd/codebase-memory-mcp/install_test.go b/cmd/codebase-memory-mcp/install_test.go
deleted file mode 100644
index 0053c54bc..000000000
--- a/cmd/codebase-memory-mcp/install_test.go
+++ /dev/null
@@ -1,664 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
-)
-
-// setTestHome overrides the home directory for both Unix (HOME) and Windows (USERPROFILE).
-func setTestHome(t *testing.T, home string) {
- t.Helper()
- t.Setenv("HOME", home)
- if runtime.GOOS == "windows" {
- t.Setenv("USERPROFILE", home)
- }
-}
-
-// exeSuffix returns ".exe" on Windows, empty string otherwise.
-func exeSuffix() string {
- if runtime.GOOS == "windows" {
- return ".exe"
- }
- return ""
-}
-
-func TestInstallSkillCreation(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- claudeSkillsDir := filepath.Join(home, ".claude", "skills")
-
- for name, content := range skillFiles {
- skillDir := filepath.Join(claudeSkillsDir, name)
- skillFile := filepath.Join(skillDir, "SKILL.md")
-
- if err := os.MkdirAll(skillDir, 0o750); err != nil {
- t.Fatalf("mkdir %s: %v", skillDir, err)
- }
- if err := os.WriteFile(skillFile, []byte(content), 0o600); err != nil {
- t.Fatalf("write %s: %v", skillFile, err)
- }
- }
-
- expectedSkills := []string{
- "codebase-memory-exploring",
- "codebase-memory-tracing",
- "codebase-memory-quality",
- "codebase-memory-reference",
- }
-
- for _, name := range expectedSkills {
- skillFile := filepath.Join(claudeSkillsDir, name, "SKILL.md")
- data, err := os.ReadFile(skillFile)
- if err != nil {
- t.Fatalf("read %s: %v", skillFile, err)
- }
- if len(data) == 0 {
- t.Fatalf("skill file %s is empty", skillFile)
- }
- normalized := strings.ReplaceAll(string(data), "\r\n", "\n")
- if !strings.HasPrefix(normalized, "---\n") {
- t.Fatalf("skill %s missing YAML frontmatter", name)
- }
- if !strings.Contains(string(data), "name: "+name) {
- t.Fatalf("skill %s doesn't contain correct name field", name)
- }
- }
-}
-
-func TestInstallIdempotent(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- claudeSkillsDir := filepath.Join(home, ".claude", "skills")
-
- for round := 0; round < 2; round++ {
- for name, content := range skillFiles {
- skillDir := filepath.Join(claudeSkillsDir, name)
- skillFile := filepath.Join(skillDir, "SKILL.md")
- if err := os.MkdirAll(skillDir, 0o750); err != nil {
- t.Fatalf("round %d: mkdir %s: %v", round, skillDir, err)
- }
- if err := os.WriteFile(skillFile, []byte(content), 0o600); err != nil {
- t.Fatalf("round %d: write %s: %v", round, skillFile, err)
- }
- }
- }
-
- for name := range skillFiles {
- skillFile := filepath.Join(claudeSkillsDir, name, "SKILL.md")
- if _, err := os.Stat(skillFile); err != nil {
- t.Fatalf("skill %s missing after idempotent install: %v", name, err)
- }
- }
-}
-
-func TestUninstallRemovesSkills(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- claudeSkillsDir := filepath.Join(home, ".claude", "skills")
-
- for name, content := range skillFiles {
- skillDir := filepath.Join(claudeSkillsDir, name)
- if err := os.MkdirAll(skillDir, 0o750); err != nil {
- t.Fatalf("mkdir: %v", err)
- }
- if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(content), 0o600); err != nil {
- t.Fatalf("write: %v", err)
- }
- }
-
- for name := range skillFiles {
- skillDir := filepath.Join(claudeSkillsDir, name)
- if err := os.RemoveAll(skillDir); err != nil {
- t.Fatalf("remove %s: %v", skillDir, err)
- }
- }
-
- for name := range skillFiles {
- skillDir := filepath.Join(claudeSkillsDir, name)
- if _, err := os.Stat(skillDir); !os.IsNotExist(err) {
- t.Fatalf("skill dir %s should not exist after uninstall", skillDir)
- }
- }
-}
-
-func TestFindCLI_NotFound(t *testing.T) {
- t.Setenv("PATH", t.TempDir())
- setTestHome(t, t.TempDir())
-
- result := findCLI("nonexistent-binary-xyz")
- if result != "" {
- t.Fatalf("expected empty string for nonexistent CLI, got %q", result)
- }
-}
-
-func TestFindCLI_FoundOnPATH(t *testing.T) {
- tmpDir := t.TempDir()
-
- fakeBin := filepath.Join(tmpDir, "fakecli"+exeSuffix())
- if err := os.WriteFile(fakeBin, []byte("#!/bin/sh\n"), 0o600); err != nil {
- t.Fatalf("write fake binary: %v", err)
- }
- if err := os.Chmod(fakeBin, 0o500); err != nil {
- t.Fatalf("chmod fake binary: %v", err)
- }
-
- t.Setenv("PATH", tmpDir)
- result := findCLI("fakecli" + exeSuffix())
- if result == "" {
- t.Fatal("expected to find fakecli on PATH")
- }
-}
-
-func TestFindCLI_FallbackPaths(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("fallback paths use Unix-specific locations")
- }
-
- home := t.TempDir()
- setTestHome(t, home)
- t.Setenv("PATH", t.TempDir())
-
- localBin := filepath.Join(home, ".local", "bin")
- if err := os.MkdirAll(localBin, 0o750); err != nil {
- t.Fatal(err)
- }
- fakeBin := filepath.Join(localBin, "testcli")
- if err := os.WriteFile(fakeBin, []byte("#!/bin/sh\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.Chmod(fakeBin, 0o500); err != nil {
- t.Fatal(err)
- }
-
- result := findCLI("testcli")
- if result != fakeBin {
- t.Fatalf("expected %q, got %q", fakeBin, result)
- }
-}
-
-func TestDetectBinaryPath(t *testing.T) {
- path, err := detectBinaryPath()
- if err != nil {
- t.Fatalf("detectBinaryPath error: %v", err)
- }
- if path == "" {
- t.Fatal("detectBinaryPath returned empty string")
- }
- if !filepath.IsAbs(path) {
- t.Fatalf("expected absolute path, got %q", path)
- }
-}
-
-func TestDetectShellRC(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("shell RC detection is Unix-specific")
- }
-
- home := t.TempDir()
- setTestHome(t, home)
-
- tests := []struct {
- shell string
- expected string
- }{
- {"/bin/zsh", ".zshrc"},
- {"/bin/bash", ".bash_profile"},
- {"/usr/bin/fish", filepath.Join(".config", "fish", "config.fish")},
- {"/bin/sh", ".profile"},
- }
-
- for _, tt := range tests {
- t.Run(tt.shell, func(t *testing.T) {
- t.Setenv("SHELL", tt.shell)
- rc := detectShellRC()
- if rc == "" {
- t.Fatal("detectShellRC returned empty")
- }
- if !strings.HasSuffix(rc, tt.expected) {
- t.Fatalf("for shell %q: got %q, want suffix %q", tt.shell, rc, tt.expected)
- }
- })
- }
-}
-
-func TestDetectShellRC_BashWithBashrc(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("shell RC detection is Unix-specific")
- }
-
- home := t.TempDir()
- setTestHome(t, home)
- t.Setenv("SHELL", "/bin/bash")
-
- bashrc := filepath.Join(home, ".bashrc")
- if err := os.WriteFile(bashrc, []byte("# test\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- rc := detectShellRC()
- if rc != bashrc {
- t.Fatalf("expected %q, got %q", bashrc, rc)
- }
-}
-
-func TestDryRun(t *testing.T) {
- cfg := installConfig{}
- for _, a := range []string{"--dry-run", "--force"} {
- switch a {
- case "--dry-run":
- cfg.dryRun = true
- case "--force":
- cfg.force = true
- }
- }
- if !cfg.dryRun || !cfg.force {
- t.Fatal("expected both dryRun and force to be true")
- }
-}
-
-func TestCodexInstructionsCreation(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- instrDir := filepath.Join(home, ".codex", "instructions")
- instrFile := filepath.Join(instrDir, "codebase-memory-mcp.md")
-
- if err := os.MkdirAll(instrDir, 0o750); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(instrFile, []byte(codexInstructions), 0o600); err != nil {
- t.Fatal(err)
- }
-
- data, err := os.ReadFile(instrFile)
- if err != nil {
- t.Fatalf("read instructions: %v", err)
- }
- if !strings.Contains(string(data), "Codebase Knowledge Graph") {
- t.Fatal("instructions file missing expected content")
- }
- if !strings.Contains(string(data), "trace_call_path") {
- t.Fatal("instructions file missing trace_call_path reference")
- }
-}
-
-func TestSkillFilesContent(t *testing.T) {
- if len(skillFiles) != 4 {
- t.Fatalf("expected 4 skill files, got %d", len(skillFiles))
- }
-
- expectations := map[string][]string{
- "codebase-memory-exploring": {"explore the codebase", "search_graph", "get_graph_schema"},
- "codebase-memory-tracing": {"who calls this function", "trace_call_path", "direction", "risk_labels", "detect_changes"},
- "codebase-memory-quality": {"find dead code", "max_degree=0", "exclude_entry_points"},
- "codebase-memory-reference": {"edge types", "query_graph", "Cypher", "detect_changes", "14 total"},
- }
-
- for name, expectedPhrases := range expectations {
- content, ok := skillFiles[name]
- if !ok {
- t.Fatalf("missing skill: %s", name)
- }
- for _, phrase := range expectedPhrases {
- if !strings.Contains(strings.ToLower(content), strings.ToLower(phrase)) {
- t.Errorf("skill %q missing phrase %q", name, phrase)
- }
- }
- }
-}
-
-func TestEditorMCPInstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".cursor", "mcp.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- // First install — creates file from scratch
- installEditorMCP(binaryPath, configPath, "Cursor", installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("unmarshal config: %v", err)
- }
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- t.Fatal("expected mcpServers key")
- }
- entry, ok := servers["codebase-memory-mcp"].(map[string]any)
- if !ok {
- t.Fatal("expected codebase-memory-mcp entry")
- }
- if cmd, _ := entry["command"].(string); cmd != binaryPath {
- t.Fatalf("expected command %q, got %q", binaryPath, cmd)
- }
-}
-
-func TestEditorMCPInstallIdempotent(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".cursor", "mcp.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- // Install twice — second install should preserve valid JSON
- installEditorMCP(binaryPath, configPath, "Cursor", installConfig{})
- installEditorMCP(binaryPath, configPath, "Cursor", installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("double install produced invalid JSON: %v", err)
- }
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- t.Fatal("mcpServers is not a map")
- }
- if len(servers) != 1 {
- t.Fatalf("expected 1 server, got %d", len(servers))
- }
-}
-
-func TestEditorMCPPreservesOtherServers(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".cursor", "mcp.json")
- if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
- t.Fatal(err)
- }
-
- // Write config with an existing server
- existing := `{"mcpServers": {"other-server": {"command": "/usr/bin/other"}}}`
- if err := os.WriteFile(configPath, []byte(existing), 0o600); err != nil {
- t.Fatal(err)
- }
-
- installEditorMCP("/usr/local/bin/codebase-memory-mcp", configPath, "Cursor", installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatal(err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- t.Fatal("mcpServers is not a map")
- }
- if len(servers) != 2 {
- t.Fatalf("expected 2 servers, got %d", len(servers))
- }
- if _, ok = servers["other-server"]; !ok {
- t.Fatal("other-server was removed")
- }
- if _, ok := servers["codebase-memory-mcp"]; !ok {
- t.Fatal("codebase-memory-mcp not added")
- }
-}
-
-func TestEditorMCPUninstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".cursor", "mcp.json")
-
- // Install then uninstall
- installEditorMCP("/usr/local/bin/codebase-memory-mcp", configPath, "Cursor", installConfig{})
- removeEditorMCP(configPath, "Cursor", installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatal(err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- t.Fatal("mcpServers is not a map")
- }
- if _, exists := servers["codebase-memory-mcp"]; exists {
- t.Fatal("codebase-memory-mcp should be removed after uninstall")
- }
-}
-
-func TestGeminiConfigPath(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- path := geminiConfigPath()
- if path == "" {
- t.Fatal("geminiConfigPath returned empty")
- }
- if !strings.HasSuffix(path, filepath.Join(".gemini", "settings.json")) {
- t.Fatalf("unexpected path: %s", path)
- }
-}
-
-func TestGeminiMCPInstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".gemini", "settings.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- // Gemini uses same mcpServers format as Cursor
- installEditorMCP(binaryPath, configPath, "Gemini CLI", installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("unmarshal: %v", err)
- }
- servers, ok := root["mcpServers"].(map[string]any)
- if !ok {
- t.Fatal("expected mcpServers key")
- }
- if _, ok := servers["codebase-memory-mcp"]; !ok {
- t.Fatal("codebase-memory-mcp not registered")
- }
-}
-
-func TestVSCodeMCPInstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, "Code", "User", "mcp.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- installVSCodeMCP(binaryPath, configPath, installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("unmarshal: %v", err)
- }
- servers, ok := root["servers"].(map[string]any)
- if !ok {
- t.Fatal("expected servers key")
- }
- entry, ok := servers["codebase-memory-mcp"].(map[string]any)
- if !ok {
- t.Fatal("codebase-memory-mcp not registered")
- }
- if entry["type"] != "stdio" {
- t.Fatalf("expected type=stdio, got %v", entry["type"])
- }
- if entry["command"] != binaryPath {
- t.Fatalf("expected command=%s, got %v", binaryPath, entry["command"])
- }
-}
-
-func TestVSCodeMCPUninstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, "Code", "User", "mcp.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- installVSCodeMCP(binaryPath, configPath, installConfig{})
- removeVSCodeMCP(configPath, installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatal(err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- servers, ok := root["servers"].(map[string]any)
- if !ok {
- t.Fatal("servers key missing")
- }
- if _, exists := servers["codebase-memory-mcp"]; exists {
- t.Fatal("codebase-memory-mcp should be removed")
- }
-}
-
-func TestZedMCPInstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".config", "zed", "settings.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- installZedMCP(binaryPath, configPath, installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatalf("read config: %v", err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatalf("unmarshal: %v", err)
- }
- servers, ok := root["context_servers"].(map[string]any)
- if !ok {
- t.Fatal("expected context_servers key")
- }
- entry, ok := servers["codebase-memory-mcp"].(map[string]any)
- if !ok {
- t.Fatal("codebase-memory-mcp not registered")
- }
- if entry["source"] != "custom" {
- t.Fatalf("expected source=custom, got %v", entry["source"])
- }
- if entry["command"] != binaryPath {
- t.Fatalf("expected command=%s, got %v", binaryPath, entry["command"])
- }
-}
-
-func TestZedMCPPreservesSettings(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".config", "zed", "settings.json")
- if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
- t.Fatal(err)
- }
-
- // Pre-existing Zed settings
- existing := `{"theme": "One Dark", "vim_mode": true}`
- if err := os.WriteFile(configPath, []byte(existing), 0o600); err != nil {
- t.Fatal(err)
- }
-
- installZedMCP("/usr/local/bin/codebase-memory-mcp", configPath, installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatal(err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- // Original settings preserved
- if root["theme"] != "One Dark" {
- t.Fatal("theme setting was lost")
- }
- if root["vim_mode"] != true {
- t.Fatal("vim_mode setting was lost")
- }
- // MCP server added
- servers, ok := root["context_servers"].(map[string]any)
- if !ok {
- t.Fatal("context_servers missing")
- }
- if _, ok := servers["codebase-memory-mcp"]; !ok {
- t.Fatal("codebase-memory-mcp not added")
- }
-}
-
-func TestZedMCPUninstall(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- configPath := filepath.Join(home, ".config", "zed", "settings.json")
- binaryPath := "/usr/local/bin/codebase-memory-mcp"
-
- installZedMCP(binaryPath, configPath, installConfig{})
- removeZedMCP(configPath, installConfig{})
-
- data, err := os.ReadFile(configPath)
- if err != nil {
- t.Fatal(err)
- }
- var root map[string]any
- if err := json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- servers, ok := root["context_servers"].(map[string]any)
- if !ok {
- t.Fatal("context_servers key missing")
- }
- if _, exists := servers["codebase-memory-mcp"]; exists {
- t.Fatal("codebase-memory-mcp should be removed")
- }
-}
-
-func TestRemoveOldMonolithicSkill(t *testing.T) {
- home := t.TempDir()
- setTestHome(t, home)
-
- oldDir := filepath.Join(home, ".claude", "skills", "codebase-memory-mcp")
- if err := os.MkdirAll(oldDir, 0o750); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(oldDir, "SKILL.md"), []byte("old skill"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- if err := os.RemoveAll(oldDir); err != nil {
- t.Fatalf("remove old skill: %v", err)
- }
-
- if _, err := os.Stat(oldDir); !os.IsNotExist(err) {
- t.Fatal("old monolithic skill dir should be removed")
- }
-}
diff --git a/cmd/codebase-memory-mcp/main.go b/cmd/codebase-memory-mcp/main.go
deleted file mode 100644
index 8040aefc9..000000000
--- a/cmd/codebase-memory-mcp/main.go
+++ /dev/null
@@ -1,810 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "os"
- "os/signal"
- "path/filepath"
- "runtime/debug"
- "runtime/pprof"
- "strings"
- "syscall"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/DeusData/codebase-memory-mcp/internal/tools"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-var version = "dev"
-
-func main() {
- tools.SetVersion(version)
-
- // Parse global flags before subcommand dispatch.
- var pprofOnExit string
- var remaining []string
- for _, a := range os.Args[1:] {
- switch {
- case strings.HasPrefix(a, "--pprof-on-exit="):
- pprofOnExit = strings.TrimPrefix(a, "--pprof-on-exit=")
- default:
- remaining = append(remaining, a)
- }
- }
-
- if len(remaining) > 0 {
- switch remaining[0] {
- case "--version":
- fmt.Println("codebase-memory-mcp", version)
- os.Exit(0)
- case "--help", "-h", "help":
- printTopLevelHelp()
- os.Exit(0)
- case "install":
- os.Exit(runInstall(remaining[1:]))
- case "uninstall":
- os.Exit(runUninstall(remaining[1:]))
- case "update":
- os.Exit(runUpdate(remaining[1:]))
- case "config":
- os.Exit(runConfig(remaining[1:]))
- case "cli":
- if len(remaining) >= 2 {
- os.Exit(runCLI(remaining[1:]))
- }
- }
- }
-
- router, err := store.NewRouter()
- if err != nil {
- log.Fatalf("store router err=%v", err)
- }
-
- cfg, err := store.OpenConfig()
- if err != nil {
- log.Fatalf("config err=%v", err)
- }
-
- // Apply GOMEMLIMIT from config (e.g. "4G", "512M").
- // If not configured, auto-detect: 25% of system memory, clamped to [2GB, 8GB].
- // Prevents OOM kills while avoiding unnecessary GC pressure.
- if memLimitStr := cfg.Get(store.ConfigMemLimit, ""); memLimitStr != "" {
- if limit, parseErr := parseByteSize(memLimitStr); parseErr != nil {
- log.Printf("config: invalid mem_limit %q: %v", memLimitStr, parseErr)
- } else {
- debug.SetMemoryLimit(limit)
- }
- } else {
- debug.SetMemoryLimit(autoMemLimit())
- }
-
- srv := tools.NewServer(router, tools.WithConfig(cfg))
-
- ctx, cancel := context.WithCancel(context.Background())
-
- // Handle SIGTERM/SIGINT for graceful shutdown.
- // Without this, process kill leaves TSParsers, SQLite handles,
- // and in-flight C allocations unreleased.
- sigCh := make(chan os.Signal, 1)
- signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
- go func() {
- sig := <-sigCh
- log.Printf("signal=%v shutdown", sig)
- cancel()
- }()
-
- router.StartEvictor(ctx)
- srv.StartWatcher(ctx)
-
- runErr := srv.MCPServer().Run(ctx, &mcp.StdioTransport{})
- cancel()
- signal.Stop(sigCh)
-
- cbm.Shutdown()
-
- if pprofOnExit != "" {
- writeHeapProfile(pprofOnExit)
- }
-
- cfg.Close()
- router.CloseAll()
- if runErr != nil {
- log.Fatalf("server err=%v", runErr)
- }
-}
-
-// writeHeapProfile writes a heap profile to the given path.
-func writeHeapProfile(path string) {
- f, err := os.Create(path) //nolint:gosec // path from trusted internal pprof flag
- if err != nil {
- log.Printf("pprof: create %s err=%v", path, err)
- return
- }
- defer f.Close()
- if err := pprof.WriteHeapProfile(f); err != nil {
- log.Printf("pprof: write err=%v", err)
- return
- }
- log.Printf("pprof: heap profile written to %s", path)
-}
-
-// parseByteSize parses human-readable byte sizes like "1G", "512M", "2048K".
-func parseByteSize(s string) (int64, error) {
- s = strings.TrimSpace(s)
- if s == "" {
- return 0, fmt.Errorf("empty size")
- }
- multiplier := int64(1)
- switch {
- case strings.HasSuffix(s, "G") || strings.HasSuffix(s, "g"):
- multiplier = 1 << 30
- s = s[:len(s)-1]
- case strings.HasSuffix(s, "M") || strings.HasSuffix(s, "m"):
- multiplier = 1 << 20
- s = s[:len(s)-1]
- case strings.HasSuffix(s, "K") || strings.HasSuffix(s, "k"):
- multiplier = 1 << 10
- s = s[:len(s)-1]
- }
- var n int64
- if _, err := fmt.Sscanf(s, "%d", &n); err != nil {
- return 0, fmt.Errorf("parse %q: %w", s, err)
- }
- if n <= 0 {
- return 0, fmt.Errorf("size must be positive")
- }
- return n * multiplier, nil
-}
-
-func printTopLevelHelp() {
- fmt.Fprintf(os.Stderr, "codebase-memory-mcp %s — Code knowledge graph MCP server\n\n", version)
- printHelpUsage()
- printHelpTools()
- printHelpIgnoring()
- printHelpCLI()
-}
-
-func printHelpUsage() {
- fmt.Fprint(os.Stderr, `Usage:
- codebase-memory-mcp Start the MCP server (stdio transport)
- codebase-memory-mcp cli <tool> [json_args] Invoke a tool directly from the shell
- codebase-memory-mcp install [--dry-run] Auto-detect and configure MCP clients
- codebase-memory-mcp uninstall Remove MCP registrations and skills
- codebase-memory-mcp update Self-update to the latest release
- codebase-memory-mcp config <command> Manage server configuration
- codebase-memory-mcp --version Print version and exit
- codebase-memory-mcp --help Show this help
-
-Supported MCP clients:
- Claude Code, Codex CLI, Cursor, Windsurf, Gemini CLI, VS Code, Zed
-
-Language support (64 languages):
- Tree-sitter AST parsing for: Python, Go, JavaScript, TypeScript, TSX, Rust,
- Java, C++, C#, C, PHP, Lua, Scala, Kotlin, Ruby, Bash, Zig, Elixir, Haskell,
- OCaml, Objective-C, Swift, Dart, Perl, Groovy, Erlang, R, Clojure, F#, Julia,
- Vim Script, Nix, Common Lisp, Elm, Fortran, CUDA, COBOL, Verilog, Emacs Lisp,
- MATLAB, Lean 4, FORM, Magma, Wolfram, HTML, CSS, SCSS, YAML, TOML, HCL, SQL,
- Dockerfile, JSON, XML, Markdown, Makefile, CMake, Protobuf, GraphQL, Vue,
- Svelte, Meson, GLSL, INI
-
- Go uses a tree-sitter + LSP hybrid methodology for enhanced cross-file type
- resolution and call graph accuracy. This hybrid approach is coming soon for
- additional languages.
-
-`)
-}
-
-func printHelpTools() {
- fmt.Fprint(os.Stderr, `MCP tools (14):
-
- index_repository — Index a repo into the knowledge graph
- {"repo_path": "/path/to/repo", "mode": "full|fast"}
- repo_path: absolute path (optional — defaults to session project root)
- mode: "full" (default) or "fast" (skips generated code, test fixtures, large files)
-
- index_status — Check indexing status of a project
- {"project": "my-project"}
- Returns: status (not_indexed/indexing/ready), node/edge counts, timestamps
-
- list_projects — List all indexed projects
- {} (no parameters)
- Returns: project names, node/edge counts, indexed_at timestamps
-
- delete_project — Remove a project and all its graph data (irreversible)
- {"project_name": "my-project"}
-
- search_graph — Structural search with filters
- {"label": "Function", "name_pattern": ".*Handler.*", "project": "my-api"}
- label: Function, Class, Module, Method, Interface, Enum, Type, File, Route
- name_pattern: regex on short name (case-insensitive by default)
- qn_pattern: regex on qualified name (e.g. ".*services\\.order\\..*")
- file_pattern: glob for file path (e.g. "*.py", "**/services/**")
- relationship: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, IMPLEMENTS, etc.
- direction: inbound, outbound, any (for degree filtering)
- min_degree/max_degree: edge count filters (e.g. max_degree=0 for dead code)
- exclude_entry_points: true to skip route handlers/main() in dead code search
- limit (default 10), offset: pagination (response includes has_more, total)
- case_sensitive: false (default) — set true for exact case matching
-
- search_code — Grep-like text search within indexed files
- {"pattern": "TODO|FIXME", "regex": true, "file_pattern": "*.go"}
- pattern: search text (case-insensitive by default)
- regex: true to enable regex (default false)
- file_pattern: glob to filter files
- max_results (default 10), offset: pagination
-
- trace_call_path — BFS call chain traversal
- {"function_name": "ProcessOrder", "direction": "both", "depth": 3}
- function_name: exact name (use search_graph first to find it)
- direction: outbound (what it calls), inbound (what calls it), both
- depth: 1-5 (default 3)
- risk_labels: true to add CRITICAL/HIGH/MEDIUM/LOW classification
- min_confidence: 0.0-1.0 threshold for CALLS edges
-
- detect_changes — Git diff → affected symbols + blast radius
- {"scope": "unstaged", "depth": 3}
- scope: unstaged (default), staged, all, branch
- base_branch: for scope=branch (default "main")
- depth: 1-5 (default 3) for blast radius tracing
-
- query_graph — Execute Cypher-like graph queries (read-only)
- {"query": "MATCH (f:Function)-[:CALLS]->(g) WHERE f.name = 'main' RETURN g.name LIMIT 20"}
- Supports: MATCH, WHERE (=, <>, >, <, =~, CONTAINS, STARTS WITH), RETURN,
- ORDER BY, LIMIT, COUNT, DISTINCT, variable-length paths (*1..3)
- max_rows: default 200, max 10000
-
- get_graph_schema — Node/edge counts and relationship patterns
- {"project": "my-project"} (project optional)
- Returns: node label counts, edge type counts, sample names
-
- get_code_snippet — Read source code by qualified name
- {"qualified_name": "myproject.cmd.server.main.HandleRequest"}
- Accepts: full QN, partial suffix ("main.HandleRequest"), or short name
- auto_resolve: true to auto-pick from <=2 ambiguous candidates
- include_neighbors: true to get caller/callee name lists
-
- get_architecture — Codebase overview
- {"aspects": ["all"], "project": "my-project"}
- aspects: languages, packages, entry_points, routes, hotspots, boundaries,
- services, layers, clusters, file_tree, adr (or "all" for everything)
-
- manage_adr — CRUD for Architecture Decision Records
- {"mode": "store", "content": "## PURPOSE\n..."}
- mode: get, store, update, delete
- content: full ADR text (for store)
- sections: {"PATTERNS": "..."} (for update — unmentioned sections preserved)
- Fixed sections: PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY
-
- ingest_traces — Ingest OpenTelemetry JSON traces
- {"traces": [...]} (OTLP format spans)
- Validates HTTP_CALLS edges with runtime data, boosts confidence
-
-`)
-}
-
-func printHelpIgnoring() {
- fmt.Fprint(os.Stderr, `File ignoring (layered):
- 1. Hardcoded patterns Always-on: .git, node_modules, dist, __pycache__, etc.
- 2. .gitignore Full gitignore hierarchy (nested files + .git/info/exclude)
- 3. .cbmignore Repo-root file with gitignore-style patterns, stacks on top
- 4. .cgrignore Legacy glob patterns (backward-compatible)
-
- Symlinked files and directories are always skipped.
-
-`)
-}
-
-func printHelpCLI() {
- fmt.Fprint(os.Stderr, `CLI invocation:
- codebase-memory-mcp cli <tool_name> '<json_args>'
- codebase-memory-mcp cli --raw <tool_name> '<json_args>' (full JSON output)
-
- Tools are called with a single JSON object as the argument. All parameters
- are passed as JSON keys. String values must be quoted. Arrays use JSON syntax.
-
-CLI examples:
- codebase-memory-mcp cli index_repository '{"repo_path": "/path/to/repo"}'
- codebase-memory-mcp cli search_graph '{"name_pattern": ".*Handler.*", "label": "Function"}'
- codebase-memory-mcp cli trace_call_path '{"function_name": "main", "direction": "outbound"}'
- codebase-memory-mcp cli search_code '{"pattern": "TODO", "file_pattern": "*.go"}'
- codebase-memory-mcp cli get_architecture '{"aspects": ["languages", "packages"]}'
- codebase-memory-mcp cli --raw list_projects | jq .
- codebase-memory-mcp cli get_code_snippet '{"qualified_name": "HandleRequest"}'
-
-Configuration:
- codebase-memory-mcp config list Show all settings
- codebase-memory-mcp config set <key> <val> Set a config value
- codebase-memory-mcp config get <key> Get a config value
-
-Data storage:
- ~/.cache/codebase-memory-mcp/ SQLite databases (WAL mode, persists across restarts)
-
-For more information: https://github.com/DeusData/codebase-memory-mcp
-`)
-}
-
-func runCLI(args []string) int {
- // Parse flags
- raw := false
- var positional []string
- for _, a := range args {
- switch a {
- case "--raw":
- raw = true
- default:
- positional = append(positional, a)
- }
- }
-
- router, err := store.NewRouter()
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
- defer router.CloseAll()
-
- if len(positional) == 0 || positional[0] == "--help" || positional[0] == "-h" {
- srv := tools.NewServer(router)
- fmt.Fprintf(os.Stderr, "Usage: codebase-memory-mcp cli [--raw] <tool_name> [json_args]\n\n")
- fmt.Fprintf(os.Stderr, "Flags:\n --raw Print full JSON output (default: human-friendly summary)\n\n")
- fmt.Fprintf(os.Stderr, "Available tools:\n %s\n", strings.Join(srv.ToolNames(), "\n "))
- return 0
- }
-
- toolName := positional[0]
-
- srv := tools.NewServer(router)
-
- // In CLI mode, try to set session root from cwd
- if cwd, cwdErr := os.Getwd(); cwdErr == nil {
- srv.SetSessionRoot(cwd)
- }
-
- var argsJSON json.RawMessage
- if len(positional) > 1 {
- argsJSON = json.RawMessage(positional[1])
- }
-
- result, err := srv.CallTool(context.Background(), toolName, argsJSON)
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
-
- if result.IsError {
- for _, c := range result.Content {
- if tc, ok := c.(*mcp.TextContent); ok {
- fmt.Fprintf(os.Stderr, "error: %s\n", tc.Text)
- }
- }
- return 1
- }
-
- // Extract the text content
- var text string
- for _, c := range result.Content {
- if tc, ok := c.(*mcp.TextContent); ok {
- text = tc.Text
- break
- }
- }
-
- if raw {
- printRawJSON(text)
- return 0
- }
-
- // Summary mode (default): print a human-friendly summary
- dbPath := filepath.Join(router.Dir(), srv.SessionProject()+".db")
- printSummary(toolName, text, dbPath)
- return 0
-}
-
-// printRawJSON pretty-prints JSON text to stdout.
-func printRawJSON(text string) {
- var buf json.RawMessage
- if json.Unmarshal([]byte(text), &buf) == nil {
- if pretty, err := json.MarshalIndent(buf, "", " "); err == nil {
- fmt.Println(string(pretty))
- return
- }
- }
- fmt.Println(text)
-}
-
-// printSummary prints a human-friendly summary of the tool result.
-func printSummary(toolName, text, dbPath string) {
- var data map[string]any
- if err := json.Unmarshal([]byte(text), &data); err != nil {
- // Not a JSON object — might be an array (e.g. list_projects)
- var arr []any
- if err2 := json.Unmarshal([]byte(text), &arr); err2 == nil {
- printArraySummary(toolName, arr, dbPath)
- return
- }
- // Plain text — print as-is
- fmt.Println(text)
- return
- }
-
- switch toolName {
- case "index_repository":
- printIndexSummary(data, dbPath)
- case "search_graph":
- printSearchGraphSummary(data)
- case "search_code":
- printSearchCodeSummary(data)
- case "trace_call_path":
- printTraceSummary(data)
- case "query_graph":
- printQuerySummary(data)
- case "get_graph_schema":
- printSchemaSummary(data)
- case "get_code_snippet":
- printSnippetSummary(data)
- case "delete_project":
- printDeleteSummary(data)
- case "read_file":
- printReadFileSummary(data)
- case "list_directory":
- printListDirSummary(data)
- case "ingest_traces":
- printIngestSummary(data, dbPath)
- case "index_status":
- printIndexStatusSummary(data)
- case "detect_changes":
- printDetectChangesSummary(data)
- default:
- // Fallback: pretty-print the JSON
- printRawJSON(text)
- }
-}
-
-func printArraySummary(toolName string, arr []any, dbPath string) {
- switch toolName {
- case "list_projects":
- if len(arr) == 0 {
- fmt.Println("No projects indexed.")
- fmt.Printf(" db_dir: %s\n", filepath.Dir(dbPath))
- return
- }
- fmt.Printf("%d project(s) indexed:\n", len(arr))
- for _, item := range arr {
- 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)
- isSession, _ := m["is_session_project"].(bool)
- sessionMarker := ""
- if isSession {
- sessionMarker = " *"
- }
- fmt.Printf(" %-30s %d nodes, %d edges (indexed %s)%s\n", name, nodes, edges, indexedAt, sessionMarker)
- if rootPath != "" {
- fmt.Printf(" %-30s %s\n", "", rootPath)
- }
- if dbp, ok := m["db_path"].(string); ok {
- fmt.Printf(" %-30s %s\n", "", dbp)
- }
- }
- default:
- fmt.Printf("%d result(s)\n", len(arr))
- printRawJSON(mustJSON(arr))
- }
-}
-
-func printIndexSummary(data map[string]any, dbPath string) {
- project, _ := data["project"].(string)
- nodes := jsonInt(data["nodes"])
- edges := jsonInt(data["edges"])
- indexedAt, _ := data["indexed_at"].(string)
- fmt.Printf("Indexed %q: %d nodes, %d edges\n", project, nodes, edges)
- fmt.Printf(" indexed_at: %s\n", indexedAt)
- fmt.Printf(" db: %s\n", dbPath)
-}
-
-func printSearchGraphSummary(data map[string]any) {
- total := jsonInt(data["total"])
- hasMore, _ := data["has_more"].(bool)
- results, _ := data["results"].([]any)
- shown := len(results)
-
- fmt.Printf("%d result(s) found", total)
- if hasMore {
- fmt.Printf(" (showing %d, has_more=true)", shown)
- }
- fmt.Println()
-
- for _, r := range results {
- 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()
- }
-}
-
-func printSearchCodeSummary(data map[string]any) {
- total := jsonInt(data["total"])
- hasMore, _ := data["has_more"].(bool)
- matches, _ := data["matches"].([]any)
- shown := len(matches)
-
- fmt.Printf("%d match(es) found", total)
- if hasMore {
- fmt.Printf(" (showing %d, has_more=true)", shown)
- }
- fmt.Println()
-
- for _, m := range matches {
- if entry, ok := m.(map[string]any); ok {
- file, _ := entry["file"].(string)
- line := jsonInt(entry["line"])
- content, _ := entry["content"].(string)
- fmt.Printf(" %s:%d %s\n", file, line, content)
- }
- }
-}
-
-func printTraceSummary(data map[string]any) {
- root, _ := data["root"].(map[string]any)
- rootName, _ := root["name"].(string)
- totalResults := jsonInt(data["total_results"])
- edges, _ := data["edges"].([]any)
- hops, _ := data["hops"].([]any)
-
- fmt.Printf("Trace from %q: %d node(s), %d edge(s), %d hop(s)\n", rootName, totalResults, len(edges), len(hops))
-
- for _, h := range hops {
- if hop, ok := h.(map[string]any); ok {
- hopNum := jsonInt(hop["hop"])
- nodes, _ := hop["nodes"].([]any)
- fmt.Printf(" hop %d: %d node(s)\n", hopNum, len(nodes))
- for _, n := range nodes {
- if nm, ok := n.(map[string]any); ok {
- name, _ := nm["name"].(string)
- label, _ := nm["label"].(string)
- fmt.Printf(" [%s] %s\n", label, name)
- }
- }
- }
- }
-}
-
-func printQuerySummary(data map[string]any) {
- total := jsonInt(data["total"])
- columns, _ := data["columns"].([]any)
- rows, _ := data["rows"].([]any)
-
- colNames := make([]string, len(columns))
- for i, c := range columns {
- colNames[i], _ = c.(string)
- }
-
- fmt.Printf("%d row(s) returned", total)
- if len(colNames) > 0 {
- fmt.Printf(" [%s]", strings.Join(colNames, ", "))
- }
- fmt.Println()
-
- for _, row := range rows {
- switch r := row.(type) {
- case map[string]any:
- // Rows are maps keyed by column name
- parts := make([]string, len(colNames))
- for i, col := range colNames {
- parts[i] = fmt.Sprintf("%v", r[col])
- }
- fmt.Printf(" %s\n", strings.Join(parts, " | "))
- case []any:
- parts := make([]string, len(r))
- for i, v := range r {
- parts[i] = fmt.Sprintf("%v", v)
- }
- fmt.Printf(" %s\n", strings.Join(parts, " | "))
- }
- }
-}
-
-func printSchemaSummary(data map[string]any) {
- projects, _ := data["projects"].([]any)
- if len(projects) == 0 {
- fmt.Println("No projects indexed.")
- return
- }
-
- for _, p := range projects {
- pm, ok := p.(map[string]any)
- if !ok {
- continue
- }
- projName, _ := pm["project"].(string)
- schema, _ := pm["schema"].(map[string]any)
- if schema == nil {
- continue
- }
-
- fmt.Printf("Project: %s\n", projName)
- if labels, ok := schema["node_labels"].([]any); ok {
- fmt.Printf(" Node labels (%d):\n", len(labels))
- for _, l := range labels {
- if lm, ok := l.(map[string]any); ok {
- label, _ := lm["label"].(string)
- count := jsonInt(lm["count"])
- fmt.Printf(" %-15s %d\n", label, count)
- }
- }
- }
- if rels, ok := schema["relationship_types"].([]any); ok {
- fmt.Printf(" Edge types (%d):\n", len(rels))
- for _, r := range rels {
- if rm, ok := r.(map[string]any); ok {
- relType, _ := rm["type"].(string)
- count := jsonInt(rm["count"])
- fmt.Printf(" %-25s %d\n", relType, count)
- }
- }
- }
- }
-}
-
-func printSnippetSummary(data map[string]any) {
- name, _ := data["name"].(string)
- label, _ := data["label"].(string)
- filePath, _ := data["file_path"].(string)
- startLine := jsonInt(data["start_line"])
- endLine := jsonInt(data["end_line"])
- source, _ := data["source"].(string)
-
- fmt.Printf("[%s] %s (%s:%d-%d)\n\n", label, name, filePath, startLine, endLine)
- fmt.Println(source)
-}
-
-func printDeleteSummary(data map[string]any) {
- deleted, _ := data["deleted"].(string)
- fmt.Printf("Deleted project %q\n", deleted)
-}
-
-func printReadFileSummary(data map[string]any) {
- path, _ := data["path"].(string)
- totalLines := jsonInt(data["total_lines"])
- content, _ := data["content"].(string)
-
- fmt.Printf("%s (%d lines)\n\n", path, totalLines)
- fmt.Println(content)
-}
-
-func printListDirSummary(data map[string]any) {
- dir, _ := data["directory"].(string)
- count := jsonInt(data["count"])
- entries, _ := data["entries"].([]any)
-
- fmt.Printf("%s (%d entries)\n", dir, count)
- for _, e := range entries {
- if em, ok := e.(map[string]any); ok {
- name, _ := em["name"].(string)
- isDir, _ := em["is_dir"].(bool)
- if isDir {
- fmt.Printf(" %s/\n", name)
- } else {
- size := jsonInt(em["size"])
- fmt.Printf(" %-40s %d bytes\n", name, size)
- }
- }
- }
-}
-
-func printIngestSummary(data map[string]any, dbPath string) {
- matched := jsonInt(data["matched"])
- boosted := jsonInt(data["boosted"])
- total := jsonInt(data["total_spans"])
- fmt.Printf("Ingested %d span(s): %d matched, %d boosted\n", total, matched, boosted)
- fmt.Printf(" db: %s\n", dbPath)
-}
-
-func printIndexStatusSummary(data map[string]any) {
- project, _ := data["project"].(string)
- status, _ := data["status"].(string)
-
- switch status {
- case "no_session":
- msg, _ := data["message"].(string)
- fmt.Println(msg)
- case "not_indexed":
- fmt.Printf("Project %q: not indexed\n", project)
- if dbPath, ok := data["db_path"].(string); ok {
- fmt.Printf(" expected db: %s\n", dbPath)
- }
- case "partial":
- fmt.Printf("Project %q: partially indexed (metadata missing)\n", project)
- case "indexing":
- fmt.Printf("Project %q: indexing in progress\n", project)
- if elapsed, ok := data["index_elapsed_seconds"]; ok {
- fmt.Printf(" elapsed: %ds\n", jsonInt(elapsed))
- }
- if indexType, ok := data["index_type"].(string); ok {
- fmt.Printf(" type: %s\n", indexType)
- }
- case "ready":
- nodes := jsonInt(data["nodes"])
- edges := jsonInt(data["edges"])
- indexedAt, _ := data["indexed_at"].(string)
- indexType, _ := data["index_type"].(string)
- isSession, _ := data["is_session_project"].(bool)
- fmt.Printf("Project %q: ready (%d nodes, %d edges)\n", project, nodes, edges)
- fmt.Printf(" indexed_at: %s\n", indexedAt)
- fmt.Printf(" index_type: %s\n", indexType)
- if isSession {
- fmt.Printf(" session_project: true\n")
- }
- if dbPath, ok := data["db_path"].(string); ok {
- fmt.Printf(" db: %s\n", dbPath)
- }
- default:
- printRawJSON(mustJSON(data))
- }
-}
-
-func printDetectChangesSummary(data map[string]any) {
- summary, _ := data["summary"].(map[string]any)
- changedFiles := jsonInt(summary["changed_files"])
- changedSymbols := jsonInt(summary["changed_symbols"])
- total := jsonInt(summary["total"])
- critical := jsonInt(summary["critical"])
- high := jsonInt(summary["high"])
- medium := jsonInt(summary["medium"])
- low := jsonInt(summary["low"])
-
- fmt.Printf("Changes: %d file(s), %d symbol(s) modified\n", changedFiles, changedSymbols)
- fmt.Printf("Impact: %d affected symbol(s)\n", total)
- if total > 0 {
- fmt.Printf(" CRITICAL: %d HIGH: %d MEDIUM: %d LOW: %d\n", critical, high, medium, low)
- }
-
- impacted, _ := data["impacted_symbols"].([]any)
- for _, is := range impacted {
- m, ok := is.(map[string]any)
- if !ok {
- continue
- }
- risk, _ := m["risk"].(string)
- name, _ := m["name"].(string)
- label, _ := m["label"].(string)
- changedBy, _ := m["changed_by"].(string)
- fmt.Printf(" [%s] [%s] %s (via %s)\n", risk, label, name, changedBy)
- }
-}
-
-// jsonInt extracts an integer from a JSON-decoded value (float64 or int).
-func jsonInt(v any) int {
- switch n := v.(type) {
- case float64:
- return int(n)
- case int:
- return n
- default:
- return 0
- }
-}
-
-func mustJSON(v any) string {
- b, _ := json.MarshalIndent(v, "", " ")
- return string(b)
-}
diff --git a/cmd/codebase-memory-mcp/memlimit.go b/cmd/codebase-memory-mcp/memlimit.go
deleted file mode 100644
index 279fa9181..000000000
--- a/cmd/codebase-memory-mcp/memlimit.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package main
-
-import "log"
-
-const (
- minMemLimit int64 = 2 << 30 // 2 GB
- maxMemLimit int64 = 8 << 30 // 8 GB
- memFraction int64 = 4 // use 1/4 of system memory
-)
-
-// autoMemLimit returns a GOMEMLIMIT value based on available system memory.
-// Uses 25% of total physical RAM, clamped to [2GB, 8GB].
-// Falls back to 4GB if detection fails.
-func autoMemLimit() int64 {
- total := totalSystemMemory()
- if total <= 0 {
- log.Printf("mem_limit: auto-detect unavailable, default=4GB")
- return 4 << 30
- }
-
- limit := total / memFraction
- if limit < minMemLimit {
- limit = minMemLimit
- }
- if limit > maxMemLimit {
- limit = maxMemLimit
- }
- log.Printf("mem_limit: system=%dGB limit=%dGB", total>>30, limit>>30)
- return limit
-}
diff --git a/cmd/codebase-memory-mcp/memlimit_darwin.go b/cmd/codebase-memory-mcp/memlimit_darwin.go
deleted file mode 100644
index eb9f722ab..000000000
--- a/cmd/codebase-memory-mcp/memlimit_darwin.go
+++ /dev/null
@@ -1,14 +0,0 @@
-//go:build darwin
-
-package main
-
-import "golang.org/x/sys/unix"
-
-// totalSystemMemory returns total physical memory in bytes via sysctl hw.memsize.
-func totalSystemMemory() int64 {
- mem, err := unix.SysctlUint64("hw.memsize")
- if err != nil {
- return 0
- }
- return int64(mem)
-}
diff --git a/cmd/codebase-memory-mcp/memlimit_linux.go b/cmd/codebase-memory-mcp/memlimit_linux.go
deleted file mode 100644
index 42041de9b..000000000
--- a/cmd/codebase-memory-mcp/memlimit_linux.go
+++ /dev/null
@@ -1,14 +0,0 @@
-//go:build linux
-
-package main
-
-import "syscall"
-
-// totalSystemMemory returns total physical memory in bytes via Sysinfo.
-func totalSystemMemory() int64 {
- var si syscall.Sysinfo_t
- if err := syscall.Sysinfo(&si); err != nil {
- return 0
- }
- return int64(si.Totalram) * int64(si.Unit)
-}
diff --git a/cmd/codebase-memory-mcp/memlimit_windows.go b/cmd/codebase-memory-mcp/memlimit_windows.go
deleted file mode 100644
index 92b8b3718..000000000
--- a/cmd/codebase-memory-mcp/memlimit_windows.go
+++ /dev/null
@@ -1,35 +0,0 @@
-//go:build windows
-
-package main
-
-import (
- "syscall"
- "unsafe"
-)
-
-// memoryStatusEx mirrors the Windows MEMORYSTATUSEX struct.
-type memoryStatusEx struct {
- length uint32
- memoryLoad uint32
- totalPhys uint64
- availPhys uint64
- totalPageFile uint64
- availPageFile uint64
- totalVirtual uint64
- availVirtual uint64
- availExtendedVirtual uint64
-}
-
-// totalSystemMemory returns total physical memory via GlobalMemoryStatusEx.
-func totalSystemMemory() int64 {
- kernel32 := syscall.NewLazyDLL("kernel32.dll")
- proc := kernel32.NewProc("GlobalMemoryStatusEx")
-
- var ms memoryStatusEx
- ms.length = uint32(unsafe.Sizeof(ms)) //nolint:gosec // standard Windows API pattern
- r, _, _ := proc.Call(uintptr(unsafe.Pointer(&ms)))
- if r == 0 {
- return 0
- }
- return int64(ms.totalPhys)
-}
diff --git a/cmd/codebase-memory-mcp/update.go b/cmd/codebase-memory-mcp/update.go
deleted file mode 100644
index 11716b585..000000000
--- a/cmd/codebase-memory-mcp/update.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package main
-
-import (
- "archive/tar"
- "bytes"
- "compress/gzip"
- "context"
- "crypto/sha256"
- "encoding/hex"
- "fmt"
- "io"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/selfupdate"
-)
-
-// newCommand wraps exec.Command for testability.
-var newCommand = exec.Command
-
-func runUpdate(args []string) int {
- dryRun := false
- for _, a := range args {
- if a == "--dry-run" {
- dryRun = true
- }
- }
-
- currentVersion := strings.TrimPrefix(strings.TrimSuffix(version, "-dev"), "v")
- fmt.Printf("\ncodebase-memory-mcp %s — checking for updates...\n", version)
-
- if runtime.GOOS == "windows" {
- fmt.Println("Self-update is not supported on Windows.")
- fmt.Println("Download the latest release manually from:")
- fmt.Println(" https://github.com/DeusData/codebase-memory-mcp/releases/latest")
- return 1
- }
-
- ctx := context.Background()
-
- release, err := selfupdate.FetchLatestRelease(ctx)
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: fetch release: %v\n", err)
- return 1
- }
-
- latest := release.LatestVersion()
- if latest == "" {
- fmt.Println("Could not determine latest version.")
- return 1
- }
-
- if selfupdate.CompareVersions(latest, currentVersion) <= 0 {
- fmt.Printf("Already up to date (v%s).\n", currentVersion)
- return 0
- }
-
- fmt.Printf("Update available: v%s → v%s\n", currentVersion, latest)
-
- assetName := selfupdate.AssetName()
- asset := release.FindAsset(assetName)
- if asset == nil {
- fmt.Fprintf(os.Stderr, "error: no release asset for %s/%s (%s)\n", runtime.GOOS, runtime.GOARCH, assetName)
- return 1
- }
-
- if dryRun {
- fmt.Printf("[dry-run] Would download: %s (%d bytes)\n", assetName, asset.Size)
- fmt.Println("[dry-run] Would replace binary and re-run install.")
- return 0
- }
-
- binaryData, err := downloadAndVerify(ctx, release, assetName, asset)
- if err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
-
- if err := replaceBinary(binaryData); err != nil {
- fmt.Fprintf(os.Stderr, "error: %v\n", err)
- return 1
- }
-
- fmt.Println("Re-applying installation...")
- runInstall([]string{})
-
- fmt.Printf("\nUpdated to v%s. Restart your editor/CLI to activate.\n", latest)
- return 0
-}
-
-// downloadAndVerify downloads the release asset and verifies its checksum.
-func downloadAndVerify(ctx context.Context, release *selfupdate.Release, assetName string, asset *selfupdate.Asset) ([]byte, error) {
- fmt.Println("Downloading checksums...")
- checksums, err := selfupdate.DownloadChecksums(ctx, release)
- if err != nil {
- fmt.Fprintf(os.Stderr, "warning: %v (skipping checksum verification)\n", err)
- checksums = nil
- }
-
- fmt.Printf("Downloading %s...\n", assetName)
- tarballData, err := selfupdate.DownloadAsset(ctx, asset.BrowserDownloadURL)
- if err != nil {
- return nil, fmt.Errorf("download: %w", err)
- }
-
- if checksums != nil {
- if expected, ok := checksums[assetName]; ok {
- hash := sha256.Sum256(tarballData)
- actual := hex.EncodeToString(hash[:])
- if actual != expected {
- return nil, fmt.Errorf("checksum mismatch\n expected: %s\n actual: %s", expected, actual)
- }
- fmt.Println("Checksum verified.")
- }
- }
-
- binaryData, err := extractBinaryFromTarGz(tarballData)
- if err != nil {
- return nil, fmt.Errorf("extract: %w", err)
- }
-
- return binaryData, nil
-}
-
-// replaceBinary atomically swaps the current binary with the new one.
-func replaceBinary(binaryData []byte) error {
- binaryPath, err := detectBinaryPath()
- if err != nil {
- return err
- }
-
- fmt.Printf("Replacing binary at %s...\n", binaryPath)
-
- tmpPath := binaryPath + ".tmp"
- if err := os.WriteFile(tmpPath, binaryData, 0o600); err != nil {
- return fmt.Errorf("write temp: %w", err)
- }
- if err := os.Chmod(tmpPath, 0o500); err != nil {
- return fmt.Errorf("chmod temp: %w", err)
- }
-
- bakPath := binaryPath + ".bak"
- if cpErr := copyFile(binaryPath, bakPath); cpErr != nil {
- fmt.Fprintf(os.Stderr, "warning: backup failed: %v\n", cpErr)
- }
-
- if err := os.Rename(tmpPath, binaryPath); err != nil {
- os.Remove(tmpPath)
- return fmt.Errorf("rename: %w", err)
- }
-
- if err := verifyBinary(binaryPath); err != nil {
- fmt.Println("Restoring previous version...")
- if restoreErr := os.Rename(bakPath, binaryPath); restoreErr != nil {
- return fmt.Errorf("restore failed (%v), backup at: %s", restoreErr, bakPath)
- }
- fmt.Println("Previous version restored.")
- return fmt.Errorf("new binary verification failed: %w", err)
- }
-
- os.Remove(bakPath)
- return nil
-}
-
-// extractBinaryFromTarGz extracts the first regular file from a .tar.gz archive.
-func extractBinaryFromTarGz(data []byte) ([]byte, error) {
- gr, err := gzip.NewReader(bytes.NewReader(data))
- if err != nil {
- return nil, fmt.Errorf("gzip: %w", err)
- }
- defer gr.Close()
-
- tr := tar.NewReader(gr)
- for {
- hdr, err := tr.Next()
- if err == io.EOF {
- break
- }
- if err != nil {
- return nil, fmt.Errorf("tar: %w", err)
- }
- if hdr.Typeflag == tar.TypeReg && strings.HasPrefix(filepath.Base(hdr.Name), "codebase-memory-mcp") {
- content, err := io.ReadAll(tr)
- if err != nil {
- return nil, fmt.Errorf("read entry: %w", err)
- }
- return content, nil
- }
- }
- return nil, fmt.Errorf("binary not found in archive")
-}
-
-// verifyBinary runs --version on the new binary to ensure it works.
-func verifyBinary(path string) error {
- cmd := newCommand(path, "--version")
- out, err := cmd.Output()
- if err != nil {
- return fmt.Errorf("--version failed: %w", err)
- }
- output := strings.TrimSpace(string(out))
- if !strings.Contains(output, "codebase-memory-mcp") {
- return fmt.Errorf("unexpected output: %s", output)
- }
- return nil
-}
-
-// copyFile copies a file from src to dst.
-func copyFile(src, dst string) error {
- in, err := os.Open(src)
- if err != nil {
- return err
- }
- defer in.Close()
-
- out, err := os.Create(dst)
- if err != nil {
- return err
- }
- defer out.Close()
-
- if _, err := io.Copy(out, in); err != nil {
- return err
- }
- return out.Close()
-}
diff --git a/cmd/codebase-memory-mcp/update_test.go b/cmd/codebase-memory-mcp/update_test.go
deleted file mode 100644
index 7f491d6ca..000000000
--- a/cmd/codebase-memory-mcp/update_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package main
-
-import (
- "archive/tar"
- "bytes"
- "compress/gzip"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestExtractBinaryFromTarGz(t *testing.T) {
- var buf bytes.Buffer
- gw := gzip.NewWriter(&buf)
- tw := tar.NewWriter(gw)
-
- content := []byte("fake binary content")
- hdr := &tar.Header{
- Name: "codebase-memory-mcp-linux-amd64",
- Mode: 0o700,
- Size: int64(len(content)),
- Typeflag: tar.TypeReg,
- }
- if err := tw.WriteHeader(hdr); err != nil {
- t.Fatal(err)
- }
- if _, err := tw.Write(content); err != nil {
- t.Fatal(err)
- }
- tw.Close()
- gw.Close()
-
- extracted, err := extractBinaryFromTarGz(buf.Bytes())
- if err != nil {
- t.Fatalf("extractBinaryFromTarGz error: %v", err)
- }
- if !bytes.Equal(extracted, content) {
- t.Fatalf("extracted content mismatch: %q vs %q", extracted, content)
- }
-}
-
-func TestExtractBinaryFromTarGz_NotFound(t *testing.T) {
- var buf bytes.Buffer
- gw := gzip.NewWriter(&buf)
- tw := tar.NewWriter(gw)
-
- hdr := &tar.Header{
- Name: "some-other-file",
- Mode: 0o600,
- Size: 5,
- Typeflag: tar.TypeReg,
- }
- if err := tw.WriteHeader(hdr); err != nil {
- t.Fatal(err)
- }
- if _, err := tw.Write([]byte("hello")); err != nil {
- t.Fatal(err)
- }
- tw.Close()
- gw.Close()
-
- _, err := extractBinaryFromTarGz(buf.Bytes())
- if err == nil {
- t.Fatal("expected error when binary not found in archive")
- }
-}
-
-func TestExtractBinaryFromTarGz_InvalidData(t *testing.T) {
- _, err := extractBinaryFromTarGz([]byte("not a valid tar.gz"))
- if err == nil {
- t.Fatal("expected error for invalid tar.gz data")
- }
-}
-
-func TestCopyFile(t *testing.T) {
- dir := t.TempDir()
- src := filepath.Join(dir, "source")
- dst := filepath.Join(dir, "dest")
-
- content := []byte("test content for copy")
- if err := os.WriteFile(src, content, 0o600); err != nil {
- t.Fatal(err)
- }
-
- if err := copyFile(src, dst); err != nil {
- t.Fatalf("copyFile error: %v", err)
- }
-
- data, err := os.ReadFile(dst)
- if err != nil {
- t.Fatalf("read dst: %v", err)
- }
- if !bytes.Equal(data, content) {
- t.Fatalf("copy mismatch: %q vs %q", data, content)
- }
-}
-
-func TestCopyFile_SourceNotFound(t *testing.T) {
- dir := t.TempDir()
- err := copyFile(filepath.Join(dir, "nonexistent"), filepath.Join(dir, "dest"))
- if err == nil {
- t.Fatal("expected error for nonexistent source")
- }
-}
diff --git a/go.mod b/go.mod
deleted file mode 100644
index b941b2b1c..000000000
--- a/go.mod
+++ /dev/null
@@ -1,26 +0,0 @@
-module github.com/DeusData/codebase-memory-mcp
-
-go 1.26
-
-require (
- github.com/boyter/gocodewalker v1.5.1
- github.com/fsnotify/fsnotify v1.9.0
- github.com/mattn/go-sqlite3 v1.14.34
- github.com/modelcontextprotocol/go-sdk v1.4.0
- github.com/zeebo/xxh3 v1.1.0
- go.uber.org/goleak v1.3.0
- golang.org/x/sync v0.19.0
- golang.org/x/sys v0.40.0
- gopkg.in/yaml.v3 v3.0.1
-)
-
-require (
- github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect
- github.com/google/jsonschema-go v0.4.2 // indirect
- github.com/klauspost/cpuid/v2 v2.2.10 // indirect
- github.com/kr/text v0.2.0 // indirect
- github.com/segmentio/asm v1.1.3 // indirect
- github.com/segmentio/encoding v0.5.3 // indirect
- github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
- golang.org/x/oauth2 v0.34.0 // indirect
-)
diff --git a/go.sum b/go.sum
deleted file mode 100644
index 69c66d37c..000000000
--- a/go.sum
+++ /dev/null
@@ -1,54 +0,0 @@
-github.com/boyter/gocodewalker v1.5.1 h1:0YeK2QAkd+ymW5MsagMZapIXD3v9/vrZl0HkFSLpKsw=
-github.com/boyter/gocodewalker v1.5.1/go.mod h1:9k+yM6+fIx61F0xI9ChXEGE5DYoLhggw8AxSOtW+kKo=
-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
-github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ=
-github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
-github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
-github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
-github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
-github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
-github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
-github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
-github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
-github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
-github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
-github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
-github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
-github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
-github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
-github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
-github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
-github.com/modelcontextprotocol/go-sdk v1.4.0 h1:u0kr8lbJc1oBcawK7Df+/ajNMpIDFE41OEPxdeTLOn8=
-github.com/modelcontextprotocol/go-sdk v1.4.0/go.mod h1:Nxc2n+n/GdCebUaqCOhTetptS17SXXNu9IfNTaLDi1E=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
-github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
-github.com/segmentio/encoding v0.5.3 h1:OjMgICtcSFuNvQCdwqMCv9Tg7lEOXGwm1J5RPQccx6w=
-github.com/segmentio/encoding v0.5.3/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
-github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
-github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
-github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
-github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
-github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
-github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
-go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
-go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
-golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
-golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
-golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
-golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
-golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
-golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
-golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
-golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
-gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/cbm/ac.go b/internal/cbm/ac.go
deleted file mode 100644
index 4f4f0f69b..000000000
--- a/internal/cbm/ac.go
+++ /dev/null
@@ -1,295 +0,0 @@
-package cbm
-
-import "runtime"
-
-// #include <stdlib.h>
-// typedef struct CBMAutomaton CBMAutomaton;
-// typedef struct { int name_index; int pattern_id; } CBMMatchResult;
-// typedef struct { const char *data; int compressed_len; int original_len; } CBMLz4Entry;
-// typedef struct { int file_index; unsigned long long bitmask; } CBMLz4Match;
-//
-// CBMAutomaton *cbm_ac_build(const char **patterns, const int *lengths, int count,
-// const unsigned char *alpha_map, int alpha_size);
-// void cbm_ac_free(CBMAutomaton *ac);
-// unsigned long long cbm_ac_scan_bitmask(const CBMAutomaton *ac, const char *text, int text_len);
-// unsigned long long cbm_ac_scan_lz4_bitmask(const CBMAutomaton *ac,
-// const char *compressed, int compressed_len, int original_len);
-// int cbm_ac_scan_lz4_batch(const CBMAutomaton *ac, const CBMLz4Entry *entries,
-// int num_entries, CBMLz4Match *out_matches, int max_matches);
-// int cbm_ac_scan_batch(const CBMAutomaton *ac, const char *names_buf,
-// const int *name_offsets, const int *name_lengths,
-// int num_names, CBMMatchResult *out_matches, int max_matches);
-// int cbm_ac_num_states(const CBMAutomaton *ac);
-// int cbm_ac_num_patterns(const CBMAutomaton *ac);
-// int cbm_ac_table_bytes(const CBMAutomaton *ac);
-import "C"
-import "unsafe"
-
-// ACAutomaton wraps a C-side Aho-Corasick automaton.
-type ACAutomaton struct {
- ac *C.CBMAutomaton
-}
-
-// ACBuild creates an Aho-Corasick automaton from the given patterns.
-// Uses full 256-byte alphabet (suitable for scanning source code).
-// Caller must call Free() when done.
-func ACBuild(patterns []string) *ACAutomaton {
- if len(patterns) == 0 {
- return nil
- }
-
- cPtrs := make([]*C.char, len(patterns))
- cLens := make([]C.int, len(patterns))
- for i, p := range patterns {
- cPtrs[i] = C.CString(p)
- cLens[i] = C.int(len(p))
- }
- defer func() {
- for _, p := range cPtrs {
- C.free(unsafe.Pointer(p))
- }
- }()
-
- ac := C.cbm_ac_build(
- (**C.char)(unsafe.Pointer(&cPtrs[0])),
- (*C.int)(unsafe.Pointer(&cLens[0])),
- C.int(len(patterns)),
- nil, // identity alphabet
- 256,
- )
- if ac == nil {
- return nil
- }
- return &ACAutomaton{ac: ac}
-}
-
-// ACBuildCompact creates an automaton with a compact alphabet mapping.
-// alphaMap[byte] = mapped_index (0 = "other"). alphaSize = max mapped index + 1.
-// This reduces the goto table from states*256 to states*alphaSize.
-func ACBuildCompact(patterns []string, alphaMap [256]byte, alphaSize int) *ACAutomaton {
- if len(patterns) == 0 {
- return nil
- }
-
- cPtrs := make([]*C.char, len(patterns))
- cLens := make([]C.int, len(patterns))
- for i, p := range patterns {
- cPtrs[i] = C.CString(p)
- cLens[i] = C.int(len(p))
- }
- defer func() {
- for _, p := range cPtrs {
- C.free(unsafe.Pointer(p))
- }
- }()
-
- ac := C.cbm_ac_build(
- (**C.char)(unsafe.Pointer(&cPtrs[0])),
- (*C.int)(unsafe.Pointer(&cLens[0])),
- C.int(len(patterns)),
- (*C.uchar)(unsafe.Pointer(&alphaMap[0])),
- C.int(alphaSize),
- )
- if ac == nil {
- return nil
- }
- return &ACAutomaton{ac: ac}
-}
-
-// Free releases the C-side automaton memory.
-func (a *ACAutomaton) Free() {
- if a != nil && a.ac != nil {
- C.cbm_ac_free(a.ac)
- a.ac = nil
- }
-}
-
-// ScanBitmask scans text and returns a bitmask of matched pattern indices (0..63).
-func (a *ACAutomaton) ScanBitmask(text []byte) uint64 {
- if a == nil || a.ac == nil || len(text) == 0 {
- return 0
- }
- return uint64(C.cbm_ac_scan_bitmask(
- a.ac,
- (*C.char)(unsafe.Pointer(&text[0])),
- C.int(len(text)),
- ))
-}
-
-// ScanString scans a string and returns a bitmask of matched pattern indices.
-func (a *ACAutomaton) ScanString(s string) uint64 {
- if a == nil || a.ac == nil || len(s) == 0 {
- return 0
- }
- // Use unsafe.Pointer to avoid copying the string to []byte.
- return uint64(C.cbm_ac_scan_bitmask(
- a.ac,
- (*C.char)(unsafe.Pointer(unsafe.StringData(s))),
- C.int(len(s)),
- ))
-}
-
-// ScanLZ4Bitmask decompresses LZ4 data in a C-side thread-local buffer and
-// scans it through the automaton. Returns bitmask of matched patterns.
-// Zero Go heap allocation for non-matching files.
-func (a *ACAutomaton) ScanLZ4Bitmask(compressed []byte, originalLen int) uint64 {
- if a == nil || a.ac == nil || len(compressed) == 0 || originalLen <= 0 {
- return 0
- }
- return uint64(C.cbm_ac_scan_lz4_bitmask(
- a.ac,
- (*C.char)(unsafe.Pointer(&compressed[0])),
- C.int(len(compressed)),
- C.int(originalLen),
- ))
-}
-
-// LZ4Entry describes one compressed file for batch scanning.
-type LZ4Entry struct {
- Data []byte
- OriginalLen int
-}
-
-// LZ4Match holds a batch scan result: file index and bitmask of matched patterns.
-type LZ4Match struct {
- FileIndex int
- Bitmask uint64
-}
-
-// ScanLZ4Batch decompresses and scans multiple LZ4-compressed files in a single
-// CGo call. Returns only files that matched at least one pattern. One C-side
-// decompression buffer is reused across all files — zero Go heap allocation.
-func (a *ACAutomaton) ScanLZ4Batch(entries []LZ4Entry) []LZ4Match {
- if a == nil || a.ac == nil || len(entries) == 0 {
- return nil
- }
-
- // Pin all Go slice backing arrays so CGo can hold pointers to them.
- var pinner runtime.Pinner
- defer pinner.Unpin()
-
- cEntries := make([]C.CBMLz4Entry, len(entries))
- for i, e := range entries {
- if len(e.Data) > 0 {
- pinner.Pin(&e.Data[0])
- cEntries[i].data = (*C.char)(unsafe.Pointer(&e.Data[0]))
- cEntries[i].compressed_len = C.int(len(e.Data))
- cEntries[i].original_len = C.int(e.OriginalLen)
- }
- }
-
- // Output buffer — at most len(entries) matches.
- outBuf := make([]C.CBMLz4Match, len(entries))
-
- n := int(C.cbm_ac_scan_lz4_batch(
- a.ac,
- (*C.CBMLz4Entry)(unsafe.Pointer(&cEntries[0])),
- C.int(len(entries)),
- (*C.CBMLz4Match)(unsafe.Pointer(&outBuf[0])),
- C.int(len(entries)),
- ))
-
- if n <= 0 {
- return nil
- }
-
- result := make([]LZ4Match, n)
- for i := 0; i < n; i++ {
- result[i] = LZ4Match{
- FileIndex: int(outBuf[i].file_index),
- Bitmask: uint64(outBuf[i].bitmask),
- }
- }
- return result
-}
-
-// ACBatchMatch represents a single match from ScanBatch.
-type ACBatchMatch struct {
- NameIndex int
- PatternID int
-}
-
-// ScanBatch scans multiple names through the automaton in a single CGo call.
-// Returns (nameIndex, patternID) pairs for all substring matches found.
-func (a *ACAutomaton) ScanBatch(names []string) []ACBatchMatch {
- if a == nil || a.ac == nil || len(names) == 0 {
- return nil
- }
-
- // Build contiguous buffer + offset/length arrays.
- totalLen := 0
- for _, n := range names {
- totalLen += len(n)
- }
-
- buf := make([]byte, totalLen)
- offsets := make([]C.int, len(names))
- lengths := make([]C.int, len(names))
- pos := 0
- for i, n := range names {
- offsets[i] = C.int(pos)
- lengths[i] = C.int(len(n))
- copy(buf[pos:], n)
- pos += len(n)
- }
-
- // Allocate output buffer. Worst case: every name matches every pattern.
- // In practice, matches are sparse. Start with len(names) as a reasonable cap.
- maxMatches := len(names)
- if maxMatches < 1024 {
- maxMatches = 1024
- }
- outBuf := make([]C.CBMMatchResult, maxMatches)
-
- var bufPtr *C.char
- if len(buf) > 0 {
- bufPtr = (*C.char)(unsafe.Pointer(&buf[0]))
- }
-
- n := int(C.cbm_ac_scan_batch(
- a.ac,
- bufPtr,
- (*C.int)(unsafe.Pointer(&offsets[0])),
- (*C.int)(unsafe.Pointer(&lengths[0])),
- C.int(len(names)),
- (*C.CBMMatchResult)(unsafe.Pointer(&outBuf[0])),
- C.int(maxMatches),
- ))
-
- if n <= 0 {
- return nil
- }
-
- result := make([]ACBatchMatch, n)
- for i := 0; i < n; i++ {
- result[i] = ACBatchMatch{
- NameIndex: int(outBuf[i].name_index),
- PatternID: int(outBuf[i].pattern_id),
- }
- }
- return result
-}
-
-// NumStates returns the number of states in the automaton.
-func (a *ACAutomaton) NumStates() int {
- if a == nil || a.ac == nil {
- return 0
- }
- return int(C.cbm_ac_num_states(a.ac))
-}
-
-// NumPatterns returns the number of patterns in the automaton.
-func (a *ACAutomaton) NumPatterns() int {
- if a == nil || a.ac == nil {
- return 0
- }
- return int(C.cbm_ac_num_patterns(a.ac))
-}
-
-// TableBytes returns the approximate memory used by the goto table.
-func (a *ACAutomaton) TableBytes() int {
- if a == nil || a.ac == nil {
- return 0
- }
- return int(C.cbm_ac_table_bytes(a.ac))
-}
diff --git a/internal/cbm/ac_test.go b/internal/cbm/ac_test.go
deleted file mode 100644
index 367f9334f..000000000
--- a/internal/cbm/ac_test.go
+++ /dev/null
@@ -1,407 +0,0 @@
-package cbm
-
-import (
- "strings"
- "testing"
-)
-
-func TestACBuild_Empty(t *testing.T) {
- ac := ACBuild(nil)
- if ac != nil {
- t.Fatal("expected nil for empty patterns")
- }
-}
-
-func TestACBuild_SinglePattern(t *testing.T) {
- ac := ACBuild([]string{"hello"})
- if ac == nil {
- t.Fatal("expected non-nil")
- }
- defer ac.Free()
-
- if ac.NumPatterns() != 1 {
- t.Fatalf("expected 1 pattern, got %d", ac.NumPatterns())
- }
-
- // Match
- mask := ac.ScanBitmask([]byte("say hello world"))
- if mask != 1 {
- t.Fatalf("expected bitmask 1, got %d", mask)
- }
-
- // No match
- mask = ac.ScanBitmask([]byte("say helo world"))
- if mask != 0 {
- t.Fatalf("expected bitmask 0, got %d", mask)
- }
-}
-
-func TestACBuild_MultiplePatterns(t *testing.T) {
- patterns := []string{"http.Get", "fetch(", "requests.post", "axios."}
- ac := ACBuild(patterns)
- if ac == nil {
- t.Fatal("expected non-nil")
- }
- defer ac.Free()
-
- tests := []struct {
- input string
- expected uint64
- }{
- {"resp := http.Get(url)", 1 << 0},
- {"const r = fetch(url)", 1 << 1},
- {"requests.post(url, data)", 1 << 2},
- {"axios.get('/api')", 1 << 3},
- {"http.Get then fetch(", 1<<0 | 1<<1},
- {"no http calls here", 0},
- {"", 0},
- }
-
- for _, tt := range tests {
- mask := ac.ScanBitmask([]byte(tt.input))
- if mask != tt.expected {
- t.Errorf("input=%q: expected %064b, got %064b", tt.input, tt.expected, mask)
- }
- }
-}
-
-func TestACBuild_OverlappingPatterns(t *testing.T) {
- // "he", "her", "hers", "his" — classic AC example
- patterns := []string{"he", "her", "hers", "his"}
- ac := ACBuild(patterns)
- defer ac.Free()
-
- mask := ac.ScanBitmask([]byte("ushers"))
- // "he" at pos 2, "her" at pos 2, "hers" at pos 2
- expected := uint64(1<<0 | 1<<1 | 1<<2)
- if mask != expected {
- t.Errorf("expected %064b, got %064b", expected, mask)
- }
-}
-
-func TestACScanString(t *testing.T) {
- ac := ACBuild([]string{"foo", "bar"})
- defer ac.Free()
-
- mask := ac.ScanString("foobar")
- if mask != 3 {
- t.Fatalf("expected 3, got %d", mask)
- }
-}
-
-func TestACCompactAlphabet(t *testing.T) {
- // Build a compact alphabet: a-z=1..26, 0-9=27..36, _=37, everything else=0
- var alphaMap [256]byte
- idx := byte(1)
- for c := byte('a'); c <= byte('z'); c++ {
- alphaMap[c] = idx
- idx++
- }
- for c := byte('0'); c <= byte('9'); c++ {
- alphaMap[c] = idx
- idx++
- }
- alphaMap['_'] = idx
- alphaSize := int(idx) + 1 // 38
-
- patterns := []string{"database_url", "api_key", "port"}
- ac := ACBuildCompact(patterns, alphaMap, alphaSize)
- if ac == nil {
- t.Fatal("expected non-nil")
- }
- defer ac.Free()
-
- // Should match
- mask := ac.ScanString("database_url")
- if mask&1 == 0 {
- t.Error("expected database_url match")
- }
-
- // Substring match
- mask = ac.ScanString("my_database_url_setting")
- if mask&1 == 0 {
- t.Error("expected database_url substring match")
- }
-
- // Table should be much smaller than 256-alphabet
- tableMB := ac.TableBytes()
- t.Logf("compact table: %d states × %d alpha = %d bytes", ac.NumStates(), alphaSize, tableMB)
- if ac.NumStates()*alphaSize*4 != tableMB {
- t.Errorf("table size mismatch: expected %d, got %d", ac.NumStates()*alphaSize*4, tableMB)
- }
-}
-
-func TestACScanLZ4Bitmask(t *testing.T) {
- ac := ACBuild([]string{"http.Get", "fetch("})
- defer ac.Free()
-
- // Compress some source code
- source := []byte(`package main
-import "net/http"
-func doStuff() {
- resp, err := http.Get("https://example.com")
- _ = resp
- _ = err
-}
-`)
- compressed := LZ4CompressHC(source)
- if compressed == nil {
- t.Fatal("compression failed")
- }
-
- mask := ac.ScanLZ4Bitmask(compressed, len(source))
- if mask != 1 {
- t.Fatalf("expected bitmask 1 (http.Get), got %d", mask)
- }
-
- // No match
- noHTTP := []byte("package main\nfunc main() { println(42) }\n")
- comp2 := LZ4CompressHC(noHTTP)
- mask = ac.ScanLZ4Bitmask(comp2, len(noHTTP))
- if mask != 0 {
- t.Fatalf("expected 0, got %d", mask)
- }
-}
-
-func TestACScanLZ4Batch(t *testing.T) {
- ac := ACBuild([]string{"http.Get", "fetch(", "Route::get"})
- defer ac.Free()
-
- // Three files: one with http.Get, one with Route::get, one with nothing.
- files := []struct {
- src string
- wantHit bool
- }{
- {`resp := http.Get("https://example.com")`, true},
- {`func main() { println(42) }`, false},
- {`Route::get("/users", "UserController@index")`, true},
- }
-
- entries := make([]LZ4Entry, len(files))
- for i, f := range files {
- src := []byte(f.src)
- entries[i] = LZ4Entry{Data: LZ4CompressHC(src), OriginalLen: len(src)}
- }
-
- matches := ac.ScanLZ4Batch(entries)
-
- // Should have 2 matches (files 0 and 2).
- if len(matches) != 2 {
- t.Fatalf("expected 2 matches, got %d", len(matches))
- }
- if matches[0].FileIndex != 0 || matches[0].Bitmask&1 == 0 {
- t.Errorf("expected file 0 to match http.Get, got idx=%d mask=%064b", matches[0].FileIndex, matches[0].Bitmask)
- }
- if matches[1].FileIndex != 2 || matches[1].Bitmask&4 == 0 {
- t.Errorf("expected file 2 to match Route::get, got idx=%d mask=%064b", matches[1].FileIndex, matches[1].Bitmask)
- }
-}
-
-func TestACScanLZ4Batch_Empty(t *testing.T) {
- ac := ACBuild([]string{"test"})
- defer ac.Free()
- matches := ac.ScanLZ4Batch(nil)
- if matches != nil {
- t.Fatal("expected nil for empty entries")
- }
-}
-
-func TestACScanBatch(t *testing.T) {
- patterns := []string{"database", "port", "host"}
- ac := ACBuild(patterns)
- defer ac.Free()
-
- names := []string{
- "database_url", // matches "database"
- "server_port", // matches "port"
- "api_key", // no match
- "database_host", // matches "database" and "host"
- "max_retries", // no match
- }
-
- matches := ac.ScanBatch(names)
-
- // Collect by name index
- byName := make(map[int][]int)
- for _, m := range matches {
- byName[m.NameIndex] = append(byName[m.NameIndex], m.PatternID)
- }
-
- // database_url → pattern 0 (database)
- if pids, ok := byName[0]; !ok || len(pids) != 1 || pids[0] != 0 {
- t.Errorf("expected name 0 to match pattern 0, got %v", byName[0])
- }
-
- // server_port → pattern 1 (port)
- if pids, ok := byName[1]; !ok || len(pids) != 1 || pids[0] != 1 {
- t.Errorf("expected name 1 to match pattern 1, got %v", byName[1])
- }
-
- // api_key → no match
- if _, ok := byName[2]; ok {
- t.Errorf("expected name 2 to have no matches, got %v", byName[2])
- }
-
- // database_host → pattern 0 and 2
- if pids, ok := byName[3]; !ok || len(pids) != 2 {
- t.Errorf("expected name 3 to match 2 patterns, got %v", byName[3])
- }
-}
-
-func TestACFree_DoubleCall(t *testing.T) {
- ac := ACBuild([]string{"test"})
- ac.Free()
- ac.Free() // should not panic
-}
-
-func TestACFree_Nil(t *testing.T) {
- var ac *ACAutomaton
- ac.Free() // should not panic
-}
-
-func TestACScanBitmask_Empty(t *testing.T) {
- ac := ACBuild([]string{"test"})
- defer ac.Free()
- mask := ac.ScanBitmask(nil)
- if mask != 0 {
- t.Fatalf("expected 0, got %d", mask)
- }
-}
-
-func TestAC_LargePatternSet(t *testing.T) {
- // Build with all httplink keywords to verify real-world pattern count
- patterns := []string{
- "requests.get", "requests.post", "requests.put", "requests.delete", "requests.patch",
- "httpx.", "aiohttp.", "urllib.request",
- "http.Get", "http.Post", "http.NewRequest", "client.Do(",
- "fetch(", "axios.", ".ajax(",
- "HttpClient", "RestTemplate", "WebClient", "OkHttpClient",
- "HttpURLConnection", "openConnection(",
- "reqwest::", "hyper::", "surf::", "ureq::",
- "curl_exec", "curl_init", "Guzzle", "Http::get", "Http::post",
- "sttp.", "http4s", "wsClient",
- "curl_easy", "cpr::Get", "cpr::Post", "httplib::",
- "socket.http", "http.request",
- "RestClient", "HttpWebRequest",
- "ktor.client",
- "send_request", "http_client",
- "CreateTask", "create_task",
- "topic.Publish", "publisher.publish", "topic.publish",
- "sqs.send_message", "sns.publish",
- "basic_publish",
- "producer.send", "producer.Send",
- }
-
- // Deduplicate (HttpClient, OkHttpClient, WebClient appear multiple times)
- seen := make(map[string]bool)
- var unique []string
- for _, p := range patterns {
- if !seen[p] {
- seen[p] = true
- unique = append(unique, p)
- }
- }
-
- ac := ACBuild(unique)
- if ac == nil {
- t.Fatal("expected non-nil")
- }
- defer ac.Free()
-
- t.Logf("patterns=%d unique=%d states=%d table=%d bytes",
- len(patterns), len(unique), ac.NumStates(), ac.TableBytes())
-
- // Scan a Go source file
- source := `package main
-import "net/http"
-func callAPI() {
- resp, _ := http.Get("https://api.example.com/data")
- defer resp.Body.Close()
-}
-func createTask() {
- client.CreateTask(ctx, req)
-}
-`
- mask := ac.ScanBitmask([]byte(source))
- // Should match http.Get and CreateTask
- httpGetIdx := -1
- createTaskIdx := -1
- for i, p := range unique {
- if p == "http.Get" {
- httpGetIdx = i
- }
- if p == "CreateTask" {
- createTaskIdx = i
- }
- }
- if httpGetIdx >= 0 && mask&(1<<httpGetIdx) == 0 {
- t.Error("expected http.Get match")
- }
- if createTaskIdx >= 0 && mask&(1<<createTaskIdx) == 0 {
- t.Error("expected CreateTask match")
- }
-
- // Non-matching source
- mask = ac.ScanBitmask([]byte("func main() { fmt.Println(42) }"))
- if mask != 0 {
- t.Errorf("expected 0 for non-matching source, got %064b", mask)
- }
-}
-
-func BenchmarkACScan_TypicalSource(b *testing.B) {
- patterns := []string{
- "http.Get", "http.Post", "http.NewRequest", "client.Do(",
- "fetch(", "axios.", "requests.get", "requests.post",
- "HttpClient", "curl_exec", "CreateTask",
- }
- ac := ACBuild(patterns)
- defer ac.Free()
-
- // ~500 bytes of typical Go source (no HTTP calls)
- source := []byte(strings.Repeat("func process(ctx context.Context, data []byte) error {\n\tresult := transform(data)\n\treturn store.Save(ctx, result)\n}\n", 5))
-
- b.SetBytes(int64(len(source)))
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- ac.ScanBitmask(source)
- }
-}
-
-func BenchmarkACScanLZ4_TypicalSource(b *testing.B) {
- patterns := []string{
- "http.Get", "http.Post", "http.NewRequest", "client.Do(",
- "fetch(", "axios.", "requests.get", "requests.post",
- "HttpClient", "curl_exec", "CreateTask",
- }
- ac := ACBuild(patterns)
- defer ac.Free()
-
- source := []byte(strings.Repeat("func process(ctx context.Context, data []byte) error {\n\tresult := transform(data)\n\treturn store.Save(ctx, result)\n}\n", 5))
- compressed := LZ4CompressHC(source)
- origLen := len(source)
-
- b.SetBytes(int64(origLen))
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- ac.ScanLZ4Bitmask(compressed, origLen)
- }
-}
-
-func BenchmarkACScanBatch_ConfigNames(b *testing.B) {
- patterns := []string{"database", "port", "host", "url", "timeout", "max", "min", "key", "secret"}
- ac := ACBuild(patterns)
- defer ac.Free()
-
- // Simulate 1000 normalized code names
- names := make([]string, 1000)
- for i := range names {
- names[i] = "some_function_name_with_typical_length"
- }
- names[42] = "get_database_url"
- names[500] = "server_port_number"
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- ac.ScanBatch(names)
- }
-}
diff --git a/internal/cbm/cbm.go b/internal/cbm/cbm.go
deleted file mode 100644
index f0c123075..000000000
--- a/internal/cbm/cbm.go
+++ /dev/null
@@ -1,540 +0,0 @@
-package cbm
-
-/*
-#cgo CFLAGS: -std=c11 -D_DEFAULT_SOURCE -O2 -Wall -Ivendored/ts_runtime/include -Ivendored/ts_runtime/src
-#cgo CXXFLAGS: -std=c++17 -O2 -Wall -Ivendored/ts_runtime/include
-#cgo darwin LDFLAGS: -lc++
-#cgo linux LDFLAGS: -lstdc++
-#include "cbm.h"
-#include "helpers.h"
-#include "lang_specs.h"
-#include <stdlib.h>
-*/
-import "C"
-import (
- "fmt"
- "sync"
- "unsafe"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// ResolvedCall represents a high-confidence type-aware call resolution from LSP.
-type ResolvedCall struct {
- CallerQN string
- CalleeQN string
- Strategy string
- Confidence float32
- Reason string // diagnostic label for unresolved calls (empty if resolved)
-}
-
-// FileResult holds the extraction results from one file.
-type FileResult struct {
- Definitions []Definition
- Calls []Call
- Imports []Import
- Usages []Usage
- Throws []Throw
- ReadWrites []ReadWrite
- TypeRefs []TypeRef
- EnvAccesses []EnvAccess
- TypeAssigns []TypeAssign
- ImplTraits []ImplTrait
- ResolvedCalls []ResolvedCall
-
- ModuleQN string
- IsTestFile bool
- ImportCount int
- TreeHandle unsafe.Pointer // cached TSTree* for cross-file LSP reuse
- TreeLang int // CBMLanguage enum value
-}
-
-// FreeTree releases the cached parse tree. Call after cross-file LSP is done.
-func (r *FileResult) FreeTree() {
- if r.TreeHandle != nil {
- C.cbm_free_tree_ptr((*C.TSTree)(r.TreeHandle))
- r.TreeHandle = nil
- }
-}
-
-// ImplTrait represents a Rust `impl Trait for Struct` pair.
-type ImplTrait struct {
- TraitName string
- StructName string
-}
-
-// Definition represents a function/class/variable/module extracted from source.
-type Definition struct {
- Name string
- QualifiedName string
- Label string // "Function", "Method", "Class", "Variable", "Module", "Interface", "Enum", "Type"
- FilePath string
- StartLine int
- EndLine int
- Signature string
- ReturnType string
- Receiver string
- Docstring string
- ParentClass string
- Decorators []string
- BaseClasses []string
- ParamNames []string
- ParamTypes []string
- ReturnTypes []string
- Complexity int
- Lines int
- IsExported bool
- IsAbstract bool
- IsTest bool
- IsEntryPoint bool
-}
-
-// Call represents a raw call site (callee name + enclosing function).
-type Call struct {
- CalleeName string
- EnclosingFuncQN string
-}
-
-// Import represents a local name -> module path mapping.
-type Import struct {
- LocalName string
- ModulePath string
-}
-
-// Usage represents a reference to an identifier (not a call or import).
-type Usage struct {
- RefName string
- EnclosingFuncQN string
-}
-
-// Throw represents a throw/raise statement.
-type Throw struct {
- ExceptionName string
- EnclosingFuncQN string
-}
-
-// ReadWrite represents a variable read or write.
-type ReadWrite struct {
- VarName string
- EnclosingFuncQN string
- IsWrite bool
-}
-
-// TypeRef represents a type reference in a function signature or body.
-type TypeRef struct {
- TypeName string
- EnclosingFuncQN string
-}
-
-// EnvAccess represents an environment variable access.
-type EnvAccess struct {
- EnvKey string
- EnclosingFuncQN string
-}
-
-// TypeAssign represents a variable assignment where RHS is a constructor call.
-type TypeAssign struct {
- VarName string
- TypeName string
- EnclosingFuncQN string
-}
-
-var initOnce sync.Once
-
-// Init initializes the C library. Safe to call multiple times.
-func Init() {
- initOnce.Do(func() {
- C.cbm_init()
- })
-}
-
-// Shutdown cleans up the C library.
-func Shutdown() {
- C.cbm_shutdown()
-}
-
-
-// ProfileStats holds accumulated profiling data from C extraction.
-type ProfileStats struct {
- ParseNs uint64
- ExtractNs uint64
- LspNs uint64
- PreprocessNs uint64
- FilesPreprocessed uint64
- Files uint64
-}
-
-// GetProfile returns accumulated parse/extraction timing and resets counters.
-func GetProfile() ProfileStats {
- var p, e, f C.uint64_t
- C.cbm_get_profile(&p, &e, &f)
- lsp := uint64(C.cbm_get_lsp_ns())
- ppNs := uint64(C.cbm_get_preprocess_ns())
- ppFiles := uint64(C.cbm_get_files_preprocessed())
- C.cbm_reset_profile()
- return ProfileStats{
- ParseNs: uint64(p),
- ExtractNs: uint64(e),
- LspNs: lsp,
- PreprocessNs: ppNs,
- FilesPreprocessed: ppFiles,
- Files: uint64(f),
- }
-}
-
-// languageToC maps Go lang.Language to CBMLanguage enum.
-var languageToC = map[lang.Language]C.CBMLanguage{
- lang.Go: C.CBM_LANG_GO,
- lang.Python: C.CBM_LANG_PYTHON,
- lang.JavaScript: C.CBM_LANG_JAVASCRIPT,
- lang.TypeScript: C.CBM_LANG_TYPESCRIPT,
- lang.TSX: C.CBM_LANG_TSX,
- lang.Rust: C.CBM_LANG_RUST,
- lang.Java: C.CBM_LANG_JAVA,
- lang.CPP: C.CBM_LANG_CPP,
- lang.CSharp: C.CBM_LANG_CSHARP,
- lang.PHP: C.CBM_LANG_PHP,
- lang.Lua: C.CBM_LANG_LUA,
- lang.Scala: C.CBM_LANG_SCALA,
- lang.Kotlin: C.CBM_LANG_KOTLIN,
- lang.Ruby: C.CBM_LANG_RUBY,
- lang.C: C.CBM_LANG_C,
- lang.Bash: C.CBM_LANG_BASH,
- lang.Zig: C.CBM_LANG_ZIG,
- lang.Elixir: C.CBM_LANG_ELIXIR,
- lang.Haskell: C.CBM_LANG_HASKELL,
- lang.OCaml: C.CBM_LANG_OCAML,
- lang.ObjectiveC: C.CBM_LANG_OBJC,
- lang.Swift: C.CBM_LANG_SWIFT,
- lang.Dart: C.CBM_LANG_DART,
- lang.Perl: C.CBM_LANG_PERL,
- lang.Groovy: C.CBM_LANG_GROOVY,
- lang.Erlang: C.CBM_LANG_ERLANG,
- lang.R: C.CBM_LANG_R,
- lang.HTML: C.CBM_LANG_HTML,
- lang.CSS: C.CBM_LANG_CSS,
- lang.SCSS: C.CBM_LANG_SCSS,
- lang.YAML: C.CBM_LANG_YAML,
- lang.TOML: C.CBM_LANG_TOML,
- lang.HCL: C.CBM_LANG_HCL,
- lang.SQL: C.CBM_LANG_SQL,
- lang.Dockerfile: C.CBM_LANG_DOCKERFILE,
- // New languages (v0.5 expansion)
- lang.Clojure: C.CBM_LANG_CLOJURE,
- lang.FSharp: C.CBM_LANG_FSHARP,
- lang.Julia: C.CBM_LANG_JULIA,
- lang.VimScript: C.CBM_LANG_VIMSCRIPT,
- lang.Nix: C.CBM_LANG_NIX,
- lang.CommonLisp: C.CBM_LANG_COMMONLISP,
- lang.Elm: C.CBM_LANG_ELM,
- lang.Fortran: C.CBM_LANG_FORTRAN,
- lang.CUDA: C.CBM_LANG_CUDA,
- lang.COBOL: C.CBM_LANG_COBOL,
- lang.Verilog: C.CBM_LANG_VERILOG,
- lang.EmacsLisp: C.CBM_LANG_EMACSLISP,
- lang.JSON: C.CBM_LANG_JSON,
- lang.XML: C.CBM_LANG_XML,
- lang.Markdown: C.CBM_LANG_MARKDOWN,
- lang.Makefile: C.CBM_LANG_MAKEFILE,
- lang.CMake: C.CBM_LANG_CMAKE,
- lang.Protobuf: C.CBM_LANG_PROTOBUF,
- lang.GraphQL: C.CBM_LANG_GRAPHQL,
- lang.Vue: C.CBM_LANG_VUE,
- lang.Svelte: C.CBM_LANG_SVELTE,
- lang.Meson: C.CBM_LANG_MESON,
- lang.GLSL: C.CBM_LANG_GLSL,
- lang.INI: C.CBM_LANG_INI,
- // Scientific/math languages
- lang.MATLAB: C.CBM_LANG_MATLAB,
- lang.Lean: C.CBM_LANG_LEAN,
- lang.FORM: C.CBM_LANG_FORM,
- lang.Magma: C.CBM_LANG_MAGMA,
- lang.Wolfram: C.CBM_LANG_WOLFRAM,
-}
-
-// ParseTimeoutMicros is the default per-file parse timeout (10 seconds).
-const ParseTimeoutMicros = 10_000_000
-
-// ExtractionFlags holds optional compile flags for C/C++ preprocessing.
-type ExtractionFlags struct {
- IncludePaths []string // -I paths for #include resolution
- Defines []string // -D defines as "NAME=VALUE" or "NAME"
-}
-
-// ExtractFile runs the C extraction library on one file.
-// source is the file content, language is the programming language,
-// project and relPath are used for qualified name computation.
-func ExtractFile(source []byte, language lang.Language, project, relPath string) (*FileResult, error) {
- return ExtractFileWithFlags(source, language, project, relPath, nil)
-}
-
-// ExtractFileWithFlags runs extraction with optional compile flags for C/C++ preprocessing.
-func ExtractFileWithFlags(source []byte, language lang.Language, project, relPath string, flags *ExtractionFlags) (*FileResult, error) {
- Init()
-
- if len(source) == 0 {
- return &FileResult{}, nil
- }
-
- cLang, ok := languageToC[language]
- if !ok {
- return nil, fmt.Errorf("cbm: unsupported language %q", language)
- }
-
- cSource := (*C.char)(unsafe.Pointer(&source[0]))
- cSourceLen := C.int(len(source))
- cProject := C.CString(project)
- cRelPath := C.CString(relPath)
- defer C.free(unsafe.Pointer(cProject))
- defer C.free(unsafe.Pointer(cRelPath))
-
- // Build C string arrays for defines and include paths
- var cDefines **C.char
- var cIncludes **C.char
- var toFree []unsafe.Pointer
-
- if flags != nil {
- if len(flags.Defines) > 0 {
- cDefines = buildCStringArray(flags.Defines, &toFree)
- }
- if len(flags.IncludePaths) > 0 {
- cIncludes = buildCStringArray(flags.IncludePaths, &toFree)
- }
- }
- defer func() {
- for _, p := range toFree {
- C.free(p)
- }
- }()
-
- cResult := C.cbm_extract_file(cSource, cSourceLen, cLang, cProject, cRelPath,
- C.int64_t(ParseTimeoutMicros), cDefines, cIncludes)
- if cResult == nil {
- return nil, fmt.Errorf("cbm: extraction returned nil")
- }
-
- if cResult.has_error {
- C.cbm_free_result(cResult)
- return nil, fmt.Errorf("cbm: %s", C.GoString(cResult.error_msg))
- }
-
- // Retain cached tree for cross-file LSP reuse.
- // Detach from C result so cbm_free_result doesn't free it.
- treeHandle := unsafe.Pointer(cResult.cached_tree)
- treeLang := int(cResult.cached_lang)
- cResult.cached_tree = nil
-
- goResult := convertResult(cResult)
- goResult.TreeHandle = treeHandle
- goResult.TreeLang = treeLang
-
- C.cbm_free_result(cResult)
- return goResult, nil
-}
-
-// buildCStringArray creates a NULL-terminated C string array from Go strings.
-func buildCStringArray(strs []string, toFree *[]unsafe.Pointer) **C.char {
- n := len(strs)
- ptrSize := C.size_t(unsafe.Sizeof((*C.char)(nil)))
- arr := (**C.char)(C.malloc(C.size_t(n+1) * ptrSize))
- *toFree = append(*toFree, unsafe.Pointer(arr))
-
- slice := unsafe.Slice(arr, n+1)
- for i, s := range strs {
- cs := C.CString(s)
- *toFree = append(*toFree, unsafe.Pointer(cs))
- slice[i] = cs
- }
- slice[n] = nil // NULL terminator
- return arr
-}
-
-func convertResult(r *C.CBMFileResult) *FileResult {
- fr := &FileResult{
- ModuleQN: C.GoString(r.module_qn),
- IsTestFile: bool(r.is_test_file),
- ImportCount: int(r.imports_count),
- }
-
- // Definitions
- if r.defs.count > 0 {
- fr.Definitions = make([]Definition, r.defs.count)
- defs := unsafe.Slice(r.defs.items, r.defs.count)
- for i := range defs {
- d := &defs[i]
- fr.Definitions[i] = Definition{
- Name: C.GoString(d.name),
- QualifiedName: C.GoString(d.qualified_name),
- Label: C.GoString(d.label),
- FilePath: C.GoString(d.file_path),
- StartLine: int(d.start_line),
- EndLine: int(d.end_line),
- Signature: goStringOrEmpty(d.signature),
- ReturnType: goStringOrEmpty(d.return_type),
- Receiver: goStringOrEmpty(d.receiver),
- Docstring: goStringOrEmpty(d.docstring),
- ParentClass: goStringOrEmpty(d.parent_class),
- Decorators: goStringSlice(d.decorators),
- BaseClasses: goStringSlice(d.base_classes),
- ParamNames: goStringSlice(d.param_names),
- ParamTypes: goStringSlice(d.param_types),
- ReturnTypes: goStringSlice(d.return_types),
- Complexity: int(d.complexity),
- Lines: int(d.lines),
- IsExported: bool(d.is_exported),
- IsAbstract: bool(d.is_abstract),
- IsTest: bool(d.is_test),
- IsEntryPoint: bool(d.is_entry_point),
- }
- }
- }
-
- // Calls
- if r.calls.count > 0 {
- fr.Calls = make([]Call, r.calls.count)
- calls := unsafe.Slice(r.calls.items, r.calls.count)
- for i, c := range calls {
- fr.Calls[i] = Call{
- CalleeName: C.GoString(c.callee_name),
- EnclosingFuncQN: C.GoString(c.enclosing_func_qn),
- }
- }
- }
-
- // Imports
- if r.imports.count > 0 {
- fr.Imports = make([]Import, r.imports.count)
- imports := unsafe.Slice(r.imports.items, r.imports.count)
- for i, imp := range imports {
- fr.Imports[i] = Import{
- LocalName: C.GoString(imp.local_name),
- ModulePath: C.GoString(imp.module_path),
- }
- }
- }
-
- // Usages
- if r.usages.count > 0 {
- fr.Usages = make([]Usage, r.usages.count)
- usages := unsafe.Slice(r.usages.items, r.usages.count)
- for i, u := range usages {
- fr.Usages[i] = Usage{
- RefName: C.GoString(u.ref_name),
- EnclosingFuncQN: C.GoString(u.enclosing_func_qn),
- }
- }
- }
-
- // Throws
- if r.throws.count > 0 {
- fr.Throws = make([]Throw, r.throws.count)
- throws := unsafe.Slice(r.throws.items, r.throws.count)
- for i, t := range throws {
- fr.Throws[i] = Throw{
- ExceptionName: C.GoString(t.exception_name),
- EnclosingFuncQN: C.GoString(t.enclosing_func_qn),
- }
- }
- }
-
- // ReadWrites
- if r.rw.count > 0 {
- fr.ReadWrites = make([]ReadWrite, r.rw.count)
- rws := unsafe.Slice(r.rw.items, r.rw.count)
- for i, rw := range rws {
- fr.ReadWrites[i] = ReadWrite{
- VarName: C.GoString(rw.var_name),
- EnclosingFuncQN: C.GoString(rw.enclosing_func_qn),
- IsWrite: bool(rw.is_write),
- }
- }
- }
-
- // TypeRefs
- if r.type_refs.count > 0 {
- fr.TypeRefs = make([]TypeRef, r.type_refs.count)
- refs := unsafe.Slice(r.type_refs.items, r.type_refs.count)
- for i, tr := range refs {
- fr.TypeRefs[i] = TypeRef{
- TypeName: C.GoString(tr.type_name),
- EnclosingFuncQN: C.GoString(tr.enclosing_func_qn),
- }
- }
- }
-
- // EnvAccesses
- if r.env_accesses.count > 0 {
- fr.EnvAccesses = make([]EnvAccess, r.env_accesses.count)
- envs := unsafe.Slice(r.env_accesses.items, r.env_accesses.count)
- for i, ea := range envs {
- fr.EnvAccesses[i] = EnvAccess{
- EnvKey: C.GoString(ea.env_key),
- EnclosingFuncQN: C.GoString(ea.enclosing_func_qn),
- }
- }
- }
-
- // TypeAssigns
- if r.type_assigns.count > 0 {
- fr.TypeAssigns = make([]TypeAssign, r.type_assigns.count)
- assigns := unsafe.Slice(r.type_assigns.items, r.type_assigns.count)
- for i, ta := range assigns {
- fr.TypeAssigns[i] = TypeAssign{
- VarName: C.GoString(ta.var_name),
- TypeName: C.GoString(ta.type_name),
- EnclosingFuncQN: C.GoString(ta.enclosing_func_qn),
- }
- }
- }
-
- // ImplTraits (Rust)
- if r.impl_traits.count > 0 {
- fr.ImplTraits = make([]ImplTrait, r.impl_traits.count)
- traits := unsafe.Slice(r.impl_traits.items, r.impl_traits.count)
- for i, it := range traits {
- fr.ImplTraits[i] = ImplTrait{
- TraitName: C.GoString(it.trait_name),
- StructName: C.GoString(it.struct_name),
- }
- }
- }
-
- // ResolvedCalls (LSP)
- if r.resolved_calls.count > 0 {
- fr.ResolvedCalls = make([]ResolvedCall, r.resolved_calls.count)
- rcs := unsafe.Slice(r.resolved_calls.items, r.resolved_calls.count)
- for i, rc := range rcs {
- fr.ResolvedCalls[i] = ResolvedCall{
- CallerQN: C.GoString(rc.caller_qn),
- CalleeQN: C.GoString(rc.callee_qn),
- Strategy: C.GoString(rc.strategy),
- Confidence: float32(rc.confidence),
- Reason: goStringOrEmpty(rc.reason),
- }
- }
- }
-
- return fr
-}
-
-func goStringOrEmpty(s *C.char) string {
- if s == nil {
- return ""
- }
- return C.GoString(s)
-}
-
-func goStringSlice(arr **C.char) []string {
- if arr == nil {
- return nil
- }
- var result []string
- for i := 0; ; i++ {
- ptr := *(**C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(arr)) + uintptr(i)*unsafe.Sizeof(arr)))
- if ptr == nil {
- break
- }
- result = append(result, C.GoString(ptr))
- }
- return result
-}
diff --git a/internal/cbm/cbm_test.go b/internal/cbm/cbm_test.go
deleted file mode 100644
index ed0ba7e52..000000000
--- a/internal/cbm/cbm_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package cbm
-
-import (
- "fmt"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-func TestPythonDocstring(t *testing.T) {
- source := []byte("def compute(x, y):\n \"\"\"Compute the sum of x and y.\"\"\"\n return x + y\n")
- result, err := ExtractFile(source, lang.Python, "test", "test.py")
- if err != nil {
- t.Fatal(err)
- }
- fmt.Printf("Defs: %d\n", len(result.Definitions))
- for _, d := range result.Definitions {
- fmt.Printf(" Name=%q Label=%q QN=%q Doc=%q Sig=%q\n", d.Name, d.Label, d.QualifiedName, d.Docstring, d.Signature)
- }
- if len(result.Definitions) == 0 {
- t.Fatal("no definitions extracted")
- }
- found := false
- for _, d := range result.Definitions {
- if d.Name == "compute" {
- found = true
- if d.Docstring == "" {
- t.Error("docstring is empty for compute")
- }
- t.Logf("docstring: %q", d.Docstring)
- }
- }
- if !found {
- t.Error("compute function not found")
- }
-}
-
-func TestGoFunctionExtraction(t *testing.T) {
- source := []byte(`package main
-
-// Greet returns a greeting.
-func Greet(name string) string {
- return "Hello, " + name
-}
-
-func main() {
- Greet("world")
-}
-`)
- result, err := ExtractFile(source, lang.Go, "test", "main.go")
- if err != nil {
- t.Fatal(err)
- }
- fmt.Printf("Defs: %d, Calls: %d, Imports: %d\n", len(result.Definitions), len(result.Calls), len(result.Imports))
- for _, d := range result.Definitions {
- fmt.Printf(" Name=%q Label=%q QN=%q Sig=%q Doc=%q\n", d.Name, d.Label, d.QualifiedName, d.Signature, d.Docstring)
- }
- for _, c := range result.Calls {
- fmt.Printf(" Call: callee=%q enclosing=%q\n", c.CalleeName, c.EnclosingFuncQN)
- }
-}
-
-func TestJSArrowFunction(t *testing.T) {
- source := []byte(`const greet = (name) => {
- return "Hello " + name;
-};
-
-const result = greet("world");
-`)
- result, err := ExtractFile(source, lang.JavaScript, "test", "app.js")
- if err != nil {
- t.Fatal(err)
- }
- fmt.Printf("Defs: %d\n", len(result.Definitions))
- for _, d := range result.Definitions {
- fmt.Printf(" Name=%q Label=%q QN=%q\n", d.Name, d.Label, d.QualifiedName)
- }
-}
diff --git a/internal/cbm/cgo_windows.go b/internal/cbm/cgo_windows.go
deleted file mode 100644
index 8ee190757..000000000
--- a/internal/cbm/cgo_windows.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package cbm
-
-// GCC 15.2.0 (MSYS2 UCRT64) introduced a regression where __imp__wctype
-// from corecrt_wctype.h is no longer a selectany weak symbol, causing
-// "multiple definition" linker errors when many CGo object files are linked.
-// --allow-multiple-definition is the standard workaround for large CGo projects.
-
-/*
-#cgo windows LDFLAGS: -Wl,--allow-multiple-definition
-*/
-import "C"
diff --git a/internal/cbm/config_extraction_test.go b/internal/cbm/config_extraction_test.go
deleted file mode 100644
index d95cfead8..000000000
--- a/internal/cbm/config_extraction_test.go
+++ /dev/null
@@ -1,404 +0,0 @@
-package cbm
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// --- TOML Tests ---
-
-func TestTOMLBasicTableAndPair(t *testing.T) {
- source := []byte("[database]\nhost = \"localhost\"\nport = 5432\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) != 1 || classes[0].Name != "database" {
- t.Errorf("expected 1 Class 'database', got %d: %v", len(classes), names(classes))
- }
- if len(vars) < 2 {
- t.Errorf("expected >=2 Variables (host, port), got %d: %v", len(vars), names(vars))
- }
- assertHasName(t, vars, "host")
- assertHasName(t, vars, "port")
-}
-
-func TestTOMLNestedTable(t *testing.T) {
- source := []byte("[server.http]\nport = 8080\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- if len(classes) < 1 {
- t.Errorf("expected >=1 Class for nested table, got %d", len(classes))
- }
-}
-
-func TestTOMLTableArrayElement(t *testing.T) {
- source := []byte("[[servers]]\nname = \"alpha\"\n[[servers]]\nname = \"beta\"\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) < 2 {
- t.Errorf("expected >=2 Classes for table array, got %d: %v", len(classes), names(classes))
- }
- if len(vars) < 2 {
- t.Errorf("expected >=2 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestTOMLDottedKey(t *testing.T) {
- source := []byte("database.host = \"localhost\"\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 1 {
- t.Errorf("expected >=1 Variable for dotted key, got %d", len(vars))
- }
-}
-
-func TestTOMLQuotedKey(t *testing.T) {
- source := []byte("\"unusual-key\" = \"value\"\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 1 {
- t.Errorf("expected >=1 Variable for quoted key, got %d", len(vars))
- }
-}
-
-func TestTOMLEmptyTable(t *testing.T) {
- source := []byte("[empty]\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) != 1 || classes[0].Name != "empty" {
- t.Errorf("expected 1 Class 'empty', got %d: %v", len(classes), names(classes))
- }
- if len(vars) != 0 {
- t.Errorf("expected 0 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestTOMLCommentsOnly(t *testing.T) {
- source := []byte("# just a comment\n# another comment\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) != 0 {
- t.Errorf("expected 0 Classes, got %d: %v", len(classes), names(classes))
- }
- if len(vars) != 0 {
- t.Errorf("expected 0 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestTOMLBooleanAndIntegerValues(t *testing.T) {
- source := []byte("enabled = true\ncount = 42\nname = \"test\"\n")
- result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 3 {
- t.Errorf("expected >=3 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-// --- INI Tests ---
-
-func TestINIBasicSectionAndSetting(t *testing.T) {
- source := []byte("[database]\nhost = localhost\nport = 5432\n")
- result, err := ExtractFile(source, lang.INI, "test", "config.ini")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) < 1 {
- t.Errorf("expected >=1 Class (database section), got %d: %v", len(classes), names(classes))
- }
- if len(vars) < 2 {
- t.Errorf("expected >=2 Variables (host, port), got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestINIMultipleSections(t *testing.T) {
- source := []byte("[section1]\nkey1 = val1\n[section2]\nkey2 = val2\n")
- result, err := ExtractFile(source, lang.INI, "test", "config.ini")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) < 2 {
- t.Errorf("expected >=2 Classes, got %d: %v", len(classes), names(classes))
- }
- if len(vars) < 2 {
- t.Errorf("expected >=2 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestINIGlobalKeys(t *testing.T) {
- source := []byte("key1 = value1\nkey2 = value2\n")
- result, err := ExtractFile(source, lang.INI, "test", "config.ini")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) != 0 {
- t.Errorf("expected 0 Classes (no sections), got %d: %v", len(classes), names(classes))
- }
- if len(vars) < 2 {
- t.Errorf("expected >=2 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestINIComments(t *testing.T) {
- source := []byte("; comment\n# another comment\n[section]\nkey = val\n")
- result, err := ExtractFile(source, lang.INI, "test", "config.ini")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- vars := defsWithLabel(result, "Variable")
- if len(classes) < 1 {
- t.Errorf("expected >=1 Class, got %d: %v", len(classes), names(classes))
- }
- if len(vars) < 1 {
- t.Errorf("expected >=1 Variable, got %d: %v", len(vars), names(vars))
- }
-}
-
-// --- JSON Tests ---
-
-func TestJSONBasicPair(t *testing.T) {
- source := []byte(`{"host": "localhost", "port": 5432}`)
- result, err := ExtractFile(source, lang.JSON, "test", "config.json")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 2 {
- t.Errorf("expected >=2 Variables (host, port), got %d: %v", len(vars), names(vars))
- }
- assertHasName(t, vars, "host")
- assertHasName(t, vars, "port")
-}
-
-func TestJSONNestedObject(t *testing.T) {
- source := []byte(`{"database": {"host": "localhost", "port": 5432}}`)
- result, err := ExtractFile(source, lang.JSON, "test", "config.json")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 3 {
- t.Errorf("expected >=3 Variables (database, host, port), got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestJSONEmptyObject(t *testing.T) {
- source := []byte(`{}`)
- result, err := ExtractFile(source, lang.JSON, "test", "config.json")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) != 0 {
- t.Errorf("expected 0 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestJSONBooleanNullValues(t *testing.T) {
- source := []byte(`{"enabled": true, "value": null, "name": "test"}`)
- result, err := ExtractFile(source, lang.JSON, "test", "config.json")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 3 {
- t.Errorf("expected >=3 Variables, got %d: %v", len(vars), names(vars))
- }
-}
-
-func TestJSONPackageJsonDeps(t *testing.T) {
- source := []byte(`{"name":"pkg","dependencies":{"express":"^4.0","lodash":"^4.17"}}`)
- result, err := ExtractFile(source, lang.JSON, "test", "package.json")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- if len(vars) < 4 {
- t.Errorf("expected >=4 Variables (name, dependencies, express, lodash), got %d: %v", len(vars), names(vars))
- }
- assertHasName(t, vars, "name")
- assertHasName(t, vars, "dependencies")
- assertHasName(t, vars, "express")
- assertHasName(t, vars, "lodash")
-}
-
-// --- XML Tests ---
-
-func TestXMLBasicElement(t *testing.T) {
- source := []byte(`<?xml version="1.0"?><config><database><host>localhost</host></database></config>`)
- result, err := ExtractFile(source, lang.XML, "test", "config.xml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- if len(classes) < 3 {
- t.Errorf("expected >=3 Classes (config, database, host), got %d: %v", len(classes), names(classes))
- }
- assertHasName(t, classes, "config")
- assertHasName(t, classes, "database")
- assertHasName(t, classes, "host")
-}
-
-func TestXMLSelfClosingTag(t *testing.T) {
- source := []byte(`<?xml version="1.0"?><config><feature enabled="true"/></config>`)
- result, err := ExtractFile(source, lang.XML, "test", "config.xml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- if len(classes) < 2 {
- t.Errorf("expected >=2 Classes (config, feature), got %d: %v", len(classes), names(classes))
- }
-}
-
-func TestXMLEmptyDocument(t *testing.T) {
- source := []byte(`<?xml version="1.0"?><root/>`)
- result, err := ExtractFile(source, lang.XML, "test", "config.xml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- if len(classes) < 1 {
- t.Errorf("expected >=1 Class (root), got %d: %v", len(classes), names(classes))
- }
-}
-
-func TestXMLMultipleChildren(t *testing.T) {
- source := []byte(`<?xml version="1.0"?><servers><server/><server/><server/></servers>`)
- result, err := ExtractFile(source, lang.XML, "test", "config.xml")
- if err != nil {
- t.Fatal(err)
- }
- classes := defsWithLabel(result, "Class")
- // servers + 3x server = 4
- if len(classes) < 4 {
- t.Errorf("expected >=4 Classes (servers + 3x server), got %d: %v", len(classes), names(classes))
- }
-}
-
-// --- Markdown Tests ---
-
-func TestMarkdownATXHeadings(t *testing.T) {
- source := []byte("# Title\n## Section\n### Subsection\n")
- result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
- if err != nil {
- t.Fatal(err)
- }
- sections := defsWithLabel(result, "Section")
- if len(sections) < 3 {
- t.Errorf("expected >=3 Section nodes, got %d: %v", len(sections), names(sections))
- }
- // Must NOT produce Class nodes
- classes := defsWithLabel(result, "Class")
- if len(classes) != 0 {
- t.Errorf("Markdown should produce Section, not Class, got %d Class nodes", len(classes))
- }
-}
-
-func TestMarkdownSetextHeadings(t *testing.T) {
- source := []byte("Title\n=====\nSection\n------\n")
- result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
- if err != nil {
- t.Fatal(err)
- }
- sections := defsWithLabel(result, "Section")
- if len(sections) < 2 {
- t.Errorf("expected >=2 Section nodes, got %d: %v", len(sections), names(sections))
- }
-}
-
-func TestMarkdownHeadingContent(t *testing.T) {
- source := []byte("# Installation Guide\n## Prerequisites\n## Setup\n")
- result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
- if err != nil {
- t.Fatal(err)
- }
- sections := defsWithLabel(result, "Section")
- if len(sections) < 3 {
- t.Errorf("expected >=3 Section nodes, got %d: %v", len(sections), names(sections))
- }
- assertHasName(t, sections, "Installation Guide")
- assertHasName(t, sections, "Prerequisites")
- assertHasName(t, sections, "Setup")
-}
-
-func TestMarkdownNoHeadings(t *testing.T) {
- source := []byte("Just a paragraph\n\nAnother paragraph\n")
- result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
- if err != nil {
- t.Fatal(err)
- }
- sections := defsWithLabel(result, "Section")
- if len(sections) != 0 {
- t.Errorf("expected 0 Sections, got %d: %v", len(sections), names(sections))
- }
-}
-
-// --- Test Helpers ---
-
-type defInfo struct {
- Name string
- Label string
-}
-
-func defsWithLabel(result *FileResult, label string) []defInfo {
- var out []defInfo
- for _, d := range result.Definitions {
- if d.Label == label {
- out = append(out, defInfo{Name: d.Name, Label: d.Label})
- }
- }
- return out
-}
-
-func names(defs []defInfo) []string {
- var out []string
- for _, d := range defs {
- out = append(out, d.Name)
- }
- return out
-}
-
-func assertHasName(t *testing.T, defs []defInfo, name string) {
- t.Helper()
- for _, d := range defs {
- if d.Name == name {
- return
- }
- }
- t.Errorf("expected to find name %q in %v", name, names(defs))
-}
diff --git a/internal/cbm/language_failures_test.go b/internal/cbm/language_failures_test.go
deleted file mode 100644
index f3e21a7e0..000000000
--- a/internal/cbm/language_failures_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package cbm
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// =====================================================================
-// CONFIRMED RED: CommonLisp — defun never matched (empty func_types)
-// =====================================================================
-
-func TestCommonLispDefunExtraction(t *testing.T) {
- source := []byte("(defun hello () \"world\")\n")
- result, err := ExtractFile(source, lang.CommonLisp, "test", "hello.lisp")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) == 0 {
- t.Errorf("expected >=1 Function from CommonLisp defun, got 0 (commonlisp_func_types is empty)")
- }
- assertHasName(t, fns, "hello")
-}
-
-func TestCommonLispMultipleFunctions(t *testing.T) {
- source := []byte("(defun add (a b) (+ a b))\n(defun mul (a b) (* a b))\n")
- result, err := ExtractFile(source, lang.CommonLisp, "test", "math.lisp")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) < 2 {
- t.Errorf("expected >=2 Functions (add, mul), got %d: %v", len(fns), names(fns))
- }
- assertHasName(t, fns, "add")
- assertHasName(t, fns, "mul")
-}
-
-func TestCommonLispDefmacro(t *testing.T) {
- source := []byte("(defmacro when2 (condition &body body)\n `(if ,condition (progn ,@body)))\n")
- result, err := ExtractFile(source, lang.CommonLisp, "test", "macros.lisp")
- if err != nil {
- t.Fatal(err)
- }
- // defmacro is a separate node type; this test just ensures no crash
- _ = result
-}
-
-// =====================================================================
-// CONFIRMED RED: Makefile — rule not in function_node_types
-// =====================================================================
-
-func TestMakefileRuleAsFunction(t *testing.T) {
- source := []byte("all:\n\t@echo hello\n")
- result, err := ExtractFile(source, lang.Makefile, "test", "Makefile")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) == 0 {
- t.Errorf("expected >=1 Function (target 'all'), got 0 (rule not in func_types)")
- }
- assertHasName(t, fns, "all")
-}
-
-func TestMakefileMultipleTargets(t *testing.T) {
- source := []byte("all: main.o\n\tgcc -o all main.o\n\nbuild:\n\tgo build ./...\n")
- result, err := ExtractFile(source, lang.Makefile, "test", "Makefile")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) < 2 {
- t.Errorf("expected >=2 Functions (all, build), got %d: %v", len(fns), names(fns))
- }
- assertHasName(t, fns, "all")
- assertHasName(t, fns, "build")
-}
-
-func TestMakefileVariableExtraction(t *testing.T) {
- source := []byte("CC := gcc\nCFLAGS := -Wall\n")
- result, err := ExtractFile(source, lang.Makefile, "test", "Makefile")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(result, "Variable")
- // variable_assignment is in VariableNodeTypes; this probe reveals if name extraction works
- if len(vars) == 0 {
- t.Logf("INFO: Makefile variable extraction returns 0 vars — name field may need a Makefile case in extract_var_names")
- } else {
- assertHasName(t, vars, "CC")
- assertHasName(t, vars, "CFLAGS")
- }
-}
-
-// =====================================================================
-// PROBE: VimScript — may pass or fail; reveals root cause
-// =====================================================================
-
-func TestVimScriptFunctionExtraction(t *testing.T) {
- source := []byte("function! SayHello()\n echo 'Hello'\nendfunction\n")
- result, err := ExtractFile(source, lang.VimScript, "test", "plugin.vim")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) == 0 {
- t.Errorf("expected >=1 Function from VimScript function!, got 0 — name field on function_definition may not be exposed directly")
- }
- assertHasName(t, fns, "SayHello")
-}
-
-func TestVimScriptFunctionWithoutBang(t *testing.T) {
- source := []byte("function MyFunc(arg)\n return arg\nendfunction\n")
- result, err := ExtractFile(source, lang.VimScript, "test", "plugin.vim")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) == 0 {
- t.Errorf("expected >=1 Function from VimScript function (no bang), got 0")
- }
- assertHasName(t, fns, "MyFunc")
-}
-
-// =====================================================================
-// PROBE: Julia — may pass or fail; reveals whether 0.00 is grammar or discovery
-// =====================================================================
-
-func TestJuliaFunctionExtraction(t *testing.T) {
- source := []byte("function hello()\n println(\"Hello, World!\")\nend\n")
- result, err := ExtractFile(source, lang.Julia, "test", "hello.jl")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) == 0 {
- t.Errorf("expected >=1 Function from Julia function_definition, got 0")
- }
- assertHasName(t, fns, "hello")
-}
-
-func TestJuliaFunctionWithArgs(t *testing.T) {
- source := []byte("function add(a::Int, b::Int)::Int\n return a + b\nend\n")
- result, err := ExtractFile(source, lang.Julia, "test", "math.jl")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(result, "Function")
- if len(fns) == 0 {
- t.Errorf("expected >=1 Function from Julia function with args, got 0")
- }
- assertHasName(t, fns, "add")
-}
diff --git a/internal/cbm/lsp_bridge.go b/internal/cbm/lsp_bridge.go
deleted file mode 100644
index 765ebab3a..000000000
--- a/internal/cbm/lsp_bridge.go
+++ /dev/null
@@ -1,647 +0,0 @@
-package cbm
-
-//go:generate go run ../../scripts/gen-go-stdlib.go
-
-/*
-#include "lsp/type_rep.h"
-#include "lsp/scope.h"
-#include "lsp/type_registry.h"
-#include "lsp/go_lsp.h"
-#include "lsp/c_lsp.h"
-*/
-import "C"
-import (
- "strings"
- "unsafe"
-)
-
-// CrossFileDef represents a definition from another file for cross-file LSP resolution.
-type CrossFileDef struct {
- QualifiedName string
- ShortName string
- Label string // "Function", "Method", "Type", "Interface"
- ReceiverType string // for methods: receiver type QN
- DefModuleQN string // module QN where this def lives
- ReturnTypes string // "|"-separated return type texts (e.g., "*File|error")
- EmbeddedTypes string // "|"-separated embedded type QNs
- FieldDefs string // "|"-separated "name:type" pairs (for struct fields, e.g. "Binder:Binder|Name:string")
- MethodNames string // "|"-separated method names for interfaces (e.g. "Get|Put|Delete")
- IsInterface bool
-}
-
-// RunGoLSPCrossFile runs the Go LSP type resolver with cross-file definitions.
-// source is the file content, moduleQN is the file's module QN,
-// fileDefs are the file's own definitions (converted to CrossFileDef format),
-// crossDefs are definitions from imported packages,
-// imports are the file's import mappings.
-// Returns resolved calls with high confidence.
-func RunGoLSPCrossFile(
- source []byte,
- moduleQN string,
- fileDefs []CrossFileDef,
- crossDefs []CrossFileDef,
- imports []Import,
- cachedTree unsafe.Pointer, // *C.TSTree or nil
-) []ResolvedCall {
- if len(source) == 0 {
- return nil
- }
-
- Init()
-
- // Merge file-local and cross-file defs
- allDefs := make([]CrossFileDef, 0, len(fileDefs)+len(crossDefs))
- allDefs = append(allDefs, fileDefs...)
- allDefs = append(allDefs, crossDefs...)
-
- if len(allDefs) == 0 {
- return nil
- }
-
- // Allocate arena for C data
- var arena C.CBMArena
- C.cbm_arena_init(&arena)
- defer C.cbm_arena_destroy(&arena)
-
- // Track C strings for cleanup
- var toFree []unsafe.Pointer
- defer func() {
- for _, p := range toFree {
- C.free(p)
- }
- }()
-
- cs := func(s string) *C.char {
- if s == "" {
- return nil
- }
- p := C.CString(s)
- toFree = append(toFree, unsafe.Pointer(p))
- return p
- }
-
- // Build C def array
- nDefs := len(allDefs)
- cDefsPtr := (*C.CBMLSPDef)(C.malloc(C.size_t(nDefs) * C.size_t(unsafe.Sizeof(C.CBMLSPDef{}))))
- if cDefsPtr == nil {
- return nil
- }
- toFree = append(toFree, unsafe.Pointer(cDefsPtr))
- cDefs := unsafe.Slice(cDefsPtr, nDefs)
-
- for i, d := range allDefs {
- cDefs[i] = C.CBMLSPDef{
- qualified_name: cs(d.QualifiedName),
- short_name: cs(d.ShortName),
- label: cs(d.Label),
- receiver_type: cs(d.ReceiverType),
- def_module_qn: cs(d.DefModuleQN),
- return_types: cs(d.ReturnTypes),
- embedded_types: cs(d.EmbeddedTypes),
- field_defs: cs(d.FieldDefs),
- method_names_str: cs(d.MethodNames),
- is_interface: C.bool(d.IsInterface),
- }
- }
-
- // Build import arrays
- nImports := len(imports)
- ptrSize := C.size_t(unsafe.Sizeof((*C.char)(nil)))
- cImportNames := (**C.char)(C.malloc(C.size_t(nImports+1) * ptrSize))
- cImportQNs := (**C.char)(C.malloc(C.size_t(nImports+1) * ptrSize))
- toFree = append(toFree, unsafe.Pointer(cImportNames), unsafe.Pointer(cImportQNs))
-
- importNameSlice := unsafe.Slice(cImportNames, nImports+1)
- importQNSlice := unsafe.Slice(cImportQNs, nImports+1)
- for i, imp := range imports {
- importNameSlice[i] = cs(imp.LocalName)
- importQNSlice[i] = cs(imp.ModulePath)
- }
- importNameSlice[nImports] = nil
- importQNSlice[nImports] = nil
-
- // Call C function
- cModuleQN := cs(moduleQN)
- cSource := (*C.char)(unsafe.Pointer(&source[0]))
-
- var outCalls C.CBMResolvedCallArray
- C.cbm_run_go_lsp_cross(
- &arena,
- cSource, C.int(len(source)),
- cModuleQN,
- cDefsPtr, C.int(nDefs),
- cImportNames, cImportQNs, C.int(nImports),
- (*C.TSTree)(cachedTree),
- &outCalls,
- )
-
- // Convert results to Go
- if outCalls.count == 0 {
- return nil
- }
- result := make([]ResolvedCall, outCalls.count)
- rcs := unsafe.Slice(outCalls.items, outCalls.count)
- for i, rc := range rcs {
- result[i] = ResolvedCall{
- CallerQN: C.GoString(rc.caller_qn),
- CalleeQN: C.GoString(rc.callee_qn),
- Strategy: C.GoString(rc.strategy),
- Confidence: float32(rc.confidence),
- Reason: goStringOrEmpty(rc.reason),
- }
- }
- return result
-}
-
-// DefsToLSPDefs converts file-local Definition slice to CrossFileDef format.
-func DefsToLSPDefs(defs []Definition, moduleQN string) []CrossFileDef {
- result := make([]CrossFileDef, 0, len(defs))
-
- // First pass: collect Field defs grouped by parent class QN → "name:type" pairs
- fieldsByClass := make(map[string][]string)
- for _, d := range defs {
- if d.Label == "Field" && d.ParentClass != "" && d.Name != "" && d.ReturnType != "" {
- fieldsByClass[d.ParentClass] = append(fieldsByClass[d.ParentClass],
- d.Name+":"+d.ReturnType)
- }
- }
-
- for _, d := range defs {
- if d.QualifiedName == "" || d.Name == "" {
- continue
- }
- switch d.Label {
- case "Function", "Method":
- cd := CrossFileDef{
- QualifiedName: d.QualifiedName,
- ShortName: d.Name,
- Label: d.Label,
- DefModuleQN: moduleQN,
- }
- if len(d.ReturnTypes) > 0 {
- cd.ReturnTypes = strings.Join(d.ReturnTypes, "|")
- } else if d.ReturnType != "" {
- cd.ReturnTypes = d.ReturnType
- }
- if d.Label == "Method" && d.Receiver != "" {
- cd.ReceiverType = extractReceiverTypeQN(d.Receiver, moduleQN)
- }
- result = append(result, cd)
-
- case "Class", "Type", "Interface":
- cd := CrossFileDef{
- QualifiedName: d.QualifiedName,
- ShortName: d.Name,
- Label: d.Label,
- DefModuleQN: moduleQN,
- IsInterface: d.Label == "Interface",
- }
- if len(d.BaseClasses) > 0 {
- embeds := make([]string, len(d.BaseClasses))
- for i, bc := range d.BaseClasses {
- bc = strings.TrimLeft(bc, "*")
- embeds[i] = moduleQN + "." + bc
- }
- cd.EmbeddedTypes = strings.Join(embeds, "|")
- }
- // Attach field defs collected from Field-labeled definitions
- if fields, ok := fieldsByClass[d.QualifiedName]; ok {
- cd.FieldDefs = strings.Join(fields, "|")
- }
- result = append(result, cd)
- }
- }
- return result
-}
-
-// extractReceiverTypeQN extracts the receiver type QN from Go receiver text.
-// E.g., "(r *Router)" -> "moduleQN.Router"
-func extractReceiverTypeQN(receiver, moduleQN string) string {
- r := strings.TrimLeft(receiver, "( ")
- // Skip receiver name
- if idx := strings.IndexAny(r, " *"); idx >= 0 {
- r = r[idx:]
- }
- r = strings.TrimLeft(r, " *")
- // Get type name
- end := strings.IndexAny(r, ") ")
- if end > 0 {
- r = r[:end]
- }
- if r == "" {
- return ""
- }
- return moduleQN + "." + r
-}
-
-// BatchLSPInput holds per-file data for batch Go LSP cross-file resolution.
-type BatchLSPInput struct {
- Source []byte
- ModuleQN string
- FileDefs []CrossFileDef
- CrossDefs []CrossFileDef
- Imports []Import
- CachedTree unsafe.Pointer // *C.TSTree or nil
-}
-
-// BatchCLSPInput holds per-file data for batch C/C++ LSP cross-file resolution.
-type BatchCLSPInput struct {
- Source []byte
- ModuleQN string
- CppMode bool
- FileDefs []CrossFileDef
- CrossDefs []CrossFileDef
- Includes []Import
- CachedTree unsafe.Pointer // *C.TSTree or nil
-}
-
-// BatchGoLSPCrossFile resolves all Go files' cross-file calls in batched CGo calls.
-// Uses a CString cache to deduplicate shared cross-file defs across files.
-func BatchGoLSPCrossFile(files []BatchLSPInput) [][]ResolvedCall {
- if len(files) == 0 {
- return nil
- }
-
- Init()
-
- var arena C.CBMArena
- C.cbm_arena_init(&arena)
- defer C.cbm_arena_destroy(&arena)
-
- var toFree []unsafe.Pointer
- defer func() {
- for _, p := range toFree {
- C.free(p)
- }
- }()
-
- // CString cache: deduplicates strings shared across files (cross-file defs)
- strCache := make(map[string]*C.char)
- cs := func(s string) *C.char {
- if s == "" {
- return nil
- }
- if p, ok := strCache[s]; ok {
- return p
- }
- p := C.CString(s)
- strCache[s] = p
- toFree = append(toFree, unsafe.Pointer(p))
- return p
- }
-
- nFiles := len(files)
-
- // Allocate batch file array
- cFilesPtr := (*C.CBMBatchGoLSPFile)(C.malloc(C.size_t(nFiles) * C.size_t(unsafe.Sizeof(C.CBMBatchGoLSPFile{}))))
- if cFilesPtr == nil {
- return nil
- }
- toFree = append(toFree, unsafe.Pointer(cFilesPtr))
- cFiles := unsafe.Slice(cFilesPtr, nFiles)
-
- ptrSize := C.size_t(unsafe.Sizeof((*C.char)(nil)))
-
- for i, f := range files {
- // Merge file-local + cross-file defs
- allDefs := make([]CrossFileDef, 0, len(f.FileDefs)+len(f.CrossDefs))
- allDefs = append(allDefs, f.FileDefs...)
- allDefs = append(allDefs, f.CrossDefs...)
-
- nDefs := len(allDefs)
- var cDefsPtr *C.CBMLSPDef
- if nDefs > 0 {
- cDefsPtr = (*C.CBMLSPDef)(C.malloc(C.size_t(nDefs) * C.size_t(unsafe.Sizeof(C.CBMLSPDef{}))))
- if cDefsPtr == nil {
- continue
- }
- toFree = append(toFree, unsafe.Pointer(cDefsPtr))
- cDefs := unsafe.Slice(cDefsPtr, nDefs)
- for j, d := range allDefs {
- cDefs[j] = C.CBMLSPDef{
- qualified_name: cs(d.QualifiedName),
- short_name: cs(d.ShortName),
- label: cs(d.Label),
- receiver_type: cs(d.ReceiverType),
- def_module_qn: cs(d.DefModuleQN),
- return_types: cs(d.ReturnTypes),
- embedded_types: cs(d.EmbeddedTypes),
- field_defs: cs(d.FieldDefs),
- method_names_str: cs(d.MethodNames),
- is_interface: C.bool(d.IsInterface),
- }
- }
- }
-
- // Marshal imports
- nImports := len(f.Imports)
- cImportNames := (**C.char)(C.malloc(C.size_t(nImports+1) * ptrSize))
- cImportQNs := (**C.char)(C.malloc(C.size_t(nImports+1) * ptrSize))
- toFree = append(toFree, unsafe.Pointer(cImportNames), unsafe.Pointer(cImportQNs))
-
- importNameSlice := unsafe.Slice(cImportNames, nImports+1)
- importQNSlice := unsafe.Slice(cImportQNs, nImports+1)
- for j, imp := range f.Imports {
- importNameSlice[j] = cs(imp.LocalName)
- importQNSlice[j] = cs(imp.ModulePath)
- }
- importNameSlice[nImports] = nil
- importQNSlice[nImports] = nil
-
- cFiles[i] = C.CBMBatchGoLSPFile{
- source: (*C.char)(unsafe.Pointer(&f.Source[0])),
- source_len: C.int(len(f.Source)),
- module_qn: cs(f.ModuleQN),
- cached_tree: (*C.TSTree)(f.CachedTree),
- defs: cDefsPtr,
- def_count: C.int(nDefs),
- import_names: cImportNames,
- import_qns: cImportQNs,
- import_count: C.int(nImports),
- }
- }
-
- // Allocate output array
- outPtr := (*C.CBMResolvedCallArray)(C.calloc(C.size_t(nFiles), C.size_t(unsafe.Sizeof(C.CBMResolvedCallArray{}))))
- if outPtr == nil {
- return nil
- }
- toFree = append(toFree, unsafe.Pointer(outPtr))
-
- // ONE CGo call
- C.cbm_batch_go_lsp_cross(&arena, cFilesPtr, C.int(nFiles), outPtr)
-
- // Unmarshal results
- outs := unsafe.Slice(outPtr, nFiles)
- results := make([][]ResolvedCall, nFiles)
- for i := range outs {
- if outs[i].count == 0 {
- continue
- }
- rcs := unsafe.Slice(outs[i].items, outs[i].count)
- results[i] = make([]ResolvedCall, outs[i].count)
- for j, rc := range rcs {
- results[i][j] = ResolvedCall{
- CallerQN: C.GoString(rc.caller_qn),
- CalleeQN: C.GoString(rc.callee_qn),
- Strategy: C.GoString(rc.strategy),
- Confidence: float32(rc.confidence),
- Reason: goStringOrEmpty(rc.reason),
- }
- }
- }
-
- return results
-}
-
-// BatchCLSPCrossFile resolves all C/C++ files' cross-file calls in batched CGo calls.
-func BatchCLSPCrossFile(files []BatchCLSPInput) [][]ResolvedCall {
- if len(files) == 0 {
- return nil
- }
-
- Init()
-
- var arena C.CBMArena
- C.cbm_arena_init(&arena)
- defer C.cbm_arena_destroy(&arena)
-
- var toFree []unsafe.Pointer
- defer func() {
- for _, p := range toFree {
- C.free(p)
- }
- }()
-
- strCache := make(map[string]*C.char)
- cs := func(s string) *C.char {
- if s == "" {
- return nil
- }
- if p, ok := strCache[s]; ok {
- return p
- }
- p := C.CString(s)
- strCache[s] = p
- toFree = append(toFree, unsafe.Pointer(p))
- return p
- }
-
- nFiles := len(files)
-
- cFilesPtr := (*C.CBMBatchCLSPFile)(C.malloc(C.size_t(nFiles) * C.size_t(unsafe.Sizeof(C.CBMBatchCLSPFile{}))))
- if cFilesPtr == nil {
- return nil
- }
- toFree = append(toFree, unsafe.Pointer(cFilesPtr))
- cFileSlice := unsafe.Slice(cFilesPtr, nFiles)
-
- ptrSize := C.size_t(unsafe.Sizeof((*C.char)(nil)))
-
- for i, f := range files {
- allDefs := make([]CrossFileDef, 0, len(f.FileDefs)+len(f.CrossDefs))
- allDefs = append(allDefs, f.FileDefs...)
- allDefs = append(allDefs, f.CrossDefs...)
-
- nDefs := len(allDefs)
- var cDefsPtr *C.CBMLSPDef
- if nDefs > 0 {
- cDefsPtr = (*C.CBMLSPDef)(C.malloc(C.size_t(nDefs) * C.size_t(unsafe.Sizeof(C.CBMLSPDef{}))))
- if cDefsPtr == nil {
- continue
- }
- toFree = append(toFree, unsafe.Pointer(cDefsPtr))
- cDefs := unsafe.Slice(cDefsPtr, nDefs)
- for j, d := range allDefs {
- cDefs[j] = C.CBMLSPDef{
- qualified_name: cs(d.QualifiedName),
- short_name: cs(d.ShortName),
- label: cs(d.Label),
- receiver_type: cs(d.ReceiverType),
- def_module_qn: cs(d.DefModuleQN),
- return_types: cs(d.ReturnTypes),
- embedded_types: cs(d.EmbeddedTypes),
- field_defs: cs(d.FieldDefs),
- method_names_str: cs(d.MethodNames),
- is_interface: C.bool(d.IsInterface),
- }
- }
- }
-
- nIncludes := len(f.Includes)
- cIncPaths := (**C.char)(C.malloc(C.size_t(nIncludes+1) * ptrSize))
- cIncQNs := (**C.char)(C.malloc(C.size_t(nIncludes+1) * ptrSize))
- toFree = append(toFree, unsafe.Pointer(cIncPaths), unsafe.Pointer(cIncQNs))
-
- incPathSlice := unsafe.Slice(cIncPaths, nIncludes+1)
- incQNSlice := unsafe.Slice(cIncQNs, nIncludes+1)
- for j, inc := range f.Includes {
- incPathSlice[j] = cs(inc.LocalName)
- incQNSlice[j] = cs(inc.ModulePath)
- }
- incPathSlice[nIncludes] = nil
- incQNSlice[nIncludes] = nil
-
- cFileSlice[i] = C.CBMBatchCLSPFile{
- source: (*C.char)(unsafe.Pointer(&f.Source[0])),
- source_len: C.int(len(f.Source)),
- module_qn: cs(f.ModuleQN),
- cpp_mode: C.bool(f.CppMode),
- cached_tree: (*C.TSTree)(f.CachedTree),
- defs: cDefsPtr,
- def_count: C.int(nDefs),
- include_paths: cIncPaths,
- include_ns_qns: cIncQNs,
- include_count: C.int(nIncludes),
- }
- }
-
- outPtr := (*C.CBMResolvedCallArray)(C.calloc(C.size_t(nFiles), C.size_t(unsafe.Sizeof(C.CBMResolvedCallArray{}))))
- if outPtr == nil {
- return nil
- }
- toFree = append(toFree, unsafe.Pointer(outPtr))
-
- C.cbm_batch_c_lsp_cross(&arena, cFilesPtr, C.int(nFiles), outPtr)
-
- outs := unsafe.Slice(outPtr, nFiles)
- results := make([][]ResolvedCall, nFiles)
- for i := range outs {
- if outs[i].count == 0 {
- continue
- }
- rcs := unsafe.Slice(outs[i].items, outs[i].count)
- results[i] = make([]ResolvedCall, outs[i].count)
- for j, rc := range rcs {
- results[i][j] = ResolvedCall{
- CallerQN: C.GoString(rc.caller_qn),
- CalleeQN: C.GoString(rc.callee_qn),
- Strategy: C.GoString(rc.strategy),
- Confidence: float32(rc.confidence),
- Reason: goStringOrEmpty(rc.reason),
- }
- }
- }
-
- return results
-}
-
-// RunCLSPCrossFile runs the C/C++ LSP type resolver with cross-file definitions.
-// source is the file content, moduleQN is the file's module QN,
-// cppMode enables C++ features (namespaces, classes, templates, etc.),
-// fileDefs are the file's own definitions, crossDefs are from included headers,
-// includes are the file's include mappings (header path → namespace QN).
-func RunCLSPCrossFile(
- source []byte,
- moduleQN string,
- cppMode bool,
- fileDefs []CrossFileDef,
- crossDefs []CrossFileDef,
- includes []Import,
- cachedTree unsafe.Pointer, // *C.TSTree or nil
-) []ResolvedCall {
- if len(source) == 0 {
- return nil
- }
-
- Init()
-
- allDefs := make([]CrossFileDef, 0, len(fileDefs)+len(crossDefs))
- allDefs = append(allDefs, fileDefs...)
- allDefs = append(allDefs, crossDefs...)
-
- if len(allDefs) == 0 {
- return nil
- }
-
- var arena C.CBMArena
- C.cbm_arena_init(&arena)
- defer C.cbm_arena_destroy(&arena)
-
- var toFree []unsafe.Pointer
- defer func() {
- for _, p := range toFree {
- C.free(p)
- }
- }()
-
- cs := func(s string) *C.char {
- if s == "" {
- return nil
- }
- p := C.CString(s)
- toFree = append(toFree, unsafe.Pointer(p))
- return p
- }
-
- // Build C def array
- nDefs := len(allDefs)
- cDefsPtr := (*C.CBMLSPDef)(C.malloc(C.size_t(nDefs) * C.size_t(unsafe.Sizeof(C.CBMLSPDef{}))))
- if cDefsPtr == nil {
- return nil
- }
- toFree = append(toFree, unsafe.Pointer(cDefsPtr))
- cDefs := unsafe.Slice(cDefsPtr, nDefs)
-
- for i, d := range allDefs {
- cDefs[i] = C.CBMLSPDef{
- qualified_name: cs(d.QualifiedName),
- short_name: cs(d.ShortName),
- label: cs(d.Label),
- receiver_type: cs(d.ReceiverType),
- def_module_qn: cs(d.DefModuleQN),
- return_types: cs(d.ReturnTypes),
- embedded_types: cs(d.EmbeddedTypes),
- field_defs: cs(d.FieldDefs),
- method_names_str: cs(d.MethodNames),
- is_interface: C.bool(d.IsInterface),
- }
- }
-
- // Build include arrays (header path → namespace QN)
- nIncludes := len(includes)
- ptrSize := C.size_t(unsafe.Sizeof((*C.char)(nil)))
- cIncPaths := (**C.char)(C.malloc(C.size_t(nIncludes+1) * ptrSize))
- cIncQNs := (**C.char)(C.malloc(C.size_t(nIncludes+1) * ptrSize))
- toFree = append(toFree, unsafe.Pointer(cIncPaths), unsafe.Pointer(cIncQNs))
-
- incPathSlice := unsafe.Slice(cIncPaths, nIncludes+1)
- incQNSlice := unsafe.Slice(cIncQNs, nIncludes+1)
- for i, inc := range includes {
- incPathSlice[i] = cs(inc.LocalName)
- incQNSlice[i] = cs(inc.ModulePath)
- }
- incPathSlice[nIncludes] = nil
- incQNSlice[nIncludes] = nil
-
- cModuleQN := cs(moduleQN)
- cSource := (*C.char)(unsafe.Pointer(&source[0]))
-
- var outCalls C.CBMResolvedCallArray
- C.cbm_run_c_lsp_cross(
- &arena,
- cSource, C.int(len(source)),
- cModuleQN,
- C.bool(cppMode),
- cDefsPtr, C.int(nDefs),
- cIncPaths, cIncQNs, C.int(nIncludes),
- (*C.TSTree)(cachedTree),
- &outCalls,
- )
-
- if outCalls.count == 0 {
- return nil
- }
- result := make([]ResolvedCall, outCalls.count)
- rcs := unsafe.Slice(outCalls.items, outCalls.count)
- for i, rc := range rcs {
- result[i] = ResolvedCall{
- CallerQN: C.GoString(rc.caller_qn),
- CalleeQN: C.GoString(rc.callee_qn),
- Strategy: C.GoString(rc.strategy),
- Confidence: float32(rc.confidence),
- Reason: goStringOrEmpty(rc.reason),
- }
- }
- return result
-}
diff --git a/internal/cbm/lsp_c_test.go b/internal/cbm/lsp_c_test.go
deleted file mode 100644
index 1fd4d868e..000000000
--- a/internal/cbm/lsp_c_test.go
+++ /dev/null
@@ -1,15179 +0,0 @@
-package cbm
-
-import (
- "strings"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// extractCWithRegistry extracts a C file and returns the result.
-func extractCWithRegistry(t *testing.T, source string) *FileResult {
- t.Helper()
- result, err := ExtractFile([]byte(source), lang.C, "test", "main.c")
- if err != nil {
- t.Fatalf("ExtractFile failed: %v", err)
- }
- return result
-}
-
-// extractCPPWithRegistry extracts a C++ file and returns the result.
-func extractCPPWithRegistry(t *testing.T, source string) *FileResult {
- t.Helper()
- result, err := ExtractFile([]byte(source), lang.CPP, "test", "main.cpp")
- if err != nil {
- t.Fatalf("ExtractFile failed: %v", err)
- }
- return result
-}
-
-// ============================================================================
-// Test Category 1: Simple variable declarations and method calls
-// ============================================================================
-
-func TestCLSP_SimpleVarDecl(t *testing.T) {
- source := `
-struct Foo {
- int value;
-};
-
-int bar(struct Foo* f);
-
-void baz() {
- struct Foo x;
- bar(&x);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "baz", "bar")
-}
-
-func TestCLSP_PointerArrow(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-void test(Foo* p) {
- p->bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_DotAccess(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-void test() {
- Foo x;
- x.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-// ============================================================================
-// Test Category 2: Auto type inference
-// ============================================================================
-
-func TestCLSP_AutoInference(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-Foo createFoo() { return Foo(); }
-
-void test() {
- auto x = createFoo();
- x.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "test", "Foo.bar")
- if rc.Strategy == "lsp_unresolved" {
- t.Errorf("auto deduction from free function return should resolve, got strategy=%s", rc.Strategy)
- }
-}
-
-// ============================================================================
-// Test Category 3: Namespace-qualified calls
-// ============================================================================
-
-func TestCLSP_NamespaceQualified(t *testing.T) {
- source := `
-namespace ns {
- class Foo {
- public:
- static int staticMethod() { return 0; }
- };
-}
-
-void test() {
- ns::Foo::staticMethod();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "staticMethod")
-}
-
-// ============================================================================
-// Test Category 4: Constructor calls
-// ============================================================================
-
-func TestCLSP_Constructor(t *testing.T) {
- source := `
-class Foo {
-public:
- Foo(int a, int b) {}
- int bar() { return 0; }
-};
-
-void test() {
- Foo x(1, 2);
- x.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_NewDelete(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-void test() {
- Foo* p = new Foo();
- p->bar();
- delete p;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-// ============================================================================
-// Test Category 5: Implicit this
-// ============================================================================
-
-func TestCLSP_ImplicitThis(t *testing.T) {
- source := `
-class Foo {
-public:
- int helper() { return 0; }
- void doWork() {
- helper();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "doWork", "helper")
- if rc == nil {
- t.Log("implicit this resolution not yet detected — may need method body scoping")
- // This is acceptable — implicit this is a stretch goal
- }
-}
-
-func TestCLSP_ExplicitThis(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
- void doWork() {
- this->bar();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "doWork", "bar")
-}
-
-// ============================================================================
-// Test Category 6: Type aliases
-// ============================================================================
-
-func TestCLSP_TypeAlias(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-using MyFoo = Foo;
-
-void test() {
- MyFoo x;
- x.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_Typedef(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-typedef Foo MyFoo;
-
-void test() {
- MyFoo x;
- x.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-// ============================================================================
-// Test Category 7: Scope chain
-// ============================================================================
-
-func TestCLSP_ScopeChain(t *testing.T) {
- source := `
-class Foo {
-public:
- int method1() { return 0; }
-};
-
-class Bar {
-public:
- int method2() { return 0; }
-};
-
-void test() {
- {
- Foo x;
- x.method1();
- }
- {
- Bar x;
- x.method2();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "method1")
- requireResolvedCall(t, result, "test", "method2")
-}
-
-// ============================================================================
-// Test Category 8: Cast expressions
-// ============================================================================
-
-func TestCLSP_StaticCast(t *testing.T) {
- source := `
-class Base {
-public:
- virtual int bar() { return 0; }
-};
-
-class Derived : public Base {
-public:
- int bar() override { return 1; }
- int extra() { return 2; }
-};
-
-void test(Base* b) {
- static_cast<Derived*>(b)->extra();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "extra")
-}
-
-// ============================================================================
-// Test Category 9: Using namespace
-// ============================================================================
-
-func TestCLSP_UsingNamespace(t *testing.T) {
- source := `
-namespace ns {
- int foo() { return 42; }
-}
-
-void test() {
- using namespace ns;
- foo();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "foo")
-}
-
-// ============================================================================
-// Test Category 10: C mode (pure C, no classes)
-// ============================================================================
-
-func TestCLSP_CMode(t *testing.T) {
- source := `
-#include <stdlib.h>
-
-struct Point {
- int x;
- int y;
-};
-
-int compute(struct Point* p) {
- return p->x + p->y;
-}
-
-void test() {
- struct Point p;
- p.x = 1;
- p.y = 2;
- compute(&p);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compute")
-}
-
-// ============================================================================
-// Test Category 11: Direct function calls
-// ============================================================================
-
-func TestCLSP_DirectCall(t *testing.T) {
- source := `
-int helper(int x) { return x + 1; }
-
-void test() {
- helper(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "helper")
-}
-
-func TestCLSP_DirectCallCPP(t *testing.T) {
- source := `
-int helper(int x) { return x + 1; }
-
-void test() {
- helper(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "helper")
-}
-
-// ============================================================================
-// Test Category 12: Stdlib calls
-// ============================================================================
-
-func TestCLSP_StdlibCall(t *testing.T) {
- source := `
-#include <string.h>
-
-void test() {
- char buf[100];
- strlen(buf);
-}
-`
- result := extractCWithRegistry(t, source)
- // strlen is registered in stdlib, should be resolvable
- rc := findResolvedCall(t, result, "test", "strlen")
- if rc != nil {
- if rc.Confidence < 0.5 {
- t.Errorf("expected high confidence for strlen, got %.2f", rc.Confidence)
- }
- }
-}
-
-// ============================================================================
-// Test Category 13: Multiple resolved calls in same function
-// ============================================================================
-
-func TestCLSP_MultipleCallsSameFunc(t *testing.T) {
- source := `
-class Logger {
-public:
- void info(const char* msg) {}
- void error(const char* msg) {}
-};
-
-class Config {
-public:
- const char* get(const char* key) { return ""; }
-};
-
-void setup(Logger* log, Config* cfg) {
- log->info("starting");
- cfg->get("port");
- log->error("failed");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "setup", "info")
- requireResolvedCall(t, result, "setup", "get")
- requireResolvedCall(t, result, "setup", "error")
-}
-
-// ============================================================================
-// Test Category 14: Return type chain
-// ============================================================================
-
-func TestCLSP_ReturnTypeChain(t *testing.T) {
- source := `
-class File {
-public:
- int read() { return 0; }
-};
-
-File* open(const char* path) { return nullptr; }
-
-void test() {
- File* f = open("test.txt");
- f->read();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "read")
-}
-
-// ============================================================================
-// Test Category 15: Method chaining
-// ============================================================================
-
-func TestCLSP_MethodChaining(t *testing.T) {
- source := `
-class Builder {
-public:
- Builder& setName(const char* name) { return *this; }
- Builder& setValue(int val) { return *this; }
- void build() {}
-};
-
-void test() {
- Builder b;
- b.setName("foo").setValue(42).build();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "setName")
- // Method chaining through return type
- rc := findResolvedCall(t, result, "test", "build")
- if rc == nil {
- t.Log("method chaining through return type not resolved — acceptable limitation")
- }
-}
-
-// ============================================================================
-// Test Category 16: Inheritance
-// ============================================================================
-
-func TestCLSP_Inheritance(t *testing.T) {
- source := `
-class Base {
-public:
- int baseMethod() { return 0; }
-};
-
-class Derived : public Base {
-public:
- int derivedMethod() { return 1; }
-};
-
-void test() {
- Derived d;
- d.derivedMethod();
- d.baseMethod();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "derivedMethod")
- // Base class method through inheritance — may or may not resolve
- rc := findResolvedCall(t, result, "test", "baseMethod")
- if rc == nil {
- t.Log("base class method through inheritance not resolved — needs cross-file enrichment")
- }
-}
-
-// ============================================================================
-// Test Category 17: Operator overloads
-// ============================================================================
-
-func TestCLSP_OperatorStream(t *testing.T) {
- source := `
-#include <iostream>
-
-void test() {
- int x = 42;
-}
-`
- // Just verify it doesn't crash on operator overload nodes
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Test Category 18: Cross-file resolution
-// ============================================================================
-
-func TestCLSP_CrossFile(t *testing.T) {
- source := `
-class Widget {
-public:
- void render() {}
-};
-
-void test() {
- Widget w;
- w.render();
-}
-`
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main-cpp.Widget",
- ShortName: "Widget",
- Label: "Class",
- DefModuleQN: "test.main-cpp",
- },
- {
- QualifiedName: "test.main-cpp.Widget.render",
- ShortName: "render",
- Label: "Method",
- ReceiverType: "test.main-cpp.Widget",
- DefModuleQN: "test.main-cpp",
- },
- }
-
- crossDefs := []CrossFileDef{
- {
- QualifiedName: "test.helper-cpp.Helper.process",
- ShortName: "process",
- Label: "Method",
- ReceiverType: "test.helper-cpp.Helper",
- DefModuleQN: "test.helper-cpp",
- },
- }
-
- resolved := RunCLSPCrossFile(
- []byte(source),
- "test.main-cpp",
- true, // cpp mode
- fileDefs,
- crossDefs,
- nil, // no includes needed for this test
- nil, // no cached tree
- )
-
- if len(resolved) == 0 {
- t.Log("cross-file resolution returned no calls — may need parser re-parse support")
- return
- }
-
- found := false
- for _, rc := range resolved {
- if contains(rc.CalleeQN, "render") {
- found = true
- break
- }
- }
- if !found {
- t.Error("expected cross-file resolution to find render() call")
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
- }
-}
-
-// ============================================================================
-// Test Category 19: Verify no crashes on various patterns
-// ============================================================================
-
-func TestCLSP_NocrashTemplateExpression(t *testing.T) {
- source := `
-#include <vector>
-#include <string>
-
-void test() {
- int x = 42;
- double y = 3.14;
- const char* s = "hello";
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-func TestCLSP_NocrashLambda(t *testing.T) {
- source := `
-void test() {
- auto f = [](int x) -> int { return x + 1; };
- f(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-func TestCLSP_NocrashNestedNamespace(t *testing.T) {
- source := `
-namespace a {
- namespace b {
- namespace c {
- void deep() {}
- }
- }
-}
-
-void test() {
- a::b::c::deep();
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-func TestCLSP_NocrashEmptySource(t *testing.T) {
- result, err := ExtractFile([]byte(""), lang.CPP, "test", "empty.cpp")
- if err != nil {
- t.Fatalf("ExtractFile failed: %v", err)
- }
- if result == nil {
- t.Fatal("expected non-nil result for empty source")
- }
-}
-
-func TestCLSP_NocrashComplexClass(t *testing.T) {
- source := `
-class Base {
-public:
- virtual ~Base() {}
- virtual void process() = 0;
-};
-
-class Derived : public Base {
- int data_;
-public:
- Derived(int d) : data_(d) {}
- void process() override {
- data_++;
- }
- int getData() const { return data_; }
-};
-
-template<typename T>
-class Container {
- T* items_;
- int count_;
-public:
- Container() : items_(nullptr), count_(0) {}
- void add(const T& item) { count_++; }
- int size() const { return count_; }
-};
-
-void test() {
- Derived d(42);
- d.process();
- d.getData();
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
- requireResolvedCall(t, result, "test", "process")
- requireResolvedCall(t, result, "test", "getData")
-}
-
-// ============================================================================
-// Test Category 20: Operator overloads
-// ============================================================================
-
-func TestCLSP_OperatorSubscript(t *testing.T) {
- source := `
-class Vec {
-public:
- int& operator[](int idx) { static int x; return x; }
-};
-
-void test() {
- Vec v;
- v[0];
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator[]")
-}
-
-func TestCLSP_OperatorBinary(t *testing.T) {
- source := `
-class Vec3 {
-public:
- Vec3 operator+(const Vec3& other) { return Vec3(); }
-};
-
-void test() {
- Vec3 a;
- Vec3 b;
- a + b;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator+")
-}
-
-func TestCLSP_OperatorUnary(t *testing.T) {
- source := `
-class Iter {
-public:
- int operator*() { return 0; }
- Iter& operator++() { return *this; }
-};
-
-void test() {
- Iter it;
- *it;
- ++it;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator*")
- requireResolvedCall(t, result, "test", "operator++")
-}
-
-// ============================================================================
-// Test Category 21: Functor (operator())
-// ============================================================================
-
-func TestCLSP_Functor(t *testing.T) {
- source := `
-class Predicate {
-public:
- bool operator()(int x) { return x > 0; }
-};
-
-void test() {
- Predicate pred;
- pred(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator()")
-}
-
-// ============================================================================
-// Test Category 22: Copy/move constructor
-// ============================================================================
-
-func TestCLSP_CopyConstructor(t *testing.T) {
- source := `
-class Foo {
-public:
- Foo() {}
- Foo(const Foo& other) {}
- int bar() { return 0; }
-};
-
-void test() {
- Foo a;
- Foo b = a;
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Should detect copy constructor call
- rc := findResolvedCall(t, result, "test", "Foo")
- if rc != nil && contains(rc.Strategy, "copy_constructor") {
- t.Log("copy constructor correctly detected")
- }
-}
-
-// ============================================================================
-// Test Category 23: Delete expression (destructor)
-// ============================================================================
-
-func TestCLSP_DeleteDestructor(t *testing.T) {
- source := `
-class Widget {
-public:
- ~Widget() {}
-};
-
-void test() {
- Widget* w = new Widget();
- delete w;
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Should emit constructor for new and destructor for delete
- rc := findResolvedCall(t, result, "test", "Widget")
- if rc == nil {
- t.Log("constructor/destructor not detected")
- }
-}
-
-// ============================================================================
-// Test Category 24: Range-for type deduction
-// ============================================================================
-
-func TestCLSP_RangeFor(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
-};
-
-void test() {
- Foo arr[3];
- for (auto& x : arr) {
- x.bar();
- }
-}
-`
- // This may or may not resolve depending on array element type deduction
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Test Category 25: Parent namespace traversal
-// ============================================================================
-
-func TestCLSP_ParentNamespace(t *testing.T) {
- source := `
-namespace outer {
- int helper() { return 42; }
-
- namespace inner {
- void test() {
- helper();
- }
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "helper")
- if rc == nil {
- t.Log("parent namespace traversal not resolving — acceptable")
- }
-}
-
-// ============================================================================
-// Test Category 26: Conversion operators
-// ============================================================================
-
-func TestCLSP_ConversionOperatorBool(t *testing.T) {
- source := `
-class Guard {
-public:
- operator bool() { return true; }
-};
-
-void test() {
- Guard g;
- if (g) {
- // implicit operator bool call
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "operator bool")
- if rc == nil {
- t.Log("implicit operator bool() not detected — acceptable limitation")
- }
-}
-
-// ============================================================================
-// Test Category 27: Namespace alias
-// ============================================================================
-
-func TestCLSP_NamespaceAlias(t *testing.T) {
- source := `
-namespace very_long_name {
- int foo() { return 42; }
-}
-
-void test() {
- namespace vln = very_long_name;
- vln::foo();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Namespace alias resolution in function scope
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Test Category 28: Template in namespace
-// ============================================================================
-
-func TestCLSP_TemplateInNamespace(t *testing.T) {
- source := `
-namespace ns {
- template<typename T>
- class Wrapper {
- public:
- T get() { return T(); }
- };
-
- template<typename T>
- void process(T val) {}
-}
-
-void test() {
- int x = 42;
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil for template in namespace")
- }
-}
-
-// ============================================================================
-// Test Category 29: No crash on various edge cases
-// ============================================================================
-
-func TestCLSP_NocrashUsingEnum(t *testing.T) {
- source := `
-enum class Color { Red, Green, Blue };
-
-void test() {
- Color c = Color::Red;
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-func TestCLSP_NocrashMultipleInheritance(t *testing.T) {
- source := `
-class A {
-public:
- void methodA() {}
-};
-
-class B {
-public:
- void methodB() {}
-};
-
-class C : public A, public B {
-public:
- void methodC() {}
-};
-
-void test() {
- C c;
- c.methodC();
- c.methodA();
- c.methodB();
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
- requireResolvedCall(t, result, "test", "methodC")
-}
-
-func TestCLSP_NocrashPointerArithmetic(t *testing.T) {
- source := `
-void test() {
- int arr[10];
- int* p = arr;
- *(p + 3) = 42;
-}
-`
- result := extractCWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Test Category 30: Function pointer resolution
-// ============================================================================
-
-func TestCLSP_FunctionPointer(t *testing.T) {
- source := `
-int target_func(int x) { return x + 1; }
-
-void test() {
- int (*fp)(int) = &target_func;
- fp(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "target_func")
-}
-
-func TestCLSP_FunctionPointerDecay(t *testing.T) {
- source := `
-int target_func(int x) { return x + 1; }
-
-void test() {
- int (*fp)(int) = target_func;
- fp(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "target_func")
-}
-
-// ============================================================================
-// Test Category 31: Overloaded function call (arg count matching)
-// ============================================================================
-
-func TestCLSP_OverloadByArgCount(t *testing.T) {
- source := `
-class Foo {
-public:
- int bar() { return 0; }
- int bar(int x) { return x; }
- int bar(int x, int y) { return x + y; }
-};
-
-void test() {
- Foo f;
- f.bar();
- f.bar(1);
- f.bar(1, 2);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Should resolve all three overloads
- requireResolvedCall(t, result, "test", "bar")
-}
-
-// ============================================================================
-// Test Category 32: Template default args
-// ============================================================================
-
-func TestCLSP_TemplateDefaultArgs(t *testing.T) {
- source := `
-class DefaultType {
-public:
- int method() { return 0; }
-};
-
-template<class T = DefaultType>
-void process() {
- T obj;
- obj.method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "process", "method")
- if rc == nil {
- t.Log("template default arg resolution not working — tree-sitter may not expose default_type field")
- }
-}
-
-// ============================================================================
-// Test Category 33: C++20 spaceship operator
-// ============================================================================
-
-func TestCLSP_SpaceshipOperator(t *testing.T) {
- source := `
-class Vec3 {
-public:
- int x, y, z;
- bool operator==(const Vec3& other) { return x == other.x; }
-};
-
-void test() {
- Vec3 a;
- Vec3 b;
- a == b;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator==")
-}
-
-// ============================================================================
-// Test Category 34: C++20 concepts (no crash)
-// ============================================================================
-
-func TestCLSP_NocrashConcept(t *testing.T) {
- source := `
-template<typename T>
-class Container {
-public:
- void push(T val) {}
- int size() { return 0; }
-};
-
-void test() {
- Container<int> c;
- c.push(42);
- c.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
- requireResolvedCall(t, result, "test", "push")
- requireResolvedCall(t, result, "test", "size")
-}
-
-// ============================================================================
-// Test Category 35: Dependent member access via template default
-// ============================================================================
-
-func TestCLSP_DependentMemberAccess(t *testing.T) {
- source := `
-class Widget {
-public:
- void render() {}
-};
-
-template<class T = Widget>
-void draw(T& obj) {
- obj.render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "draw", "render")
- if rc == nil {
- t.Log("dependent member access through template default not resolved — acceptable")
- }
-}
-
-func TestCLSP_NocrashTryCatch(t *testing.T) {
- source := `
-class Exception {
-public:
- const char* what() { return "error"; }
-};
-
-void test() {
- try {
- throw Exception();
- } catch (Exception& e) {
- e.what();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Test Category: Macro expansion via simplecpp preprocessor (dual-parse)
-// ============================================================================
-
-// hasRawCall checks if any raw Call has the given callee name.
-func hasRawCall(result *FileResult, calleeName string) bool {
- for _, c := range result.Calls {
- if c.CalleeName == calleeName {
- return true
- }
- }
- return false
-}
-
-func TestCLSP_MacroWrappedCall(t *testing.T) {
- source := `
-#define CALL(f) f()
-void foo(void);
-void test(void) { CALL(foo); }
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "foo") {
- t.Errorf("expected raw call to 'foo' from macro expansion, got calls: %v", result.Calls)
- }
-}
-
-func TestCLSP_MacroWithArgs(t *testing.T) {
- source := `
-int printf(const char* fmt, ...);
-#define LOG(msg) printf(msg)
-void test(void) { LOG("hi"); }
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "printf") {
- t.Errorf("expected raw call to 'printf' from macro expansion, got calls: %v", result.Calls)
- }
-}
-
-func TestCLSP_RecursiveMacro(t *testing.T) {
- source := `
-void target(int x);
-#define B(x) target(x)
-#define A(x) B(x)
-void test(void) { A(1); }
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "target") {
- t.Errorf("expected raw call to 'target' from recursive macro, got calls: %v", result.Calls)
- }
-}
-
-func TestCLSP_ConditionalMacro(t *testing.T) {
- source := `
-void new_func(void);
-void old_func(void);
-#define USE_NEW 1
-#ifdef USE_NEW
-void test(void) { new_func(); }
-#else
-void test(void) { old_func(); }
-#endif
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "new_func") {
- t.Errorf("expected call to 'new_func' from #ifdef branch, got calls: %v", result.Calls)
- }
-}
-
-func TestCLSP_TokenPaste(t *testing.T) {
- source := `
-void order_handler(void);
-#define HANDLER(name) name##_handler()
-void test(void) { HANDLER(order); }
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "order_handler") {
- t.Errorf("expected raw call to 'order_handler' from ## paste, got calls: %v", result.Calls)
- }
-}
-
-func TestCLSP_NoMacroNoOverhead(t *testing.T) {
- // Pure C without #define — preprocessor should return NULL (fast path).
- source := `
-void foo(void);
-void bar(void);
-void test(void) { foo(); bar(); }
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "foo") || !hasRawCall(result, "bar") {
- t.Errorf("expected calls to 'foo' and 'bar', got: %v", result.Calls)
- }
-}
-
-func TestCLSP_VariadicMacro(t *testing.T) {
- source := `
-int fprintf(void* stream, const char* fmt, ...);
-#define DBG(fmt, ...) fprintf(0, fmt, __VA_ARGS__)
-void test(void) { DBG("x=%d", 42); }
-`
- result := extractCWithRegistry(t, source)
- if !hasRawCall(result, "fprintf") {
- t.Errorf("expected raw call to 'fprintf' from variadic macro, got calls: %v", result.Calls)
- }
-}
-
-func TestCLSP_CPPMacroMethodCall(t *testing.T) {
- source := `
-class Logger {
-public:
- void log(const char* msg) {}
-};
-
-Logger* getLogger();
-#define LOG(msg) getLogger()->log(msg)
-
-void test() {
- LOG("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- if !hasRawCall(result, "getLogger") {
- t.Errorf("expected raw call to 'getLogger' from macro expansion, got calls: %v", result.Calls)
- }
-}
-
-// ============================================================================
-// Test Category: Struct field extraction
-// ============================================================================
-
-func TestCLSP_StructFieldExtraction(t *testing.T) {
- source := `
-struct Point {
- int x;
- int y;
- float z;
-};
-`
- result := extractCWithRegistry(t, source)
- // Check that Field definitions are extracted
- fieldCount := 0
- fieldNames := map[string]string{} // name → return_type
- for _, d := range result.Definitions {
- if d.Label == "Field" {
- fieldCount++
- fieldNames[d.Name] = d.ReturnType
- }
- }
- if fieldCount != 3 {
- t.Errorf("expected 3 Field defs, got %d", fieldCount)
- for _, d := range result.Definitions {
- t.Logf(" def: %s label=%s type=%s", d.Name, d.Label, d.ReturnType)
- }
- }
- for _, name := range []string{"x", "y", "z"} {
- if _, ok := fieldNames[name]; !ok {
- t.Errorf("expected field %q to be extracted", name)
- }
- }
- if fieldNames["x"] != "int" {
- t.Errorf("expected field x type 'int', got %q", fieldNames["x"])
- }
- if fieldNames["z"] != "float" {
- t.Errorf("expected field z type 'float', got %q", fieldNames["z"])
- }
-}
-
-func TestCLSP_StructFieldDefsToLSPDefs(t *testing.T) {
- source := `
-struct Config {
- int timeout;
- char* name;
- void (*callback)(int);
-};
-`
- result := extractCWithRegistry(t, source)
-
- // Convert to LSP defs
- lspDefs := DefsToLSPDefs(result.Definitions, "test.main_c")
- var configDef *CrossFileDef
- for i := range lspDefs {
- if lspDefs[i].ShortName == "Config" && lspDefs[i].Label == "Class" {
- configDef = &lspDefs[i]
- break
- }
- }
- if configDef == nil {
- t.Fatal("Config class def not found in LSP defs")
- }
- // FieldDefs should contain at least timeout:int and name:char
- if configDef.FieldDefs == "" {
- t.Errorf("expected FieldDefs to be populated, got empty string")
- for _, d := range result.Definitions {
- t.Logf(" def: %s label=%s type=%s parent=%s", d.Name, d.Label, d.ReturnType, d.ParentClass)
- }
- }
- // Function pointer field (callback) should NOT be in FieldDefs (it's a method)
- if configDef.FieldDefs != "" {
- t.Logf("FieldDefs: %s", configDef.FieldDefs)
- }
-}
-
-func TestCLSP_MakeSharedTemplateArg(t *testing.T) {
- source := `
-#include <memory>
-
-class Widget {
-public:
- void resize(int w, int h) {}
-};
-
-void test() {
- auto ptr = std::make_shared<Widget>();
- ptr->resize(10, 20);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "resize")
-}
-
-func TestCLSP_MakeUniqueTemplateArg(t *testing.T) {
- source := `
-#include <memory>
-
-class Engine {
-public:
- void start() {}
-};
-
-void test() {
- auto e = std::make_unique<Engine>();
- e->start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "start")
-}
-
-func TestCLSP_TemplateClassMethodReturnType(t *testing.T) {
- source := `
-template<typename T>
-class Box {
-public:
- T get() { return val; }
- void set(T v) { val = v; }
-private:
- T val;
-};
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- Box<Widget> b;
- b.get().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_TrailingReturnType(t *testing.T) {
- source := `
-class Foo {
-public:
- void bar() {}
-};
-
-auto createFoo() -> Foo* {
- return new Foo();
-}
-
-void test() {
- auto f = createFoo();
- f->bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_TrailingReturnTypeMethod(t *testing.T) {
- source := `
-class Builder {
-public:
- auto self() -> Builder& { return *this; }
- void build() {}
-};
-
-void test() {
- Builder b;
- b.self().build();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "build")
-}
-
-func TestCLSP_CPPClassFieldExtraction(t *testing.T) {
- source := `
-class Widget {
-public:
- int width;
- int height;
- void resize(int w, int h) {}
-private:
- float scale;
-};
-`
- result := extractCPPWithRegistry(t, source)
- fieldCount := 0
- methodCount := 0
- for _, d := range result.Definitions {
- if d.Label == "Field" {
- fieldCount++
- }
- if d.Label == "Method" {
- methodCount++
- }
- }
- if fieldCount != 3 {
- t.Errorf("expected 3 Field defs (width, height, scale), got %d", fieldCount)
- for _, d := range result.Definitions {
- t.Logf(" def: %s label=%s type=%s", d.Name, d.Label, d.ReturnType)
- }
- }
- if methodCount != 1 {
- t.Errorf("expected 1 Method def (resize), got %d", methodCount)
- }
-}
-
-// --- STL stub coverage tests ---
-
-func TestCLSP_StdVariant(t *testing.T) {
- source := `
-#include <variant>
-#include <string>
-
-void test() {
- std::variant<int, std::string> v;
- v.index();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "index")
-}
-
-func TestCLSP_StdDeque(t *testing.T) {
- source := `
-#include <deque>
-
-class Task {
-public:
- void run() {}
-};
-
-void test() {
- std::deque<Task> q;
- q.push_back(Task());
- q.front().run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
- requireResolvedCall(t, result, "test", "front")
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_StdFilesystem(t *testing.T) {
- source := `
-#include <filesystem>
-
-void test() {
- std::filesystem::path p("/tmp/test");
- p.filename();
- std::filesystem::exists(p);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "filename")
- requireResolvedCall(t, result, "test", "exists")
-}
-
-func TestCLSP_StdAccumulate(t *testing.T) {
- source := `
-#include <vector>
-#include <numeric>
-
-void test() {
- std::vector<int> v;
- std::accumulate(v.begin(), v.end(), 0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "accumulate")
- requireResolvedCall(t, result, "test", "begin")
- requireResolvedCall(t, result, "test", "end")
-}
-
-func TestCLSP_StdStringStream(t *testing.T) {
- source := `
-#include <sstream>
-#include <string>
-
-void test() {
- std::stringstream ss;
- ss.str();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "str")
-}
-
-// --- Third-party stub coverage tests ---
-
-func TestCLSP_AbseilStatusOr(t *testing.T) {
- source := `
-namespace absl {
- class Status {
- public:
- bool ok() { return true; }
- int code() { return 0; }
- };
- template<typename T> class StatusOr {
- public:
- bool ok() { return true; }
- T value() { return T(); }
- Status status() { return Status(); }
- };
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- absl::StatusOr<Widget> result;
- if (result.ok()) {
- result.value().draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "ok")
- requireResolvedCall(t, result, "test", "value")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_SpdlogLogger(t *testing.T) {
- source := `
-namespace spdlog {
- class logger {
- public:
- void info(const char* msg) {}
- void warn(const char* msg) {}
- void error(const char* msg) {}
- };
- void info(const char* msg) {}
-}
-
-void test() {
- spdlog::logger log;
- log.info("hello");
- log.warn("caution");
- spdlog::info("global");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "info")
- requireResolvedCall(t, result, "test", "warn")
-}
-
-func TestCLSP_QtQString(t *testing.T) {
- source := `
-class QString {
-public:
- int length() { return 0; }
- bool isEmpty() { return true; }
- QString trimmed() { return *this; }
- const char* toUtf8() { return ""; }
-};
-
-void test() {
- QString s;
- s.trimmed().length();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "trimmed")
- requireResolvedCall(t, result, "test", "length")
-}
-
-// --- ADL (Argument-Dependent Lookup) tests ---
-
-func TestCLSP_ADL_Swap(t *testing.T) {
- source := `
-namespace mylib {
- class Widget {
- public:
- void draw() {}
- };
- void swap(Widget& a, Widget& b) {}
-}
-
-void test() {
- mylib::Widget a, b;
- swap(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "swap")
-}
-
-func TestCLSP_ADL_OperatorFreeFunc(t *testing.T) {
- source := `
-namespace geo {
- class Point {
- public:
- int x, y;
- };
- double distance(Point& a, Point& b) { return 0.0; }
-}
-
-void test() {
- geo::Point p1, p2;
- distance(p1, p2);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "distance")
-}
-
-func TestCLSP_ADL_StdSort(t *testing.T) {
- // std::sort with std::vector iterators — ADL should find std::sort
- source := `
-#include <vector>
-#include <algorithm>
-
-void test() {
- std::vector<int> v;
- sort(v.begin(), v.end());
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sort")
-}
-
-func TestCLSP_ADL_NoFalsePositive(t *testing.T) {
- // Non-namespace type should NOT trigger ADL for missing functions
- source := `
-class Foo {
-public:
- int x;
-};
-
-void test() {
- Foo f;
- unknown_func(f);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Should NOT resolve — Foo is not in a namespace
- for _, rc := range result.ResolvedCalls {
- if rc.CallerQN != "" && rc.CalleeQN != "" {
- if strings.Contains(rc.CalleeQN, "unknown_func") && rc.Strategy != "lsp_unresolved" {
- t.Errorf("ADL should not resolve unknown_func for non-namespaced type, got strategy=%s", rc.Strategy)
- }
- }
- }
-}
-
-// ============================================================================
-// Task 1: Overload Resolution by Parameter Type
-// ============================================================================
-
-func TestCLSP_OverloadByType(t *testing.T) {
- source := `
-class Widget {};
-class Gadget {};
-
-class Foo {
-public:
- void process(Widget* w) {}
- void process(Gadget* g) {}
-};
-
-void test() {
- Foo f;
- Widget w;
- f.process(&w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_OverloadByTypeMethod(t *testing.T) {
- source := `
-class Renderer {
-public:
- void draw(int x) {}
- void draw(double x) {}
-};
-
-void test() {
- Renderer r;
- r.draw(42);
- r.draw(3.14);
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "draw")
- if len(calls) < 2 {
- t.Errorf("expected at least 2 draw calls resolved, got %d", len(calls))
- }
-}
-
-// ============================================================================
-// Task 2: Lambda Return Type Inference
-// ============================================================================
-
-func TestCLSP_LambdaTrailingReturn(t *testing.T) {
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- auto fn = [](int x) -> Widget { Widget w; return w; };
- fn(1).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Lambda has trailing return type -> Widget, so .draw() should resolve
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("lambda trailing return type not resolving draw — tree-sitter may not expose trailing_return_type on lambda")
- }
-}
-
-func TestCLSP_LambdaBodyInference(t *testing.T) {
- source := `
-class Widget {
-public:
- void activate() {}
-};
-
-Widget global_widget;
-
-void test() {
- auto fn = []() { return global_widget; };
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Just verify no crash and the lambda is parsed
- _ = result
-}
-
-// ============================================================================
-// Task 3: Inline Namespace Normalization
-// ============================================================================
-
-func TestCLSP_InlineNamespace_Libc(t *testing.T) {
- source := `
-namespace std {
-namespace __1 {
-class string {
-public:
- int size() { return 0; }
-};
-}
-}
-
-void test() {
- std::__1::string s;
- s.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // std::__1::string should normalize to std.string
- requireResolvedCall(t, result, "test", "size")
-}
-
-func TestCLSP_InlineNamespace_GCC(t *testing.T) {
- source := `
-namespace std {
-namespace __cxx11 {
-class basic_string {
-public:
- int length() { return 0; }
-};
-}
-}
-
-void test() {
- std::__cxx11::basic_string s;
- s.length();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // std::__cxx11::basic_string should normalize to std.basic_string
- requireResolvedCall(t, result, "test", "length")
-}
-
-// ============================================================================
-// Task 4: Implicit Conversions
-// ============================================================================
-
-func TestCLSP_ImplicitStringConversion(t *testing.T) {
- source := `
-namespace std {
-class string {
-public:
- int size() { return 0; }
-};
-}
-
-class Logger {
-public:
- void log(std::string msg) {}
- void log(int code) {}
-};
-
-void test() {
- Logger l;
- l.log("hello");
- l.log(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "log")
- if len(calls) < 2 {
- t.Errorf("expected at least 2 log calls, got %d", len(calls))
- }
-}
-
-func TestCLSP_NumericPromotion(t *testing.T) {
- source := `
-class Math {
-public:
- double compute(double x) { return x; }
- int compute(int x) { return x; }
-};
-
-void test() {
- Math m;
- m.compute(42);
- m.compute(3.14);
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "compute")
- if len(calls) < 2 {
- t.Errorf("expected at least 2 compute calls, got %d", len(calls))
- }
-}
-
-// ============================================================================
-// Task 5: Virtual Dispatch (Override Preference)
-// ============================================================================
-
-func TestCLSP_VirtualOverride(t *testing.T) {
- source := `
-class Base {
-public:
- virtual void draw() {}
-};
-
-class Derived : public Base {
-public:
- void draw() {}
-};
-
-void test() {
- Derived d;
- d.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "test", "draw")
- // Should prefer Derived::draw over Base::draw
- if rc.Strategy != "lsp_type_dispatch" && rc.Strategy != "lsp_virtual_dispatch" {
- t.Logf("virtual dispatch strategy: %s (expected lsp_type_dispatch or lsp_virtual_dispatch)", rc.Strategy)
- }
-}
-
-func TestCLSP_BasePointerCall(t *testing.T) {
- source := `
-class Base {
-public:
- virtual void render() {}
-};
-
-class Derived : public Base {
-};
-
-void test() {
- Derived d;
- d.render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "test", "render")
- // No override in Derived — should resolve to Base::render via base dispatch
- if rc.Strategy != "lsp_base_dispatch" {
- t.Logf("base dispatch strategy: %s (expected lsp_base_dispatch)", rc.Strategy)
- }
-}
-
-// ============================================================================
-// Task 6: CRTP Detection
-// ============================================================================
-
-func TestCLSP_CRTP_Basic(t *testing.T) {
- source := `
-template<class T>
-class Base {
-public:
- T& self() { return static_cast<T&>(*this); }
- void base_method() {
- self().impl();
- }
-};
-
-class Derived : public Base<Derived> {
-public:
- void impl() {}
-};
-`
- result := extractCPPWithRegistry(t, source)
- // CRTP: Base<Derived> should bind T=Derived, so self().impl() should resolve
- rc := findResolvedCall(t, result, "base_method", "impl")
- if rc == nil {
- t.Log("CRTP resolution not fully working — T not bound to Derived in template scope")
- }
-}
-
-func TestCLSP_CRTP_MultiParam(t *testing.T) {
- source := `
-template<class T, class Policy>
-class CRTPBase {
-public:
- void apply() {
- static_cast<T*>(this)->do_work();
- }
-};
-
-class MyClass : public CRTPBase<MyClass, int> {
-public:
- void do_work() {}
-};
-`
- result := extractCPPWithRegistry(t, source)
- // Multi-param CRTP: only T should be bound to MyClass
- rc := findResolvedCall(t, result, "apply", "do_work")
- if rc == nil {
- t.Log("multi-param CRTP not resolving do_work — expected T bound to MyClass")
- }
-}
-
-// ============================================================================
-// Task 7: Range-For Iterator Protocol
-// ============================================================================
-
-func TestCLSP_RangeForMap(t *testing.T) {
- source := `
-namespace std {
-template<class K, class V>
-class map {
-public:
- K* begin() { return nullptr; }
-};
-
-template<class A, class B>
-class pair {
-public:
- A first;
- B second;
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::map<int, Widget> m;
- for (auto& p : m) {
- p.second.draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Map elements should be pair<int, Widget>, so p.second.draw() resolves
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("map range-for not resolving draw on pair.second — field lookup on std.pair not working")
- }
-}
-
-func TestCLSP_RangeForCustomIterator(t *testing.T) {
- source := `
-class Widget {
-public:
- void activate() {}
-};
-
-class Iterator {
-public:
- Widget operator*() { Widget w; return w; }
-};
-
-class Container {
-public:
- Iterator begin() { Iterator it; return it; }
- Iterator end() { Iterator it; return it; }
-};
-
-void test() {
- Container c;
- for (auto& w : c) {
- w.activate();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Iterator protocol: begin() -> Iterator, operator*() -> Widget
- rc := findResolvedCall(t, result, "test", "activate")
- if rc == nil {
- t.Log("custom iterator protocol not resolving — begin()/operator*() chain not working")
- }
-}
-
-// ============================================================================
-// Template Argument Deduction (TAD)
-// ============================================================================
-
-func TestCLSP_TAD_FreeFunctionIdentity(t *testing.T) {
- // Template free function where return type = param type (identity)
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-template<class T>
-T identity(T x) { return x; }
-
-void test() {
- Widget w;
- identity(w).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_TAD_MakePairLike(t *testing.T) {
- // Template free function returning pair<T,U>
- source := `
-namespace std {
-template<class A, class B>
-class pair {
-public:
- A first;
- B second;
-};
-}
-
-class Widget {
-public:
- void activate() {}
-};
-
-template<class T, class U>
-std::pair<T, U> make_my_pair(T a, U b) { std::pair<T,U> p; return p; }
-
-void test() {
- Widget w;
- auto p = make_my_pair(42, w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Should deduce T=int, U=Widget
- _ = result
-}
-
-// ============================================================================
-// Structured Bindings
-// ============================================================================
-
-func TestCLSP_StructuredBindingPair(t *testing.T) {
- source := `
-namespace std {
-template<class A, class B>
-class pair {
-public:
- A first;
- B second;
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::pair<int, Widget> p;
- auto [x, w] = p;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("structured binding not decomposing pair<int, Widget> — w.draw() unresolved")
- }
-}
-
-func TestCLSP_StructuredBindingStruct(t *testing.T) {
- source := `
-class Engine {
-public:
- void start() {}
-};
-
-struct Car {
- int year;
- Engine engine;
-};
-
-void test() {
- Car c;
- auto [y, eng] = c;
- eng.start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "start")
- if rc == nil {
- t.Log("structured binding not decomposing struct fields — eng.start() unresolved")
- }
-}
-
-// ============================================================================
-// Conditional / Ternary expression type
-// ============================================================================
-
-func TestCLSP_TernaryType(t *testing.T) {
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-Widget global_w;
-
-void test() {
- Widget* p = &global_w;
- auto& w = true ? *p : global_w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// Static cast expression type
-// ============================================================================
-
-// ============================================================================
-// Gap assessment: patterns that should work
-// ============================================================================
-
-func TestCLSP_ChainedMethodCalls(t *testing.T) {
- // builder.setX().setY().build() — common pattern
- source := `
-class Widget {
-public:
- void render() {}
-};
-
-class Builder {
-public:
- Builder& setWidth(int w) { return *this; }
- Builder& setHeight(int h) { return *this; }
- Widget build() { Widget w; return w; }
-};
-
-void test() {
- Builder b;
- b.setWidth(10).setHeight(20).build().render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "render")
-}
-
-func TestCLSP_StdVectorPushBack(t *testing.T) {
- // Common pattern: vec.push_back() then vec[i].method()
- source := `
-namespace std {
-template<class T>
-class vector {
-public:
- void push_back(T x) {}
- T& operator[](int i) { return *(T*)0; }
- int size() { return 0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::vector<Widget> widgets;
- widgets.push_back(Widget());
- widgets[0].draw();
- widgets.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- requireResolvedCall(t, result, "test", "push_back")
- requireResolvedCall(t, result, "test", "size")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_IteratorDeref(t *testing.T) {
- // it->method() with smart pointer or iterator
- source := `
-namespace std {
-template<class T>
-class unique_ptr {
-public:
- T* operator->() { return (T*)0; }
- T& operator*() { return *(T*)0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::unique_ptr<Widget> p;
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_EnumClassUsage(t *testing.T) {
- // enum class shouldn't cause issues
- source := `
-class Logger {
-public:
- void log(int level) {}
-};
-
-void test() {
- Logger l;
- l.log(0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "log")
-}
-
-func TestCLSP_MultipleReturnPaths(t *testing.T) {
- // Function returning different types based on branches — should get first return
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-Widget make_widget() { Widget w; return w; }
-
-void test() {
- auto w = make_widget();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_NestedTemplate(t *testing.T) {
- // vector<vector<Widget>> — nested templates
- source := `
-namespace std {
-template<class T>
-class vector {
-public:
- T& operator[](int i) { return *(T*)0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::vector<std::vector<Widget>> grid;
- grid[0][0].draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_ConstRef(t *testing.T) {
- // const Widget& should resolve methods
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-void process(const Widget& w) {
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "process", "draw")
-}
-
-func TestCLSP_StdFunctionCallback(t *testing.T) {
- // std::function<void(int)> — functor call
- source := `
-namespace std {
-template<class T>
-class function {};
-
-template<class R, class... Args>
-class function<R(Args...)> {
-public:
- R operator()(Args... args) { return R(); }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::function<Widget()> factory;
- factory().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("std::function operator() not resolving — variadic template specialization not supported")
- }
-}
-
-func TestCLSP_OptionalValueAccess(t *testing.T) {
- // optional<T>::value() / operator*()
- source := `
-namespace std {
-template<class T>
-class optional {
-public:
- T& value() { return *(T*)0; }
- T& operator*() { return *(T*)0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::optional<Widget> opt;
- opt.value().draw();
- (*opt).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_TypedefChain(t *testing.T) {
- // using + typedef chains
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-using WidgetRef = Widget&;
-typedef Widget* WidgetPtr;
-
-void test(WidgetPtr p) {
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_IfInitStatement(t *testing.T) {
- // C++17 if-init: if (auto x = expr; condition)
- source := `
-class Widget {
-public:
- void draw() {}
- bool valid() { return true; }
-};
-
-Widget make() { Widget w; return w; }
-
-void test() {
- if (auto w = make(); w.valid()) {
- w.draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
- requireResolvedCall(t, result, "test", "valid")
-}
-
-func TestCLSP_DependentTypeMember(t *testing.T) {
- // T::value_type — dependent type member access
- source := `
-namespace std {
-template<class T>
-class vector {
-public:
- T& operator[](int i) { return *(T*)0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-template<class Container>
-void process(Container& c) {
- c[0].draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Template function with unknown Container — c[0] returns unknown
- rc := findResolvedCall(t, result, "process", "draw")
- if rc != nil {
- t.Log("dependent type member access resolved — better than expected!")
- } else {
- t.Log("dependent type: process->draw not resolved (expected — Container is uninstantiated)")
- }
-}
-
-func TestCLSP_AutoReturnFunction(t *testing.T) {
- // auto return type deduction
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-auto make_widget() {
- Widget w;
- return w;
-}
-
-void test() {
- auto w = make_widget();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc != nil {
- t.Log("auto return type deduction working!")
- } else {
- t.Log("auto return: test->draw not resolved (make_widget() returns unknown)")
- }
-}
-
-func TestCLSP_MoveSemantics(t *testing.T) {
- // std::move should preserve type
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-namespace std {
-template<class T>
-T&& move(T& x) { return (T&&)x; }
-}
-
-void test() {
- Widget w;
- auto w2 = std::move(w);
- w2.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_MultiLevelInheritance(t *testing.T) {
- // A -> B -> C, C calls method from A
- source := `
-class A {
-public:
- void base_op() {}
-};
-
-class B : public A {
-public:
- void mid_op() {}
-};
-
-class C : public B {
-public:
- void leaf_op() {}
-};
-
-void test() {
- C c;
- c.base_op();
- c.mid_op();
- c.leaf_op();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "leaf_op")
- rc := findResolvedCall(t, result, "test", "base_op")
- if rc == nil {
- t.Log("multi-level inheritance: base_op not resolved through C->B->A chain")
- }
-}
-
-func TestCLSP_RangeForStructuredBinding(t *testing.T) {
- // for (auto& [key, val] : map) — combination of range-for + structured binding
- source := `
-namespace std {
-template<class K, class V>
-class map {
-public:
- void* begin() { return 0; }
-};
-
-template<class A, class B>
-class pair {
-public:
- A first;
- B second;
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::map<int, Widget> m;
- for (auto& [key, widget] : m) {
- widget.draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc != nil {
- t.Log("range-for + structured binding resolving draw!")
- } else {
- t.Log("range-for + structured binding: draw not resolved (structured binding in range-for)")
- }
-}
-
-func TestCLSP_CrossFileInclude(t *testing.T) {
- // In cross-file mode, functions from other files should resolve
- // This tests the basic cross-file infrastructure
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-void render(Widget& w) {
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "render", "draw")
-}
-
-func TestCLSP_FunctionReturningRef(t *testing.T) {
- // Method returning T& — unwrap ref to get underlying type
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-class Container {
-public:
- Widget& front() { return *(Widget*)0; }
-};
-
-void test() {
- Container c;
- c.front().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_TemplateMethodChain(t *testing.T) {
- // vector<Widget>.front().draw() — uses stdlib-registered std::vector methods
- source := `
-namespace std {
-template<class T> class vector {};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::vector<Widget> v;
- v.front().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
- rc := findResolvedCall(t, result, "test", "draw")
- if rc != nil && rc.Strategy != "lsp_unresolved" {
- t.Logf("template method chain resolving! strategy=%s", rc.Strategy)
- } else {
- t.Log("template method chain: front().draw() not fully resolved")
- }
-}
-
-func TestCLSP_AlgorithmWithLambda(t *testing.T) {
- // std::for_each(v.begin(), v.end(), [](Widget& w) { w.draw(); })
- source := `
-namespace std {
-template<class It, class Fn>
-void for_each(It first, It last, Fn f) {}
-
-template<class T>
-class vector {
-public:
- T* begin() { return (T*)0; }
- T* end() { return (T*)0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::vector<Widget> widgets;
- std::for_each(widgets.begin(), widgets.end(), [](Widget& w) {
- w.draw();
- });
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_StaticCastChain(t *testing.T) {
- source := `
-class Base {
-public:
- void base_method() {}
-};
-
-class Derived : public Base {
-public:
- void derived_method() {}
-};
-
-void test() {
- Base* b = nullptr;
- static_cast<Derived*>(b)->derived_method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "derived_method")
-}
-
-// ============================================================================
-// Gap assessment: patterns needed for LSP parity
-// ============================================================================
-
-func TestCLSP_SmartPointerArrow(t *testing.T) {
- source := `
-namespace std {
-template<class T> class unique_ptr {
-public:
- T* operator->() { return (T*)0; }
- T& operator*() { return *(T*)0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::unique_ptr<Widget> p;
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_StaticMethodCall(t *testing.T) {
- source := `
-class Widget {
-public:
- static Widget create() { return Widget(); }
- void draw() {}
-};
-
-void test() {
- Widget w = Widget::create();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_SubscriptDraw(t *testing.T) {
- source := `
-namespace std {
-template<class T> class vector {
-public:
- T& operator[](int i) { return *(T*)0; }
- int size() { return 0; }
-};
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- std::vector<Widget> v;
- v[0].draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_AutoFromMethodReturn(t *testing.T) {
- source := `
-class Product {
-public:
- void use() {}
-};
-
-class Factory {
-public:
- Product create() { return Product(); }
-};
-
-void test() {
- Factory f;
- auto p = f.create();
- p.use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "use")
-}
-
-func TestCLSP_NestedClassReturnType(t *testing.T) {
- source := `
-class Factory {
-public:
- class Product {
- public:
- void use() {}
- };
- Product create() { return Product(); }
-};
-
-void test() {
- Factory f;
- auto p = f.create();
- p.use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "use")
-}
-
-func TestCLSP_MakeSharedChain(t *testing.T) {
- source := `
-namespace std {
-template<class T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<class T> shared_ptr<T> make_shared() { return shared_ptr<T>(); }
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- auto p = std::make_shared<Widget>();
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_shared")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_DependentMemberCall(t *testing.T) {
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-template<class T>
-void process(T item) {
- item.draw();
-}
-
-void test() {
- Widget w;
- process(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // process(w) should be resolved
- requireResolvedCall(t, result, "test", "process")
- // item.draw() inside process should be resolved via template instantiation
- found := false
- for _, rc := range result.ResolvedCalls {
- if strings.Contains(rc.CalleeQN, "Widget") && strings.Contains(rc.CalleeQN, "draw") &&
- rc.Strategy != "lsp_unresolved" {
- found = true
- t.Logf("dependent member call resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
- }
- if !found {
- t.Error("dependent member call item.draw() not resolved via template instantiation")
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- }
-}
-
-// ============================================================================
-// Test Category 48: Default argument overload resolution
-// ============================================================================
-
-func TestCLSP_DefaultArgs(t *testing.T) {
- source := `
-class Logger {
-public:
- void log(const char* msg, int level = 0) {}
- void log(const char* msg, int level, int flags) {}
-};
-
-void test() {
- Logger lg;
- lg.log("hello"); // 1 arg → matches log(msg, level=0)
- lg.log("hello", 2); // 2 args → matches log(msg, level)
- lg.log("hello", 2, 3); // 3 args → matches log(msg, level, flags)
-}
-`
- result := extractCPPWithRegistry(t, source)
- // All three calls should resolve to a log method
- logCalls := 0
- for _, rc := range result.ResolvedCalls {
- if strings.Contains(rc.CallerQN, "test") &&
- strings.Contains(rc.CalleeQN, "log") &&
- rc.Strategy != "lsp_unresolved" {
- logCalls++
- t.Logf("default args: %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- }
- if logCalls < 3 {
- t.Errorf("expected 3 resolved log() calls with default args, got %d", logCalls)
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- }
-}
-
-// ============================================================================
-// Gap analysis: probe remaining coverage gaps
-// ============================================================================
-
-func TestCLSP_Gap_StdForward(t *testing.T) {
- source := `
-class Widget {
-public:
- void draw() {}
-};
-
-template<typename T>
-void wrapper(T&& arg) {
- arg.draw();
-}
-
-void test() {
- Widget w;
- wrapper(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "wrapper")
- found := false
- for _, rc := range result.ResolvedCalls {
- if strings.Contains(rc.CalleeQN, "Widget") && strings.Contains(rc.CalleeQN, "draw") &&
- rc.Strategy != "lsp_unresolved" {
- found = true
- t.Logf("forwarding ref resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
- }
- if !found {
- t.Log("forwarding reference arg.draw() not resolved — dependent member call in rvalue-ref template")
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- }
-}
-
-func TestCLSP_Gap_GenericLambda(t *testing.T) {
- source := `
-class Gadget {
-public:
- int compute() { return 0; }
-};
-
-void test() {
- auto fn = [](auto& x) { return x.compute(); };
- Gadget g;
- fn(g);
-}
-`
- result := extractCPPWithRegistry(t, source)
- found := false
- for _, rc := range result.ResolvedCalls {
- if strings.Contains(rc.CalleeQN, "compute") && rc.Strategy != "lsp_unresolved" {
- found = true
- t.Logf("generic lambda resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
- }
- if !found {
- t.Log("generic lambda auto& param not resolved — needs auto param deduction")
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- }
-}
-
-func TestCLSP_Gap_DecltypeReturn(t *testing.T) {
- source := `
-class Sensor {
-public:
- int read() { return 0; }
-};
-
-auto make_sensor() -> decltype(Sensor()) { return Sensor(); }
-
-void test() {
- auto s = make_sensor();
- s.read();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_sensor")
- rc := findResolvedCall(t, result, "test", "Sensor.read")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("decltype return type not resolved — auto s = make_sensor() → s.read()")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- }
-}
-
-func TestCLSP_Gap_StdMove(t *testing.T) {
- source := `
-class Resource {
-public:
- void release() {}
-};
-
-void test() {
- Resource r;
- Resource moved = static_cast<Resource&&>(r);
- moved.release();
-}
-`
- result := extractCPPWithRegistry(t, source)
- found := false
- for _, rc := range result.ResolvedCalls {
- if strings.Contains(rc.CalleeQN, "release") && rc.Strategy != "lsp_unresolved" {
- found = true
- t.Logf("move resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
- }
- if !found {
- t.Log("std::move/rvalue cast not preserving type — moved.release() not resolved")
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", rc.CallerQN, rc.CalleeQN, rc.Strategy)
- }
- }
-}
-
-// ============================================================================
-// Gap probes: Systematic coverage testing for C and moderate C++
-// These use soft assertions (t.Log) to identify gaps without breaking CI
-// ============================================================================
-
-func TestCLSP_Probe_C_StructCallback(t *testing.T) {
- // C pattern: function pointer as struct member (callback pattern)
- source := `
-struct EventHandler {
- int (*on_click)(int x, int y);
-};
-
-int handle_click(int x, int y) { return x + y; }
-
-void test() {
- struct EventHandler h;
- h.on_click = handle_click;
- h.on_click(10, 20);
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "on_click")
- if rc == nil {
- t.Errorf("PROBE-FAIL: C struct callback — h.on_click(10, 20) not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: C struct callback resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_C_TypedefStruct(t *testing.T) {
- // C pattern: typedef struct (C-style OOP)
- // Free function calls are resolved by pipeline linker, not LSP.
- // LSP correctly emits them as lsp_unresolved.
- source := `
-typedef struct {
- int x;
- int y;
-} Point;
-
-int point_length(Point* p);
-
-void test() {
- Point p;
- point_length(&p);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "point_length")
-}
-
-func TestCLSP_Probe_C_NestedStruct(t *testing.T) {
- // C pattern: nested struct member access — free function call
- source := `
-struct Inner { int value; };
-struct Outer { struct Inner inner; };
-
-int get_inner_value(struct Inner* i);
-
-void test() {
- struct Outer o;
- get_inner_value(&o.inner);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_inner_value")
-}
-
-func TestCLSP_Probe_C_ArrayDecay(t *testing.T) {
- // C pattern: array decays to pointer, call with array
- source := `
-int strlen(const char* s);
-
-void test() {
- char buf[256];
- strlen(buf);
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "strlen")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C array decay — strlen(buf) not resolved")
- }
-}
-
-func TestCLSP_Probe_C_CompoundLiteral(t *testing.T) {
- // C pattern: compound literal (C99)
- source := `
-struct Point { int x; int y; };
-
-int distance(struct Point* p);
-
-void test() {
- distance(&(struct Point){10, 20});
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "distance")
-}
-
-func TestCLSP_Probe_C_ChainedFuncCalls(t *testing.T) {
- // C pattern: using return value of one function as argument to another
- source := `
-char* strdup(const char* s);
-int strlen(const char* s);
-
-void test() {
- int len = strlen(strdup("hello"));
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "strdup")
- requireResolvedCall(t, result, "test", "strlen")
-}
-
-func TestCLSP_Probe_C_EnumParam(t *testing.T) {
- // C pattern: enum as function parameter
- source := `
-enum Color { RED, GREEN, BLUE };
-
-void set_color(enum Color c);
-
-void test() {
- set_color(RED);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_color")
-}
-
-func TestCLSP_Probe_C_GlobalVarFuncCall(t *testing.T) {
- // C pattern: call function on result stored in global
- source := `
-struct Logger { int level; };
-struct Logger* get_logger();
-void log_msg(struct Logger* l, const char* msg);
-
-struct Logger* g_logger;
-
-void test() {
- g_logger = get_logger();
- log_msg(g_logger, "hello");
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_logger")
- requireResolvedCall(t, result, "test", "log_msg")
-}
-
-func TestCLSP_Probe_CPP_DynamicCast(t *testing.T) {
- // C++ pattern: dynamic_cast
- source := `
-class Base { public: virtual void draw() {} };
-class Circle : public Base { public: void radius() {} };
-
-void test() {
- Base* b = new Circle();
- Circle* c = dynamic_cast<Circle*>(b);
- c->radius();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Circle.radius")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ dynamic_cast — c->radius() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: dynamic_cast resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_ReinterpretCast(t *testing.T) {
- source := `
-class Data { public: void process() {} };
-
-void test() {
- void* raw = 0;
- Data* d = reinterpret_cast<Data*>(raw);
- d->process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Data.process")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ reinterpret_cast — d->process() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: reinterpret_cast resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_ConstCast(t *testing.T) {
- source := `
-class Config { public: void reload() {} };
-
-void test() {
- const Config* cc = 0;
- Config* c = const_cast<Config*>(cc);
- c->reload();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Config.reload")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ const_cast — c->reload() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: const_cast resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_ConstMethodOverload(t *testing.T) {
- // C++ pattern: const vs non-const method overload
- source := `
-class Container {
-public:
- int& get(int i) { return data[i]; }
- const int& get(int i) const { return data[i]; }
- int data[10];
-};
-
-void test() {
- Container c;
- c.get(0);
- const Container cc;
- cc.get(0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "Container.get")
- if len(calls) < 2 {
- t.Log("PROBE-FAIL: C++ const method overload — expected 2 get() calls")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: const overload resolved: %d calls", len(calls))
- }
-}
-
-func TestCLSP_Probe_CPP_UsingBaseMethod(t *testing.T) {
- // C++ pattern: using Base::method in derived class
- source := `
-class Base {
-public:
- void process() {}
-};
-class Derived : public Base {
-public:
- using Base::process;
- void extra() {}
-};
-
-void test() {
- Derived d;
- d.process();
- d.extra();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "extra")
- rc := findResolvedCall(t, result, "test", "process")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ using Base::method — d.process() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: using Base::method resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_PairAccess(t *testing.T) {
- // C++ pattern: std::pair .first / .second
- source := `
-namespace std {
- template<typename K, typename V>
- struct pair {
- K first;
- V second;
- };
-}
-
-class Foo { public: void bar() {} };
-
-void test() {
- std::pair<int, Foo> p;
- p.second.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Foo.bar")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("PROBE-FAIL: C++ pair access — p.second.bar() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: pair access resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_BuilderPattern(t *testing.T) {
- // C++ pattern: builder/fluent interface
- source := `
-class QueryBuilder {
-public:
- QueryBuilder& select(const char* col) { return *this; }
- QueryBuilder& from(const char* table) { return *this; }
- QueryBuilder& where(const char* cond) { return *this; }
- void execute() {}
-};
-
-void test() {
- QueryBuilder qb;
- qb.select("name").from("users").where("id=1").execute();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "execute")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ builder pattern — chain.execute() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: builder pattern resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_ExceptionCatchVar(t *testing.T) {
- // C++ pattern: catch variable type
- source := `
-class MyError {
-public:
- const char* what() { return "error"; }
-};
-
-void risky();
-
-void test() {
- try {
- risky();
- } catch (MyError& e) {
- e.what();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "MyError.what")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ catch variable — e.what() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: catch variable resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_ForLoopIterator(t *testing.T) {
- // C++ pattern: traditional for loop with iterators
- source := `
-namespace std {
- template<typename T> class vector {
- public:
- class iterator {
- public:
- T& operator*();
- iterator& operator++();
- bool operator!=(const iterator& other);
- };
- iterator begin();
- iterator end();
- };
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::vector<Widget> widgets;
- for (std::vector<Widget>::iterator it = widgets.begin(); it != widgets.end(); ++it) {
- (*it).draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("PROBE-FAIL: C++ traditional iterator — (*it).draw() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: traditional iterator resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_NestedClassAccess(t *testing.T) {
- // C++ pattern: nested class member access
- source := `
-class Outer {
-public:
- class Inner {
- public:
- void do_work() {}
- };
- Inner get_inner() { return Inner(); }
-};
-
-void test() {
- Outer o;
- Outer::Inner i = o.get_inner();
- i.do_work();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Inner.do_work")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ nested class — i.do_work() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: nested class access resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_StaticMemberVar(t *testing.T) {
- // C++ pattern: static member variable access
- source := `
-class Config {
-public:
- static Config& instance() { static Config c; return c; }
- void load() {}
-};
-
-void test() {
- Config::instance().load();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Config.load")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: static member chain — Config::instance().load() needs qualified_identifier type eval to try method lookup")
- } else {
- t.Logf("PROBE-PASS: static member chain resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_StdArrayAccess(t *testing.T) {
- // C++ pattern: std::array element access
- source := `
-namespace std {
- template<typename T, int N>
- class array {
- public:
- T& operator[](int i);
- T& at(int i);
- int size() const;
- };
-}
-
-class Sensor { public: int read() { return 0; } };
-
-void test() {
- std::array<Sensor, 4> sensors;
- sensors[0].read();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Sensor.read")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ std::array access — sensors[0].read() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: std::array access resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_UnorderedMapAccess(t *testing.T) {
- // C++ pattern: unordered_map bracket access
- source := `
-namespace std {
- template<typename K, typename V>
- class unordered_map {
- public:
- V& operator[](const K& key);
- V& at(const K& key);
- };
-}
-
-class Handler { public: void handle() {} };
-
-void test() {
- std::unordered_map<int, Handler> handlers;
- handlers[42].handle();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Handler.handle")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ unordered_map[] — handlers[42].handle() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: unordered_map access resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_LambdaCapture(t *testing.T) {
- // C++ pattern: lambda captures local variable by reference and calls method
- source := `
-class Logger {
-public:
- void log(const char* msg) {}
-};
-
-void test() {
- Logger logger;
- auto fn = [&logger]() { logger.log("hello"); };
- fn();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Logger.log")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ lambda capture — logger.log() inside lambda not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: lambda capture resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_TupleGet(t *testing.T) {
- // C++ pattern: std::get<N>(tuple)
- source := `
-namespace std {
- template<typename... Args>
- class tuple {};
- template<int N, typename T>
- auto get(T& t) -> int&;
-}
-
-void test() {
- std::tuple<int, double, int> tup;
- std::get<0>(tup);
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "get")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("PROBE-FAIL: C++ std::get — std::get<0>(tup) not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: std::get resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Probe_CPP_InitializerList(t *testing.T) {
- // C++ pattern: brace initialization
- source := `
-class Widget { public: void draw() {} };
-
-Widget make_widget() { return Widget(); }
-
-void test() {
- Widget w{};
- w.draw();
- Widget w2 = Widget{};
- w2.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "Widget.draw")
- if len(calls) < 2 {
- t.Errorf("PROBE-FAIL: C++ brace init — expected 2 draw() calls, got %d", len(calls))
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: brace init resolved: %d calls", len(calls))
- }
-}
-
-func TestCLSP_Probe_CPP_ConditionalMethod(t *testing.T) {
- // C++ pattern: method call after if/else assignment
- source := `
-class FileReader { public: void read() {} };
-class NetReader { public: void read() {} };
-
-class FileReader* make_file_reader();
-
-void test() {
- FileReader* r = make_file_reader();
- if (r) {
- r->read();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "FileReader.read")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Errorf("PROBE-FAIL: C++ conditional method — r->read() after null check not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("PROBE-PASS: conditional method resolved: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Gap_MultipleInheritance(t *testing.T) {
- source := `
-class A { public: void method_a() {} };
-class B : public A { public: void method_b() {} };
-class C : public A { public: void method_c() {} };
-class D : public B, public C { public: void method_d() {} };
-
-void test() {
- D d;
- d.method_b();
- d.method_d();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "method_b")
- requireResolvedCall(t, result, "test", "method_d")
-}
-
-// ============================================================================
-// Comprehensive C Coverage Matrix
-// Every pure-C call pattern that should be resolved.
-// ============================================================================
-
-func TestCLSP_C_UnionMemberAccess(t *testing.T) {
- source := `
-union Data {
- int i;
- float f;
-};
-
-int process_int(int val);
-
-void test() {
- union Data d;
- d.i = 42;
- process_int(d.i);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process_int")
-}
-
-func TestCLSP_C_VoidPointerCast(t *testing.T) {
- source := `
-struct Widget { int x; };
-void widget_draw(struct Widget* w);
-
-void test(void* raw) {
- struct Widget* w = (struct Widget*)raw;
- widget_draw(w);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "widget_draw")
-}
-
-func TestCLSP_C_DoublePointer(t *testing.T) {
- source := `
-struct Node { int val; };
-void node_init(struct Node** out);
-void node_process(struct Node* n);
-
-void test() {
- struct Node* n;
- node_init(&n);
- node_process(n);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "node_init")
- requireResolvedCall(t, result, "test", "node_process")
-}
-
-func TestCLSP_C_StaticLocalCall(t *testing.T) {
- source := `
-int compute(int x);
-
-void test() {
- static int cached = 0;
- cached = compute(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compute")
-}
-
-func TestCLSP_C_ArrayOfStructLoop(t *testing.T) {
- source := `
-struct Sensor { int id; };
-int read_sensor(struct Sensor* s);
-
-void test() {
- struct Sensor sensors[10];
- for (int i = 0; i < 10; i++) {
- read_sensor(&sensors[i]);
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "read_sensor")
-}
-
-func TestCLSP_C_FuncPtrTypedef(t *testing.T) {
- // Function pointer typedef — the call through `cmp` is emitted as lsp_unresolved
- // because LSP can't track data flow (cmp = compare_ints).
- // We verify the direct call to compare_ints assignment is captured.
- source := `
-typedef int (*Comparator)(const void*, const void*);
-
-int compare_ints(const void* a, const void* b);
-void qsort(void* base, int n, int size, Comparator cmp);
-
-void test() {
- qsort(0, 10, 4, compare_ints);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "qsort")
-}
-
-func TestCLSP_C_NestedFuncCalls(t *testing.T) {
- source := `
-int abs(int x);
-int max(int a, int b);
-int min(int a, int b);
-
-void test() {
- int result = max(abs(-5), min(3, 7));
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "abs")
- requireResolvedCall(t, result, "test", "max")
- requireResolvedCall(t, result, "test", "min")
-}
-
-func TestCLSP_C_StructReturnChain(t *testing.T) {
- source := `
-struct Point { int x; int y; };
-struct Point make_point(int x, int y);
-int point_distance(struct Point* p);
-
-void test() {
- struct Point p = make_point(1, 2);
- point_distance(&p);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_point")
- requireResolvedCall(t, result, "test", "point_distance")
-}
-
-func TestCLSP_C_ConditionalCall(t *testing.T) {
- source := `
-int validate(int x);
-int process(int x);
-void report_error(int code);
-
-void test(int input) {
- if (validate(input)) {
- process(input);
- } else {
- report_error(input);
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "validate")
- requireResolvedCall(t, result, "test", "process")
- requireResolvedCall(t, result, "test", "report_error")
-}
-
-func TestCLSP_C_SwitchCaseCall(t *testing.T) {
- source := `
-enum Mode { READ, WRITE, EXEC };
-void do_read();
-void do_write();
-void do_exec();
-
-void test(enum Mode m) {
- switch (m) {
- case READ: do_read(); break;
- case WRITE: do_write(); break;
- case EXEC: do_exec(); break;
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "do_read")
- requireResolvedCall(t, result, "test", "do_write")
- requireResolvedCall(t, result, "test", "do_exec")
-}
-
-func TestCLSP_C_RecursiveCall(t *testing.T) {
- source := `
-int factorial(int n) {
- if (n <= 1) return 1;
- return n * factorial(n - 1);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "factorial", "factorial")
-}
-
-func TestCLSP_C_StructMemberFuncPtr(t *testing.T) {
- source := `
-struct VTable {
- void (*init)(void);
- void (*destroy)(void);
-};
-
-void my_init(void) {}
-void my_destroy(void) {}
-
-void test() {
- struct VTable vt;
- vt.init = my_init;
- vt.destroy = my_destroy;
- vt.init();
- vt.destroy();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "init")
- requireResolvedCall(t, result, "test", "destroy")
-}
-
-func TestCLSP_C_VariadicCall(t *testing.T) {
- source := `
-int printf(const char* fmt, ...);
-int sprintf(char* buf, const char* fmt, ...);
-
-void test() {
- char buf[256];
- printf("hello %d", 42);
- sprintf(buf, "world %s", "!");
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "printf")
- requireResolvedCall(t, result, "test", "sprintf")
-}
-
-func TestCLSP_C_ConstQualifiedParam(t *testing.T) {
- source := `
-struct Config { int level; };
-int config_get_level(const struct Config* c);
-
-void test() {
- const struct Config cfg = {3};
- config_get_level(&cfg);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "config_get_level")
-}
-
-func TestCLSP_C_WhileLoopCall(t *testing.T) {
- source := `
-int has_next(void* iter);
-void* get_next(void* iter);
-void process_item(void* item);
-
-void test(void* iter) {
- while (has_next(iter)) {
- void* item = get_next(iter);
- process_item(item);
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "has_next")
- requireResolvedCall(t, result, "test", "get_next")
- requireResolvedCall(t, result, "test", "process_item")
-}
-
-func TestCLSP_C_DoWhileCall(t *testing.T) {
- source := `
-int read_byte(void);
-int is_valid(int b);
-
-void test() {
- int b;
- do {
- b = read_byte();
- } while (is_valid(b));
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "read_byte")
- requireResolvedCall(t, result, "test", "is_valid")
-}
-
-func TestCLSP_C_TernaryCall(t *testing.T) {
- source := `
-int fast_path(int x);
-int slow_path(int x);
-
-void test(int x) {
- int result = x > 0 ? fast_path(x) : slow_path(x);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "fast_path")
- requireResolvedCall(t, result, "test", "slow_path")
-}
-
-func TestCLSP_C_MultipleReturnCalls(t *testing.T) {
- source := `
-int check_a(void);
-int check_b(void);
-int fallback(void);
-
-int test() {
- if (check_a()) return 1;
- if (check_b()) return 2;
- return fallback();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "check_a")
- requireResolvedCall(t, result, "test", "check_b")
- requireResolvedCall(t, result, "test", "fallback")
-}
-
-// ============================================================================
-// Comprehensive Moderate C++ Coverage Matrix
-// Every moderate C++ call pattern that should be resolved.
-// ============================================================================
-
-func TestCLSP_CPP_RefParam(t *testing.T) {
- // Method call on reference parameter
- source := `
-class Widget { public: void draw() {} };
-
-void render(Widget& w) {
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "render", "draw")
-}
-
-func TestCLSP_CPP_ConstRefParam(t *testing.T) {
- source := `
-class Widget { public: int width() const { return 0; } };
-
-int measure(const Widget& w) {
- return w.width();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "measure", "width")
-}
-
-func TestCLSP_CPP_RvalueRefParam(t *testing.T) {
- source := `
-class Buffer {
-public:
- void consume() {}
-};
-
-void sink(Buffer&& b) {
- b.consume();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "sink", "consume")
-}
-
-func TestCLSP_CPP_AnonymousNamespace(t *testing.T) {
- source := `
-namespace {
- class Helper { public: void work() {} };
-}
-
-void test() {
- Helper h;
- h.work();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "work")
-}
-
-func TestCLSP_CPP_NestedNamespaceDecl(t *testing.T) {
- source := `
-namespace a::b::c {
- class Engine { public: void run() {} };
-}
-
-void test() {
- a::b::c::Engine e;
- e.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_CPP_PureVirtual(t *testing.T) {
- source := `
-class Shape {
-public:
- virtual void draw() = 0;
-};
-
-class Circle : public Shape {
-public:
- void draw() override {}
- void radius() {}
-};
-
-void test() {
- Circle c;
- c.draw();
- c.radius();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
- requireResolvedCall(t, result, "test", "radius")
-}
-
-func TestCLSP_CPP_ProtectedInheritance(t *testing.T) {
- source := `
-class Base { public: void work() {} };
-class Derived : protected Base {
-public:
- void do_stuff() { work(); }
-};
-
-void test() {
- Derived d;
- d.do_stuff();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "do_stuff")
-}
-
-func TestCLSP_CPP_ConstexprCall(t *testing.T) {
- source := `
-class Math {
-public:
- static constexpr int square(int x) { return x * x; }
-};
-
-void test() {
- int val = Math::square(5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "square")
-}
-
-func TestCLSP_CPP_DefaultMemberInit(t *testing.T) {
- // Object with default member initializer, method call
- source := `
-class Config {
-public:
- int level = 0;
- void set_level(int l) { level = l; }
- int get_level() { return level; }
-};
-
-void test() {
- Config c;
- c.set_level(5);
- c.get_level();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_level")
- requireResolvedCall(t, result, "test", "get_level")
-}
-
-func TestCLSP_CPP_MultipleVarsOneType(t *testing.T) {
- // Multiple variables of same type, each calling methods
- source := `
-class Conn { public: void open() {} void close() {} };
-
-void test() {
- Conn a, b;
- a.open();
- b.close();
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "")
- openFound := false
- closeFound := false
- for _, c := range calls {
- if strings.Contains(c.CalleeQN, "open") {
- openFound = true
- }
- if strings.Contains(c.CalleeQN, "close") {
- closeFound = true
- }
- }
- if !openFound {
- t.Errorf("expected open() call resolved")
- }
- if !closeFound {
- t.Errorf("expected close() call resolved")
- }
-}
-
-func TestCLSP_CPP_WhileMethodCall(t *testing.T) {
- source := `
-class Iterator {
-public:
- bool has_next() { return false; }
- int next() { return 0; }
-};
-
-void test() {
- Iterator it;
- while (it.has_next()) {
- it.next();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "has_next")
- requireResolvedCall(t, result, "test", "next")
-}
-
-func TestCLSP_CPP_ForRangeAutoRef(t *testing.T) {
- // Range-for with auto& element type
- source := `
-namespace std {
- template<typename T> class vector {
- public:
- T* begin();
- T* end();
- };
-}
-
-class Task { public: void execute() {} };
-
-void test() {
- std::vector<Task> tasks;
- for (auto& t : tasks) {
- t.execute();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "execute")
-}
-
-func TestCLSP_CPP_ForRangeConstAutoRef(t *testing.T) {
- source := `
-namespace std {
- template<typename T> class vector {
- public:
- const T* begin() const;
- const T* end() const;
- };
-}
-
-class Item { public: int id() const { return 0; } };
-
-void test() {
- std::vector<Item> items;
- for (const auto& item : items) {
- item.id();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "id")
-}
-
-func TestCLSP_CPP_NewExpression(t *testing.T) {
- // new expression -> pointer -> arrow access
- source := `
-class Node {
-public:
- void link(Node* other) {}
-};
-
-void test() {
- Node* a = new Node();
- Node* b = new Node();
- a->link(b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "link")
-}
-
-func TestCLSP_CPP_ScopedEnumParam(t *testing.T) {
- source := `
-enum class Color { Red, Green, Blue };
-
-class Renderer {
-public:
- void set_color(Color c) {}
- void render() {}
-};
-
-void test() {
- Renderer r;
- r.set_color(Color::Red);
- r.render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_color")
- requireResolvedCall(t, result, "test", "render")
-}
-
-func TestCLSP_CPP_MultipleSmartPtrs(t *testing.T) {
- source := `
-namespace std {
- template<class T> class unique_ptr {
- public:
- T* operator->() { return (T*)0; }
- };
- template<class T> class shared_ptr {
- public:
- T* operator->() { return (T*)0; }
- };
- template<class T, class... Args>
- unique_ptr<T> make_unique(Args... a) { return unique_ptr<T>(); }
- template<class T, class... Args>
- shared_ptr<T> make_shared(Args... a) { return shared_ptr<T>(); }
-}
-
-class DB { public: void query() {} };
-class Cache { public: void get() {} };
-
-void test() {
- auto db = std::make_unique<DB>();
- auto cache = std::make_shared<Cache>();
- db->query();
- cache->get();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "query")
- requireResolvedCall(t, result, "test", "get")
-}
-
-func TestCLSP_CPP_TryCatchMultiple(t *testing.T) {
- source := `
-class IOError { public: const char* file() { return ""; } };
-class ParseError { public: int line() { return 0; } };
-
-void risky();
-
-void test() {
- try {
- risky();
- } catch (IOError& e) {
- e.file();
- } catch (ParseError& e) {
- e.line();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "IOError.file")
- requireResolvedCall(t, result, "test", "ParseError.line")
-}
-
-func TestCLSP_CPP_LambdaCaptureThis(t *testing.T) {
- source := `
-class Server {
-public:
- int port;
- void start() {}
- void setup() {
- auto fn = [this]() { start(); };
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "setup", "start")
-}
-
-func TestCLSP_CPP_OperatorPlusMethod(t *testing.T) {
- source := `
-class Vec2 {
-public:
- Vec2 operator+(const Vec2& other) { return *this; }
- float length() { return 0.0f; }
-};
-
-void test() {
- Vec2 a, b;
- Vec2 c = a + b;
- c.length();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "length")
-}
-
-func TestCLSP_CPP_OperatorAssign(t *testing.T) {
- source := `
-class Matrix {
-public:
- Matrix& operator=(const Matrix& other) { return *this; }
- void invert() {}
-};
-
-void test() {
- Matrix a, b;
- a = b;
- a.invert();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "invert")
-}
-
-func TestCLSP_CPP_ExplicitTemplateInstantiation(t *testing.T) {
- source := `
-template<typename T>
-class Container {
-public:
- void add(T val) {}
- T get() { return T(); }
-};
-
-class Widget { public: void draw() {} };
-
-void test() {
- Container<Widget> c;
- c.add(Widget());
- Widget w = c.get();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "add")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_CPP_NestedMethodCallInArg(t *testing.T) {
- // Method call result used as argument to another method
- source := `
-class Formatter { public: const char* format() { return ""; } };
-class Logger { public: void log(const char* msg) {} };
-
-void test() {
- Formatter f;
- Logger l;
- l.log(f.format());
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Formatter.format")
- requireResolvedCall(t, result, "test", "Logger.log")
-}
-
-func TestCLSP_CPP_ReturnMethodCallResult(t *testing.T) {
- source := `
-class Parser {
-public:
- int parse() { return 0; }
-};
-
-int test() {
- Parser p;
- return p.parse();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "parse")
-}
-
-func TestCLSP_CPP_StaticFactoryMethod(t *testing.T) {
- source := `
-class Connection {
-public:
- static Connection create() { return Connection(); }
- void send() {}
-};
-
-void test() {
- Connection c = Connection::create();
- c.send();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "send")
-}
-
-func TestCLSP_CPP_DeepInheritanceChain(t *testing.T) {
- source := `
-class A { public: void base_method() {} };
-class B : public A {};
-class C : public B {};
-class D : public C {};
-class E : public D {};
-
-void test() {
- E e;
- e.base_method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "base_method")
-}
-
-func TestCLSP_CPP_OverrideVirtual(t *testing.T) {
- source := `
-class Animal {
-public:
- virtual void speak() {}
-};
-
-class Dog : public Animal {
-public:
- void speak() override {}
- void fetch() {}
-};
-
-void test() {
- Dog d;
- d.speak();
- d.fetch();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "speak")
- requireResolvedCall(t, result, "test", "fetch")
-}
-
-func TestCLSP_CPP_ScopeResolutionCall(t *testing.T) {
- source := `
-namespace net {
- class Socket {
- public:
- void connect() {}
- void send() {}
- };
-}
-
-void test() {
- net::Socket s;
- s.connect();
- s.send();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "connect")
- requireResolvedCall(t, result, "test", "send")
-}
-
-func TestCLSP_CPP_InitListConstruct(t *testing.T) {
- source := `
-class Point {
-public:
- Point(int x, int y) {}
- int distanceTo(const Point& other) { return 0; }
-};
-
-void test() {
- Point a(1, 2);
- Point b{3, 4};
- a.distanceTo(b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "distanceTo")
-}
-
-func TestCLSP_CPP_ReturnSmartPtr(t *testing.T) {
- // Direct smart pointer construction (factory return type inference is a known gap)
- source := `
-namespace std {
- template<class T> class unique_ptr {
- public:
- T* operator->() { return (T*)0; }
- };
- template<class T, class... Args>
- unique_ptr<T> make_unique(Args... a) { return unique_ptr<T>(); }
-}
-
-class Service { public: void start() {} };
-
-void test() {
- std::unique_ptr<Service> svc = std::make_unique<Service>();
- svc->start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "start")
-}
-
-func TestCLSP_CPP_AssignInIf(t *testing.T) {
- source := `
-class Parser {
-public:
- int parse() { return 0; }
-};
-
-Parser* get_parser();
-
-void test() {
- if (Parser* p = get_parser()) {
- p->parse();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "parse")
-}
-
-func TestCLSP_CPP_NullptrCheck(t *testing.T) {
- source := `
-class Handler { public: void handle() {} };
-Handler* find_handler(int id);
-
-void test() {
- Handler* h = find_handler(42);
- if (h != nullptr) {
- h->handle();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle")
-}
-
-func TestCLSP_CPP_ExplicitPtrFromNew(t *testing.T) {
- source := `
-class Worker { public: void run() {} };
-
-void test() {
- Worker* w = new Worker();
- w->run();
- delete w;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_CPP_MultipleMethodsSameObj(t *testing.T) {
- source := `
-class Stream {
-public:
- void open() {}
- void write(const char* data) {}
- void flush() {}
- void close() {}
-};
-
-void test() {
- Stream s;
- s.open();
- s.write("data");
- s.flush();
- s.close();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "open")
- requireResolvedCall(t, result, "test", "write")
- requireResolvedCall(t, result, "test", "flush")
- requireResolvedCall(t, result, "test", "close")
-}
-
-func TestCLSP_CPP_NestedClassMethod(t *testing.T) {
- // Nested class with methods called from outer class
- source := `
-class Database {
-public:
- class Transaction {
- public:
- void commit() {}
- void rollback() {}
- };
- Transaction begin() { return Transaction(); }
-};
-
-void test() {
- Database db;
- Database::Transaction tx = db.begin();
- tx.commit();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "begin")
- requireResolvedCall(t, result, "test", "commit")
-}
-
-func TestCLSP_CPP_DiamondInheritance(t *testing.T) {
- source := `
-class Base { public: void common() {} };
-class Left : public Base { public: void left_op() {} };
-class Right : public Base { public: void right_op() {} };
-class Diamond : public Left, public Right {};
-
-void test() {
- Diamond d;
- d.left_op();
- d.right_op();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "left_op")
- requireResolvedCall(t, result, "test", "right_op")
-}
-
-func TestCLSP_CPP_SwitchMethodCall(t *testing.T) {
- source := `
-class Logger {
-public:
- void debug(const char* msg) {}
- void info(const char* msg) {}
- void error(const char* msg) {}
-};
-
-void test(int level) {
- Logger l;
- switch (level) {
- case 0: l.debug("msg"); break;
- case 1: l.info("msg"); break;
- case 2: l.error("msg"); break;
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "debug")
- requireResolvedCall(t, result, "test", "info")
- requireResolvedCall(t, result, "test", "error")
-}
-
-func TestCLSP_CPP_ThrowExpression(t *testing.T) {
- source := `
-class Error {
-public:
- Error(const char* msg) {}
- const char* what() { return ""; }
-};
-
-void test(int x) {
- if (x < 0) {
- Error e("negative");
- e.what();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "what")
-}
-
-func TestCLSP_CPP_ForInitDecl(t *testing.T) {
- source := `
-class Timer {
-public:
- void start() {}
- bool expired() { return true; }
- void tick() {}
-};
-
-void test() {
- for (Timer t; !t.expired(); t.tick()) {
- t.start();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "expired")
- requireResolvedCall(t, result, "test", "tick")
- requireResolvedCall(t, result, "test", "start")
-}
-
-// ============================================================================
-// Known Heavy C++ Limitations (soft assertions — documented gaps)
-// These patterns require deep template/type system features beyond our LSP.
-// ============================================================================
-
-func TestCLSP_HeavyCPP_ConstOverloadDiscrimination(t *testing.T) {
- // Heavy C++: const-qualified dispatch (distinguishing `get()` vs `get() const`)
- // Our LSP doesn't track const-qualification of receiver types.
- source := `
-class Container {
-public:
- int& get(int i) { return data[i]; }
- const int& get(int i) const { return data[i]; }
- int data[10];
-};
-
-void test() {
- Container c;
- c.get(0);
- const Container cc;
- cc.get(0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "get")
- if len(calls) < 1 {
- t.Errorf("expected at least 1 get() call resolved, got 0")
- }
- if len(calls) < 2 {
- t.Log("KNOWN-GAP: const overload discrimination — only resolves 1 of 2 get() calls")
- }
-}
-
-func TestCLSP_HeavyCPP_PairFieldType(t *testing.T) {
- // Heavy C++: template field type tracking (pair<A,B>::second → B)
- // Uses non-namespaced Pair to avoid namespace QN mismatch with extract_defs
- source := `
-template<typename K, typename V>
-struct Pair { K first; V second; };
-class Foo { public: void bar() {} };
-void test() {
- Pair<int, Foo> p;
- p.second.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Foo.bar")
-}
-
-func TestCLSP_HeavyCPP_IteratorDeref(t *testing.T) {
- // Heavy C++: operator*() resolution for iterators
- source := `
-namespace std {
- template<typename T> class vector {
- public:
- class iterator {
- public:
- T& operator*();
- iterator& operator++();
- bool operator!=(const iterator& other);
- };
- iterator begin();
- iterator end();
- };
-}
-class Widget { public: void draw() {} };
-void test() {
- std::vector<Widget> widgets;
- for (std::vector<Widget>::iterator it = widgets.begin(); it != widgets.end(); ++it) {
- (*it).draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("KNOWN-GAP: iterator operator* deref — (*it).draw() not resolved")
- }
-}
-
-func TestCLSP_HeavyCPP_TemplateFuncSyntax(t *testing.T) {
- // Heavy C++: std::get<N>() template function specialization
- source := `
-namespace std {
- template<typename... Args> class tuple {};
- template<int N, typename T> auto get(T& t) -> int&;
-}
-void test() {
- std::tuple<int, double> tup;
- std::get<0>(tup);
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "get")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("KNOWN-GAP: template function syntax — std::get<0>() not resolved")
- }
-}
-
-// ============================================================================
-// Gap Audit: Honest assessment of real-world C patterns
-// These use soft assertions (t.Log) to measure actual coverage without
-// breaking the build. Every AUDIT-FAIL is a real gap in our LSP.
-// ============================================================================
-
-func TestCLSP_Audit_C_CommaOperator(t *testing.T) {
- source := `
-int init(void);
-int process(void);
-
-void test() {
- int r = (init(), process());
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "init")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Audit_C_CastThenFieldCall(t *testing.T) {
- // Common C pattern: cast void* to struct*, call through member func ptr
- source := `
-struct Device {
- void (*reset)(void);
-};
-void test(void* ctx) {
- ((struct Device*)ctx)->reset();
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "reset")
- if rc == nil {
- t.Log("AUDIT-FAIL: C cast-then-field-call — ((struct Device*)ctx)->reset() not resolved")
- } else {
- t.Logf("AUDIT-PASS: cast-then-field-call: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_C_NestedStructFieldCall(t *testing.T) {
- source := `
-struct Inner { int (*compute)(int); };
-struct Outer { struct Inner inner; };
-
-void test() {
- struct Outer o;
- o.inner.compute(42);
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "compute")
- if rc == nil {
- t.Log("AUDIT-FAIL: C nested struct field call — o.inner.compute(42) not resolved")
- } else {
- t.Logf("AUDIT-PASS: nested struct field call: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_C_ArraySubscriptCall(t *testing.T) {
- source := `
-struct Handler { void (*handle)(void); };
-
-void test() {
- struct Handler handlers[4];
- handlers[2].handle();
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "handle")
- if rc == nil {
- t.Log("AUDIT-FAIL: C array subscript field call — handlers[2].handle() not resolved")
- } else {
- t.Logf("AUDIT-PASS: array subscript field call: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_C_FuncPtrAlias(t *testing.T) {
- // Calling through a function pointer variable (requires data-flow analysis)
- source := `
-int real_func(int x);
-typedef int (*fn_t)(int);
-
-void test() {
- fn_t f = real_func;
- f(42);
-}
-`
- result := extractCWithRegistry(t, source)
- // We can only check if the call is emitted, not if it points to real_func
- rc := findResolvedCall(t, result, "test", "")
- callCount := len(findAllResolvedCalls(t, result, "test", ""))
- if callCount < 2 {
- t.Log("AUDIT-FAIL: C func ptr alias — f(42) call not emitted alongside real_func assignment")
- } else {
- t.Log("AUDIT-PASS: func ptr alias — both calls emitted")
- }
- _ = rc
-}
-
-func TestCLSP_Audit_C_GenericSelection(t *testing.T) {
- // C11 _Generic — extremely rare in practice
- source := `
-int process_int(int x);
-float process_float(float x);
-
-void test() {
- int x = 42;
- process_int(x);
-}
-`
- // We don't test _Generic directly (tree-sitter support varies)
- // Just verify normal calls work in same context
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process_int")
-}
-
-func TestCLSP_Audit_C_ForLoopFuncCall(t *testing.T) {
- source := `
-int count(void);
-int get_item(int i);
-void process(int item);
-
-void test() {
- for (int i = 0; i < count(); i++) {
- process(get_item(i));
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "count")
- requireResolvedCall(t, result, "test", "get_item")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Audit_C_AssertMacroCall(t *testing.T) {
- // Calls inside assert() or other macro wrappers
- source := `
-int validate(int x);
-int transform(int x);
-
-void test(int x) {
- if (validate(x)) {
- transform(x);
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "validate")
- requireResolvedCall(t, result, "test", "transform")
-}
-
-// ============================================================================
-// Gap Audit: Honest assessment of real-world moderate C++ patterns
-// ============================================================================
-
-func TestCLSP_Audit_CPP_AutoFromNew(t *testing.T) {
- // Very common: auto* w = new Widget(); w->method()
- source := `
-class Widget { public: void draw() {} };
-
-void test() {
- auto* w = new Widget();
- w->draw();
- delete w;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_Audit_CPP_AutoFromFactory(t *testing.T) {
- // Very common: auto obj = factory(); obj.method()
- source := `
-class Connection { public: void send() {} };
-Connection create_connection() { return Connection(); }
-
-void test() {
- auto conn = create_connection();
- conn.send();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Connection.send")
-}
-
-func TestCLSP_Audit_CPP_AutoFromSmartPtrFactory(t *testing.T) {
- // auto svc = create_service() where factory returns unique_ptr<T>
- source := `
-namespace std {
- template<class T> class unique_ptr {
- public:
- T* operator->() { return (T*)0; }
- };
- template<class T, class... Args>
- unique_ptr<T> make_unique(Args... a) { return unique_ptr<T>(); }
-}
-
-class Service { public: void start() {} };
-
-std::unique_ptr<Service> create_service() {
- return std::make_unique<Service>();
-}
-
-void test() {
- auto svc = create_service();
- svc->start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Service.start")
-}
-
-func TestCLSP_Audit_CPP_DecltypeVar(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-void test() {
- Widget w;
- decltype(w) w2;
- w2.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_Audit_CPP_AutoFromTernary(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-Widget* make_a();
-Widget* make_b();
-
-void test(bool flag) {
- auto* w = flag ? make_a() : make_b();
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: auto from ternary — w->draw() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("AUDIT-PASS: auto from ternary: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_CPP_IfConstexpr(t *testing.T) {
- // C++17 if constexpr — calls in both branches should be resolved
- source := `
-class FastPath { public: void execute() {} };
-class SlowPath { public: void execute() {} };
-
-void test() {
- FastPath f;
- f.execute();
- SlowPath s;
- s.execute();
-}
-`
- // We don't test actual if constexpr (template context needed), just verify
- // that calls to both types are resolved in a non-template context
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "FastPath.execute")
- requireResolvedCall(t, result, "test", "SlowPath.execute")
-}
-
-func TestCLSP_Audit_CPP_StructuredBindingFromTuple(t *testing.T) {
- // structured binding from std::tuple requires std::get<N>
- source := `
-namespace std {
- template<typename... Args> class tuple {};
-}
-class Foo { public: void bar() {} };
-
-void test() {
- Foo f;
- f.bar();
-}
-`
- // Can't test actual structured binding from tuple (needs std::get)
- // Just verify basic call resolution works in presence of tuple types
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_Audit_CPP_CTAD(t *testing.T) {
- // Class template argument deduction (C++17)
- source := `
-template<typename T>
-class Container {
-public:
- Container(T val) {}
- void process() {}
-};
-
-void test() {
- Container c(42);
- c.process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "process")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: CTAD — c.process() not resolved after Container c(42)")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("AUDIT-PASS: CTAD: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_CPP_UserDefinedLiteral(t *testing.T) {
- // C++11 user-defined literals — rare, but tests edge case
- source := `
-class Duration { public: int seconds() { return 0; } };
-Duration operator"" _s(unsigned long long val) { return Duration(); }
-
-void test() {
- auto d = 5_s;
- d.seconds();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "seconds")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: user-defined literal — d.seconds() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("AUDIT-PASS: user-defined literal: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_CPP_AggregateInit(t *testing.T) {
- // C++20 designated initializers for aggregates
- source := `
-class Renderer { public: void render() {} };
-
-struct Config {
- int width;
- int height;
- Renderer* renderer;
-};
-
-void test() {
- Renderer r;
- Config cfg{.width=800, .height=600, .renderer=&r};
- cfg.renderer->render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Renderer.render")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: aggregate init field access — cfg.renderer->render() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- } else {
- t.Logf("AUDIT-PASS: aggregate init: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_CPP_CovariantReturn(t *testing.T) {
- // Covariant return type: Derived::clone() returns Derived* but declared as Base*
- source := `
-class Base {
-public:
- virtual Base* clone() { return new Base(); }
- void base_op() {}
-};
-class Derived : public Base {
-public:
- Derived* clone() override { return new Derived(); }
- void derived_op() {}
-};
-
-void test() {
- Derived d;
- Derived* d2 = d.clone();
- d2->derived_op();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "derived_op")
-}
-
-// ============================================================================
-// Gap Audit: Heavy template C++ — probing fixability
-// ============================================================================
-
-func TestCLSP_Audit_HeavyCPP_VariadicTemplate(t *testing.T) {
- source := `
-template<typename... Args>
-class Visitor {
-public:
- void visit() {}
-};
-
-void test() {
- Visitor<int, double, char> v;
- v.visit();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "visit")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: variadic template — v.visit() not resolved")
- } else {
- t.Logf("AUDIT-PASS: variadic template: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_HeavyCPP_EnableIf(t *testing.T) {
- // SFINAE — enable_if
- source := `
-namespace std {
- template<bool B, class T = void> struct enable_if {};
- template<class T> struct enable_if<true, T> { typedef T type; };
- template<class T> struct is_integral { static const bool value = false; };
-}
-
-class Processor { public: void process() {} };
-
-void test() {
- Processor p;
- p.process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Audit_HeavyCPP_PerfectForwarding(t *testing.T) {
- source := `
-namespace std {
- template<typename T> T&& forward(T& t) { return (T&&)t; }
- template<typename T> T&& move(T& t) { return (T&&)t; }
-}
-
-class Widget { public: void draw() {} };
-
-template<typename T>
-void wrapper(T&& arg) {
- arg.draw();
-}
-
-void test() {
- Widget w;
- wrapper(w);
- wrapper(std::move(w));
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "", "draw")
-}
-
-func TestCLSP_Audit_HeavyCPP_PolicyBasedDesign(t *testing.T) {
- source := `
-struct LogToFile {
- void log(const char* msg) {}
-};
-struct LogToConsole {
- void log(const char* msg) {}
-};
-
-template<typename LogPolicy>
-class Server {
- LogPolicy logger;
-public:
- void start() { logger.log("starting"); }
-};
-
-void test() {
- Server<LogToFile> s;
- s.start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "", "start")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: policy-based design — s.start() not resolved")
- } else {
- t.Logf("AUDIT-PASS: policy-based design: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_HeavyCPP_ExpressionTemplate(t *testing.T) {
- // Simplified expression template (Eigen-style)
- source := `
-class Vector {
-public:
- Vector operator+(const Vector& other) { return *this; }
- Vector operator*(float scalar) { return *this; }
- float norm() { return 0.0f; }
-};
-
-void test() {
- Vector a, b;
- Vector c = a + b;
- float n = c.norm();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "norm")
-}
-
-func TestCLSP_Audit_HeavyCPP_TemplateTemplateParam(t *testing.T) {
- source := `
-template<typename T>
-class MyVector {
-public:
- void push(T val) {}
-};
-
-template<template<typename> class Container, typename T>
-class Adapter {
- Container<T> storage;
-public:
- void add(T val) { storage.push(val); }
-};
-
-void test() {
- Adapter<MyVector, int> a;
- a.add(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "add")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("AUDIT-FAIL: template template param — a.add() not resolved")
- } else {
- t.Logf("AUDIT-PASS: template template param: %s [%s]", rc.CalleeQN, rc.Strategy)
- }
-}
-
-func TestCLSP_Audit_HeavyCPP_ConceptConstrained(t *testing.T) {
- source := `
-class Serializable {
-public:
- void serialize() {}
-};
-
-void test() {
- Serializable s;
- s.serialize();
-}
-`
- // Concepts don't affect call resolution — they constrain template args
- // Just verify normal calls work in same context
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "serialize")
-}
-
-func TestCLSP_Audit_HeavyCPP_Coroutine(t *testing.T) {
- // C++20 coroutines — simplified
- source := `
-class Task {
-public:
- void resume() {}
- bool done() { return true; }
-};
-
-void test() {
- Task t;
- t.resume();
- t.done();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "resume")
- requireResolvedCall(t, result, "test", "done")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Expression Type Evaluation Paths
-// Every handler in c_eval_expr_type that was not covered by existing tests
-// ============================================================================
-
-func TestCLSP_ExprGap_SizeofType(t *testing.T) {
- // sizeof returns size_t — test that it's usable in expressions
- source := `
-struct Buffer {
- void reserve(int n) {}
-};
-
-void test() {
- Buffer buf;
- buf.reserve(sizeof(int));
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "reserve")
-}
-
-func TestCLSP_ExprGap_SizeofExpr(t *testing.T) {
- // sizeof(expr) — variable form
- source := `
-struct Buffer {
- void reserve(int n) {}
-};
-
-void test() {
- int x = 42;
- Buffer buf;
- buf.reserve(sizeof(x));
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "reserve")
-}
-
-func TestCLSP_ExprGap_AlignofExpr(t *testing.T) {
- // alignof returns size_t — should work in expressions
- source := `
-struct Allocator {
- void set_alignment(int n) {}
-};
-
-void test() {
- Allocator a;
- a.set_alignment(alignof(double));
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_alignment")
-}
-
-func TestCLSP_ExprGap_BinaryComparisonBool(t *testing.T) {
- // Comparison operators return bool — test type propagation
- // (a == b) should be bool, then calling method on result tests type handling
- source := `
-void process(bool flag) {}
-
-struct Widget {
- int value() { return 0; }
-};
-
-void test() {
- Widget a;
- Widget b;
- bool eq = (a.value() == b.value());
- process(eq);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "value")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_LogicalAndOr(t *testing.T) {
- // && and || return bool
- source := `
-struct Validator {
- bool check_a() { return true; }
- bool check_b() { return true; }
-};
-
-void on_valid() {}
-
-void test() {
- Validator v;
- if (v.check_a() && v.check_b()) {
- on_valid();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "check_a")
- requireResolvedCall(t, result, "test", "check_b")
- requireResolvedCall(t, result, "test", "on_valid")
-}
-
-func TestCLSP_ExprGap_ParenthesizedMethodCall(t *testing.T) {
- // (obj).method() — parenthesized expression type propagation
- source := `
-struct Engine {
- void start() {}
-};
-
-void test() {
- Engine e;
- (e).start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "start")
-}
-
-func TestCLSP_ExprGap_AssignmentTypeChain(t *testing.T) {
- // Assignment expression returns the assigned value type
- // (a = b).method() — assignment propagates type
- source := `
-struct Config {
- void apply() {}
-};
-
-void test() {
- Config a;
- Config b;
- (a = b).apply();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "apply")
-}
-
-func TestCLSP_ExprGap_UpdateExprTypePreservation(t *testing.T) {
- // ++iter should preserve iterator type for method calls
- source := `
-struct Counter {
- int value() { return 0; }
-};
-
-void test() {
- int x = 0;
- int y = ++x;
- Counter c;
- c.value();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "value")
-}
-
-func TestCLSP_ExprGap_UnaryBitwiseNot(t *testing.T) {
- // ~x preserves type of x
- source := `
-void process(int x) {}
-
-void test() {
- int mask = 0xFF;
- process(~mask);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_UnaryPlus(t *testing.T) {
- // +x preserves type of x
- source := `
-void process(int x) {}
-
-void test() {
- int val = 42;
- process(+val);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_AddressOfThenArrow(t *testing.T) {
- // &x gives pointer to x, then -> accesses members
- source := `
-struct Point {
- int x;
- int y;
- void reset() {}
-};
-
-void test() {
- Point p;
- Point* pp = &p;
- pp->reset();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "reset")
-}
-
-func TestCLSP_ExprGap_DoublePointerDeref(t *testing.T) {
- // **pp dereferences twice to get the base type
- source := `
-struct Widget {
- void draw() {}
-};
-
-void test() {
- Widget w;
- Widget* pw = &w;
- Widget** ppw = &pw;
- (**ppw).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_ExprGap_DerefThenArrow(t *testing.T) {
- // *pp gives single pointer, then -> dereferences again
- source := `
-struct Node {
- void process() {}
-};
-
-void test() {
- Node n;
- Node* pn = &n;
- Node** ppn = &pn;
- (*ppn)->process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_CommaExprMethodCall(t *testing.T) {
- // Comma operator returns rightmost expression type
- source := `
-struct Logger {
- void flush() {}
-};
-
-void side_effect() {}
-
-void test() {
- Logger log;
- // comma expression: side_effect returns void, log is Logger
- // This tests that comma result is used in member access
- log.flush();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "flush")
-}
-
-func TestCLSP_ExprGap_RawStringLiteral(t *testing.T) {
- // R"(...)" is const char* — should be resolvable as string parameter
- source := `
-void process(const char* s) {}
-
-void test() {
- process(R"(hello world)");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_ConcatenatedString(t *testing.T) {
- // Adjacent string literals are concatenated
- source := `
-void process(const char* s) {}
-
-void test() {
- process("hello" " " "world");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_CharLiteralType(t *testing.T) {
- // 'x' has type char (C) or char (C++)
- source := `
-void process(char c) {}
-
-void test() {
- process('x');
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_BoolLiteralType(t *testing.T) {
- // true/false have type bool
- source := `
-void set_flag(bool b) {}
-
-void test() {
- set_flag(true);
- set_flag(false);
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "set_flag")
- if rc == nil {
- t.Errorf("expected resolved call to set_flag")
- }
-}
-
-func TestCLSP_ExprGap_NullptrType(t *testing.T) {
- // nullptr has its own type, should work as argument
- source := `
-void set_ptr(void* p) {}
-
-void test() {
- set_ptr(nullptr);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_ptr")
-}
-
-func TestCLSP_ExprGap_NumberLiteralInt(t *testing.T) {
- // Integer literal type
- source := `
-void process(int n) {}
-
-void test() {
- process(42);
- process(0xFF);
- process(0b1010);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ExprGap_NumberLiteralFloat(t *testing.T) {
- // Floating point literal type
- source := `
-void process(double d) {}
-
-void test() {
- process(3.14);
- process(1.0e10);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Statement Handler Edge Cases
-// ============================================================================
-
-func TestCLSP_StmtGap_ArrayParamDecl(t *testing.T) {
- // Parameter with array_declarator: void f(int arr[])
- source := `
-struct Item {
- void process() {}
-};
-
-void handle(Item items[], int count) {
- items[0].process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "handle", "process")
-}
-
-func TestCLSP_StmtGap_CArrayParamBracket(t *testing.T) {
- // C-style array parameter: int arr[10]
- source := `
-struct Point { int x; int y; };
-
-void reset_point(struct Point* p) {}
-
-void test(struct Point points[10]) {
- reset_point(&points[0]);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "reset_point")
-}
-
-func TestCLSP_StmtGap_ForRangeOverReturnValue(t *testing.T) {
- // Range-for over method return value
- source := `
-namespace std {
-template<typename T> struct vector {
- T* begin() { return nullptr; }
- T* end() { return nullptr; }
-};
-}
-
-struct Item {
- void process() {}
-};
-
-struct Container {
- std::vector<Item> items() { return std::vector<Item>(); }
-};
-
-void test() {
- Container c;
- for (auto& item : c.items()) {
- item.process();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "items")
- // process() may or may not resolve depending on range-for deduction from return value
- rc := findResolvedCall(t, result, "test", "process")
- if rc != nil {
- t.Logf("PASS: range-for over method return value resolved process()")
- } else {
- t.Logf("KNOWN-GAP: range-for over method return deduction not supported")
- }
-}
-
-func TestCLSP_StmtGap_MultipleUsingDecl(t *testing.T) {
- // Multiple using declarations in same scope
- source := `
-namespace ns1 {
- void foo() {}
-}
-namespace ns2 {
- void bar() {}
-}
-
-void test() {
- using ns1::foo;
- using ns2::bar;
- foo();
- bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Direct using-declaration import into local scope
- requireResolvedCall(t, result, "test", "foo")
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_StmtGap_TypedefFuncPtr(t *testing.T) {
- // typedef for function pointer: typedef int (*Comparator)(int, int);
- source := `
-int compare(int a, int b) { return a - b; }
-
-typedef int (*Comparator)(int, int);
-
-void test() {
- Comparator cmp = compare;
- compare(1, 2);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compare")
-}
-
-func TestCLSP_StmtGap_CatchMultipleTypes(t *testing.T) {
- // Multiple catch clauses bind different exception types
- source := `
-class IOException {
-public:
- const char* what() { return "io"; }
-};
-
-class ParseError {
-public:
- int code() { return 0; }
-};
-
-void might_fail() {}
-
-void test() {
- try {
- might_fail();
- } catch (IOException& e) {
- e.what();
- } catch (ParseError& e) {
- e.code();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "might_fail")
- requireResolvedCall(t, result, "test", "what")
- requireResolvedCall(t, result, "test", "code")
-}
-
-func TestCLSP_StmtGap_NamespaceAliasChain(t *testing.T) {
- // namespace alias: namespace fs = std::filesystem;
- source := `
-namespace std {
-namespace filesystem {
- void remove(const char* path) {}
-}}
-
-void test() {
- namespace fs = std::filesystem;
- fs::remove("/tmp/test");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "remove")
-}
-
-func TestCLSP_StmtGap_UsingAliasTemplate(t *testing.T) {
- // using alias: using Vec = std::vector<int>;
- source := `
-namespace std {
-template<typename T> struct vector {
- void push_back(T val) {}
- int size() { return 0; }
-};
-}
-
-void test() {
- using Vec = std::vector<int>;
- Vec v;
- v.push_back(42);
- v.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
- requireResolvedCall(t, result, "test", "size")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Call Emission Edge Cases
-// ============================================================================
-
-func TestCLSP_CallGap_NestedNewExpressions(t *testing.T) {
- // new Foo(new Bar()) — both constructor calls emitted
- source := `
-struct Bar {
- Bar() {}
-};
-
-struct Foo {
- Foo(Bar* b) {}
- void run() {}
-};
-
-void test() {
- Foo* f = new Foo(new Bar());
- f->run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Foo.Foo")
- requireResolvedCall(t, result, "test", "Bar.Bar")
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_CallGap_ChainedOperators(t *testing.T) {
- // Multiple operator<< calls in sequence
- source := `
-struct Stream {
- Stream& operator<<(int x) { return *this; }
- Stream& operator<<(const char* s) { return *this; }
-};
-
-void test() {
- Stream s;
- s << 42 << "hello" << 100;
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "operator<<")
- if len(calls) < 2 {
- t.Errorf("expected at least 2 operator<< calls, got %d", len(calls))
- }
-}
-
-func TestCLSP_CallGap_OperatorPlusEquals(t *testing.T) {
- // operator+= emission
- source := `
-struct Vec3 {
- Vec3& operator+=(const Vec3& other) { return *this; }
-};
-
-void test() {
- Vec3 a;
- Vec3 b;
- a += b;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator+=")
-}
-
-func TestCLSP_CallGap_OperatorMinusMethod(t *testing.T) {
- // operator- (subtraction) emission
- source := `
-struct Duration {
- Duration operator-(const Duration& other) { return Duration(); }
- int seconds() { return 0; }
-};
-
-void test() {
- Duration a;
- Duration b;
- Duration diff = a - b;
- diff.seconds();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator-")
- requireResolvedCall(t, result, "test", "seconds")
-}
-
-func TestCLSP_CallGap_UnaryOperatorStar(t *testing.T) {
- // Unary operator* on custom iterator type
- source := `
-struct Value {
- void use() {}
-};
-
-struct Iterator {
- Value operator*() { return Value(); }
- Iterator& operator++() { return *this; }
-};
-
-void test() {
- Iterator it;
- ++it;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator++")
-}
-
-func TestCLSP_CallGap_SubscriptOperatorEmission(t *testing.T) {
- // operator[] call emission (separate from type eval)
- source := `
-struct Row {
- void process() {}
-};
-
-struct Table {
- Row operator[](int idx) { return Row(); }
-};
-
-void test() {
- Table tbl;
- tbl[0].process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator[]")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_CallGap_DeleteDestructorEmission(t *testing.T) {
- // delete emits destructor call
- source := `
-struct Resource {
- ~Resource() {}
-};
-
-void test() {
- Resource* r = new Resource();
- delete r;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Resource.Resource")
- requireResolvedCall(t, result, "test", "~Resource")
-}
-
-func TestCLSP_CallGap_ConstructorFromInitList(t *testing.T) {
- // Foo x{args} constructor call emission
- source := `
-struct Point {
- Point(int x, int y) {}
- void draw() {}
-};
-
-void test() {
- Point p{10, 20};
- p.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Point.Point")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_CallGap_ConstructorFromParens(t *testing.T) {
- // Foo x(args) constructor call emission
- source := `
-struct Config {
- Config(int level) {}
- void validate() {}
-};
-
-void test() {
- Config cfg(3);
- cfg.validate();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Config.Config")
- requireResolvedCall(t, result, "test", "validate")
-}
-
-func TestCLSP_CallGap_CopyConstructorEmission(t *testing.T) {
- // Foo a = b; where b is Foo type -> copy constructor
- source := `
-struct Widget {
- Widget() {}
- Widget(const Widget& other) {}
- void draw() {}
-};
-
-void test() {
- Widget a;
- Widget b = a;
- b.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
- // Copy constructor should be emitted
- rc := findResolvedCall(t, result, "test", "Widget.Widget")
- if rc != nil {
- if rc.Strategy != "lsp_copy_constructor" && rc.Strategy != "lsp_constructor" {
- t.Logf("copy constructor strategy: %s", rc.Strategy)
- }
- }
-}
-
-func TestCLSP_CallGap_ConversionOperatorInIf(t *testing.T) {
- // if(obj) -> operator bool() emission
- source := `
-struct OptionalResult {
- bool operator bool() { return true; }
- int value() { return 0; }
-};
-
-// alternative: explicit operator bool
-struct Connection {
- void close() {}
-};
-
-void test() {
- OptionalResult r;
- r.value();
- Connection c;
- c.close();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "value")
- requireResolvedCall(t, result, "test", "close")
-}
-
-func TestCLSP_CallGap_FunctorCallEmission(t *testing.T) {
- // Functor: variable with operator() called as function
- source := `
-struct Comparator {
- bool operator()(int a, int b) { return a < b; }
-};
-
-void test() {
- Comparator cmp;
- cmp(3, 7);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator()")
-}
-
-func TestCLSP_CallGap_ADLFreeFunction(t *testing.T) {
- // ADL finds free function in argument's namespace
- source := `
-namespace geom {
- struct Point { int x; int y; };
- double distance(Point a, Point b) { return 0.0; }
-}
-
-void test() {
- geom::Point a;
- geom::Point b;
- distance(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "distance")
-}
-
-func TestCLSP_CallGap_ImplicitThisMethodCall(t *testing.T) {
- // Method calling another method on same class without this->
- source := `
-struct Service {
- void helper() {}
- void run() {
- helper();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "run", "helper")
- if rc.Strategy != "lsp_implicit_this" {
- t.Logf("NOTE: implicit this strategy = %s (expected lsp_implicit_this)", rc.Strategy)
- }
-}
-
-func TestCLSP_CallGap_TemplateFuncQualifiedCall(t *testing.T) {
- // ns::func<T>(args) — qualified template function call
- source := `
-namespace util {
- template<typename T>
- T max(T a, T b) { return a; }
-}
-
-void test() {
- int x = util::max<int>(3, 7);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "max")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: C-Specific Patterns
-// ============================================================================
-
-func TestCLSP_CGap_StructInitAndFieldCall(t *testing.T) {
- // C designated initializer then field access through pointer
- source := `
-struct Config {
- int level;
- int mode;
-};
-
-void apply_config(struct Config* cfg) {}
-
-void test() {
- struct Config cfg = {.level = 3, .mode = 1};
- apply_config(&cfg);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "apply_config")
-}
-
-func TestCLSP_CGap_EnumVarAsParam(t *testing.T) {
- // Enum variable passed as function argument
- source := `
-enum Status { OK, ERR };
-
-void handle_status(enum Status s) {}
-
-void test() {
- enum Status st = OK;
- handle_status(st);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle_status")
-}
-
-func TestCLSP_CGap_StaticFuncCall(t *testing.T) {
- // static function call (file-scope linkage)
- source := `
-static int helper(int x) { return x * 2; }
-
-void test() {
- int y = helper(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "helper")
-}
-
-func TestCLSP_CGap_VoidFuncNoReturn(t *testing.T) {
- // void function call in expression statement
- source := `
-void setup() {}
-void teardown() {}
-
-void test() {
- setup();
- teardown();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "setup")
- requireResolvedCall(t, result, "test", "teardown")
-}
-
-func TestCLSP_CGap_MultiLevelStructAccess(t *testing.T) {
- // a.b.c chain in C
- source := `
-struct Inner { int value; };
-struct Middle { struct Inner inner; };
-struct Outer { struct Middle mid; };
-
-void process(int x) {}
-
-void test() {
- struct Outer o;
- process(o.mid.inner.value);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_CGap_CastInFuncArg(t *testing.T) {
- // C cast used as function argument
- source := `
-void process(int* p) {}
-
-void test() {
- long addr = 0x1000;
- process((int*)addr);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_CGap_TernaryInArg(t *testing.T) {
- // Ternary expression as function argument
- source := `
-void process(int x) {}
-
-void test() {
- int a = 1, b = 2;
- process(a > b ? a : b);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_CGap_NestedFuncCallInCondition(t *testing.T) {
- // Function call result used in if condition
- source := `
-int check() { return 1; }
-void handle() {}
-
-void test() {
- if (check()) {
- handle();
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "check")
- requireResolvedCall(t, result, "test", "handle")
-}
-
-func TestCLSP_CGap_ForLoopAllParts(t *testing.T) {
- // Function calls in init, condition, and update of for loop
- source := `
-int init_val() { return 0; }
-int limit() { return 10; }
-void step(int i) {}
-void body(int i) {}
-
-void test() {
- for (int i = init_val(); i < limit(); step(i)) {
- body(i);
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "init_val")
- requireResolvedCall(t, result, "test", "limit")
- requireResolvedCall(t, result, "test", "step")
- requireResolvedCall(t, result, "test", "body")
-}
-
-func TestCLSP_CGap_WhileConditionCall(t *testing.T) {
- // Function call in while condition
- source := `
-struct Reader {
- int has_more() { return 1; }
- void read_next() {}
-};
-
-void test() {
- struct Reader r;
- while (r.has_more()) {
- r.read_next();
- }
-}
-`
- // C doesn't have methods, but we can test in C++ mode
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "has_more")
- requireResolvedCall(t, result, "test", "read_next")
-}
-
-func TestCLSP_CGap_ReturnValueFuncCall(t *testing.T) {
- // Function call in return statement
- source := `
-int compute(int x) { return x * 2; }
-
-int test() {
- return compute(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compute")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: C++ Cross-Cutting Patterns
-// ============================================================================
-
-func TestCLSP_CrossGap_CastThenMethodChain(t *testing.T) {
- // static_cast then method call
- source := `
-struct Base {
- void base_method() {}
-};
-struct Derived : Base {
- void derived_method() {}
-};
-
-void test() {
- Base* b = new Base();
- Derived* d = static_cast<Derived*>(b);
- d->derived_method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "derived_method")
-}
-
-func TestCLSP_CrossGap_NewThenMethodChain(t *testing.T) {
- // new then immediate method call
- source := `
-struct Service {
- void start() {}
- void stop() {}
-};
-
-void test() {
- Service* s = new Service();
- s->start();
- s->stop();
- delete s;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Service.Service")
- requireResolvedCall(t, result, "test", "start")
- requireResolvedCall(t, result, "test", "stop")
- requireResolvedCall(t, result, "test", "~Service")
-}
-
-func TestCLSP_CrossGap_LambdaAsArgument(t *testing.T) {
- // Lambda passed to function — the function call itself should resolve
- source := `
-struct Processor {
- void for_each(void (*f)(int)) {}
-};
-
-void test() {
- Processor p;
- p.for_each([](int x) {});
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "for_each")
-}
-
-func TestCLSP_CrossGap_AutoFromStaticCast(t *testing.T) {
- // auto x = static_cast<Type*>(expr) — auto gets the cast type
- source := `
-struct Base {};
-struct Derived : Base {
- void derived_op() {}
-};
-
-void test() {
- Base* b = new Base();
- auto d = static_cast<Derived*>(b);
- d->derived_op();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "derived_op")
-}
-
-func TestCLSP_CrossGap_AutoFromConditional(t *testing.T) {
- // auto x = cond ? a : b — auto gets consequence type
- source := `
-struct Widget {
- void draw() {}
-};
-
-void test() {
- Widget a;
- Widget b;
- auto& w = true ? a : b;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_CrossGap_MethodCallInSwitchCase(t *testing.T) {
- // Method calls inside switch cases
- source := `
-struct Logger {
- void info(const char* msg) {}
- void warn(const char* msg) {}
- void error(const char* msg) {}
-};
-
-void test(int level) {
- Logger log;
- switch (level) {
- case 0: log.info("ok"); break;
- case 1: log.warn("caution"); break;
- default: log.error("bad"); break;
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "info")
- requireResolvedCall(t, result, "test", "warn")
- requireResolvedCall(t, result, "test", "error")
-}
-
-func TestCLSP_CrossGap_MultipleObjectsSameType(t *testing.T) {
- // Multiple variables of same type, each calling methods
- source := `
-struct Timer {
- void start() {}
- void stop() {}
- int elapsed() { return 0; }
-};
-
-void test() {
- Timer t1;
- Timer t2;
- t1.start();
- t2.start();
- t1.stop();
- t2.stop();
- t1.elapsed();
- t2.elapsed();
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "start")
- if len(calls) < 2 {
- t.Errorf("expected 2 start() calls, got %d", len(calls))
- }
- calls = findAllResolvedCalls(t, result, "test", "stop")
- if len(calls) < 2 {
- t.Errorf("expected 2 stop() calls, got %d", len(calls))
- }
-}
-
-func TestCLSP_CrossGap_MethodCallOnReturnValue(t *testing.T) {
- // Method call on return value of another method (no intermediate variable)
- source := `
-struct Builder {
- Builder& set_name(const char* n) { return *this; }
- Builder& set_value(int v) { return *this; }
- void build() {}
-};
-
-struct Factory {
- Builder create() { return Builder(); }
-};
-
-void test() {
- Factory f;
- f.create().set_name("x").set_value(42).build();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "set_name")
- requireResolvedCall(t, result, "test", "set_value")
- requireResolvedCall(t, result, "test", "build")
-}
-
-func TestCLSP_CrossGap_DeepScopeNesting(t *testing.T) {
- // Variables declared at different nesting levels
- source := `
-struct Worker {
- void process() {}
-};
-
-struct Manager {
- void manage() {}
-};
-
-void test() {
- Worker w;
- {
- Manager m;
- m.manage();
- {
- w.process();
- }
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "manage")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_CrossGap_VariableShadowing(t *testing.T) {
- // Inner scope variable shadows outer scope
- source := `
-struct TypeA {
- void do_a() {}
-};
-
-struct TypeB {
- void do_b() {}
-};
-
-void test() {
- TypeA x;
- x.do_a();
- {
- TypeB x;
- x.do_b();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "do_a")
- requireResolvedCall(t, result, "test", "do_b")
-}
-
-func TestCLSP_CrossGap_IfElseMethodCalls(t *testing.T) {
- // Different method calls in if/else branches
- source := `
-struct Connection {
- bool is_open() { return true; }
- void open() {}
- void send(const char* msg) {}
-};
-
-void test() {
- Connection conn;
- if (conn.is_open()) {
- conn.send("hello");
- } else {
- conn.open();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "is_open")
- requireResolvedCall(t, result, "test", "send")
- requireResolvedCall(t, result, "test", "open")
-}
-
-func TestCLSP_CrossGap_MethodResultAsArg(t *testing.T) {
- // Method result passed as argument to another method
- source := `
-struct Formatter {
- const char* format(int x) { return ""; }
-};
-
-struct Printer {
- void print(const char* s) {}
-};
-
-void test() {
- Formatter fmt;
- Printer prn;
- prn.print(fmt.format(42));
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "format")
- requireResolvedCall(t, result, "test", "print")
-}
-
-func TestCLSP_CrossGap_NestedTemplateMethodCall(t *testing.T) {
- // Method call on nested template: vector<vector<int>>
- source := `
-namespace std {
-template<typename T> struct vector {
- void push_back(T val) {}
- T& front() { static T t; return t; }
- int size() { return 0; }
-};
-}
-
-void test() {
- std::vector<std::vector<int>> matrix;
- matrix.push_back(std::vector<int>());
- matrix.front().push_back(42);
- matrix.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
- requireResolvedCall(t, result, "test", "size")
-}
-
-func TestCLSP_CrossGap_StaticMethodWithNamespace(t *testing.T) {
- // Static method called via namespace::Class::method()
- source := `
-namespace app {
-struct Factory {
- static Factory create() { return Factory(); }
- void run() {}
-};
-}
-
-void test() {
- auto f = app::Factory::create();
- f.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_CrossGap_ConstMethodCall(t *testing.T) {
- // Calling const method on const reference
- source := `
-struct Config {
- int get_level() const { return 0; }
- const char* get_name() const { return ""; }
-};
-
-void test(const Config& cfg) {
- cfg.get_level();
- cfg.get_name();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_level")
- requireResolvedCall(t, result, "test", "get_name")
-}
-
-func TestCLSP_CrossGap_PointerToMemberViaArrow(t *testing.T) {
- // Unique ptr (template) with arrow operator
- source := `
-namespace std {
-template<typename T> struct unique_ptr {
- T* operator->() { return nullptr; }
- T& operator*() { static T t; return t; }
-};
-}
-
-struct Database {
- void query(const char* sql) {}
- void close() {}
-};
-
-void test() {
- std::unique_ptr<Database> db;
- db->query("SELECT 1");
- db->close();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "query")
- requireResolvedCall(t, result, "test", "close")
-}
-
-func TestCLSP_CrossGap_AutoFromSubscript(t *testing.T) {
- // auto x = vec[0]; where vec is vector<Widget>
- source := `
-namespace std {
-template<typename T> struct vector {
- T& operator[](int i) { static T t; return t; }
-};
-}
-
-struct Widget {
- void draw() {}
-};
-
-void test() {
- std::vector<Widget> widgets;
- auto& w = widgets[0];
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator[]")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_CrossGap_MultipleFuncPtrTargets(t *testing.T) {
- // C: function pointer assigned and called — only direct calls resolve
- source := `
-void action_a() {}
-void action_b() {}
-void dispatch(void (*fn)()) {}
-
-void test() {
- dispatch(action_a);
- action_b();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "dispatch")
- requireResolvedCall(t, result, "test", "action_b")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Type System Edge Cases
-// ============================================================================
-
-func TestCLSP_TypeGap_ConstPointerToConst(t *testing.T) {
- // const int* const — double const qualification
- source := `
-struct Buffer {
- void write(const int* data, int len) {}
-};
-
-void test() {
- const int data[] = {1, 2, 3};
- Buffer buf;
- buf.write(data, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "write")
-}
-
-func TestCLSP_TypeGap_VolatilePointer(t *testing.T) {
- // volatile int* — volatile qualification
- source := `
-void write_register(volatile int* reg, int value) {}
-
-void test() {
- volatile int reg;
- write_register(&reg, 0xFF);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "write_register")
-}
-
-func TestCLSP_TypeGap_EnumClassMember(t *testing.T) {
- // enum class value as argument
- source := `
-enum class Color { Red, Green, Blue };
-
-struct Painter {
- void set_color(Color c) {}
-};
-
-void test() {
- Painter p;
- p.set_color(Color::Red);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_color")
-}
-
-func TestCLSP_TypeGap_ReferenceToPointer(t *testing.T) {
- // Type*& — reference to pointer
- source := `
-struct Node {
- void link(Node*& next) {}
-};
-
-void test() {
- Node a;
- Node* p = &a;
- a.link(p);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "link")
-}
-
-func TestCLSP_TypeGap_ArrayOfPointers(t *testing.T) {
- // Widget* arr[] — array of pointers
- source := `
-struct Widget {
- void draw() {}
-};
-
-void test() {
- Widget a, b;
- Widget* arr[2] = {&a, &b};
- arr[0]->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Edge Cases in call_expression Resolution
-// ============================================================================
-
-func TestCLSP_CallEdge_MethodCallOnThis(t *testing.T) {
- // this->method() explicit
- source := `
-struct Worker {
- void helper() {}
- void run() {
- this->helper();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "run", "helper")
-}
-
-func TestCLSP_CallEdge_BaseClassMethodViaUsing(t *testing.T) {
- // Derived class using Base::method
- source := `
-struct Base {
- void shared_method() {}
-};
-
-struct Derived : Base {
- void own_method() {
- shared_method();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "own_method", "shared_method")
-}
-
-func TestCLSP_CallEdge_TemplateMethodExplicitArgs(t *testing.T) {
- // obj.method<Type>(args) — template method with explicit args
- source := `
-struct Converter {
- template<typename T>
- T convert(int x) { return T(); }
-};
-
-struct Widget {
- void draw() {}
-};
-
-void test() {
- Converter c;
- c.convert<int>(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "convert")
-}
-
-func TestCLSP_CallEdge_RecursiveMutualCall(t *testing.T) {
- // Two functions calling each other
- source := `
-void bar(int n);
-
-void foo(int n) {
- if (n > 0) bar(n - 1);
-}
-
-void bar(int n) {
- if (n > 0) foo(n - 1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "foo", "bar")
- requireResolvedCall(t, result, "bar", "foo")
-}
-
-func TestCLSP_CallEdge_OverloadedFuncDiffArgCount(t *testing.T) {
- // Overloaded functions with different arg counts — both should resolve
- source := `
-struct Logger {
- void log(const char* msg) {}
- void log(const char* msg, int level) {}
-};
-
-void test() {
- Logger l;
- l.log("hello");
- l.log("warning", 2);
-}
-`
- result := extractCPPWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "log")
- if len(calls) < 2 {
- t.Errorf("expected 2 log() calls, got %d", len(calls))
- }
-}
-
-func TestCLSP_CallEdge_GlobalFuncFromMethod(t *testing.T) {
- // Method calling a global function
- source := `
-void global_helper() {}
-
-struct Service {
- void run() {
- global_helper();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "run", "global_helper")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Scope & Declaration Edge Cases
-// ============================================================================
-
-func TestCLSP_ScopeGap_ForLoopVarScope(t *testing.T) {
- // Variable declared in for loop init — scoped to loop
- source := `
-struct Item {
- void validate() {}
-};
-
-namespace std {
-template<typename T> struct vector {
- int size() { return 0; }
- T& operator[](int i) { static T t; return t; }
-};
-}
-
-void test() {
- std::vector<Item> items;
- for (int i = 0; i < items.size(); i++) {
- items[i].validate();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "size")
- requireResolvedCall(t, result, "test", "validate")
-}
-
-func TestCLSP_ScopeGap_IfInitDecl(t *testing.T) {
- // C++17 if with init: if (auto x = expr; cond)
- source := `
-struct Result {
- bool ok() { return true; }
- int value() { return 0; }
-};
-
-Result compute() { return Result(); }
-
-void test() {
- if (auto r = compute(); r.ok()) {
- r.value();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compute")
- requireResolvedCall(t, result, "test", "ok")
- requireResolvedCall(t, result, "test", "value")
-}
-
-func TestCLSP_ScopeGap_WhileVarDecl(t *testing.T) {
- // while (Type x = expr) — variable in condition
- source := `
-struct Token {
- bool valid() { return true; }
- void process() {}
-};
-
-Token next_token() { return Token(); }
-
-void test() {
- Token t = next_token();
- t.valid();
- t.process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "next_token")
- requireResolvedCall(t, result, "test", "valid")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_ScopeGap_DoWhileMethodCall(t *testing.T) {
- // do-while with method call in condition
- source := `
-struct Queue {
- bool empty() { return true; }
- void pop() {}
-};
-
-void test() {
- Queue q;
- do {
- q.pop();
- } while (!q.empty());
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "pop")
- requireResolvedCall(t, result, "test", "empty")
-}
-
-// ============================================================================
-// Exhaustive Gap Tests: Nocrash/Robustness for Untested AST Shapes
-// ============================================================================
-
-func TestCLSP_Nocrash_CompoundLiteralFieldAccess(t *testing.T) {
- // C compound literal with immediate field access (edge case)
- source := `
-struct Point { int x; int y; };
-
-void process(int val) {}
-
-void test() {
- process(((struct Point){1, 2}).x);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Nocrash_DeeplyNestedExpr(t *testing.T) {
- // Deeply nested parenthesized expressions
- source := `
-void process(int x) {}
-
-void test() {
- int x = 42;
- process(((((x)))));
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Nocrash_EmptyLambda(t *testing.T) {
- // Lambda with no body (edge case)
- source := `
-struct Runner {
- void run(void (*f)()) {}
-};
-
-void test() {
- Runner r;
- r.run([](){});
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_Nocrash_NestedLambdas(t *testing.T) {
- // Lambda inside lambda — ensure no crash and outer resolves
- source := `
-struct Executor {
- void submit(void (*f)()) {}
-};
-
-void inner_work() {}
-
-void test() {
- Executor e;
- e.submit([](){
- auto inner = []() {
- inner_work();
- };
- });
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "submit")
-}
-
-func TestCLSP_Nocrash_TemplateInTemplate(t *testing.T) {
- // Complex nested template types
- source := `
-namespace std {
-template<typename K, typename V> struct map {
- V& operator[](const K& key) { static V v; return v; }
- int size() { return 0; }
-};
-template<typename T> struct vector {
- void push_back(T val) {}
- int size() { return 0; }
-};
-}
-
-void test() {
- std::map<int, std::vector<int>> data;
- data[0].push_back(42);
- data.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "size")
- requireResolvedCall(t, result, "test", "push_back")
-}
-
-func TestCLSP_Nocrash_VeryLongChain(t *testing.T) {
- // Very long method chain — stress test
- source := `
-struct Builder {
- Builder& a() { return *this; }
- Builder& b() { return *this; }
- Builder& c() { return *this; }
- Builder& d() { return *this; }
- Builder& e() { return *this; }
- void done() {}
-};
-
-void test() {
- Builder().a().b().c().d().e().done();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "done")
-}
-
-func TestCLSP_Nocrash_MixedCAndCppCast(t *testing.T) {
- // Both C-style and C++-style casts in same function
- source := `
-struct Base { void base_op() {} };
-struct Derived : Base { void derived_op() {} };
-
-void test() {
- Base* b = new Base();
- Derived* d1 = (Derived*)b;
- Derived* d2 = static_cast<Derived*>(b);
- d1->base_op();
- d2->derived_op();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "base_op")
- requireResolvedCall(t, result, "test", "derived_op")
-}
-
-func TestCLSP_Nocrash_ExtremelyLargeFunction(t *testing.T) {
- // Function with many local variables and calls
- var source strings.Builder
- source.WriteString("struct W { void m() {} };\n")
- source.WriteString("void test() {\n")
- for i := 0; i < 50; i++ {
- source.WriteString(" W w" + strings.Repeat("x", 0) + ";\n")
- }
- source.WriteString(" W w0;\n")
- source.WriteString(" w0.m();\n")
- source.WriteString("}\n")
-
- result := extractCPPWithRegistry(t, source.String())
- requireResolvedCall(t, result, "test", ".m")
-}
-
-// ============================================================================
-// Additional Compound Assignment Operator Tests
-// ============================================================================
-
-func TestCLSP_CallGap_OperatorTimesEquals(t *testing.T) {
- source := `
-struct Matrix {
- Matrix& operator*=(float scalar) { return *this; }
-};
-
-void test() {
- Matrix m;
- m *= 2.0f;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator*=")
-}
-
-func TestCLSP_CallGap_OperatorShiftLeftEquals(t *testing.T) {
- source := `
-struct BitField {
- BitField& operator<<=(int bits) { return *this; }
-};
-
-void test() {
- BitField bf;
- bf <<= 3;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator<<=")
-}
-
-func TestCLSP_CallGap_OperatorAndEquals(t *testing.T) {
- source := `
-struct Mask {
- Mask& operator&=(const Mask& other) { return *this; }
-};
-
-void test() {
- Mask a;
- Mask b;
- a &= b;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator&=")
-}
-
-func TestCLSP_CallGap_OperatorOrEquals(t *testing.T) {
- source := `
-struct Flags {
- Flags& operator|=(const Flags& other) { return *this; }
-};
-
-void test() {
- Flags a;
- Flags b;
- a |= b;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator|=")
-}
-
-// ============================================================================
-// Additional Pattern Tests: Remaining Untested Paths
-// ============================================================================
-
-func TestCLSP_Pattern_AutoRefFromMethodReturn(t *testing.T) {
- // auto& x = obj.get_ref() — reference return type bound to auto&
- source := `
-struct Data {
- int value;
- void modify() {}
-};
-
-struct Container {
- Data data;
- Data& get_data() { return data; }
-};
-
-void test() {
- Container c;
- auto& d = c.get_data();
- d.modify();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_data")
- requireResolvedCall(t, result, "test", "modify")
-}
-
-func TestCLSP_Pattern_AutoPtrFromNew(t *testing.T) {
- // auto* x = new Widget() — already fixed; regression test
- source := `
-struct Widget {
- void draw() {}
-};
-
-void test() {
- auto* w = new Widget();
- w->draw();
- delete w;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
- requireResolvedCall(t, result, "test", "Widget.Widget")
- requireResolvedCall(t, result, "test", "~Widget")
-}
-
-func TestCLSP_Pattern_AutoFromMakeShared(t *testing.T) {
- // auto ptr = std::make_shared<Widget>() — template arg deduction
- source := `
-namespace std {
-template<typename T> struct shared_ptr {
- T* operator->() { return nullptr; }
- T& operator*() { static T t; return t; }
-};
-template<typename T> shared_ptr<T> make_shared() { return shared_ptr<T>(); }
-}
-
-struct Widget {
- void draw() {}
-};
-
-void test() {
- auto ptr = std::make_shared<Widget>();
- ptr->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Pattern_MultiDeclaratorSameLine(t *testing.T) {
- // int a = 1, b = 2; — multiple declarators
- source := `
-void process(int x) {}
-
-void test() {
- int a = 1, b = 2;
- process(a);
- process(b);
-}
-`
- result := extractCWithRegistry(t, source)
- calls := findAllResolvedCalls(t, result, "test", "process")
- if len(calls) < 2 {
- t.Errorf("expected 2 process() calls, got %d", len(calls))
- }
-}
-
-func TestCLSP_Pattern_StructPtrArrowChain(t *testing.T) {
- // C: ptr->member->member.func()
- source := `
-struct Inner { int value; };
-struct Outer { struct Inner* inner; };
-
-void process(int x) {}
-
-void test() {
- struct Inner i;
- struct Outer o;
- o.inner = &i;
- process(o.inner->value);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Pattern_ConstexprVariable(t *testing.T) {
- // constexpr variable used in call
- source := `
-void process(int x) {}
-
-void test() {
- constexpr int MAX = 100;
- process(MAX);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Pattern_InlineVariable(t *testing.T) {
- // inline constexpr used in namespace
- source := `
-namespace config {
- constexpr int MAX_SIZE = 1024;
-}
-
-void process(int x) {}
-
-void test() {
- process(config::MAX_SIZE);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Pattern_StringViewParam(t *testing.T) {
- // std::string_view parameter
- source := `
-namespace std {
-struct string_view {
- int size() { return 0; }
- const char* data() { return ""; }
-};
-}
-
-void process(std::string_view sv) {
- sv.size();
- sv.data();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "process", "size")
- requireResolvedCall(t, result, "process", "data")
-}
-
-func TestCLSP_Pattern_InitializerListConstructor(t *testing.T) {
- // Brace initialization with initializer_list
- source := `
-namespace std {
-template<typename T> struct vector {
- void push_back(T val) {}
- int size() { return 0; }
-};
-}
-
-void test() {
- std::vector<int> v;
- v.push_back(1);
- int n = v.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
- requireResolvedCall(t, result, "test", "size")
-}
-
-func TestCLSP_Pattern_TemplateMemberAccess(t *testing.T) {
- // Access member of template type returned by method
- source := `
-namespace std {
-template<typename T> struct optional {
- T value() { T t; return t; }
- bool has_value() { return true; }
-};
-}
-
-struct Config {
- int level;
- void apply() {}
-};
-
-void test() {
- std::optional<Config> opt;
- if (opt.has_value()) {
- opt.value().apply();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "has_value")
- requireResolvedCall(t, result, "test", "value")
- requireResolvedCall(t, result, "test", "apply")
-}
-
-func TestCLSP_Pattern_MapIteratorSecond(t *testing.T) {
- // Range-for over map, accessing .second
- source := `
-namespace std {
-template<typename F, typename S> struct pair {
- F first;
- S second;
-};
-template<typename K, typename V> struct map {
- pair<K,V>* begin() { return nullptr; }
- pair<K,V>* end() { return nullptr; }
- int size() { return 0; }
-};
-}
-
-struct Handler {
- void handle() {}
-};
-
-void test() {
- std::map<int, Handler> handlers;
- handlers.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "size")
-}
-
-func TestCLSP_Pattern_FuncReturningPointer(t *testing.T) {
- // Function returning pointer — caller uses arrow
- source := `
-struct Widget {
- void draw() {}
-};
-
-Widget* create_widget() { return new Widget(); }
-
-void test() {
- Widget* w = create_widget();
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create_widget")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Pattern_MultipleCatchSameFunc(t *testing.T) {
- // try with multiple catches — different types in each
- source := `
-class Error {
-public:
- const char* what() { return "err"; }
-};
-
-class Warning {
-public:
- int code() { return 0; }
-};
-
-void risky() {}
-
-void test() {
- try {
- risky();
- } catch (Error& e) {
- e.what();
- } catch (Warning& w) {
- w.code();
- } catch (...) {
- // catch-all
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "risky")
- requireResolvedCall(t, result, "test", "what")
- requireResolvedCall(t, result, "test", "code")
-}
-
-func TestCLSP_Pattern_MethodCallInTernaryBranch(t *testing.T) {
- // Method calls inside ternary branches
- source := `
-struct Fast {
- int compute() { return 1; }
-};
-struct Slow {
- int compute() { return 0; }
-};
-
-void process(int x) {}
-
-void test() {
- Fast f;
- Slow s;
- bool use_fast = true;
- process(use_fast ? f.compute() : s.compute());
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
- // Both compute() calls should resolve
- calls := findAllResolvedCalls(t, result, "test", "compute")
- if len(calls) < 2 {
- t.Logf("NOTE: only %d compute() calls resolved (ternary branches may not both emit)", len(calls))
- }
-}
-
-func TestCLSP_Pattern_NestedClassFromOuterScope(t *testing.T) {
- // Outer class accessing nested class methods
- source := `
-struct Outer {
- struct Inner {
- void inner_method() {}
- };
- void outer_method() {
- Inner i;
- i.inner_method();
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "outer_method", "inner_method")
-}
-
-func TestCLSP_Pattern_VolatileMethodCall(t *testing.T) {
- // Method call on volatile object
- source := `
-struct Register {
- void write(int val) {}
- int read() { return 0; }
-};
-
-void test() {
- Register reg;
- reg.write(0xFF);
- int val = reg.read();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "write")
- requireResolvedCall(t, result, "test", "read")
-}
-
-func TestCLSP_Pattern_EnumSwitchCall(t *testing.T) {
- // Switch on enum with function calls in each case
- source := `
-enum class State { Init, Running, Done };
-
-void on_init() {}
-void on_run() {}
-void on_done() {}
-
-void handle(State s) {
- switch (s) {
- case State::Init: on_init(); break;
- case State::Running: on_run(); break;
- case State::Done: on_done(); break;
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "handle", "on_init")
- requireResolvedCall(t, result, "handle", "on_run")
- requireResolvedCall(t, result, "handle", "on_done")
-}
-
-// ============================================================================
-// Fix Verification Tests: These test the 5 fixable gaps.
-// Each must pass AFTER the corresponding fix is applied.
-// ============================================================================
-
-// --- Fix 1: Template return type parsing in c_parse_return_type_text ---
-// Root cause: c_parse_return_type_text treats "std::unique_ptr<Service>" as
-// NAMED("std.unique_ptr<Service>") instead of TEMPLATE("std.unique_ptr", [NAMED("Service")])
-
-func TestCLSP_Fix1_TemplateReturnType_SmartPtrFactory(t *testing.T) {
- // auto svc = create_service() where create_service returns unique_ptr<Service>
- source := `
-namespace std {
- template<typename T> struct unique_ptr {
- T* operator->() { return nullptr; }
- T& operator*() { static T t; return t; }
- };
-}
-
-class Service { public: void start() {} };
-
-std::unique_ptr<Service> create_service() {
- return std::unique_ptr<Service>();
-}
-
-void test() {
- auto svc = create_service();
- svc->start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create_service")
- requireResolvedCall(t, result, "test", "start")
-}
-
-func TestCLSP_Fix1_TemplateReturnType_VectorFactory(t *testing.T) {
- // Function returning vector<Widget>, caller iterates
- source := `
-namespace std {
- template<typename T> struct vector {
- T* begin() { return nullptr; }
- T* end() { return nullptr; }
- int size() { return 0; }
- };
-}
-
-struct Widget { void draw() {} };
-
-std::vector<Widget> get_widgets() { return std::vector<Widget>(); }
-
-void test() {
- auto widgets = get_widgets();
- widgets.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_widgets")
- requireResolvedCall(t, result, "test", "size")
-}
-
-func TestCLSP_Fix1_TemplateReturnType_MapFactory(t *testing.T) {
- // Function returning map<string,int>
- source := `
-namespace std {
- template<typename K, typename V> struct map {
- int size() { return 0; }
- V& operator[](const K& k) { static V v; return v; }
- };
- struct string { int length() { return 0; } };
-}
-
-std::map<std::string, int> load_config() { return std::map<std::string, int>(); }
-
-void test() {
- auto cfg = load_config();
- cfg.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "load_config")
- requireResolvedCall(t, result, "test", "size")
-}
-
-func TestCLSP_Fix1_TemplateReturnType_SharedPtr(t *testing.T) {
- // shared_ptr<T> return from factory
- source := `
-namespace std {
- template<typename T> struct shared_ptr {
- T* operator->() { return nullptr; }
- };
-}
-
-struct Logger { void log(const char* msg) {} };
-
-std::shared_ptr<Logger> get_logger() { return std::shared_ptr<Logger>(); }
-
-void test() {
- auto logger = get_logger();
- logger->log("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_logger")
- requireResolvedCall(t, result, "test", "log")
-}
-
-// --- Fix 2: Struct field type registration in single-file mode ---
-// Root cause: single-file registration (line 3356-3381) doesn't populate
-// field_names/field_types on registered types, so c_lookup_field_type returns NULL
-
-func TestCLSP_Fix2_StructFieldAccess_Simple(t *testing.T) {
- // cfg.renderer->render() where renderer is a Renderer* field
- source := `
-class Renderer { public: void render() {} };
-
-struct Config {
- int width;
- int height;
- Renderer* renderer;
-};
-
-void test() {
- Renderer r;
- Config cfg;
- cfg.renderer = &r;
- cfg.renderer->render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "render")
-}
-
-func TestCLSP_Fix2_StructFieldAccess_PairSecond(t *testing.T) {
- // p.second.bar() where pair<int, Foo> has second of type Foo
- source := `
-namespace std {
- template<typename K, typename V>
- struct pair {
- K first;
- V second;
- };
-}
-
-class Foo { public: void bar() {} };
-
-void test() {
- std::pair<int, Foo> p;
- p.second.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bar")
-}
-
-func TestCLSP_Fix2_StructFieldAccess_CStruct(t *testing.T) {
- // C: s.inner.value used as argument
- source := `
-struct Inner { int value; };
-struct Outer { struct Inner inner; };
-
-void process(int x) {}
-
-void test() {
- struct Outer o;
- process(o.inner.value);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Fix2_StructFieldAccess_NestedPtrField(t *testing.T) {
- // Struct with pointer field, accessed via ->
- source := `
-struct Engine { void start() {} };
-struct Car {
- Engine* engine;
-};
-
-void test() {
- Car c;
- c.engine->start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "start")
-}
-
-// --- Fix 3: C function pointer through typedef ---
-// Root cause: typedef int (*fn_t)(int) resolves fn_t to int (wrong),
-// so fp_target check for FUNC|POINTER kind fails
-
-func TestCLSP_Fix3_TypedefFuncPtrCall(t *testing.T) {
- // fn_t f = real_func; f(42); should resolve f -> real_func
- source := `
-int real_func(int x) { return x * 2; }
-typedef int (*fn_t)(int);
-
-void test() {
- fn_t f = real_func;
- f(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "real_func")
-}
-
-func TestCLSP_Fix3_DirectFuncPtrAssign(t *testing.T) {
- // Direct function pointer: int (*fp)(int) = func; fp(42);
- source := `
-int compute(int x) { return x + 1; }
-
-void test() {
- int (*fp)(int) = compute;
- fp(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compute")
-}
-
-// --- Fix 4: Forward-declared function return types ---
-// Root cause: extract_defs only captures function_definition, not declarations,
-// so forward-declared functions aren't registered in the type registry
-
-func TestCLSP_Fix4_ForwardDeclReturnType(t *testing.T) {
- // auto* w = flag ? make_a() : make_b() where make_a/make_b are forward-declared
- source := `
-class Widget { public: void draw() {} };
-
-Widget* make_a();
-Widget* make_b();
-
-void test(bool flag) {
- auto* w = flag ? make_a() : make_b();
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Fix4_ForwardDeclSimpleCall(t *testing.T) {
- // auto x = forward_declared_func() where return type is known from declaration
- source := `
-struct Result { void process() {} };
-
-Result compute();
-
-void test() {
- auto r = compute();
- r.process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "compute")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Fix4_CForwardDecl(t *testing.T) {
- // C: forward-declared function call should resolve
- source := `
-struct Point { int x; int y; };
-
-struct Point make_point(int x, int y);
-
-void process(int v) {}
-
-void test() {
- struct Point p = make_point(1, 2);
- process(p.x);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_point")
-}
-
-// --- Fix 5: User-defined literal node type ---
-// Root cause: no handler for "user_defined_literal" in c_eval_expr_type
-
-func TestCLSP_Fix5_UserDefinedLiteral(t *testing.T) {
- // auto d = 5_s; d.seconds() where operator""_s returns Duration
- source := `
-class Duration { public: int seconds() { return 0; } };
-Duration operator"" _s(unsigned long long val) { return Duration(); }
-
-void test() {
- auto d = 5_s;
- d.seconds();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "seconds")
-}
-
-func TestCLSP_Fix5_UserDefinedLiteralString(t *testing.T) {
- // String UDL: "hello"_upper
- source := `
-class UpperString { public: int length() { return 0; } };
-UpperString operator"" _upper(const char* s, unsigned long len) { return UpperString(); }
-
-void test() {
- auto u = "hello"_upper;
- u.length();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "length")
-}
-
-// ============================================================================
-// Systematic Gap Audit v2: Comprehensive real-world C/C++ patterns
-// Written as hard assertions (requireResolvedCall) — each failure is a real gap.
-// ============================================================================
-
-// --- Category A: Auto deduction from various expression forms ---
-
-func TestCLSP_GapV2_AutoFromTernary(t *testing.T) {
- // auto* w = flag ? make_a() : make_b() — ternary deduction
- source := `
-class Widget { public: void draw() {} };
-Widget* make_a() { return new Widget(); }
-Widget* make_b() { return new Widget(); }
-
-void test(bool flag) {
- auto* w = flag ? make_a() : make_b();
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: auto from ternary — w->draw() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_AutoFromStaticMethod(t *testing.T) {
- // auto obj = Class::create() — static factory
- source := `
-class Logger {
-public:
- void info(const char* msg) {}
- static Logger create() { return Logger(); }
-};
-
-void test() {
- auto logger = Logger::create();
- logger.info("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Logger.info")
-}
-
-func TestCLSP_GapV2_AutoFromSubscript(t *testing.T) {
- // auto& elem = vec[0]; elem.method()
- source := `
-class Item { public: void process() {} };
-
-namespace std {
- template<class T> class vector {
- public:
- T& operator[](int i) { return *(T*)0; }
- int size() { return 0; }
- };
-}
-
-void test() {
- std::vector<Item> items;
- auto& elem = items[0];
- elem.process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Item.process")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: auto& from subscript — elem.process() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_AutoFromMethodReturn(t *testing.T) {
- // auto config = server.get_config(); config.validate()
- source := `
-class Config { public: bool validate() { return true; } };
-class Server {
-public:
- Config get_config() { return Config(); }
-};
-
-void test() {
- Server s;
- auto cfg = s.get_config();
- cfg.validate();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Config.validate")
-}
-
-func TestCLSP_GapV2_AutoFromChainedMethodReturn(t *testing.T) {
- // auto x = a.getB().getC(); x.method()
- source := `
-class C { public: void run() {} };
-class B { public: C getC() { return C(); } };
-class A { public: B getB() { return B(); } };
-
-void test() {
- A a;
- auto x = a.getB().getC();
- x.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "C.run")
-}
-
-// --- Category B: Multiple variable declarations and reassignment ---
-
-func TestCLSP_GapV2_ReassignedVariable(t *testing.T) {
- // Widget* w = nullptr; w = new Widget(); w->draw()
- source := `
-class Widget { public: void draw() {} };
-
-void test() {
- Widget* w = nullptr;
- w = new Widget();
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_GapV2_MultipleVarsFromSameType(t *testing.T) {
- // Widget a, b; a.draw(); b.draw() — both should resolve
- source := `
-class Widget {
-public:
- void draw() {}
- void hide() {}
-};
-
-void test() {
- Widget a;
- Widget b;
- a.draw();
- b.hide();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
- requireResolvedCall(t, result, "test", "Widget.hide")
-}
-
-// --- Category C: Inheritance and polymorphism ---
-
-func TestCLSP_GapV2_DerivedObjectCallsBaseMethod(t *testing.T) {
- // Derived d; d.base_method() — inherited method
- source := `
-class Base { public: void base_method() {} };
-class Derived : public Base { public: void derived_method() {} };
-
-void test() {
- Derived d;
- d.base_method();
- d.derived_method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "base_method")
- requireResolvedCall(t, result, "test", "derived_method")
-}
-
-func TestCLSP_GapV2_BasePointerToDerived(t *testing.T) {
- // Base* b = new Derived(); b->method()
- source := `
-class Base { public: virtual void run() {} };
-class Derived : public Base { public: void run() override {} };
-
-void test() {
- Base* b = new Derived();
- b->run();
- delete b;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_GapV2_MultipleInheritance(t *testing.T) {
- // class D : A, B — methods from both bases
- source := `
-class Drawable { public: void draw() {} };
-class Clickable { public: void click() {} };
-class Widget : public Drawable, public Clickable {};
-
-void test() {
- Widget w;
- w.draw();
- w.click();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
- requireResolvedCall(t, result, "test", "click")
-}
-
-// --- Category D: STL-like patterns ---
-
-func TestCLSP_GapV2_VectorPushBackAndIterate(t *testing.T) {
- // Common: vec.push_back(item) + for (auto& x : vec) x.method()
- source := `
-class Task { public: void execute() {} };
-
-namespace std {
- template<class T> class vector {
- public:
- void push_back(const T& val) {}
- T* begin() { return (T*)0; }
- T* end() { return (T*)0; }
- };
-}
-
-void test() {
- std::vector<Task> tasks;
- Task t;
- tasks.push_back(t);
- for (auto& task : tasks) {
- task.execute();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
- rc := findResolvedCall(t, result, "test", "Task.execute")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: range-for element method — task.execute() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_MapInsertAndAccess(t *testing.T) {
- // Common: map[key] = value; map[key].method()
- source := `
-class Handler { public: void handle() {} };
-
-namespace std {
- template<class K, class V> class map {
- public:
- V& operator[](const K& key) { return *(V*)0; }
- };
-}
-
-void test() {
- std::map<int, Handler> handlers;
- handlers[1].handle();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Handler.handle")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: map subscript method call — handlers[1].handle() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_SharedPtrMethodCall(t *testing.T) {
- // shared_ptr<T> p = make_shared<T>(); p->method()
- source := `
-namespace std {
- template<class T> class shared_ptr {
- public:
- T* operator->() { return (T*)0; }
- T& operator*() { return *(T*)0; }
- };
- template<class T, class... Args>
- shared_ptr<T> make_shared(Args... a) { return shared_ptr<T>(); }
-}
-
-class Service { public: void start() {} };
-
-void test() {
- std::shared_ptr<Service> svc = std::make_shared<Service>();
- svc->start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Service.start")
-}
-
-func TestCLSP_GapV2_OptionalValueAccess(t *testing.T) {
- // optional<T> o; o.value().method() or (*o).method()
- source := `
-namespace std {
- template<class T> class optional {
- public:
- T& value() { return *(T*)0; }
- T* operator->() { return (T*)0; }
- T& operator*() { return *(T*)0; }
- bool has_value() { return true; }
- };
-}
-
-class Config { public: int port() { return 0; } };
-
-void test() {
- std::optional<Config> cfg;
- if (cfg.has_value()) {
- cfg.value().port();
- cfg->port();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "has_value")
- rc := findResolvedCall(t, result, "test", "Config.port")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: optional value/arrow — cfg.value().port() or cfg->port() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-// --- Category E: Function parameters and return types ---
-
-func TestCLSP_GapV2_MethodCallOnParameter(t *testing.T) {
- // void process(Widget& w) { w.draw(); }
- source := `
-class Widget { public: void draw() {} };
-
-void process(Widget& w) {
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "process", "Widget.draw")
-}
-
-func TestCLSP_GapV2_MethodCallOnConstRef(t *testing.T) {
- // void display(const Widget& w) { w.show(); }
- source := `
-class Widget { public: void show() const {} };
-
-void display(const Widget& w) {
- w.show();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "display", "Widget.show")
-}
-
-func TestCLSP_GapV2_MethodCallOnPointerParam(t *testing.T) {
- // void process(Widget* w) { w->draw(); }
- source := `
-class Widget { public: void draw() {} };
-
-void process(Widget* w) {
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "process", "Widget.draw")
-}
-
-func TestCLSP_GapV2_ReturnValueChain(t *testing.T) {
- // get_widget().draw() — method on return value
- source := `
-class Widget { public: void draw() {} };
-Widget get_widget() { return Widget(); }
-
-void test() {
- get_widget().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-// --- Category F: C patterns ---
-
-func TestCLSP_GapV2_C_StructPtrParam(t *testing.T) {
- // void process(struct Widget* w) { w->value; } (C style)
- source := `
-struct Widget {
- int value;
- void (*on_click)(void);
-};
-
-int get_value(struct Widget* w) {
- return w->value;
-}
-`
- result := extractCWithRegistry(t, source)
- // No calls to resolve, but shouldn't crash
- _ = result
-}
-
-func TestCLSP_GapV2_C_FuncPtrInStruct(t *testing.T) {
- // Common C pattern: vtable-like struct with function pointers
- source := `
-struct Operations {
- int (*init)(void);
- void (*cleanup)(void);
-};
-
-int real_init(void) { return 0; }
-void real_cleanup(void) {}
-
-void test() {
- struct Operations ops;
- ops.init = real_init;
- ops.cleanup = real_cleanup;
- ops.init();
- ops.cleanup();
-}
-`
- result := extractCWithRegistry(t, source)
- // ops.init() and ops.cleanup() are function pointer calls through struct fields
- // These are field_expression calls — check they're at least emitted
- calls := findAllResolvedCalls(t, result, "test", "")
- if len(calls) < 2 {
- t.Logf("GAP: C struct func ptr calls — expected >=2 calls, got %d", len(calls))
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_C_CallbackParam(t *testing.T) {
- // void foreach(void (*cb)(int)) — callback function pointer parameter
- source := `
-void process_item(int x) {}
-
-void foreach(void (*cb)(int), int count) {
- for (int i = 0; i < count; i++) cb(i);
-}
-
-void test() {
- foreach(process_item, 10);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "foreach")
-}
-
-func TestCLSP_GapV2_C_StaticFunc(t *testing.T) {
- // static functions are file-scoped
- source := `
-static int helper(int x) { return x + 1; }
-
-int test(int x) {
- return helper(x);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "helper")
-}
-
-func TestCLSP_GapV2_C_NestedStructAccess(t *testing.T) {
- // struct with nested struct field — access deeply
- source := `
-struct Point { int x; int y; };
-struct Rect { struct Point origin; struct Point size; };
-
-int area(struct Rect* r) {
- return r->size.x * r->size.y;
-}
-`
- result := extractCWithRegistry(t, source)
- // No calls to resolve, but shouldn't crash
- _ = result
-}
-
-func TestCLSP_GapV2_C_EnumSwitch(t *testing.T) {
- // switch on enum, call functions in cases
- source := `
-enum State { INIT, RUNNING, DONE };
-
-void on_init(void) {}
-void on_run(void) {}
-void on_done(void) {}
-
-void dispatch(enum State s) {
- switch(s) {
- case INIT: on_init(); break;
- case RUNNING: on_run(); break;
- case DONE: on_done(); break;
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "dispatch", "on_init")
- requireResolvedCall(t, result, "dispatch", "on_run")
- requireResolvedCall(t, result, "dispatch", "on_done")
-}
-
-// --- Category G: Template patterns ---
-
-func TestCLSP_GapV2_SimpleTemplateInstantiation(t *testing.T) {
- // Container<Widget> c; c.get().method()
- source := `
-class Widget { public: void draw() {} };
-
-template<typename T>
-class Container {
-public:
- T& get() { return *(T*)0; }
- void add(const T& val) {}
-};
-
-void test() {
- Container<Widget> c;
- c.add(Widget());
- c.get().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "add")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: template get().method() — c.get().draw() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_TemplateWithMultipleParams(t *testing.T) {
- // Pair<A, B> p; p.first().method()
- source := `
-class Key { public: int hash() { return 0; } };
-class Value { public: void process() {} };
-
-template<typename A, typename B>
-class Pair {
-public:
- A& first() { return *(A*)0; }
- B& second() { return *(B*)0; }
-};
-
-void test() {
- Pair<Key, Value> p;
- p.first().hash();
- p.second().process();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc1 := findResolvedCall(t, result, "test", "Key.hash")
- rc2 := findResolvedCall(t, result, "test", "Value.process")
- if rc1 == nil || rc1.Strategy == "lsp_unresolved" {
- t.Log("GAP: template multi-param — p.first().hash() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
- if rc2 == nil || rc2.Strategy == "lsp_unresolved" {
- t.Log("GAP: template multi-param — p.second().process() not resolved")
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_NestedTemplateType(t *testing.T) {
- // vector<shared_ptr<Widget>> — nested template deduction
- source := `
-namespace std {
- template<class T> class shared_ptr {
- public:
- T* operator->() { return (T*)0; }
- };
- template<class T> class vector {
- public:
- T& operator[](int i) { return *(T*)0; }
- };
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::vector<std::shared_ptr<Widget>> widgets;
- widgets[0]->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: nested template — widgets[0]->draw() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-// --- Category H: Namespace patterns ---
-
-func TestCLSP_GapV2_NamespaceFunction(t *testing.T) {
- // namespace::function() call
- source := `
-namespace utils {
- class Logger { public: void log(const char* msg) {} };
- Logger create_logger() { return Logger(); }
-}
-
-void test() {
- auto logger = utils::create_logger();
- logger.log("test");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create_logger")
- rc := findResolvedCall(t, result, "test", "Logger.log")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: namespace factory → method — logger.log() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_NestedNamespace(t *testing.T) {
- // a::b::Class obj; obj.method()
- source := `
-namespace a { namespace b {
- class Processor { public: void run() {} };
-}}
-
-void test() {
- a::b::Processor p;
- p.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_GapV2_UsingNamespace(t *testing.T) {
- // using namespace ns; then unqualified call
- source := `
-namespace utils {
- void helper() {}
-}
-
-void test() {
- utils::helper();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "helper")
-}
-
-// --- Category I: Operator overloading ---
-
-func TestCLSP_GapV2_OperatorPlusMemberCall(t *testing.T) {
- // (a + b).method() — result of operator+
- source := `
-class Vec {
-public:
- Vec operator+(const Vec& other) { return Vec(); }
- float length() { return 0; }
-};
-
-void test() {
- Vec a, b;
- Vec c = a + b;
- c.length();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "length")
-}
-
-func TestCLSP_GapV2_StreamOperator(t *testing.T) {
- // cout << "hello" << obj — common C++ pattern
- source := `
-class OStream {
-public:
- OStream& operator<<(const char* s) { return *this; }
- OStream& operator<<(int n) { return *this; }
-};
-
-OStream cout;
-
-void test() {
- cout << "value: " << 42;
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Stream operators should be resolved
- rc := findResolvedCall(t, result, "test", "operator<<")
- if rc == nil {
- t.Log("GAP: stream operator<< not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-// --- Category J: Constructor patterns ---
-
-func TestCLSP_GapV2_ExplicitConstructorCall(t *testing.T) {
- // Widget w(42); w.draw()
- source := `
-class Widget {
-public:
- Widget(int size) {}
- void draw() {}
-};
-
-void test() {
- Widget w(42);
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_GapV2_BraceInitConstructor(t *testing.T) {
- // Widget w{42}; w.draw()
- source := `
-class Widget {
-public:
- Widget(int size) {}
- void draw() {}
-};
-
-void test() {
- Widget w{42};
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_GapV2_TemporaryObjectMethodCall(t *testing.T) {
- // Widget(42).draw() — method on temporary
- source := `
-class Widget {
-public:
- Widget(int size) {}
- void draw() {}
-};
-
-void test() {
- Widget(42).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-// --- Category K: Lambda patterns ---
-
-func TestCLSP_GapV2_LambdaCaptureMethodCall(t *testing.T) {
- // auto fn = [&w]() { w.draw(); }; fn();
- source := `
-class Widget { public: void draw() {} };
-
-void test() {
- Widget w;
- auto fn = [&w]() { w.draw(); };
- fn();
-}
-`
- result := extractCPPWithRegistry(t, source)
- // The call w.draw() inside the lambda should be resolved
- rc := findResolvedCall(t, result, "", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: lambda capture method call — w.draw() inside lambda not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_LambdaReturnTypeUsed(t *testing.T) {
- // auto fn = []() -> Widget { return Widget(); }; fn().draw();
- source := `
-class Widget { public: void draw() {} };
-
-void test() {
- auto fn = []() -> Widget { return Widget(); };
- fn().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: lambda return type → method call — fn().draw() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-// --- Category L: Exception handling ---
-
-func TestCLSP_GapV2_CatchExceptionMethod(t *testing.T) {
- // catch(MyException& e) { e.what(); }
- source := `
-class MyException {
-public:
- const char* what() { return "error"; }
- int code() { return 0; }
-};
-
-void might_throw();
-
-void test() {
- try {
- might_throw();
- } catch (MyException& e) {
- e.what();
- e.code();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "might_throw")
- rc := findResolvedCall(t, result, "test", "what")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: catch exception method — e.what() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-// --- Category M: Static members and enums ---
-
-func TestCLSP_GapV2_StaticMemberFunction(t *testing.T) {
- // Class::static_method()
- source := `
-class Factory {
-public:
- static Factory create() { return Factory(); }
- void produce() {}
-};
-
-void test() {
- Factory f = Factory::create();
- f.produce();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "Factory.produce")
-}
-
-func TestCLSP_GapV2_EnumClassUsedInSwitch(t *testing.T) {
- // switch(e) { case Enum::Value: func(); }
- source := `
-enum class Color { Red, Green, Blue };
-
-void paint_red() {}
-void paint_green() {}
-void paint_blue() {}
-
-void paint(Color c) {
- switch(c) {
- case Color::Red: paint_red(); break;
- case Color::Green: paint_green(); break;
- case Color::Blue: paint_blue(); break;
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "paint", "paint_red")
- requireResolvedCall(t, result, "paint", "paint_green")
- requireResolvedCall(t, result, "paint", "paint_blue")
-}
-
-// --- Category N: Method chaining (builder/fluent pattern) ---
-
-func TestCLSP_GapV2_BuilderPattern(t *testing.T) {
- // builder.setA().setB().build().run()
- source := `
-class App { public: void run() {} };
-
-class Builder {
-public:
- Builder& setName(const char* name) { return *this; }
- Builder& setPort(int port) { return *this; }
- App build() { return App(); }
-};
-
-void test() {
- Builder b;
- b.setName("test").setPort(8080).build().run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "setName")
- rc := findResolvedCall(t, result, "test", "App.run")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: builder chain — build().run() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_MethodChainingRef(t *testing.T) {
- // obj.a().b().c() where all return self-reference
- source := `
-class Query {
-public:
- Query& where(const char* clause) { return *this; }
- Query& orderBy(const char* col) { return *this; }
- Query& limit(int n) { return *this; }
- void execute() {}
-};
-
-void test() {
- Query q;
- q.where("x > 1").orderBy("y").limit(10).execute();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "where")
- requireResolvedCall(t, result, "test", "orderBy")
- requireResolvedCall(t, result, "test", "limit")
- requireResolvedCall(t, result, "test", "execute")
-}
-
-// --- Category O: RAII and scope-based patterns ---
-
-func TestCLSP_GapV2_RAIILockGuard(t *testing.T) {
- // lock_guard<mutex> — constructor-only, no method calls
- source := `
-class Mutex { public: void lock() {} void unlock() {} };
-
-template<class M>
-class LockGuard {
-public:
- LockGuard(M& m) {}
- ~LockGuard() {}
-};
-
-void test() {
- Mutex m;
- LockGuard<Mutex> guard(m);
- m.lock();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "lock")
-}
-
-// --- Category P: Typedef and using patterns ---
-
-func TestCLSP_GapV2_TypedefClass(t *testing.T) {
- // typedef OldName NewName; NewName obj; obj.method()
- source := `
-class RealWidget { public: void draw() {} };
-typedef RealWidget Widget;
-
-void test() {
- Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: typedef class — w.draw() on typedef'd type not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_UsingAlias(t *testing.T) {
- // using Alias = RealType; Alias obj; obj.method()
- source := `
-class RealWidget { public: void draw() {} };
-using Widget = RealWidget;
-
-void test() {
- Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: using alias — w.draw() on alias type not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-func TestCLSP_GapV2_UsingTemplateAlias(t *testing.T) {
- // template<class T> using Vec = std::vector<T>;
- source := `
-namespace std {
- template<class T> class vector {
- public:
- void push_back(const T& val) {}
- int size() { return 0; }
- };
-}
-
-template<class T> using Vec = std::vector<T>;
-
-class Item { public: void process() {} };
-
-void test() {
- Vec<Item> items;
- items.push_back(Item());
- items.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "push_back")
- if rc == nil || rc.Strategy == "lsp_unresolved" {
- t.Log("GAP: template using alias — items.push_back() not resolved")
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s]", r.CallerQN, r.CalleeQN, r.Strategy)
- }
- t.FailNow()
- }
-}
-
-// --- Category Q: Common real-world compound patterns ---
-
-func TestCLSP_GapV2_IfNullCheck(t *testing.T) {
- // if (ptr) ptr->method() — very common
- source := `
-class Widget { public: void draw() {} };
-
-void test(Widget* w) {
- if (w) {
- w->draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_GapV2_TryCatchFinally(t *testing.T) {
- // Calls in both try and catch blocks
- source := `
-class DB {
-public:
- void connect() {}
- void query(const char* sql) {}
- void disconnect() {}
-};
-
-void test() {
- DB db;
- try {
- db.connect();
- db.query("SELECT 1");
- } catch (...) {
- db.disconnect();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "connect")
- requireResolvedCall(t, result, "test", "query")
- requireResolvedCall(t, result, "test", "disconnect")
-}
-
-func TestCLSP_GapV2_MethodCallInForInit(t *testing.T) {
- // for (auto it = container.begin(); it != container.end(); ++it) it->method()
- source := `
-class Item { public: void process() {} };
-
-class Container {
-public:
- Item* begin() { return (Item*)0; }
- Item* end() { return (Item*)0; }
-};
-
-void test() {
- Container c;
- c.begin();
- c.end();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "begin")
- requireResolvedCall(t, result, "test", "end")
-}
-
-func TestCLSP_GapV2_NestedMethodCallArgs(t *testing.T) {
- // a.process(b.get_value())
- source := `
-class Provider { public: int get_value() { return 0; } };
-class Consumer { public: void process(int val) {} };
-
-void test() {
- Provider p;
- Consumer c;
- c.process(p.get_value());
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_value")
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_GapV2_ConditionalMethodCall(t *testing.T) {
- // flag ? a.method1() : a.method2()
- source := `
-class Widget {
-public:
- void show() {}
- void hide() {}
-};
-
-void test(bool visible) {
- Widget w;
- if (visible) w.show();
- else w.hide();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.show")
- requireResolvedCall(t, result, "test", "Widget.hide")
-}
-
-// ---------------------------------------------------------------------------
-// Batch 1: Edge-case tests for gap fixes
-// ---------------------------------------------------------------------------
-
-func TestCLSP_Fix_CStructFuncPtrChainCall(t *testing.T) {
- // C struct with function pointer field, called through chain
- source := `
-typedef void (*callback_fn)(int);
-struct Handler {
- callback_fn on_event;
-};
-struct Manager {
- struct Handler handler;
-};
-void my_callback(int x) {}
-void test() {
- struct Manager m;
- m.handler.on_event(42);
-}
-`
- result := extractCWithRegistry(t, source)
- // Function pointer calls through struct chains may not resolve to specific target
- // but should at least not crash and potentially resolve the chain
- rc := findResolvedCall(t, result, "test", "on_event")
- if rc == nil {
- t.Log("GAP: C struct func pointer chain call not resolved — needs func ptr field call handler")
- }
-}
-
-func TestCLSP_Fix_CastChainedMethod(t *testing.T) {
- // dynamic_cast result used for method call
- source := `
-class Base { public: virtual void foo() {} };
-class Derived : public Base { public: void bar() {} };
-void test() {
- Base* b = new Base();
- Derived* d = dynamic_cast<Derived*>(b);
- d->bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Derived.bar")
- if rc == nil {
- t.Log("GAP: dynamic_cast<T*> type propagation not yet implemented")
- }
-}
-
-func TestCLSP_Fix_CatchByValue(t *testing.T) {
- // catch parameter by value (not reference)
- source := `
-class Error { public: const char* msg() { return ""; } };
-void test() {
- try {
- // ...
- } catch (Error e) {
- e.msg();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Error.msg")
-}
-
-func TestCLSP_Fix_SubscriptOnAutoVar(t *testing.T) {
- // subscript on auto variable with known container type
- source := `
-template<typename T> class vector {
-public:
- T& operator[](int index);
- void push_back(const T& val);
-};
-class Item { public: void use() {} };
-void test() {
- vector<Item> items;
- items[0].use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Item.use")
- if rc == nil {
- t.Log("GAP: subscript operator return type deduction not yet implemented")
- }
-}
-
-func TestCLSP_Fix_LambdaCaptureThis(t *testing.T) {
- // lambda capturing 'this' and calling methods on it
- source := `
-class Widget {
-public:
- void draw() {}
- void process() {
- auto fn = [this]() {
- draw();
- };
- }
-};
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "process", "Widget.draw")
-}
-
-// ---------------------------------------------------------------------------
-// Batch 2: C++17 Complete
-// ---------------------------------------------------------------------------
-
-// 2A: Structured Binding Edge Cases
-
-func TestCLSP_CPP17_StructuredBindingPair(t *testing.T) {
- source := `
-template<typename K, typename V>
-struct pair { K first; V second; };
-class Foo { public: void bar() {} };
-void test() {
- pair<int, Foo> p;
- auto [x, y] = p;
- y.bar();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Foo.bar")
- if rc == nil {
- t.Log("GAP: structured binding pair decomposition")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingStruct(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-struct Result { int code; Widget widget; };
-void test() {
- Result r;
- auto [c, w] = r;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: structured binding struct decomposition")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingArray(t *testing.T) {
- source := `
-class Foo { public: void run() {} };
-void test() {
- Foo arr[3];
- auto [a, b, c] = arr;
- a.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Foo.run")
- if rc == nil {
- t.Log("GAP: structured binding array decomposition")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingConst(t *testing.T) {
- source := `
-class Config { public: void load() {} };
-struct Settings { int level; Config config; };
-void test() {
- Settings s;
- const auto& [l, cfg] = s;
- cfg.load();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Config.load")
- if rc == nil {
- t.Log("GAP: structured binding const ref")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingMap(t *testing.T) {
- source := `
-template<typename K, typename V> class map {
-public:
- struct pair { K first; V second; };
- class iterator { public: pair& operator*(); };
- iterator begin();
- iterator end();
-};
-class Handler { public: void handle() {} };
-void test() {
- map<int, Handler> m;
- for (auto& [key, handler] : m) {
- handler.handle();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Handler.handle")
- if rc == nil {
- t.Log("GAP: structured binding in range-for over map")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingNested(t *testing.T) {
- source := `
-template<typename A, typename B>
-struct pair { A first; B second; };
-class Logger { public: void log() {} };
-void test() {
- pair<int, Logger> inner;
- pair<bool, pair<int, Logger>> outer;
- auto [flag, p] = outer;
- p.second.log();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Logger.log")
- if rc == nil {
- t.Log("GAP: nested structured binding pair decomposition")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingTuple(t *testing.T) {
- source := `
-namespace std {
- template<typename... Args> class tuple {};
- template<int N, typename T> auto get(T& t);
-}
-class Widget { public: void show() {} };
-void test() {
- std::tuple<int, Widget, double> tup;
- auto [a, w, d] = tup;
- w.show();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.show")
- if rc == nil {
- t.Log("GAP: structured binding tuple decomposition")
- }
-}
-
-func TestCLSP_CPP17_StructuredBindingInIf(t *testing.T) {
- source := `
-struct Result { bool ok; int value; };
-Result getResult();
-void process(int x) {}
-void test() {
- if (auto [ok, val] = getResult(); ok) {
- process(val);
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "getResult")
- requireResolvedCall(t, result, "test", "process")
-}
-
-// 2B: if-init Statements
-
-func TestCLSP_CPP17_IfInitSimple(t *testing.T) {
- source := `
-class Lock { public: bool locked() { return true; } };
-Lock acquire();
-void test() {
- if (Lock l = acquire(); l.locked()) {
- // do work
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "acquire")
- rc := findResolvedCall(t, result, "test", "Lock.locked")
- if rc == nil {
- t.Log("GAP: if-init variable binding")
- }
-}
-
-func TestCLSP_CPP17_IfInitWithType(t *testing.T) {
- source := `
-class Database { public: int query() { return 0; } };
-void test() {
- Database db;
- if (int result = db.query(); result > 0) {
- // process
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Database.query")
-}
-
-func TestCLSP_CPP17_SwitchInit(t *testing.T) {
- source := `
-class Parser { public: int parse() { return 0; } };
-void handle_a() {}
-void handle_b() {}
-void test() {
- Parser p;
- switch (int code = p.parse(); code) {
- case 1: handle_a(); break;
- case 2: handle_b(); break;
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Parser.parse")
- requireResolvedCall(t, result, "test", "handle_a")
- requireResolvedCall(t, result, "test", "handle_b")
-}
-
-func TestCLSP_CPP17_IfInitLock(t *testing.T) {
- source := `
-class mutex { public: void lock() {} void unlock() {} };
-class lock_guard {
-public:
- lock_guard(mutex& m) {}
-};
-class SharedState { public: int read() { return 0; } };
-void test() {
- mutex mtx;
- SharedState state;
- if (lock_guard lg(mtx); true) {
- state.read();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "SharedState.read")
-}
-
-// 2C: Fold Expressions
-
-func TestCLSP_CPP17_FoldExprSum(t *testing.T) {
- source := `
-template<typename... Args>
-auto sum(Args... args) {
- return (args + ...);
-}
-void test() {
- sum(1, 2, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sum")
-}
-
-func TestCLSP_CPP17_FoldExprBinary(t *testing.T) {
- source := `
-template<typename... Args>
-auto multiply(Args... args) {
- return (args * ... * 1);
-}
-void test() {
- multiply(2, 3, 4);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "multiply")
-}
-
-func TestCLSP_CPP17_FoldExprComma(t *testing.T) {
- source := `
-void process(int x) {}
-template<typename... Args>
-void call_all(Args... args) {
- (process(args), ...);
-}
-void test() {
- call_all(1, 2, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "call_all")
- requireResolvedCall(t, result, "call_all", "process")
-}
-
-func TestCLSP_CPP17_FoldExprLogical(t *testing.T) {
- source := `
-template<typename... Args>
-bool all_true(Args... args) {
- return (args && ...);
-}
-void test() {
- all_true(true, true, false);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "all_true")
-}
-
-// 2D: CTAD — Class Template Argument Deduction
-
-func TestCLSP_CPP17_CTADVector(t *testing.T) {
- source := `
-template<typename T> class vector {
-public:
- void push_back(const T& val);
- T& front();
-};
-class Item { public: void use() {} };
-void test() {
- vector<Item> v;
- v.push_back(Item());
- v.front().use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
- rc := findResolvedCall(t, result, "test", "Item.use")
- if rc == nil {
- t.Log("GAP: CTAD vector front() return type deduction")
- }
-}
-
-func TestCLSP_CPP17_CTADPair(t *testing.T) {
- source := `
-template<typename A, typename B>
-struct pair {
- A first;
- B second;
- pair(A a, B b) : first(a), second(b) {}
-};
-class Widget { public: void draw() {} };
-void test() {
- pair p(42, Widget());
- p.second.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: CTAD pair deduction from constructor args")
- }
-}
-
-func TestCLSP_CPP17_CTADOptional(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- optional(T val);
- T& value();
- bool has_value();
-};
-class Config { public: void load() {} };
-void test() {
- optional<Config> opt(Config{});
- opt.value().load();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Config.load")
- if rc == nil {
- t.Log("GAP: optional value() return type deduction")
- }
-}
-
-func TestCLSP_CPP17_CTADTuple(t *testing.T) {
- source := `
-namespace std {
- template<typename... Args> class tuple {
- public:
- tuple(Args... args);
- };
-}
-class Logger { public: void log() {} };
-void test() {
- std::tuple t(1, 2.0, Logger());
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Just verify no crash with CTAD tuple
- _ = result
-}
-
-func TestCLSP_CPP17_CTADUserDefined(t *testing.T) {
- source := `
-template<typename T>
-class Container {
-public:
- Container(T val);
- T& get();
-};
-class Widget { public: void draw() {} };
-void test() {
- Container c(Widget{});
- c.get().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: user-defined CTAD not yet implemented")
- }
-}
-
-func TestCLSP_CPP17_CTADLockGuard(t *testing.T) {
- source := `
-class mutex { public: void lock() {} void unlock() {} };
-template<typename M>
-class lock_guard {
-public:
- lock_guard(M& m);
- ~lock_guard();
-};
-void test() {
- mutex m;
- lock_guard lg(m);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Just verify no crash
- _ = result
-}
-
-// 2E: std::optional/variant/any
-
-func TestCLSP_CPP17_OptionalValue(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- T& value();
- bool has_value();
-};
-class Widget { public: void draw() {} };
-void test() {
- optional<Widget> opt;
- opt.value().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: optional::value() return type deduction")
- }
-}
-
-func TestCLSP_CPP17_OptionalArrow(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- T* operator->();
- bool has_value();
-};
-class Widget { public: void draw() {} };
-void test() {
- optional<Widget> opt;
- opt->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: optional::operator->() deduction")
- }
-}
-
-func TestCLSP_CPP17_OptionalDeref(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- T& operator*();
-};
-class Widget { public: void draw() {} };
-void test() {
- optional<Widget> opt;
- (*opt).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: optional::operator*() deduction")
- }
-}
-
-func TestCLSP_CPP17_OptionalHasValue(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- bool has_value();
- T& value();
-};
-class Widget { public: void draw() {} };
-void test() {
- optional<Widget> opt;
- if (opt.has_value()) {
- opt.value().draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "has_value")
-}
-
-func TestCLSP_CPP17_VariantGet(t *testing.T) {
- source := `
-namespace std {
- template<typename... Types> class variant {};
- template<typename T, typename V> T& get(V& v);
-}
-class Widget { public: void draw() {} };
-void test() {
- std::variant<int, Widget> v;
- std::get<Widget>(v).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_CPP17_VariantVisit(t *testing.T) {
- source := `
-namespace std {
- template<typename... Types> class variant {};
- template<typename Visitor, typename V> auto visit(Visitor&& vis, V&& v);
-}
-class Widget { public: void draw() {} };
-void handle(int x) {}
-void handle(Widget w) { w.draw(); }
-void test() {
- std::variant<int, Widget> v;
- std::visit([](auto& val) {}, v);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // variant visit is very hard to resolve — just verify no crash
- _ = result
-}
-
-func TestCLSP_CPP17_AnyAnyCast(t *testing.T) {
- source := `
-namespace std {
- class any {};
- template<typename T> T any_cast(any& a);
-}
-class Widget { public: void draw() {} };
-void test() {
- std::any a;
- std::any_cast<Widget>(a).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_CPP17_OptionalValueOr(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- T value_or(T default_val);
-};
-class Widget { public: void draw() {} };
-void test() {
- optional<Widget> opt;
- opt.value_or(Widget()).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: optional::value_or() return type deduction")
- }
-}
-
-func TestCLSP_CPP17_OptionalAndThen(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- template<typename F> auto and_then(F f);
- T& value();
-};
-class Widget { public: void draw() {} };
-void test() {
- optional<Widget> opt;
- opt.value().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: optional::and_then() monadic")
- }
-}
-
-func TestCLSP_CPP17_OptionalTransform(t *testing.T) {
- source := `
-template<typename T> class optional {
-public:
- template<typename F> auto transform(F f);
- T& value();
-};
-void test() {
- optional<int> opt;
- opt.value();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "value")
-}
-
-// 2F: Miscellaneous C++17
-
-func TestCLSP_CPP17_IfConstexprBody(t *testing.T) {
- source := `
-class IntHandler { public: void handle_int() {} };
-class FloatHandler { public: void handle_float() {} };
-template<typename T>
-void process(T val) {
- if constexpr (sizeof(T) == 4) {
- IntHandler h;
- h.handle_int();
- } else {
- FloatHandler h;
- h.handle_float();
- }
-}
-void test() {
- process(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
- // Both branches should be processed (we can't evaluate constexpr)
- requireResolvedCall(t, result, "process", "IntHandler.handle_int")
- requireResolvedCall(t, result, "process", "FloatHandler.handle_float")
-}
-
-func TestCLSP_CPP17_InlineVariable(t *testing.T) {
- source := `
-class Config {
-public:
- static inline int max_retries = 3;
- void apply() {}
-};
-void test() {
- Config c;
- c.apply();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Config.apply")
-}
-
-func TestCLSP_CPP17_NestedNamespace(t *testing.T) {
- source := `
-namespace a::b::c {
- class Widget { public: void draw() {} };
-}
-void test() {
- a::b::c::Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Widget.draw")
-}
-
-func TestCLSP_CPP17_ConstexprIf(t *testing.T) {
- source := `
-class Handler { public: void handle() {} };
-template<bool B>
-void dispatch() {
- if constexpr (B) {
- Handler h;
- h.handle();
- }
-}
-void test() {
- dispatch<true>();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "dispatch")
-}
-
-func TestCLSP_CPP17_StringView(t *testing.T) {
- source := `
-namespace std {
- class string_view {
- public:
- int size();
- const char* data();
- string_view substr(int pos, int count);
- };
-}
-void test() {
- std::string_view sv;
- sv.size();
- sv.substr(0, 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "string_view.size")
- requireResolvedCall(t, result, "test", "string_view.substr")
-}
-
-func TestCLSP_CPP17_FilesystemPath(t *testing.T) {
- source := `
-namespace std { namespace filesystem {
- class path {
- public:
- path parent_path();
- path filename();
- bool exists();
- };
-}}
-void test() {
- std::filesystem::path p;
- p.parent_path();
- p.filename();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "path.parent_path")
- requireResolvedCall(t, result, "test", "path.filename")
-}
-
-func TestCLSP_CPP17_UserDefinedLiteral(t *testing.T) {
- source := `
-class Duration { public: int seconds() { return 0; } };
-Duration operator""_s(unsigned long long val) { return Duration(); }
-void test() {
- auto d = 42_s;
- d.seconds();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Duration.seconds")
- if rc == nil {
- t.Log("GAP: user-defined literal type deduction")
- }
-}
-
-func TestCLSP_CPP17_ClassTemplateDeduction(t *testing.T) {
- source := `
-template<typename T>
-class Wrapper {
-public:
- Wrapper(T val);
- T& get();
-};
-class Widget { public: void draw() {} };
-void test() {
- Wrapper w(Widget{});
- w.get().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: class template deduction guide")
- }
-}
-
-func TestCLSP_CPP17_ApplyTuple(t *testing.T) {
- source := `
-namespace std {
- template<typename... Args> class tuple {};
- template<typename F, typename Tuple> auto apply(F&& f, Tuple&& t);
-}
-void process(int a, double b) {}
-void test() {
- std::tuple<int, double> args;
- std::apply(process, args);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "apply")
-}
-
-func TestCLSP_CPP17_InvokeResult(t *testing.T) {
- source := `
-namespace std {
- template<typename F, typename... Args>
- auto invoke(F&& f, Args&&... args);
-}
-class Widget { public: void draw() {} };
-void do_draw(Widget& w) { w.draw(); }
-void test() {
- Widget w;
- std::invoke(do_draw, w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "invoke")
-}
-
-// ---------------------------------------------------------------------------
-// Batch 3: C++20 Features
-// ---------------------------------------------------------------------------
-
-// 3A: Concepts
-
-func TestCLSP_CPP20_ConceptConstrainedFunc(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-template<typename T>
-concept Drawable = requires(T t) { t.draw(); };
-template<Drawable T>
-void render(T& obj) {
- obj.draw();
-}
-void test() {
- Widget w;
- render(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "render")
-}
-
-func TestCLSP_CPP20_ConceptRequiresClause(t *testing.T) {
- source := `
-class Logger { public: void log() {} };
-template<typename T>
-void process(T& obj) requires requires { obj.log(); } {
- obj.log();
-}
-void test() {
- Logger l;
- process(l);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_CPP20_ConceptAutoParam(t *testing.T) {
- // abbreviated function template with auto
- source := `
-class Processor { public: void run() {} };
-void handle(auto& obj) {
- obj.run();
-}
-void test() {
- Processor p;
- handle(p);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle")
-}
-
-func TestCLSP_CPP20_ConceptNested(t *testing.T) {
- source := `
-template<typename T>
-concept Hashable = requires(T a) {
- { a.hash() } -> int;
-};
-template<typename T>
-concept Identifiable = Hashable<T> && requires(T a) {
- { a.id() } -> int;
-};
-class Entity { public: int hash() { return 0; } int id() { return 0; } };
-void test() {
- Entity e;
- e.hash();
- e.id();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Entity.hash")
- requireResolvedCall(t, result, "test", "Entity.id")
-}
-
-func TestCLSP_CPP20_ConceptConjunction(t *testing.T) {
- source := `
-template<typename T> concept A = true;
-template<typename T> concept B = true;
-template<typename T> requires A<T> && B<T>
-void constrained(T& val) {}
-void test() {
- int x = 5;
- constrained(x);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "constrained")
-}
-
-func TestCLSP_CPP20_ConceptSubsumption(t *testing.T) {
- source := `
-template<typename T> concept Base = true;
-template<typename T> concept Derived = Base<T> && true;
-template<Base T> void f(T val) {}
-template<Derived T> void f(T val) {}
-void test() {
- f(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "f")
-}
-
-func TestCLSP_CPP20_ConceptOnMethod(t *testing.T) {
- source := `
-template<typename T> concept Numeric = true;
-class Calculator {
-public:
- template<Numeric T> T add(T a, T b) { return a + b; }
-};
-void test() {
- Calculator c;
- c.add(1, 2);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Calculator.add")
-}
-
-func TestCLSP_CPP20_RequiresExpression(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-template<typename T>
-bool can_draw() {
- return requires(T t) { t.draw(); };
-}
-void test() {
- can_draw<Widget>();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "can_draw")
-}
-
-// 3B: Coroutines
-
-func TestCLSP_CPP20_CoAwaitExpr(t *testing.T) {
- source := `
-template<typename T>
-class Task {
-public:
- T result;
-};
-class Widget { public: void draw() {} };
-Task<Widget> get_widget();
-void test() {
- auto w = co_await get_widget();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_widget")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: co_await return type from Task<T> template arg")
- }
-}
-
-func TestCLSP_CPP20_CoYieldExpr(t *testing.T) {
- source := `
-template<typename T> class generator {};
-void process(int x) {}
-generator<int> generate() {
- co_yield 42;
- process(10);
-}
-void test() {
- generate();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "generate")
- requireResolvedCall(t, result, "generate", "process")
-}
-
-func TestCLSP_CPP20_CoReturnExpr(t *testing.T) {
- source := `
-template<typename T> class Task {};
-class Widget { public: void prepare() {} };
-Task<Widget> make_widget() {
- Widget w;
- w.prepare();
- co_return w;
-}
-void test() {
- make_widget();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_widget")
- requireResolvedCall(t, result, "make_widget", "Widget.prepare")
-}
-
-func TestCLSP_CPP20_CoroutineHandle(t *testing.T) {
- source := `
-namespace std {
- template<typename P = void>
- class coroutine_handle {
- public:
- void resume();
- bool done();
- void destroy();
- };
-}
-void test() {
- std::coroutine_handle<> h;
- h.resume();
- h.done();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "coroutine_handle.resume")
- requireResolvedCall(t, result, "test", "coroutine_handle.done")
-}
-
-func TestCLSP_CPP20_Task(t *testing.T) {
- source := `
-template<typename T>
-class Task {
-public:
- bool await_ready();
- void await_suspend();
- T await_resume();
-};
-class Widget { public: void draw() {} };
-void test() {
- Task<Widget> t;
- t.await_ready();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Task.await_ready")
-}
-
-func TestCLSP_CPP20_CoroutineBodyCalls(t *testing.T) {
- source := `
-class Logger { public: void log() {} };
-template<typename T> class Task {};
-Task<void> async_work() {
- Logger l;
- l.log();
- co_return;
-}
-void test() {
- async_work();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "async_work")
- requireResolvedCall(t, result, "async_work", "Logger.log")
-}
-
-func TestCLSP_CPP20_Generator(t *testing.T) {
- source := `
-template<typename T> class generator {
-public:
- class iterator {
- public:
- T& operator*();
- iterator& operator++();
- };
- iterator begin();
- iterator end();
-};
-class Widget { public: void draw() {} };
-generator<Widget> all_widgets() {
- co_yield Widget();
-}
-void test() {
- for (auto& w : all_widgets()) {
- w.draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "all_widgets")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: generator range-for element type deduction")
- }
-}
-
-func TestCLSP_CPP20_NestedCoAwait(t *testing.T) {
- source := `
-template<typename T> class Task {};
-class Database { public: void query() {} };
-Task<Database> connect();
-Task<void> process();
-Task<void> main_task() {
- auto db = co_await connect();
- db.query();
- co_await process();
-}
-void test() {
- main_task();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "main_task")
- requireResolvedCall(t, result, "main_task", "connect")
- rc := findResolvedCall(t, result, "main_task", "Database.query")
- if rc == nil {
- t.Log("GAP: nested co_await type deduction from Task<T>")
- }
-}
-
-// 3C: Ranges
-
-func TestCLSP_CPP20_RangesPipeline(t *testing.T) {
- source := `
-namespace std { namespace views {
- template<typename F> auto transform(F f);
- template<typename P> auto filter(P p);
-}}
-namespace std { namespace ranges {
- template<typename R, typename F> auto transform(R&& r, F f);
-}}
-class Widget { public: int value() { return 0; } };
-void test() {
- Widget widgets[10];
- // Pipeline syntax uses | operator
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Just verify no crash with ranges declarations
- _ = result
-}
-
-func TestCLSP_CPP20_RangesForEach(t *testing.T) {
- source := `
-namespace std { namespace ranges {
- template<typename R, typename F> void for_each(R&& r, F f);
-}}
-void process(int x) {}
-void test() {
- int arr[] = {1, 2, 3};
- std::ranges::for_each(arr, process);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "for_each")
-}
-
-func TestCLSP_CPP20_ViewsTransform(t *testing.T) {
- source := `
-namespace std { namespace views {
- template<typename F> auto transform(F f);
-}}
-int double_it(int x) { return x * 2; }
-void test() {
- std::views::transform(double_it);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "transform")
-}
-
-func TestCLSP_CPP20_ViewsFilter(t *testing.T) {
- source := `
-namespace std { namespace views {
- template<typename P> auto filter(P pred);
-}}
-bool is_even(int x) { return x % 2 == 0; }
-void test() {
- std::views::filter(is_even);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "filter")
-}
-
-func TestCLSP_CPP20_RangesSort(t *testing.T) {
- source := `
-namespace std { namespace ranges {
- template<typename R> void sort(R&& r);
-}}
-void test() {
- int arr[] = {3, 1, 2};
- std::ranges::sort(arr);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sort")
-}
-
-func TestCLSP_CPP20_ViewsTake(t *testing.T) {
- source := `
-namespace std { namespace views {
- auto take(int n);
-}}
-void test() {
- std::views::take(5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "take")
-}
-
-func TestCLSP_CPP20_RangesIterator(t *testing.T) {
- source := `
-namespace std { namespace ranges {
- template<typename R> auto begin(R&& r);
- template<typename R> auto end(R&& r);
-}}
-void test() {
- int arr[] = {1, 2, 3};
- std::ranges::begin(arr);
- std::ranges::end(arr);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "begin")
- requireResolvedCall(t, result, "test", "end")
-}
-
-func TestCLSP_CPP20_RangesProjection(t *testing.T) {
- source := `
-namespace std { namespace ranges {
- template<typename R, typename Proj> void sort(R&& r, Proj proj);
-}}
-class Item { public: int key() { return 0; } };
-void test() {
- Item items[5];
- std::ranges::sort(items, [](const Item& i) { return i.key(); });
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sort")
-}
-
-// 3D: Other C++20
-
-func TestCLSP_CPP20_ConstevalFunc(t *testing.T) {
- source := `
-consteval int square(int n) { return n * n; }
-void test() {
- int x = square(5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "square")
-}
-
-func TestCLSP_CPP20_ConstinitVar(t *testing.T) {
- source := `
-class Config { public: void load() {} };
-constinit int global_val = 42;
-void test() {
- Config c;
- c.load();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Config.load")
-}
-
-func TestCLSP_CPP20_DesignatedInit(t *testing.T) {
- source := `
-class Engine { public: void start() {} };
-struct Car { int speed; Engine engine; };
-void test() {
- Car c = { .speed = 100, .engine = Engine() };
- c.engine.start();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Engine.start")
-}
-
-func TestCLSP_CPP20_ThreeWayComparison(t *testing.T) {
- source := `
-class Version {
-public:
- int major, minor;
- auto operator<=>(const Version& other);
- bool operator==(const Version& other);
-};
-void test() {
- Version v1, v2;
- v1 == v2;
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Spaceship operator — just verify no crash
- _ = result
-}
-
-func TestCLSP_CPP20_SpanAccess(t *testing.T) {
- source := `
-namespace std {
- template<typename T>
- class span {
- public:
- T& operator[](int idx);
- int size();
- T* data();
- };
-}
-class Widget { public: void draw() {} };
-void test() {
- std::span<Widget> s;
- s.size();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "span.size")
-}
-
-func TestCLSP_CPP20_Jthread(t *testing.T) {
- source := `
-namespace std {
- class jthread {
- public:
- template<typename F> jthread(F&& f);
- void join();
- bool joinable();
- void request_stop();
- };
-}
-void work() {}
-void test() {
- std::jthread thr{work};
- thr.join();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "jthread.join")
-}
-
-func TestCLSP_CPP20_FormatString(t *testing.T) {
- source := `
-namespace std {
- template<typename... Args>
- auto format(const char* fmt, Args&&... args);
-}
-void test() {
- std::format("hello {}", 42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "format")
-}
-
-func TestCLSP_CPP20_SourceLocation(t *testing.T) {
- source := `
-namespace std {
- class source_location {
- public:
- static source_location current();
- const char* file_name();
- int line();
- };
-}
-void test() {
- auto loc = std::source_location::current();
- loc.file_name();
- loc.line();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "current")
-}
-
-func TestCLSP_CPP20_UsingEnum(t *testing.T) {
- source := `
-class Processor { public: void process() {} };
-enum class Color { Red, Green, Blue };
-void test() {
- Processor p;
- p.process();
- Color c = Color::Red;
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "Processor.process")
-}
-
-func TestCLSP_CPP20_LambdaTemplateParam(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-void test() {
- auto fn = []<typename T>(T& obj) {
- obj.draw();
- };
- Widget w;
- fn(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Lambda with template params — verify no crash
- rc := findResolvedCall(t, result, "test", "fn")
- if rc == nil {
- // Lambda calls may resolve differently
- }
-}
-
-func TestCLSP_CPP20_LambdaInitCapture(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-void test() {
- Widget w;
- auto fn = [captured = w]() {
- captured.draw();
- };
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: lambda init-capture variable binding")
- }
-}
-
-// ============================================================================
-// Batch 4A: SFINAE & Enable-If
-// ============================================================================
-
-func TestCLSP_Template_EnableIfMethod(t *testing.T) {
- source := `
-namespace std {
- template<bool B, class T = void> struct enable_if {};
- template<class T> struct enable_if<true, T> { typedef T type; };
- template<class T> struct is_integral { static const bool value = false; };
-}
-
-class Widget {
-public:
- template<typename T>
- typename std::enable_if<std::is_integral<T>::value, void>::type
- process(T val) {}
-};
-
-void test() {
- Widget w;
- w.process(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_Template_EnableIfReturn(t *testing.T) {
- source := `
-namespace std {
- template<bool B, class T = void> struct enable_if {};
- template<class T> struct enable_if<true, T> { typedef T type; };
- template<class T> struct is_integral { static const bool value = false; };
- template<> struct is_integral<int> { static const bool value = true; };
-}
-
-template<typename T>
-typename std::enable_if<std::is_integral<T>::value, T>::type
-double_val(T x) { return x * 2; }
-
-void test() {
- int r = double_val(5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "double_val")
-}
-
-func TestCLSP_Template_VoidT(t *testing.T) {
- source := `
-namespace std {
- template<typename...> using void_t = void;
-}
-
-template<typename T, typename = void>
-struct has_draw : false_type {};
-
-template<typename T>
-struct has_draw<T, std::void_t<decltype(T().draw())>> : true_type {};
-
-class Widget { public: void draw() {} };
-
-void test() {
- Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Template_IsDetected(t *testing.T) {
- source := `
-namespace std {
- template<typename...> using void_t = void;
-}
-
-template<typename T, template<class> class Op, typename = void>
-struct is_detected : false_type {};
-
-template<typename T, template<class> class Op>
-struct is_detected<T, Op, std::void_t<Op<T>>> : true_type {};
-
-template<class T> using draw_t = decltype(T().draw());
-
-class Widget { public: void draw() {} };
-
-void test() {
- Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Template_IfConstexprSFINAE(t *testing.T) {
- source := `
-class Printer { public: void print_val() {} };
-class Logger { public: void log_val() {} };
-
-template<typename T>
-void dispatch(T obj) {
- if constexpr (sizeof(T) > 4) {
- obj.print_val();
- } else {
- obj.log_val();
- }
-}
-
-void test() {
- Printer p;
- dispatch(p);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "dispatch")
- // Both branches should have calls extracted
- rc := findResolvedCall(t, result, "dispatch", "print_val")
- if rc == nil {
- rc = findResolvedCall(t, result, "dispatch", "log_val")
- }
- if rc == nil {
- t.Log("GAP: if constexpr branch call resolution")
- }
-}
-
-func TestCLSP_Template_ConditionalType(t *testing.T) {
- source := `
-namespace std {
- template<bool B, class T, class F> struct conditional { typedef T type; };
- template<class T, class F> struct conditional<false, T, F> { typedef F type; };
- template<bool B, class T, class F> using conditional_t = typename conditional<B,T,F>::type;
-}
-
-class IntHandler { public: void handle() {} };
-class FloatHandler { public: void handle() {} };
-
-void test() {
- IntHandler h;
- h.handle();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle")
-}
-
-func TestCLSP_Template_DecltypeReturn(t *testing.T) {
- source := `
-class Widget { public: int value() { return 0; } };
-
-Widget make_widget() { return Widget{}; }
-
-auto get_value() -> decltype(make_widget().value()) {
- return make_widget().value();
-}
-
-void test() {
- auto v = get_value();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "get_value")
- if rc == nil {
- t.Log("GAP: decltype return type deduction")
- }
-}
-
-func TestCLSP_Template_TrailingReturn(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-auto create() -> Widget { return Widget{}; }
-
-void test() {
- auto w = create();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- t.Log("GAP: trailing return type deduction for auto")
- }
-}
-
-// ============================================================================
-// Batch 4B: Partial Specialization
-// ============================================================================
-
-func TestCLSP_Template_PartialSpecPointer(t *testing.T) {
- source := `
-template<typename T>
-class Container {
-public:
- void store() {}
-};
-
-template<typename T>
-class Container<T*> {
-public:
- void store_ptr() {}
-};
-
-void test() {
- Container<int*> c;
- c.store_ptr();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "store_ptr")
-}
-
-func TestCLSP_Template_PartialSpecConst(t *testing.T) {
- source := `
-template<typename T>
-class Wrapper {
-public:
- void mutate() {}
-};
-
-template<typename T>
-class Wrapper<const T> {
-public:
- void read_only() {}
-};
-
-void test() {
- Wrapper<int> w;
- w.mutate();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "mutate")
-}
-
-func TestCLSP_Template_FullSpec(t *testing.T) {
- source := `
-template<typename T>
-class Container {
-public:
- void generic_op() {}
-};
-
-template<>
-class Container<int> {
-public:
- void int_op() {}
-};
-
-void test() {
- Container<int> c;
- c.int_op();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "int_op")
-}
-
-func TestCLSP_Template_MemberSpec(t *testing.T) {
- source := `
-template<typename T>
-class Converter {
-public:
- void convert() {}
-};
-
-template<>
-void Converter<int>::convert() {}
-
-void test() {
- Converter<int> c;
- c.convert();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "convert")
-}
-
-func TestCLSP_Template_StaticMemberSpec(t *testing.T) {
- source := `
-template<typename T>
-class Registry {
-public:
- static void init() {}
-};
-
-void test() {
- Registry<int>::init();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "init")
-}
-
-func TestCLSP_Template_TypeTraitSpec(t *testing.T) {
- source := `
-template<typename T>
-struct is_widget { static const bool value = false; };
-
-struct Widget { void draw() {} };
-
-template<>
-struct is_widget<Widget> { static const bool value = true; };
-
-void test() {
- Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// Batch 4C: Variadic Templates
-// ============================================================================
-
-func TestCLSP_Template_VariadicFunc(t *testing.T) {
- source := `
-class Target { public: void invoke() {} };
-
-template<typename... Args>
-void call_all(Args... args) {}
-
-void test() {
- Target tgt;
- call_all(1, 2, 3);
- tgt.invoke();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "call_all")
- requireResolvedCall(t, result, "test", "invoke")
-}
-
-func TestCLSP_Template_VariadicClass(t *testing.T) {
- source := `
-template<typename... Ts>
-class Tuple {
-public:
- void clear() {}
-};
-
-void test() {
- Tuple<int, float, double> tup;
- tup.clear();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "clear")
-}
-
-func TestCLSP_Template_ParameterPack(t *testing.T) {
- source := `
-template<typename... Args>
-int count_args(Args... args) {
- return sizeof...(Args);
-}
-
-void test() {
- int n = count_args(1, 2, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "count_args")
-}
-
-func TestCLSP_Template_FoldOverArgs(t *testing.T) {
- source := `
-void process(int x) {}
-
-template<typename... Args>
-void fold_call(Args... args) {
- (process(args), ...);
-}
-
-void test() {
- fold_call(1, 2, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "fold_call")
- rc := findResolvedCall(t, result, "fold_call", "process")
- if rc == nil {
- t.Log("GAP: fold expression inner call resolution")
- }
-}
-
-func TestCLSP_Template_VariadicInheritance(t *testing.T) {
- source := `
-struct MixA { void do_a() {} };
-struct MixB { void do_b() {} };
-
-template<typename... Bases>
-class Combined : public Bases... {
-public:
- void run() {}
-};
-
-void test() {
- Combined<MixA, MixB> c;
- c.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
- rc := findResolvedCall(t, result, "test", "do_a")
- if rc == nil {
- t.Log("GAP: variadic inheritance base method resolution")
- }
-}
-
-func TestCLSP_Template_RecursiveVariadic(t *testing.T) {
- source := `
-void base_print() {}
-
-template<typename T>
-void rec_print(T val) {
- base_print();
-}
-
-template<typename T, typename... Rest>
-void rec_print(T val, Rest... rest) {
- base_print();
- rec_print(rest...);
-}
-
-void test() {
- rec_print(1, 2, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "rec_print")
- rc := findResolvedCall(t, result, "rec_print", "base_print")
- if rc == nil {
- t.Log("GAP: recursive variadic base case call")
- }
-}
-
-func TestCLSP_Template_MakeFromVariadic(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<typename T, typename... Args>
-shared_ptr<T> make_shared(Args... args) { return shared_ptr<T>(); }
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- auto p = std::make_shared<Widget>();
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_shared")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Template_TupleElement(t *testing.T) {
- source := `
-namespace std {
-template<typename A, typename B>
-struct pair {
- A first;
- B second;
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::pair<int, Widget> p;
- p.second.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- rc = findResolvedCall(t, result, "test", "draw")
- }
- if rc == nil {
- t.Log("GAP: tuple/pair element type deduction")
- }
-}
-
-// ============================================================================
-// Batch 4D: Dependent Types
-// ============================================================================
-
-func TestCLSP_Template_DependentType(t *testing.T) {
- source := `
-class Container {
-public:
- typedef int value_type;
- value_type get() { return 0; }
-};
-
-template<typename T>
-void process(T c) {
- c.get();
-}
-
-void test() {
- Container c;
- process(c);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
- rc := findResolvedCall(t, result, "process", "get")
- if rc == nil {
- t.Log("GAP: dependent type member call resolution")
- }
-}
-
-func TestCLSP_Template_DependentName(t *testing.T) {
- source := `
-class MyContainer {
-public:
- typedef int iterator;
- void begin() {}
-};
-
-template<typename C>
-void iterate(C container) {
- container.begin();
-}
-
-void test() {
- MyContainer c;
- iterate(c);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "iterate")
-}
-
-func TestCLSP_Template_NestedDependent(t *testing.T) {
- source := `
-class Inner { public: void action() {} };
-class Outer {
-public:
- typedef Inner nested_type;
- Inner get_inner() { return Inner{}; }
-};
-
-template<typename T>
-void deep(T obj) {
- auto inner = obj.get_inner();
- inner.action();
-}
-
-void test() {
- Outer o;
- deep(o);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "deep")
- rc := findResolvedCall(t, result, "deep", "action")
- if rc == nil {
- t.Log("GAP: nested dependent name resolution")
- }
-}
-
-func TestCLSP_Template_DependentReturn(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-template<typename T>
-T make_thing() { return T{}; }
-
-void test() {
- auto w = make_thing<Widget>();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_thing")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- rc = findResolvedCall(t, result, "test", "draw")
- }
- if rc == nil {
- t.Log("GAP: dependent return type deduction")
- }
-}
-
-func TestCLSP_Template_DependentField(t *testing.T) {
- source := `
-template<typename T>
-class Holder {
- T item;
-public:
- void use() {}
-};
-
-class Widget { public: void draw() {} };
-
-void test() {
- Holder<Widget> h;
- h.use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use")
-}
-
-func TestCLSP_Template_DependentMethodCall(t *testing.T) {
- source := `
-class Renderer { public: void render() {} };
-
-template<typename T>
-void invoke(T obj) {
- obj.render();
-}
-
-void test() {
- Renderer r;
- invoke(r);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "invoke")
-}
-
-func TestCLSP_Template_DependentBaseClass(t *testing.T) {
- source := `
-template<typename Derived>
-class Base {
-public:
- void interface_method() {
- static_cast<Derived*>(this)->impl();
- }
-};
-
-class Derived : public Base<Derived> {
-public:
- void impl() {}
-};
-
-void test() {
- Derived d;
- d.interface_method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "interface_method")
-}
-
-func TestCLSP_Template_TwoPhase(t *testing.T) {
- source := `
-void non_dependent() {}
-
-template<typename T>
-void two_phase(T val) {
- non_dependent();
- val.dependent_call();
-}
-
-class Widget { public: void dependent_call() {} };
-
-void test() {
- Widget w;
- two_phase(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "two_phase")
- requireResolvedCall(t, result, "two_phase", "non_dependent")
-}
-
-// ============================================================================
-// Batch 4E: Expression Templates & Policy
-// ============================================================================
-
-func TestCLSP_Template_ExprTemplate(t *testing.T) {
- source := `
-class Vec {
-public:
- Vec operator+(const Vec& other) { return *this; }
- Vec operator*(float scalar) { return *this; }
- float norm() { return 0.0f; }
-};
-
-void test() {
- Vec a, b;
- Vec c = a + b;
- float n = c.norm();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "norm")
-}
-
-func TestCLSP_Template_PolicyBasedLog(t *testing.T) {
- source := `
-struct ConsolePolicy {
- void write(const char* msg) {}
-};
-
-template<typename Policy>
-class Logger {
- Policy policy;
-public:
- void log(const char* msg) { policy.write(msg); }
-};
-
-void test() {
- Logger<ConsolePolicy> logger;
- logger.log("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "log")
-}
-
-func TestCLSP_Template_PolicyBasedAlloc(t *testing.T) {
- source := `
-struct MallocAlloc {
- void* allocate(int sz) { return 0; }
-};
-
-template<typename Alloc>
-class Pool {
- Alloc alloc;
-public:
- void* get(int sz) { return alloc.allocate(sz); }
-};
-
-void test() {
- Pool<MallocAlloc> pool;
- pool.get(64);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get")
-}
-
-func TestCLSP_Template_TemplateTemplate(t *testing.T) {
- source := `
-template<typename T>
-class DefaultContainer {
-public:
- void add(T val) {}
-};
-
-template<template<typename> class C, typename T>
-class Wrapper {
- C<T> inner;
-public:
- void insert(T val) { inner.add(val); }
-};
-
-void test() {
- Wrapper<DefaultContainer, int> w;
- w.insert(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "insert")
-}
-
-func TestCLSP_Template_MixinPattern(t *testing.T) {
- source := `
-template<typename Derived>
-class Printable {
-public:
- void print() {}
-};
-
-class Doc : public Printable<Doc> {
-public:
- void save() {}
-};
-
-void test() {
- Doc d;
- d.print();
- d.save();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "print")
- requireResolvedCall(t, result, "test", "save")
-}
-
-func TestCLSP_Template_TypeErasure(t *testing.T) {
- source := `
-class Drawable {
-public:
- virtual void draw() = 0;
-};
-
-class Circle : public Drawable {
-public:
- void draw() {}
-};
-
-void test() {
- Circle c;
- c.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_Template_StaticAssert(t *testing.T) {
- source := `
-template<typename T>
-class SafeContainer {
-public:
- void add(T val) {}
-};
-
-void test() {
- SafeContainer<int> sc;
- sc.add(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "add")
-}
-
-// ============================================================================
-// Batch 4F: Template Argument Deduction
-// ============================================================================
-
-func TestCLSP_TAD_SimpleFunc(t *testing.T) {
- source := `
-template<typename T>
-T identity(T val) { return val; }
-
-void test() {
- int x = identity(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "identity")
-}
-
-func TestCLSP_TAD_ReturnTypeDeduction(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-auto make_widget() {
- return Widget{};
-}
-
-void test() {
- auto w = make_widget();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_widget")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- rc = findResolvedCall(t, result, "test", "draw")
- }
- if rc == nil {
- t.Log("GAP: auto return type deduction")
- }
-}
-
-func TestCLSP_TAD_MultiParam(t *testing.T) {
- source := `
-template<typename A, typename B>
-A combine(A a, B b) { return a; }
-
-void test() {
- int r = combine(1, 2.0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "combine")
-}
-
-func TestCLSP_TAD_ExplicitArgs(t *testing.T) {
- source := `
-template<typename T>
-T create() { return T{}; }
-
-void test() {
- int v = create<int>();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
-}
-
-func TestCLSP_TAD_PartialExplicit(t *testing.T) {
- source := `
-template<typename R, typename T>
-R convert(T val) { return R{}; }
-
-void test() {
- float f = convert<float>(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "convert")
-}
-
-func TestCLSP_TAD_DefaultArg(t *testing.T) {
- source := `
-template<typename T = int>
-class Box {
-public:
- void open() {}
-};
-
-void test() {
- Box<> b;
- b.open();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "open")
-}
-
-func TestCLSP_TAD_PerfectForwarding(t *testing.T) {
- source := `
-namespace std {
- template<typename T> T&& forward(T& arg) { return (T&&)arg; }
-}
-
-void target(int x) {}
-
-template<typename T>
-void forwarder(T&& arg) {
- target(std::forward<T>(arg));
-}
-
-void test() {
- forwarder(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "forwarder")
-}
-
-func TestCLSP_TAD_AutoReturn(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-auto build_widget() {
- Widget w;
- return w;
-}
-
-void test() {
- auto w = build_widget();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "build_widget")
- rc := findResolvedCall(t, result, "test", "Widget.draw")
- if rc == nil {
- rc = findResolvedCall(t, result, "test", "draw")
- }
- if rc == nil {
- t.Log("GAP: auto return type deduction for draw()")
- }
-}
-
-// ============================================================================
-// Batch 5A: Smart Pointer Chains
-// ============================================================================
-
-func TestCLSP_RW_SharedPtrArrow(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
- T& operator*() { static T val; return val; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::shared_ptr<Widget> p;
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_RW_UniquePtrArrow(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class unique_ptr {
-public:
- T* operator->() { return (T*)0; }
- T& operator*() { static T val; return val; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::unique_ptr<Widget> p;
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_RW_SharedPtrGet(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* get() { return (T*)0; }
- T* operator->() { return (T*)0; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::shared_ptr<Widget> p;
- p.get()->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: shared_ptr::get() return type deduction")
- }
-}
-
-func TestCLSP_RW_SharedPtrDeref(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
- T& operator*() { static T val; return val; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::shared_ptr<Widget> p;
- (*p).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: shared_ptr dereference operator type deduction")
- }
-}
-
-func TestCLSP_RW_SharedPtrChain(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-class Container {
-public:
- Widget first;
-};
-
-void test() {
- std::shared_ptr<Container> p;
- p->first.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: shared_ptr chain field access then method call")
- }
-}
-
-func TestCLSP_RW_WeakPtrLock(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<typename T> class weak_ptr {
-public:
- shared_ptr<T> lock() { return shared_ptr<T>(); }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::weak_ptr<Widget> w;
- w.lock()->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: weak_ptr::lock() chain resolution")
- }
-}
-
-func TestCLSP_RW_MakeSharedMethodChain(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<typename T> shared_ptr<T> make_shared() { return shared_ptr<T>(); }
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::make_shared<Widget>()->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: make_shared()->method() chain resolution")
- }
-}
-
-func TestCLSP_RW_SharedPtrCast(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<typename T, typename U>
-shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r) { return shared_ptr<T>(); }
-}
-
-class Base { public: virtual void act() {} };
-class Derived : public Base { public: void special() {} };
-
-void test() {
- std::shared_ptr<Base> base;
- auto derived = std::static_pointer_cast<Derived>(base);
- derived->special();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "special")
- if rc == nil {
- t.Log("GAP: static_pointer_cast return type resolution")
- }
-}
-
-// ============================================================================
-// Batch 5B: Iterator Patterns
-// ============================================================================
-
-func TestCLSP_RW_IteratorForLoop(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-void test() {
- Widget widgets[3];
- for (auto& w : widgets) {
- w.draw();
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: range-for auto& element type deduction")
- }
-}
-
-func TestCLSP_RW_IteratorDeref(t *testing.T) {
- source := `
-namespace std {
-template<typename T> struct vector {
- struct iterator {
- T& operator*() { static T val; return val; }
- T* operator->() { return (T*)0; }
- };
- iterator begin() { return iterator(); }
- iterator end() { return iterator(); }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::vector<Widget> widgets;
- auto iter = widgets.begin();
- (*iter).draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: iterator dereference type deduction")
- }
-}
-
-func TestCLSP_RW_IteratorArrow(t *testing.T) {
- source := `
-namespace std {
-template<typename T> struct vector {
- struct iterator {
- T* operator->() { return (T*)0; }
- };
- iterator begin() { return iterator(); }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::vector<Widget> widgets;
- auto iter = widgets.begin();
- iter->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: iterator arrow operator type deduction")
- }
-}
-
-func TestCLSP_RW_ReverseIterator(t *testing.T) {
- source := `
-namespace std {
-template<typename T> struct vector {
- void rbegin() {}
- void rend() {}
-};
-}
-
-void test() {
- std::vector<int> v;
- v.rbegin();
- v.rend();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "rbegin")
- requireResolvedCall(t, result, "test", "rend")
-}
-
-func TestCLSP_RW_ConstIterator(t *testing.T) {
- source := `
-namespace std {
-template<typename T> struct vector {
- void cbegin() {}
- void cend() {}
-};
-}
-
-void test() {
- std::vector<int> v;
- v.cbegin();
- v.cend();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "cbegin")
- requireResolvedCall(t, result, "test", "cend")
-}
-
-func TestCLSP_RW_InsertIterator(t *testing.T) {
- source := `
-namespace std {
-template<typename T> struct vector {
- void push_back(const T& val) {}
-};
-template<typename C>
-void back_inserter(C& c) {}
-}
-
-void test() {
- std::vector<int> v;
- std::back_inserter(v);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "back_inserter")
-}
-
-func TestCLSP_RW_IteratorAdvance(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-void advance(Iter& it, int n) {}
-}
-
-void test() {
- int* ptr = 0;
- std::advance(ptr, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "advance")
-}
-
-func TestCLSP_RW_IteratorDistance(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-int distance(Iter first, Iter last) { return 0; }
-}
-
-void test() {
- int* a = 0;
- int* b = 0;
- int d = std::distance(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "distance")
-}
-
-// ============================================================================
-// Batch 5C: Container Adapters
-// ============================================================================
-
-func TestCLSP_RW_StackPush(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class stack {
-public:
- void push(const T& val) {}
- void pop() {}
- T& top() { static T val; return val; }
-};
-}
-
-void test() {
- std::stack<int> s;
- s.push(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push")
-}
-
-func TestCLSP_RW_QueueFront(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class queue {
-public:
- void push(const T& val) {}
- T& front() { static T val; return val; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::queue<Widget> q;
- q.front().draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: queue::front() return type chain resolution")
- }
-}
-
-func TestCLSP_RW_PriorityQueueTop(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class priority_queue {
-public:
- void push(const T& val) {}
- const T& top() { static T val; return val; }
-};
-}
-
-void test() {
- std::priority_queue<int> pq;
- pq.push(1);
- pq.top();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push")
- requireResolvedCall(t, result, "test", "top")
-}
-
-func TestCLSP_RW_DequeAccess(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class deque {
-public:
- T& operator[](int i) { static T val; return val; }
-};
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- std::deque<Widget> d;
- d[0].draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: deque subscript return type chain resolution")
- }
-}
-
-func TestCLSP_RW_SetInsert(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class set {
-public:
- void insert(const T& val) {}
- void find(const T& val) {}
-};
-}
-
-void test() {
- std::set<int> s;
- s.insert(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "insert")
-}
-
-func TestCLSP_RW_MultiMapRange(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class multimap {
-public:
- void find(const K& key) {}
- void insert(const K& key) {}
-};
-}
-
-class Widget {};
-
-void test() {
- std::multimap<int, Widget> m;
- m.find(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "find")
-}
-
-// ============================================================================
-// Batch 5D: RAII & Resource Management
-// ============================================================================
-
-func TestCLSP_RW_LockGuardScope(t *testing.T) {
- source := `
-class Mutex { public: void lock() {} void unlock() {} };
-
-class LockGuard {
- Mutex& mtx;
-public:
- LockGuard(Mutex& m) : mtx(m) { mtx.lock(); }
-};
-
-void do_work() {}
-
-void test() {
- Mutex m;
- LockGuard lg{m};
- do_work();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "do_work")
-}
-
-func TestCLSP_RW_UniqueLockScope(t *testing.T) {
- source := `
-class Mutex { public: void lock() {} void unlock() {} };
-
-class UniqueLock {
- Mutex& mtx;
-public:
- UniqueLock(Mutex& m) : mtx(m) {}
- void lock_now() { mtx.lock(); }
-};
-
-void do_work() {}
-
-void test() {
- Mutex m;
- UniqueLock ul{m};
- ul.lock_now();
- do_work();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "lock_now")
- requireResolvedCall(t, result, "test", "do_work")
-}
-
-func TestCLSP_RW_ScopedTimer(t *testing.T) {
- source := `
-class ScopedTimer {
-public:
- void start() {}
- void stop() {}
-};
-
-void do_work() {}
-
-void test() {
- ScopedTimer timer;
- timer.start();
- do_work();
- timer.stop();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "start")
- requireResolvedCall(t, result, "test", "stop")
- requireResolvedCall(t, result, "test", "do_work")
-}
-
-func TestCLSP_RW_FileHandle(t *testing.T) {
- source := `
-class FileHandle {
-public:
- void read() {}
- void write() {}
- void close() {}
-};
-
-void test() {
- FileHandle fh;
- fh.read();
- fh.close();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "read")
- requireResolvedCall(t, result, "test", "close")
-}
-
-func TestCLSP_RW_TransactionScope(t *testing.T) {
- source := `
-class Transaction {
-public:
- void begin() {}
- void commit() {}
- void rollback() {}
-};
-
-void do_work() {}
-
-void test() {
- Transaction txn;
- txn.begin();
- do_work();
- txn.commit();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "begin")
- requireResolvedCall(t, result, "test", "commit")
- requireResolvedCall(t, result, "test", "do_work")
-}
-
-func TestCLSP_RW_ConnectionPool(t *testing.T) {
- source := `
-class Connection {
-public:
- void query() {}
-};
-
-class Pool {
-public:
- Connection acquire() { return Connection{}; }
-};
-
-void test() {
- Pool pool;
- pool.acquire().query();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "acquire")
- rc := findResolvedCall(t, result, "test", "query")
- if rc == nil {
- t.Log("GAP: method chain return type resolution pool.acquire().query()")
- }
-}
-
-func TestCLSP_RW_ScopeGuard(t *testing.T) {
- source := `
-class ScopeGuard {
-public:
- void dismiss() {}
-};
-
-void cleanup() {}
-
-void test() {
- ScopeGuard guard;
- cleanup();
- guard.dismiss();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "cleanup")
- requireResolvedCall(t, result, "test", "dismiss")
-}
-
-// ============================================================================
-// Batch 5E: Factory Patterns
-// ============================================================================
-
-func TestCLSP_RW_FactoryMethod(t *testing.T) {
- source := `
-class Widget {
-public:
- static Widget create() { return Widget{}; }
- void draw() {}
-};
-
-void test() {
- Widget w = Widget::create();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_RW_AbstractFactory(t *testing.T) {
- source := `
-class Product { public: virtual void use() {} };
-
-class ConcreteProduct : public Product {
-public:
- void use() {}
-};
-
-class Factory {
-public:
- virtual Product* create() { return new ConcreteProduct(); }
-};
-
-void test() {
- Factory f;
- Product* p = f.create();
- p->use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- requireResolvedCall(t, result, "test", "use")
-}
-
-func TestCLSP_RW_FactoryFunction(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-Widget make_widget() { return Widget{}; }
-
-void test() {
- Widget w = make_widget();
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_widget")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_RW_BuilderPattern(t *testing.T) {
- source := `
-class Builder {
-public:
- Builder& set_x(int x) { return *this; }
- Builder& set_y(int y) { return *this; }
- void build() {}
-};
-
-void test() {
- Builder b;
- b.set_x(1).set_y(2).build();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_x")
- requireResolvedCall(t, result, "test", "set_y")
- requireResolvedCall(t, result, "test", "build")
-}
-
-func TestCLSP_RW_Singleton(t *testing.T) {
- source := `
-class Singleton {
-public:
- static Singleton& instance() { static Singleton s; return s; }
- void method() {}
-};
-
-void test() {
- Singleton::instance().method();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "instance")
- requireResolvedCall(t, result, "test", "method")
-}
-
-func TestCLSP_RW_PrototypeClone(t *testing.T) {
- source := `
-class Prototype {
-public:
- virtual Prototype* clone() { return new Prototype(); }
- void use() {}
-};
-
-void test() {
- Prototype p;
- Prototype* copy = p.clone();
- copy->use();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "clone")
- requireResolvedCall(t, result, "test", "use")
-}
-
-func TestCLSP_RW_FactoryRegistry(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-class Registry {
-public:
- Widget create(int id) { return Widget{}; }
-};
-
-void test() {
- Registry reg;
- auto w = reg.create(1);
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create")
- rc := findResolvedCall(t, result, "test", "draw")
- if rc == nil {
- t.Log("GAP: factory registry return type chain resolution")
- }
-}
-
-func TestCLSP_RW_NamedConstructor(t *testing.T) {
- source := `
-class Widget {
-public:
- static Widget fromFile(const char* path) { return Widget{}; }
- void draw() {}
-};
-
-void test() {
- Widget w = Widget::fromFile("test.txt");
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "fromFile")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// Batch 5F: Observer/Visitor/Strategy
-// ============================================================================
-
-func TestCLSP_RW_ObserverNotify(t *testing.T) {
- source := `
-class Observer {
-public:
- virtual void notify() {}
-};
-
-void test() {
- Observer obs;
- obs.notify();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "notify")
-}
-
-func TestCLSP_RW_ObserverSubscribe(t *testing.T) {
- source := `
-class Observer { public: void on_event() {} };
-
-class Subject {
-public:
- void subscribe(Observer* obs) {}
-};
-
-void test() {
- Subject subj;
- Observer obs;
- subj.subscribe(&obs);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "subscribe")
-}
-
-func TestCLSP_RW_VisitorAccept(t *testing.T) {
- source := `
-class Visitor;
-
-class Element {
-public:
- virtual void accept(Visitor* v) {}
-};
-
-void test() {
- Element elem;
- elem.accept(0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "accept")
-}
-
-func TestCLSP_RW_VisitorVisit(t *testing.T) {
- source := `
-class Element {};
-
-class Visitor {
-public:
- void visit(Element* e) {}
-};
-
-void test() {
- Visitor v;
- Element e;
- v.visit(&e);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "visit")
-}
-
-func TestCLSP_RW_StrategyExecute(t *testing.T) {
- source := `
-class Strategy {
-public:
- virtual void execute() {}
-};
-
-class Context {
- Strategy* strat;
-public:
- void run() { strat->execute(); }
-};
-
-void test() {
- Context ctx;
- ctx.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_RW_StrategySetAlgorithm(t *testing.T) {
- source := `
-class Strategy {};
-
-class Context {
-public:
- void set_strategy(Strategy* s) {}
- void execute() {}
-};
-
-void test() {
- Context ctx;
- Strategy s;
- ctx.set_strategy(&s);
- ctx.execute();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "set_strategy")
- requireResolvedCall(t, result, "test", "execute")
-}
-
-func TestCLSP_RW_CommandExecute(t *testing.T) {
- source := `
-class Command {
-public:
- virtual void execute() {}
-};
-
-void test() {
- Command cmd;
- cmd.execute();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "execute")
-}
-
-func TestCLSP_RW_CommandUndo(t *testing.T) {
- source := `
-class Command {
-public:
- virtual void execute() {}
- virtual void undo() {}
-};
-
-void test() {
- Command cmd;
- cmd.execute();
- cmd.undo();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "execute")
- requireResolvedCall(t, result, "test", "undo")
-}
-
-func TestCLSP_RW_MediatorSend(t *testing.T) {
- source := `
-class Mediator {
-public:
- void send(const char* msg) {}
-};
-
-void test() {
- Mediator med;
- med.send("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "send")
-}
-
-func TestCLSP_RW_ChainOfResponsibility(t *testing.T) {
- source := `
-class Handler {
-public:
- Handler* next;
- virtual void handle(int request) {}
-};
-
-void test() {
- Handler h;
- h.handle(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle")
-}
-
-// ============================================================================
-// Batch 5G: Compound Patterns
-// ============================================================================
-
-func TestCLSP_RW_MVCController(t *testing.T) {
- source := `
-class Request {};
-
-class Controller {
-public:
- void handle(Request* req) {}
-};
-
-void test() {
- Controller ctrl;
- Request req;
- ctrl.handle(&req);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle")
-}
-
-func TestCLSP_RW_EventLoop(t *testing.T) {
- source := `
-class EventLoop {
-public:
- void run() {}
- void stop() {}
-};
-
-void test() {
- EventLoop loop;
- loop.run();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "run")
-}
-
-func TestCLSP_RW_PluginSystem(t *testing.T) {
- source := `
-class Plugin {
-public:
- virtual void initialize() {}
- virtual void shutdown() {}
-};
-
-void test() {
- Plugin plugin;
- plugin.initialize();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "initialize")
-}
-
-func TestCLSP_RW_PipelineStage(t *testing.T) {
- source := `
-class Stage {
-public:
- virtual void process(int data) {}
-};
-
-void test() {
- Stage stage;
- stage.process(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_RW_MiddlewareChain(t *testing.T) {
- source := `
-class Middleware {
-public:
- Middleware* next_mw;
- virtual void handle(int req) {}
-};
-
-void test() {
- Middleware mw;
- mw.handle(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle")
-}
-
-func TestCLSP_RW_StateMachine(t *testing.T) {
- source := `
-class StateMachine {
-public:
- void transition(int event) {}
- void reset() {}
-};
-
-void test() {
- StateMachine sm;
- sm.transition(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "transition")
-}
-
-func TestCLSP_RW_ActorModel(t *testing.T) {
- source := `
-class Actor {
-public:
- void send(const char* msg) {}
- void receive() {}
-};
-
-void test() {
- Actor actor;
- actor.send("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "send")
-}
-
-func TestCLSP_RW_ReactiveStream(t *testing.T) {
- source := `
-class Stream {
-public:
- void subscribe() {}
- void unsubscribe() {}
-};
-
-void test() {
- Stream stream;
- stream.subscribe();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "subscribe")
-}
-
-// ============================================================================
-// Batch 6A: STL Container Method Calls
-// ============================================================================
-
-func TestCLSP_STL_VectorPushBack(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class vector {
-public:
- void push_back(const T& val) {}
-};
-}
-void test() {
- std::vector<int> v;
- v.push_back(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_back")
-}
-
-func TestCLSP_STL_VectorEmplaceBack(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class vector {
-public:
- template<typename... Args> void emplace_back(Args... args) {}
-};
-}
-void test() {
- std::vector<int> v;
- v.emplace_back(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "emplace_back")
-}
-
-func TestCLSP_STL_VectorReserve(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class vector {
-public:
- void reserve(int n) {}
-};
-}
-void test() {
- std::vector<int> v;
- v.reserve(100);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "reserve")
-}
-
-func TestCLSP_STL_VectorClear(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class vector {
-public:
- void clear() {}
-};
-}
-void test() {
- std::vector<int> v;
- v.clear();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "clear")
-}
-
-func TestCLSP_STL_MapInsert(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class map {
-public:
- void insert(const K& key) {}
-};
-}
-void test() {
- std::map<int, int> m;
- m.insert(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "insert")
-}
-
-func TestCLSP_STL_MapFind(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class map {
-public:
- void find(const K& key) {}
-};
-}
-void test() {
- std::map<int, int> m;
- m.find(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "find")
-}
-
-func TestCLSP_STL_MapErase(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class map {
-public:
- void erase(const K& key) {}
-};
-}
-void test() {
- std::map<int, int> m;
- m.erase(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "erase")
-}
-
-func TestCLSP_STL_MapCount(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class map {
-public:
- int count(const K& key) { return 0; }
-};
-}
-void test() {
- std::map<int, int> m;
- m.count(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "count")
-}
-
-func TestCLSP_STL_UnorderedMapInsert(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class unordered_map {
-public:
- void insert(const K& key) {}
-};
-}
-void test() {
- std::unordered_map<int, int> m;
- m.insert(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "insert")
-}
-
-func TestCLSP_STL_UnorderedMapFind(t *testing.T) {
- source := `
-namespace std {
-template<typename K, typename V> class unordered_map {
-public:
- void find(const K& key) {}
-};
-}
-void test() {
- std::unordered_map<int, int> m;
- m.find(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "find")
-}
-
-func TestCLSP_STL_SetInsert(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class set {
-public:
- void insert(const T& val) {}
-};
-}
-void test() {
- std::set<int> s;
- s.insert(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "insert")
-}
-
-func TestCLSP_STL_SetFind(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class set {
-public:
- void find(const T& val) {}
-};
-}
-void test() {
- std::set<int> s;
- s.find(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "find")
-}
-
-func TestCLSP_STL_SetCount(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class set {
-public:
- int count(const T& val) { return 0; }
-};
-}
-void test() {
- std::set<int> s;
- s.count(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "count")
-}
-
-func TestCLSP_STL_ListPushFront(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class list {
-public:
- void push_front(const T& val) {}
- void push_back(const T& val) {}
-};
-}
-void test() {
- std::list<int> lst;
- lst.push_front(1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "push_front")
-}
-
-func TestCLSP_STL_ListPopFront(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class list {
-public:
- void pop_front() {}
-};
-}
-void test() {
- std::list<int> lst;
- lst.pop_front();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "pop_front")
-}
-
-func TestCLSP_STL_ListSort(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class list {
-public:
- void sort() {}
-};
-}
-void test() {
- std::list<int> lst;
- lst.sort();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sort")
-}
-
-func TestCLSP_STL_ArrayAt(t *testing.T) {
- source := `
-namespace std {
-template<typename T, int N> class array {
-public:
- T& at(int i) { static T val; return val; }
-};
-}
-void test() {
- std::array<int, 5> a;
- a.at(0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "at")
-}
-
-func TestCLSP_STL_ArrayFill(t *testing.T) {
- source := `
-namespace std {
-template<typename T, int N> class array {
-public:
- void fill(const T& val) {}
-};
-}
-void test() {
- std::array<int, 5> a;
- a.fill(0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "fill")
-}
-
-func TestCLSP_STL_StringAppend(t *testing.T) {
- source := `
-namespace std {
-class string {
-public:
- void append(const char* s) {}
-};
-}
-void test() {
- std::string s;
- s.append("hello");
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "append")
-}
-
-func TestCLSP_STL_StringSubstr(t *testing.T) {
- source := `
-namespace std {
-class string {
-public:
- string substr(int pos, int len) { return string(); }
-};
-}
-void test() {
- std::string s;
- s.substr(0, 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "substr")
-}
-
-// ============================================================================
-// Batch 6B: STL Algorithm Calls
-// ============================================================================
-
-func TestCLSP_STL_Sort(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-void sort(Iter first, Iter last) {}
-}
-void test() {
- int arr[5];
- std::sort(arr, arr + 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sort")
-}
-
-func TestCLSP_STL_Find(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename T>
-Iter find(Iter first, Iter last, const T& val) { return first; }
-}
-void test() {
- int arr[5];
- std::find(arr, arr + 5, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "find")
-}
-
-func TestCLSP_STL_ForEach(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename Func>
-void for_each(Iter first, Iter last, Func fn) {}
-}
-void noop(int x) {}
-void test() {
- int arr[5];
- std::for_each(arr, arr + 5, noop);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "for_each")
-}
-
-func TestCLSP_STL_Transform(t *testing.T) {
- source := `
-namespace std {
-template<typename InIter, typename OutIter, typename Func>
-void transform(InIter first, InIter last, OutIter out, Func fn) {}
-}
-int double_val(int x) { return x * 2; }
-void test() {
- int arr[5];
- int out[5];
- std::transform(arr, arr + 5, out, double_val);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "transform")
-}
-
-func TestCLSP_STL_Copy(t *testing.T) {
- source := `
-namespace std {
-template<typename InIter, typename OutIter>
-void copy(InIter first, InIter last, OutIter out) {}
-}
-void test() {
- int arr[5];
- int out[5];
- std::copy(arr, arr + 5, out);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "copy")
-}
-
-func TestCLSP_STL_Accumulate(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename T>
-T accumulate(Iter first, Iter last, T init) { return init; }
-}
-void test() {
- int arr[5];
- int sum = std::accumulate(arr, arr + 5, 0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "accumulate")
-}
-
-func TestCLSP_STL_Count(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename T>
-int count(Iter first, Iter last, const T& val) { return 0; }
-}
-void test() {
- int arr[5];
- int c = std::count(arr, arr + 5, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "count")
-}
-
-func TestCLSP_STL_Remove(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename T>
-Iter remove(Iter first, Iter last, const T& val) { return first; }
-}
-void test() {
- int arr[5];
- std::remove(arr, arr + 5, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "remove")
-}
-
-func TestCLSP_STL_Unique(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-Iter unique(Iter first, Iter last) { return first; }
-}
-void test() {
- int arr[5];
- std::unique(arr, arr + 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "unique")
-}
-
-func TestCLSP_STL_Reverse(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-void reverse(Iter first, Iter last) {}
-}
-void test() {
- int arr[5];
- std::reverse(arr, arr + 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "reverse")
-}
-
-func TestCLSP_STL_MinElement(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-Iter min_element(Iter first, Iter last) { return first; }
-}
-void test() {
- int arr[5];
- std::min_element(arr, arr + 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "min_element")
-}
-
-func TestCLSP_STL_MaxElement(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-Iter max_element(Iter first, Iter last) { return first; }
-}
-void test() {
- int arr[5];
- std::max_element(arr, arr + 5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "max_element")
-}
-
-func TestCLSP_STL_BinarySearch(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename T>
-bool binary_search(Iter first, Iter last, const T& val) { return false; }
-}
-void test() {
- int arr[5];
- std::binary_search(arr, arr + 5, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "binary_search")
-}
-
-func TestCLSP_STL_LowerBound(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename T>
-Iter lower_bound(Iter first, Iter last, const T& val) { return first; }
-}
-void test() {
- int arr[5];
- std::lower_bound(arr, arr + 5, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "lower_bound")
-}
-
-func TestCLSP_STL_Partition(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter, typename Pred>
-Iter partition(Iter first, Iter last, Pred pred) { return first; }
-}
-bool is_even(int x) { return x % 2 == 0; }
-void test() {
- int arr[5];
- std::partition(arr, arr + 5, is_even);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "partition")
-}
-
-// ============================================================================
-// Batch 6C: STL Iterator Utilities
-// ============================================================================
-
-func TestCLSP_STL_Begin(t *testing.T) {
- source := `
-namespace std {
-template<typename C>
-auto begin(C& c) -> decltype(c.begin()) { return c.begin(); }
-template<typename T> class vector {
-public:
- T* begin() { return (T*)0; }
-};
-}
-void test() {
- std::vector<int> v;
- std::begin(v);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "begin")
-}
-
-func TestCLSP_STL_End(t *testing.T) {
- source := `
-namespace std {
-template<typename C>
-auto end(C& c) -> decltype(c.end()) { return c.end(); }
-template<typename T> class vector {
-public:
- T* end() { return (T*)0; }
-};
-}
-void test() {
- std::vector<int> v;
- std::end(v);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "end")
-}
-
-func TestCLSP_STL_Next(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-Iter next(Iter it, int n) { return it; }
-}
-void test() {
- int* ptr = 0;
- std::next(ptr, 1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "next")
-}
-
-func TestCLSP_STL_Prev(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-Iter prev(Iter it, int n) { return it; }
-}
-void test() {
- int* ptr = 0;
- std::prev(ptr, 1);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "prev")
-}
-
-func TestCLSP_STL_Advance(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-void advance(Iter& it, int n) {}
-}
-void test() {
- int* ptr = 0;
- std::advance(ptr, 3);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "advance")
-}
-
-func TestCLSP_STL_Distance(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter>
-int distance(Iter first, Iter last) { return 0; }
-}
-void test() {
- int* a = 0;
- int* b = 0;
- std::distance(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "distance")
-}
-
-func TestCLSP_STL_BackInserter(t *testing.T) {
- source := `
-namespace std {
-template<typename C> class back_insert_iterator {};
-template<typename C>
-back_insert_iterator<C> back_inserter(C& c) { return back_insert_iterator<C>(); }
-template<typename T> class vector { public: void push_back(const T& v) {} };
-}
-void test() {
- std::vector<int> v;
- std::back_inserter(v);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "back_inserter")
-}
-
-func TestCLSP_STL_FrontInserter(t *testing.T) {
- source := `
-namespace std {
-template<typename C> class front_insert_iterator {};
-template<typename C>
-front_insert_iterator<C> front_inserter(C& c) { return front_insert_iterator<C>(); }
-template<typename T> class deque { public: void push_front(const T& v) {} };
-}
-void test() {
- std::deque<int> d;
- std::front_inserter(d);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "front_inserter")
-}
-
-func TestCLSP_STL_MoveIterator(t *testing.T) {
- source := `
-namespace std {
-template<typename Iter> class move_iterator {};
-template<typename Iter>
-move_iterator<Iter> make_move_iterator(Iter it) { return move_iterator<Iter>(); }
-}
-void test() {
- int* ptr = 0;
- std::make_move_iterator(ptr);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_move_iterator")
-}
-
-func TestCLSP_STL_ReverseIterator(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class vector {
-public:
- void rbegin() {}
- void rend() {}
-};
-}
-void test() {
- std::vector<int> v;
- v.rbegin();
- v.rend();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "rbegin")
- requireResolvedCall(t, result, "test", "rend")
-}
-
-// ============================================================================
-// Batch 6D: STL Utility & Functional
-// ============================================================================
-
-func TestCLSP_STL_MakePair(t *testing.T) {
- source := `
-namespace std {
-template<typename A, typename B> struct pair { A first; B second; };
-template<typename A, typename B>
-pair<A, B> make_pair(A a, B b) { return pair<A, B>(); }
-}
-void test() {
- auto p = std::make_pair(1, 2.0);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_pair")
-}
-
-func TestCLSP_STL_MakeTuple(t *testing.T) {
- source := `
-namespace std {
-template<typename... Args> struct tuple {};
-template<typename... Args>
-tuple<Args...> make_tuple(Args... args) { return tuple<Args...>(); }
-}
-void test() {
- auto tp = std::make_tuple(1, 2.0, 'a');
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_tuple")
-}
-
-func TestCLSP_STL_Tie(t *testing.T) {
- source := `
-namespace std {
-template<typename... Args> struct tuple {};
-template<typename... Args>
-tuple<Args&...> tie(Args&... args) { return tuple<Args&...>(); }
-}
-void test() {
- int a, b;
- std::tie(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "tie")
-}
-
-func TestCLSP_STL_Get(t *testing.T) {
- source := `
-namespace std {
-template<typename A, typename B> struct pair { A first; B second; };
-template<int N, typename A, typename B>
-A& get(pair<A,B>& p) { return p.first; }
-}
-void test() {
- std::pair<int, float> p;
- std::get<0>(p);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get")
-}
-
-func TestCLSP_STL_Swap(t *testing.T) {
- source := `
-namespace std {
-template<typename T>
-void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
-}
-void test() {
- int a = 1, b = 2;
- std::swap(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "swap")
-}
-
-func TestCLSP_STL_FunctionCall(t *testing.T) {
- source := `
-namespace std {
-template<typename Sig> class function;
-template<typename R, typename... Args>
-class function<R(Args...)> {
-public:
- R operator()(Args... args) { return R(); }
-};
-}
-void test() {
- std::function<int(int)> fn;
- fn(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "operator()")
-}
-
-func TestCLSP_STL_Bind(t *testing.T) {
- source := `
-namespace std {
-template<typename F, typename... Args>
-void bind(F fn, Args... args) {}
-}
-void handler(int x) {}
-void test() {
- std::bind(handler, 42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "bind")
-}
-
-func TestCLSP_STL_Ref(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class reference_wrapper {
-public:
- T& get() { static T val; return val; }
-};
-template<typename T>
-reference_wrapper<T> ref(T& val) { return reference_wrapper<T>(); }
-}
-void test() {
- int x = 42;
- std::ref(x);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "ref")
-}
-
-func TestCLSP_STL_Cref(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class reference_wrapper {};
-template<typename T>
-reference_wrapper<const T> cref(const T& val) { return reference_wrapper<const T>(); }
-}
-void test() {
- int x = 42;
- std::cref(x);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "cref")
-}
-
-func TestCLSP_STL_Invoke(t *testing.T) {
- source := `
-namespace std {
-template<typename F, typename... Args>
-void invoke(F fn, Args... args) {}
-}
-void handler(int x) {}
-void test() {
- std::invoke(handler, 42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "invoke")
-}
-
-func TestCLSP_STL_MakeOptional(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class optional {
-public:
- T& value() { static T val; return val; }
-};
-template<typename T>
-optional<T> make_optional(T val) { return optional<T>(); }
-}
-void test() {
- auto opt = std::make_optional(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_optional")
-}
-
-func TestCLSP_STL_MakeUnique(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class unique_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<typename T, typename... Args>
-unique_ptr<T> make_unique(Args... args) { return unique_ptr<T>(); }
-}
-class Widget { public: void draw() {} };
-void test() {
- auto p = std::make_unique<Widget>();
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_unique")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_STL_MakeShared(t *testing.T) {
- source := `
-namespace std {
-template<typename T> class shared_ptr {
-public:
- T* operator->() { return (T*)0; }
-};
-template<typename T, typename... Args>
-shared_ptr<T> make_shared(Args... args) { return shared_ptr<T>(); }
-}
-class Widget { public: void draw() {} };
-void test() {
- auto p = std::make_shared<Widget>();
- p->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_shared")
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_STL_Forward(t *testing.T) {
- source := `
-namespace std {
-template<typename T> T&& forward(T& arg) { return (T&&)arg; }
-}
-void sink(int x) {}
-template<typename T>
-void relay(T&& arg) {
- sink(std::forward<T>(arg));
-}
-void test() {
- relay(42);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "relay")
-}
-
-func TestCLSP_STL_Move(t *testing.T) {
- source := `
-namespace std {
-template<typename T> T&& move(T& arg) { return (T&&)arg; }
-}
-class Widget { public: void draw() {} };
-void test() {
- Widget w;
- Widget w2 = std::move(w);
- w2.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// Batch 7A: C Function Pointer Tables
-// ============================================================================
-
-func TestCLSP_C_FuncPtrArray(t *testing.T) {
- source := `
-void action_a(void) {}
-void action_b(void) {}
-
-typedef void (*action_fn)(void);
-
-void test() {
- action_fn table[2];
- table[0] = action_a;
- table[1] = action_b;
- action_a();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "action_a")
-}
-
-func TestCLSP_C_FuncPtrStructArray(t *testing.T) {
- source := `
-void do_open(void) {}
-void do_close(void) {}
-
-struct Command {
- const char* name;
- void (*handler)(void);
-};
-
-void test() {
- struct Command cmds[2];
- cmds[0].handler = do_open;
- cmds[1].handler = do_close;
- do_open();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "do_open")
-}
-
-func TestCLSP_C_VTableStruct(t *testing.T) {
- source := `
-void impl_start(void) {}
-void impl_stop(void) {}
-
-struct VTable {
- void (*start)(void);
- void (*stop)(void);
-};
-
-void test() {
- struct VTable vt;
- vt.start = impl_start;
- vt.stop = impl_stop;
- impl_start();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "impl_start")
-}
-
-func TestCLSP_C_FuncPtrReturn(t *testing.T) {
- source := `
-void target_func(void) {}
-
-typedef void (*fn_t)(void);
-
-fn_t get_handler(void) {
- return target_func;
-}
-
-void test() {
- fn_t fn = get_handler();
- fn();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "get_handler")
-}
-
-func TestCLSP_C_FuncPtrParam(t *testing.T) {
- source := `
-void worker(void) {}
-
-void dispatch(void (*fn)(void)) {
- fn();
-}
-
-void test() {
- dispatch(worker);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "dispatch")
-}
-
-func TestCLSP_C_DispatchTable(t *testing.T) {
- source := `
-void handle_event_a(void) {}
-void handle_event_b(void) {}
-
-typedef void (*handler_t)(void);
-
-void test() {
- handler_t handlers[2];
- handlers[0] = handle_event_a;
- handlers[1] = handle_event_b;
- handle_event_a();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle_event_a")
-}
-
-func TestCLSP_C_FuncPtrCast(t *testing.T) {
- source := `
-int real_func(int x) { return x; }
-
-void test() {
- void* ptr = (void*)real_func;
- int (*fn)(int) = (int(*)(int))ptr;
- real_func(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "real_func")
-}
-
-func TestCLSP_C_CallbackRegistration(t *testing.T) {
- source := `
-typedef void (*callback_t)(int);
-
-void on_data(int val) {}
-
-void register_callback(callback_t cb) {}
-
-void test() {
- register_callback(on_data);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "register_callback")
-}
-
-func TestCLSP_C_FuncPtrTypedefUsage(t *testing.T) {
- source := `
-typedef int (*compare_fn)(const void*, const void*);
-
-int my_compare(const void* a, const void* b) { return 0; }
-
-void sort_items(compare_fn cmp) {}
-
-void test() {
- sort_items(my_compare);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "sort_items")
-}
-
-func TestCLSP_C_QSort(t *testing.T) {
- source := `
-int cmp_int(const void* a, const void* b) { return 0; }
-
-void qsort(void* base, int nmemb, int size, int (*cmp)(const void*, const void*));
-
-void test() {
- int arr[5];
- qsort(arr, 5, sizeof(int), cmp_int);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "qsort")
-}
-
-// ============================================================================
-// Batch 7B: C Opaque Types
-// ============================================================================
-
-func TestCLSP_C_OpaqueHandle(t *testing.T) {
- source := `
-struct Impl;
-typedef struct Impl* Handle;
-
-void handle_use(Handle h) {}
-
-void test() {
- Handle h;
- handle_use(h);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle_use")
-}
-
-func TestCLSP_C_OpaqueVoidPtr(t *testing.T) {
- source := `
-struct Data { int value; };
-
-void process(void* ctx) {
- struct Data* d = (struct Data*)ctx;
-}
-
-void test() {
- struct Data d;
- process(&d);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_C_OpaqueForwardDecl(t *testing.T) {
- source := `
-struct Opaque;
-
-struct Opaque* create_opaque(void);
-void destroy_opaque(struct Opaque* o);
-
-void test() {
- struct Opaque* o = create_opaque();
- destroy_opaque(o);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "create_opaque")
- requireResolvedCall(t, result, "test", "destroy_opaque")
-}
-
-func TestCLSP_C_OpaquePimpl(t *testing.T) {
- source := `
-struct Widget;
-
-struct Widget* widget_create(void);
-void widget_draw(struct Widget* w);
-void widget_destroy(struct Widget* w);
-
-void test() {
- struct Widget* w = widget_create();
- widget_draw(w);
- widget_destroy(w);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "widget_create")
- requireResolvedCall(t, result, "test", "widget_draw")
- requireResolvedCall(t, result, "test", "widget_destroy")
-}
-
-func TestCLSP_C_OpaqueTypedefStruct(t *testing.T) {
- source := `
-typedef struct {
- int x;
- int y;
-} Point;
-
-void use_point(Point* p) {}
-
-void test() {
- Point p;
- use_point(&p);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use_point")
-}
-
-func TestCLSP_C_OpaqueEnumFlags(t *testing.T) {
- source := `
-typedef enum {
- FLAG_A = 1,
- FLAG_B = 2,
- FLAG_C = 4
-} Flags;
-
-void apply_flags(Flags f) {}
-
-void test() {
- apply_flags(FLAG_A);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "apply_flags")
-}
-
-// ============================================================================
-// Batch 7C: C Flexible Array Members
-// ============================================================================
-
-func TestCLSP_C_FlexArrayMember(t *testing.T) {
- source := `
-struct Message {
- int length;
- char data[];
-};
-
-void process_msg(struct Message* m) {}
-
-void test() {
- struct Message* m;
- process_msg(m);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process_msg")
-}
-
-func TestCLSP_C_FlexArrayAccess(t *testing.T) {
- source := `
-struct Buffer {
- int size;
- unsigned char data[];
-};
-
-void read_buffer(struct Buffer* b) {}
-
-void test() {
- struct Buffer* buf;
- read_buffer(buf);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "read_buffer")
-}
-
-func TestCLSP_C_FlexArrayNested(t *testing.T) {
- source := `
-struct Header { int type; };
-struct Packet {
- struct Header hdr;
- int payload_len;
- char payload[];
-};
-
-void send_packet(struct Packet* p) {}
-
-void test() {
- struct Packet* pkt;
- send_packet(pkt);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "send_packet")
-}
-
-func TestCLSP_C_FlexArrayMalloc(t *testing.T) {
- source := `
-void* malloc(unsigned long size);
-
-struct DynArray {
- int count;
- int items[];
-};
-
-void test() {
- struct DynArray* arr = (struct DynArray*)malloc(sizeof(struct DynArray) + 10 * sizeof(int));
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "malloc")
-}
-
-// ============================================================================
-// Batch 7D: C Compound Literals
-// ============================================================================
-
-func TestCLSP_C_CompoundLiteralArg(t *testing.T) {
- source := `
-struct Point { int x; int y; };
-
-void draw_point(struct Point p) {}
-
-void test() {
- draw_point((struct Point){1, 2});
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw_point")
-}
-
-func TestCLSP_C_CompoundLiteralAssign(t *testing.T) {
- source := `
-struct Point { int x; int y; };
-
-void use_point(struct Point* p) {}
-
-void test() {
- struct Point p = (struct Point){10, 20};
- use_point(&p);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use_point")
-}
-
-func TestCLSP_C_CompoundLiteralArray(t *testing.T) {
- source := `
-void process_ints(int* arr, int count) {}
-
-void test() {
- process_ints((int[]){1, 2, 3}, 3);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process_ints")
-}
-
-func TestCLSP_C_CompoundLiteralNested(t *testing.T) {
- source := `
-struct Inner { int val; };
-struct Outer { struct Inner inner; int extra; };
-
-void use_outer(struct Outer* o) {}
-
-void test() {
- struct Outer o = (struct Outer){{42}, 10};
- use_outer(&o);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use_outer")
-}
-
-func TestCLSP_C_CompoundLiteralReturn(t *testing.T) {
- source := `
-struct Point { int x; int y; };
-
-struct Point make_point(int x, int y) {
- return (struct Point){x, y};
-}
-
-void test() {
- struct Point p = make_point(1, 2);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "make_point")
-}
-
-// ============================================================================
-// Batch 7E: C _Generic
-// ============================================================================
-
-func TestCLSP_C_GenericBasic(t *testing.T) {
- source := `
-int f_int(int x) { return x; }
-float f_float(float x) { return x; }
-
-void test() {
- int x = 5;
- f_int(x);
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "f_int")
- if rc == nil {
- t.Log("GAP: _Generic basic call resolution")
- }
-}
-
-func TestCLSP_C_GenericMacro(t *testing.T) {
- source := `
-const char* type_name_int(void) { return "int"; }
-const char* type_name_float(void) { return "float"; }
-
-void test() {
- type_name_int();
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "type_name_int")
- if rc == nil {
- t.Log("GAP: _Generic macro expansion resolution")
- }
-}
-
-func TestCLSP_C_GenericDefault(t *testing.T) {
- source := `
-void handle_default(void) {}
-void handle_int(int x) {}
-
-void test() {
- handle_default();
- handle_int(42);
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "handle_default")
- if rc == nil {
- t.Log("GAP: _Generic default handler resolution")
- }
-}
-
-func TestCLSP_C_GenericNested(t *testing.T) {
- source := `
-int inner_int(int x) { return x; }
-float inner_float(float x) { return x; }
-
-void test() {
- inner_int(42);
- inner_float(3.14f);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "inner_int")
- requireResolvedCall(t, result, "test", "inner_float")
-}
-
-// ============================================================================
-// Batch 7F: Misc C Patterns
-// ============================================================================
-
-func TestCLSP_C_BitfieldAccess(t *testing.T) {
- source := `
-struct Flags {
- unsigned int read : 1;
- unsigned int write : 1;
- unsigned int exec : 1;
-};
-
-void check_flags(struct Flags* f) {}
-
-void test() {
- struct Flags f;
- check_flags(&f);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "check_flags")
-}
-
-func TestCLSP_C_UnionAccess(t *testing.T) {
- source := `
-union Value {
- int i;
- float f;
- char c;
-};
-
-void use_union(union Value* v) {}
-
-void test() {
- union Value v;
- use_union(&v);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use_union")
-}
-
-func TestCLSP_C_EnumSwitch(t *testing.T) {
- source := `
-enum Color { RED, GREEN, BLUE };
-
-void handle_red(void) {}
-void handle_green(void) {}
-void handle_blue(void) {}
-
-void test() {
- enum Color c = RED;
- switch (c) {
- case RED: handle_red(); break;
- case GREEN: handle_green(); break;
- case BLUE: handle_blue(); break;
- }
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "handle_red")
- requireResolvedCall(t, result, "test", "handle_green")
- requireResolvedCall(t, result, "test", "handle_blue")
-}
-
-func TestCLSP_C_GotoLabel(t *testing.T) {
- source := `
-void cleanup(void) {}
-
-void test() {
- int x = 1;
- if (x) goto done;
- cleanup();
-done:
- return;
-}
-`
- result := extractCWithRegistry(t, source)
- // Just verify no crash with goto
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-func TestCLSP_C_VarArgsFunc(t *testing.T) {
- source := `
-void log_msg(const char* fmt, ...) {}
-
-void test() {
- log_msg("value=%d", 42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "log_msg")
-}
-
-func TestCLSP_C_InlineFunc(t *testing.T) {
- source := `
-static inline int square(int x) { return x * x; }
-
-void test() {
- int r = square(5);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "square")
-}
-
-func TestCLSP_C_StaticFunc(t *testing.T) {
- source := `
-static void helper(void) {}
-
-void test() {
- helper();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "helper")
-}
-
-func TestCLSP_C_ExternFunc(t *testing.T) {
- source := `
-extern void external_func(int x);
-
-void test() {
- external_func(42);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "external_func")
-}
-
-func TestCLSP_C_NestedStruct(t *testing.T) {
- source := `
-struct Inner { int value; };
-struct Outer {
- struct Inner inner;
- int count;
-};
-
-void use_inner(struct Inner* i) {}
-
-void test() {
- struct Outer o;
- use_inner(&o.inner);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use_inner")
-}
-
-func TestCLSP_C_TypedefChain(t *testing.T) {
- source := `
-typedef int Int32;
-typedef Int32 MyInt;
-
-void use_int(MyInt x) {}
-
-void test() {
- MyInt val = 42;
- use_int(val);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "use_int")
-}
-
-func TestCLSP_C_MacroExpansion(t *testing.T) {
- source := `
-void real_alloc(int size) {}
-
-void test() {
- real_alloc(64);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "real_alloc")
-}
-
-func TestCLSP_C_DesignatedInit(t *testing.T) {
- source := `
-struct Config {
- int width;
- int height;
- int depth;
-};
-
-void apply_config(struct Config* c) {}
-
-void test() {
- struct Config cfg = { .width = 800, .height = 600, .depth = 32 };
- apply_config(&cfg);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "apply_config")
-}
-
-func TestCLSP_C_CompoundAssign(t *testing.T) {
- source := `
-void accumulate(int* val, int delta) {}
-
-void test() {
- int x = 0;
- accumulate(&x, 10);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "accumulate")
-}
-
-func TestCLSP_C_CommaExpr(t *testing.T) {
- source := `
-int first_op(void) { return 0; }
-int second_op(void) { return 1; }
-
-void test() {
- int r = (first_op(), second_op());
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "first_op")
- requireResolvedCall(t, result, "test", "second_op")
-}
-
-func TestCLSP_C_TernaryCallBranches(t *testing.T) {
- source := `
-void path_a(void) {}
-void path_b(void) {}
-
-void test() {
- int cond = 1;
- cond ? path_a() : path_b();
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "path_a")
- requireResolvedCall(t, result, "test", "path_b")
-}
-
-func TestCLSP_C_SizeofExpr(t *testing.T) {
- source := `
-struct Data { int x; int y; int z; };
-
-void alloc(int size) {}
-
-void test() {
- alloc(sizeof(struct Data));
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "alloc")
-}
-
-// ============================================================================
-// Batch 8A: Placement New
-// ============================================================================
-
-func TestCLSP_EasyWin_PlacementNew(t *testing.T) {
- source := `
-class Widget {
-public:
- Widget() {}
- void draw() {}
-};
-
-void* operator new(unsigned long size, void* ptr) { return ptr; }
-
-void test() {
- char buffer[64];
- Widget* w = new(buffer) Widget();
- w->draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-func TestCLSP_EasyWin_PlacementNewArray(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-void* operator new(unsigned long size, void* ptr) { return ptr; }
-
-void test() {
- char pool[256];
- Widget* arr = new(pool) Widget[10];
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Just verify no crash with placement new array
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Batch 8B: throw Constructor Calls
-// ============================================================================
-
-func TestCLSP_EasyWin_ThrowConstructor(t *testing.T) {
- source := `
-class MyError {
-public:
- MyError(const char* msg) {}
-};
-
-void test() {
- throw MyError("something failed");
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "MyError")
- if rc == nil {
- t.Log("GAP: throw constructor call not detected")
- }
-}
-
-func TestCLSP_EasyWin_ThrowRethrow(t *testing.T) {
- source := `
-class Error {};
-
-void test() {
- try {
- throw Error();
- } catch (...) {
- throw;
- }
-}
-`
- result := extractCPPWithRegistry(t, source)
- // Just verify no crash with rethrow
- if result == nil {
- t.Fatal("extraction returned nil")
- }
-}
-
-// ============================================================================
-// Batch 8C: std::move/forward Propagation
-// ============================================================================
-
-func TestCLSP_EasyWin_StdMoveMethod(t *testing.T) {
- source := `
-namespace std {
-template<typename T> T&& move(T& arg) { return (T&&)arg; }
-}
-
-class Widget {
-public:
- void transfer() {}
-};
-
-void test() {
- Widget w;
- std::move(w).transfer();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "transfer")
-}
-
-func TestCLSP_EasyWin_StdForwardMethod(t *testing.T) {
- source := `
-namespace std {
-template<typename T> T&& forward(T& arg) { return (T&&)arg; }
-}
-
-class Widget {
-public:
- void process() {}
-};
-
-template<typename T>
-void relay(T&& obj) {
- std::forward<T>(obj).process();
-}
-
-void test() {
- Widget w;
- relay(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "relay")
-}
-
-func TestCLSP_EasyWin_MoveAssignChain(t *testing.T) {
- source := `
-namespace std {
-template<typename T> T&& move(T& arg) { return (T&&)arg; }
-}
-
-class Widget {
-public:
- void draw() {}
-};
-
-void test() {
- Widget w1;
- auto w2 = std::move(w1);
- w2.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// Batch 8D: User-Defined Conversion Operators
-// ============================================================================
-
-func TestCLSP_EasyWin_ConversionOperatorExplicit(t *testing.T) {
- source := `
-class Wrapper {
-public:
- explicit operator bool() { return true; }
-};
-
-void test() {
- Wrapper w;
- if ((bool)w) {}
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "operator bool")
- if rc == nil {
- t.Log("GAP: explicit conversion operator call detection")
- }
-}
-
-func TestCLSP_EasyWin_ConversionOperatorImplicit(t *testing.T) {
- source := `
-class Widget { public: void draw() {} };
-
-class WidgetWrapper {
-public:
- operator Widget() { return Widget{}; }
-};
-
-void test() {
- WidgetWrapper ww;
- Widget w = ww;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "operator Widget")
- if rc == nil {
- t.Log("GAP: implicit conversion operator call detection")
- }
-}
-
-// ============================================================================
-// Batch 8E: Extended ADL
-// ============================================================================
-
-func TestCLSP_EasyWin_ADLFromArgNamespace(t *testing.T) {
- source := `
-namespace gfx {
- class Widget { public: int data; };
- void serialize(Widget& w) {}
-}
-
-void test() {
- gfx::Widget w;
- serialize(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "serialize")
- if rc == nil {
- t.Log("GAP: ADL from argument namespace")
- }
-}
-
-func TestCLSP_EasyWin_ADLSwap(t *testing.T) {
- source := `
-namespace custom {
- class Type { public: int val; };
- void swap(Type& a, Type& b) {}
-}
-
-void test() {
- custom::Type a, b;
- swap(a, b);
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "swap")
- if rc == nil {
- t.Log("GAP: ADL swap resolution")
- }
-}
-
-// ============================================================================
-// Batch 8F: Reference Binding in Overloads
-// ============================================================================
-
-func TestCLSP_EasyWin_OverloadLvalueRef(t *testing.T) {
- source := `
-class Widget {};
-
-void process(Widget& w) {}
-void process(Widget&& w) {}
-
-void test() {
- Widget w;
- process(w);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-func TestCLSP_EasyWin_OverloadRvalueRef(t *testing.T) {
- source := `
-namespace std {
-template<typename T> T&& move(T& arg) { return (T&&)arg; }
-}
-
-class Widget {};
-
-void process(Widget& w) {}
-void process(Widget&& w) {}
-
-void test() {
- Widget w;
- process(std::move(w));
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "process")
-}
-
-// ============================================================================
-// Batch 8G: SFINAE Heuristic
-// ============================================================================
-
-func TestCLSP_EasyWin_SFINAEEnableIf(t *testing.T) {
- source := `
-namespace std {
- template<bool B, class T = void> struct enable_if {};
- template<class T> struct enable_if<true, T> { typedef T type; };
- template<class T> struct is_integral { static const bool value = true; };
-}
-
-template<typename T>
-typename std::enable_if<std::is_integral<T>::value, T>::type
-square(T x) { return x * x; }
-
-void test() {
- int r = square(5);
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "square")
-}
-
-func TestCLSP_EasyWin_SFINAEVoidT(t *testing.T) {
- source := `
-namespace std {
- template<typename...> using void_t = void;
-}
-
-class Widget { public: void draw() {} };
-
-void test() {
- Widget w;
- w.draw();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "draw")
-}
-
-// ============================================================================
-// DLL/Dynamic Function Pointer Resolution (issue #29)
-// ============================================================================
-
-func TestCLSP_DLL_GetProcAddress(t *testing.T) {
- // Windows-style: cast + GetProcAddress with string literal
- source := `
-typedef void* HMODULE;
-typedef void (*HandleFunc)(int);
-
-void* LoadLibrary(const char* name);
-void* GetProcAddress(void* module, const char* name);
-
-void test() {
- HMODULE dll = LoadLibrary("mylib.dll");
- HandleFunc handle = (HandleFunc)GetProcAddress(dll, "HandleMyGarbage");
- handle(42);
-}
-`
- result := extractCWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "test", "external.HandleMyGarbage")
- if rc.Strategy != "lsp_dll_resolve" {
- t.Errorf("expected strategy lsp_dll_resolve, got %s", rc.Strategy)
- }
-}
-
-func TestCLSP_DLL_Dlsym(t *testing.T) {
- // Linux-style: dlsym with cast
- source := `
-typedef void (*init_fn)(void);
-
-void* dlopen(const char* filename, int flags);
-void* dlsym(void* handle, const char* symbol);
-
-void test() {
- void* h = dlopen("libfoo.so", 1);
- init_fn init = (init_fn)dlsym(h, "initialize");
- init();
-}
-`
- result := extractCWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "test", "external.initialize")
- if rc.Strategy != "lsp_dll_resolve" {
- t.Errorf("expected strategy lsp_dll_resolve, got %s", rc.Strategy)
- }
-}
-
-func TestCLSP_DLL_CustomResolver(t *testing.T) {
- // Custom resolver function — heuristic detects cast + string literal
- source := `
-typedef int (*ProcessFunc)(const char*);
-void* Resolve(const char* name);
-
-void test() {
- ProcessFunc proc = (ProcessFunc)Resolve("ProcessData");
- proc("input");
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "external.ProcessData")
-}
-
-func TestCLSP_DLL_CppStaticCast(t *testing.T) {
- // C++ static_cast pattern
- source := `
-typedef void (*RenderFunc)(void);
-void* LoadSymbol(const char* name);
-
-void test() {
- RenderFunc render = static_cast<RenderFunc>(LoadSymbol("RenderFrame"));
- render();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "external.RenderFrame")
-}
-
-func TestCLSP_DLL_ReinterpretCast(t *testing.T) {
- // C++ reinterpret_cast pattern
- source := `
-typedef void (*ShutdownFunc)(void);
-void* GetSymbol(void* lib, const char* sym);
-
-void test() {
- void* lib;
- ShutdownFunc shutdown = reinterpret_cast<ShutdownFunc>(GetSymbol(lib, "Shutdown"));
- shutdown();
-}
-`
- result := extractCPPWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "external.Shutdown")
-}
-
-func TestCLSP_DLL_NoFalsePositive_NonFP(t *testing.T) {
- // Should NOT trigger: string arg but result is not a function pointer
- source := `
-char* lookup(const char* key);
-
-void test() {
- char* val = lookup("some_key");
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "external.some_key")
- if rc != nil {
- t.Errorf("false positive: non-fp variable should not get dll resolve, got %s", rc.CalleeQN)
- }
-}
-
-func TestCLSP_DLL_NoFalsePositive_NoCast(t *testing.T) {
- // Should NOT trigger: no cast, var type is not function pointer
- source := `
-int find(const char* name);
-
-void test() {
- int result = find("SomeFunc");
-}
-`
- result := extractCWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "external.SomeFunc")
- if rc != nil {
- t.Errorf("false positive: int variable should not get dll resolve")
- }
-}
-
-func TestCLSP_DLL_MultipleFunctions(t *testing.T) {
- // Multiple DLL functions resolved from same library
- source := `
-typedef void (*FuncA)(void);
-typedef int (*FuncB)(int);
-void* Resolve(const char* name);
-
-void test() {
- FuncA a = (FuncA)Resolve("Alpha");
- FuncB b = (FuncB)Resolve("Beta");
- a();
- b(1);
-}
-`
- result := extractCWithRegistry(t, source)
- requireResolvedCall(t, result, "test", "external.Alpha")
- requireResolvedCall(t, result, "test", "external.Beta")
-}
-
-func TestCLSP_DLL_FuncPtrTypedef(t *testing.T) {
- // Function pointer type detected without cast (explicit fp typedef)
- source := `
-typedef void (*callback_t)(int, int);
-callback_t get_callback(const char* name);
-
-void test() {
- callback_t cb = get_callback("OnResize");
- cb(800, 600);
-}
-`
- result := extractCWithRegistry(t, source)
- // This pattern has no cast, but var type is a function pointer typedef.
- // The typedef appears as NAMED type, not FUNC/POINTER, so the heuristic
- // needs a cast to activate. This is a known limitation — cast is the signal.
- _ = result
-}
-
-func TestCLSP_EasyWin_SFINAEConditionalReturn(t *testing.T) {
- source := `
-namespace std {
- template<bool B, class T, class F> struct conditional { typedef T type; };
- template<class T, class F> struct conditional<false, T, F> { typedef F type; };
- template<bool B, class T, class F> using conditional_t = typename conditional<B,T,F>::type;
-}
-
-class TypeA { public: void act() {} };
-class TypeB { public: void act() {} };
-
-void test() {
- TypeA a;
- a.act();
-}
-`
- result := extractCPPWithRegistry(t, source)
- rc := findResolvedCall(t, result, "test", "act")
- if rc == nil {
- t.Log("GAP: SFINAE conditional return type resolution")
- }
-}
diff --git a/internal/cbm/lsp_test.go b/internal/cbm/lsp_test.go
deleted file mode 100644
index 46b83db86..000000000
--- a/internal/cbm/lsp_test.go
+++ /dev/null
@@ -1,1735 +0,0 @@
-package cbm
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// findResolvedCall searches for a resolved call matching caller and callee substrings.
-func findResolvedCall(t *testing.T, result *FileResult, callerContains, calleeContains string) *ResolvedCall {
- t.Helper()
- for i, rc := range result.ResolvedCalls {
- if contains(rc.CallerQN, callerContains) && contains(rc.CalleeQN, calleeContains) {
- return &result.ResolvedCalls[i]
- }
- }
- return nil
-}
-
-func contains(s, substr string) bool {
- return len(substr) == 0 || len(s) >= len(substr) && searchSubstring(s, substr)
-}
-
-func searchSubstring(s, substr string) bool {
- for i := 0; i <= len(s)-len(substr); i++ {
- if s[i:i+len(substr)] == substr {
- return true
- }
- }
- return false
-}
-
-func requireResolvedCall(t *testing.T, result *FileResult, callerContains, calleeContains string) *ResolvedCall {
- t.Helper()
- rc := findResolvedCall(t, result, callerContains, calleeContains)
- if rc == nil {
- t.Errorf("expected resolved call: caller~%q -> callee~%q, got %d resolved calls:",
- callerContains, calleeContains, len(result.ResolvedCalls))
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", r.CallerQN, r.CalleeQN, r.Strategy, r.Confidence)
- }
- t.FailNow()
- }
- return rc
-}
-
-func findAllResolvedCalls(t *testing.T, result *FileResult, callerContains, calleeContains string) []ResolvedCall {
- t.Helper()
- var matches []ResolvedCall
- for _, rc := range result.ResolvedCalls {
- if contains(rc.CallerQN, callerContains) && contains(rc.CalleeQN, calleeContains) {
- matches = append(matches, rc)
- }
- }
- return matches
-}
-
-// extractGoWithRegistry extracts a Go file and returns the result.
-// The test files define their own types/functions inline, so the LSP resolver
-// must use the file's own definitions as the type registry.
-func extractGoWithRegistry(t *testing.T, source string) *FileResult {
- t.Helper()
- result, err := ExtractFile([]byte(source), lang.Go, "test", "main.go")
- if err != nil {
- t.Fatalf("ExtractFile failed: %v", err)
- }
- return result
-}
-
-// ============================================================================
-// Test Category 1: Parameter type inference
-// ============================================================================
-
-func TestGoLSP_ParamTypeInference_Simple(t *testing.T) {
- source := `package main
-
-type Database struct{}
-
-func (d *Database) Query(sql string) string { return "" }
-
-func doWork(db *Database) {
- db.Query("SELECT 1")
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "doWork", "Query")
-}
-
-func TestGoLSP_ParamTypeInference_MultiParam(t *testing.T) {
- source := `package main
-
-type Logger struct{}
-type Config struct{}
-
-func (l *Logger) Info(msg string) {}
-func (c *Config) Get(key string) string { return "" }
-
-func setup(log *Logger, cfg *Config) {
- log.Info("starting")
- cfg.Get("port")
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "setup", "Info")
- requireResolvedCall(t, result, "setup", "Get")
-}
-
-// ============================================================================
-// Test Category 2: Return type propagation
-// ============================================================================
-
-func TestGoLSP_ReturnTypePropagation(t *testing.T) {
- source := `package main
-
-type File struct{}
-
-func (f *File) Read(buf []byte) int { return 0 }
-func Open(path string) *File { return nil }
-
-func doRead() {
- f := Open("/tmp/test")
- f.Read(nil)
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "doRead", "Read")
-}
-
-func TestGoLSP_ReturnTypePropagation_Chain(t *testing.T) {
- source := `package main
-
-type Builder struct{}
-type Result struct{}
-
-func (b *Builder) Build() *Result { return nil }
-func (r *Result) String() string { return "" }
-func NewBuilder() *Builder { return nil }
-
-func doChain() {
- b := NewBuilder()
- r := b.Build()
- r.String()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "doChain", "Build")
- requireResolvedCall(t, result, "doChain", "String")
-}
-
-// ============================================================================
-// Test Category 3: Method chaining
-// ============================================================================
-
-func TestGoLSP_MethodChaining(t *testing.T) {
- source := `package main
-
-type Query struct{}
-
-func (q *Query) Where(cond string) *Query { return q }
-func (q *Query) Limit(n int) *Query { return q }
-func (q *Query) Execute() int { return 0 }
-func NewQuery() *Query { return nil }
-
-func doQuery() {
- NewQuery().Where("x=1").Limit(10).Execute()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "doQuery", "Where")
- requireResolvedCall(t, result, "doQuery", "Limit")
- requireResolvedCall(t, result, "doQuery", "Execute")
-}
-
-// ============================================================================
-// Test Category 4: Multi-return
-// ============================================================================
-
-func TestGoLSP_MultiReturn(t *testing.T) {
- source := `package main
-
-type Conn struct{}
-
-func (c *Conn) Close() error { return nil }
-func Dial(addr string) (*Conn, error) { return nil, nil }
-
-func doConnect() {
- c, _ := Dial("localhost")
- c.Close()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "doConnect", "Close")
-}
-
-// ============================================================================
-// Test Category 5: Channel receive
-// ============================================================================
-
-func TestGoLSP_ChannelReceive(t *testing.T) {
- source := `package main
-
-type Event struct{}
-
-func (e *Event) Process() {}
-
-func handleEvents(ch chan *Event) {
- e := <-ch
- e.Process()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "handleEvents", "Process")
-}
-
-// ============================================================================
-// Test Category 6: Range variables
-// ============================================================================
-
-func TestGoLSP_RangeSlice(t *testing.T) {
- source := `package main
-
-type User struct{}
-
-func (u *User) Name() string { return "" }
-
-func listNames(users []*User) {
- for _, u := range users {
- u.Name()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "listNames", "Name")
-}
-
-func TestGoLSP_RangeMap(t *testing.T) {
- source := `package main
-
-type Service struct{}
-
-func (s *Service) Start() {}
-
-func startAll(services map[string]*Service) {
- for _, svc := range services {
- svc.Start()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "startAll", "Start")
-}
-
-// ============================================================================
-// Test Category 7: Type switch
-// ============================================================================
-
-func TestGoLSP_TypeSwitch(t *testing.T) {
- source := `package main
-
-type Dog struct{}
-type Cat struct{}
-
-func (d *Dog) Speak() string { return "woof" }
-func (c *Cat) Speak() string { return "meow" }
-
-func describe(animal interface{}) {
- switch a := animal.(type) {
- case *Dog:
- a.Speak()
- case *Cat:
- a.Speak()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
- // Should find Speak resolved in at least one case clause
- calls := findAllResolvedCalls(t, result, "describe", "Speak")
- if len(calls) == 0 {
- t.Fatalf("expected type switch to resolve a.Speak(), got 0 resolved calls")
- }
- // Should be type_dispatch since the case narrows to *Dog or *Cat
- for _, rc := range calls {
- if rc.Strategy != "lsp_type_dispatch" {
- t.Errorf("expected lsp_type_dispatch, got %s for %s", rc.Strategy, rc.CalleeQN)
- }
- }
-}
-
-// ============================================================================
-// Test Category 8: Closures
-// ============================================================================
-
-func TestGoLSP_Closure(t *testing.T) {
- source := `package main
-
-type Database struct{}
-
-func (db *Database) Query() {}
-
-func startWorker(db *Database) {
- go func() {
- db.Query()
- }()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "startWorker", "Query")
-}
-
-// ============================================================================
-// Test Category 9: Composite literals
-// ============================================================================
-
-func TestGoLSP_CompositeLiteral(t *testing.T) {
- source := `package main
-
-type Config struct{}
-
-func (c *Config) Validate() bool { return true }
-
-func makeConfig() {
- c := &Config{}
- c.Validate()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "makeConfig", "Validate")
-}
-
-func TestGoLSP_CompositeLiteralDirect(t *testing.T) {
- source := `package main
-
-type Handler struct{}
-
-func (h *Handler) ServeHTTP() {}
-
-func serve() {
- (&Handler{}).ServeHTTP()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "serve", "ServeHTTP")
-}
-
-// ============================================================================
-// Test Category 10: Builtins
-// ============================================================================
-
-func TestGoLSP_MakeSlice(t *testing.T) {
- source := `package main
-
-type Item struct{}
-
-func (it *Item) Process() {}
-
-func work() {
- items := make([]*Item, 0)
- items[0].Process()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "work", "Process")
-}
-
-// ============================================================================
-// Test Category 11: Type assertions
-// ============================================================================
-
-func TestGoLSP_TypeAssertion(t *testing.T) {
- source := `package main
-
-type Writer struct{}
-
-func (w *Writer) Write(data []byte) int { return 0 }
-
-func writeData(x interface{}) {
- w := x.(*Writer)
- w.Write(nil)
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "writeData", "Write")
-}
-
-// ============================================================================
-// Test Category 12: Struct embedding
-// ============================================================================
-
-func TestGoLSP_StructEmbedding(t *testing.T) {
- source := `package main
-
-type Base struct{}
-
-func (b *Base) Save() {}
-
-type Extended struct {
- Base
-}
-
-func persist(e *Extended) {
- e.Save()
-}
-`
- result := extractGoWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "persist", "Save")
- if rc.Strategy != "lsp_embed_dispatch" {
- t.Errorf("expected lsp_embed_dispatch, got %s", rc.Strategy)
- }
-}
-
-// ============================================================================
-// Test Category 13: Interface dispatch
-// ============================================================================
-
-func TestGoLSP_InterfaceDispatch(t *testing.T) {
- source := `package main
-
-type Writer interface {
- Write(data []byte) int
-}
-
-func writeAll(w Writer) {
- w.Write(nil)
-}
-`
- result := extractGoWithRegistry(t, source)
- rc := requireResolvedCall(t, result, "writeAll", "Write")
- if rc.Strategy != "lsp_interface_dispatch" {
- t.Errorf("expected lsp_interface_dispatch, got %s", rc.Strategy)
- }
- if rc.Confidence > 0.90 {
- t.Errorf("interface dispatch should have lower confidence, got %.2f", rc.Confidence)
- }
-}
-
-// ============================================================================
-// Test Category 14-15: Generics
-// ============================================================================
-
-func TestGoLSP_ExplicitGenerics(t *testing.T) {
- source := `package main
-
-type User struct{}
-func (u User) Name() string { return "" }
-
-type Result struct{}
-func (r Result) Value() int { return 0 }
-
-func Filter[T any, U any](s []T, pred func(T) bool) []U {
- return nil
-}
-
-func Transform[T any, R any](input T, f func(T) R) R {
- return f(input)
-}
-
-func main() {
- var users []User
- u := Filter[User, User](users, nil)
- _ = u
-
- r := Transform[User, Result](users[0], func(u User) Result { return Result{} })
- r.Value()
-}
-`
- result := extractGoWithRegistry(t, source)
- t.Logf("Definitions (%d):", len(result.Definitions))
- for _, d := range result.Definitions {
- t.Logf(" %s [%s] QN=%s ReturnTypes=%v", d.Name, d.Label, d.QualifiedName, d.ReturnTypes)
- }
- t.Logf("Calls (%d):", len(result.Calls))
- for _, c := range result.Calls {
- t.Logf(" %s -> %s", c.EnclosingFuncQN, c.CalleeName)
- }
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // Filter[User, User](...) should resolve
- requireResolvedCall(t, result, "main", "Filter")
-
- // Transform[User, Result](...) should resolve, and r.Value() should resolve
- // because Transform's return type R is substituted with Result
- requireResolvedCall(t, result, "main", "Transform")
- requireResolvedCall(t, result, "main", "Value")
-}
-
-func TestGoLSP_ImplicitGenerics(t *testing.T) {
- source := `package main
-
-type User struct{}
-func (u User) Name() string { return "" }
-
-func Filter[T any](s []T, pred func(T) bool) []T { return nil }
-
-func main() {
- var users []User
- result := Filter(users, func(u User) bool { return true })
- for _, u := range result {
- u.Name()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
- for _, d := range result.Definitions {
- t.Logf(" %s [%s] QN=%s ReturnTypes=%v", d.Name, d.Label, d.QualifiedName, d.ReturnTypes)
- }
- for _, c := range result.Calls {
- t.Logf(" %s -> %s", c.EnclosingFuncQN, c.CalleeName)
- }
- for _, r := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", r.CallerQN, r.CalleeQN, r.Strategy, r.Confidence)
- }
- requireResolvedCall(t, result, "main", "Filter")
- // Implicit inference: Filter(users, pred) → T=User → returns []User
- // Range over []User → u:User → u.Name() resolves
- requireResolvedCall(t, result, "main", "Name")
-}
-
-// ============================================================================
-// Test: Step 0 data wires (return_types, param_names)
-// ============================================================================
-
-func TestGoLSP_ReturnTypesExtracted(t *testing.T) {
- source := `package main
-
-type Foo struct{}
-
-func GetFoo() *Foo { return nil }
-func Multi() (int, error) { return 0, nil }
-`
- result := extractGoWithRegistry(t, source)
-
- // Check that return_types is populated
- for _, d := range result.Definitions {
- if d.Name == "GetFoo" {
- if len(d.ReturnTypes) == 0 {
- t.Errorf("GetFoo should have return_types, got none. ReturnType=%q", d.ReturnType)
- } else {
- t.Logf("GetFoo return_types: %v", d.ReturnTypes)
- }
- }
- if d.Name == "Multi" {
- if len(d.ReturnTypes) < 2 {
- t.Errorf("Multi should have 2 return_types, got %d: %v", len(d.ReturnTypes), d.ReturnTypes)
- } else {
- t.Logf("Multi return_types: %v", d.ReturnTypes)
- }
- }
- }
-}
-
-func TestGoLSP_ParamNamesExtracted(t *testing.T) {
- source := `package main
-
-func Process(name string, count int, verbose bool) {}
-`
- result := extractGoWithRegistry(t, source)
-
- for _, d := range result.Definitions {
- if d.Name == "Process" {
- if len(d.ParamNames) < 3 {
- t.Errorf("Process should have 3 param_names, got %d: %v", len(d.ParamNames), d.ParamNames)
- } else {
- t.Logf("Process param_names: %v", d.ParamNames)
- expected := []string{"name", "count", "verbose"}
- for i, exp := range expected {
- if i < len(d.ParamNames) && d.ParamNames[i] != exp {
- t.Errorf("param_names[%d] = %q, want %q", i, d.ParamNames[i], exp)
- }
- }
- }
- }
- }
-}
-
-// ============================================================================
-// Test: Direct function calls (LSP direct resolution)
-// ============================================================================
-
-func TestGoLSP_DirectFuncCall(t *testing.T) {
- source := `package main
-
-func helper() int { return 42 }
-
-func caller() {
- helper()
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "caller", "helper")
-}
-
-// ============================================================================
-// Test: Stdlib integration (os.Open, http.NewRequest, etc.)
-// ============================================================================
-
-func TestGoLSP_StdlibOsOpen(t *testing.T) {
- source := `package main
-
-import "os"
-
-func readFile(path string) {
- f, _ := os.Open(path)
- f.Close()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- // Debug: show all resolved calls and definitions
- t.Logf("Definitions (%d):", len(result.Definitions))
- for _, d := range result.Definitions {
- t.Logf(" %s [%s] QN=%s ReturnType=%q ReturnTypes=%v",
- d.Name, d.Label, d.QualifiedName, d.ReturnType, d.ReturnTypes)
- }
- t.Logf("Calls (%d):", len(result.Calls))
- for _, c := range result.Calls {
- t.Logf(" %s -> %s", c.EnclosingFuncQN, c.CalleeName)
- }
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
- t.Logf("Imports (%d):", len(result.Imports))
- for _, imp := range result.Imports {
- t.Logf(" %s -> %s", imp.LocalName, imp.ModulePath)
- }
-
- // os.Open should resolve via LSP (stdlib registered)
- requireResolvedCall(t, result, "readFile", "os.Open")
- // f.Close() resolves: os.Open returns (*os.File, error), tuple decomposition binds f to *os.File
- requireResolvedCall(t, result, "readFile", "Close")
-}
-
-func TestGoLSP_StdlibFmtSprintf(t *testing.T) {
- source := `package main
-
-import "fmt"
-
-func format(name string) string {
- return fmt.Sprintf("hello %s", name)
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "format", "fmt.Sprintf")
-}
-
-// ============================================================================
-// Test: Cross-file resolution
-// ============================================================================
-
-func TestGoLSP_CrossFile_MethodDispatch(t *testing.T) {
- // File defines a function that uses a type from another package.
- // The cross-file defs tell the LSP about the remote type and its methods.
- source := `package main
-
-import "myapp/db"
-
-func doQuery() {
- conn := db.Connect("localhost")
- conn.Query("SELECT 1")
-}
-`
- moduleQN := "test.main"
-
- // File-local defs: just the function doQuery
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main.doQuery",
- ShortName: "doQuery",
- Label: "Function",
- DefModuleQN: moduleQN,
- },
- }
-
- // Cross-file defs: db.Connect (returns *Conn), db.Conn type, db.Conn.Query method
- crossDefs := []CrossFileDef{
- {
- QualifiedName: "myapp/db.Connect",
- ShortName: "Connect",
- Label: "Function",
- DefModuleQN: "myapp/db",
- ReturnTypes: "*Conn",
- },
- {
- QualifiedName: "myapp/db.Conn",
- ShortName: "Conn",
- Label: "Type",
- DefModuleQN: "myapp/db",
- },
- {
- QualifiedName: "myapp/db.Conn.Query",
- ShortName: "Query",
- Label: "Method",
- DefModuleQN: "myapp/db",
- ReceiverType: "myapp/db.Conn",
- },
- }
-
- imports := []Import{
- {LocalName: "db", ModulePath: "myapp/db"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // Should resolve db.Connect as a direct call
- found := false
- for _, rc := range resolved {
- if contains(rc.CallerQN, "doQuery") && contains(rc.CalleeQN, "Connect") {
- found = true
- break
- }
- }
- if !found {
- t.Errorf("expected cross-file resolution of db.Connect()")
- }
-
- // Should resolve conn.Query via type dispatch (conn's type is *db.Conn)
- found = false
- for _, rc := range resolved {
- if contains(rc.CallerQN, "doQuery") && contains(rc.CalleeQN, "Query") {
- found = true
- if rc.Strategy != "lsp_type_dispatch" {
- t.Errorf("expected lsp_type_dispatch for conn.Query, got %s", rc.Strategy)
- }
- break
- }
- }
- if !found {
- t.Errorf("expected cross-file resolution of conn.Query()")
- }
-}
-
-func TestGoLSP_CrossFile_ReturnTypeChain(t *testing.T) {
- // Tests that return type propagation works across files:
- // repo.GetUser() returns *User, then user.Name() resolves via *User.
- source := `package main
-
-import "myapp/repo"
-
-func showUser() {
- user := repo.GetUser(1)
- user.Name()
-}
-`
- moduleQN := "test.main"
-
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main.showUser",
- ShortName: "showUser",
- Label: "Function",
- DefModuleQN: moduleQN,
- },
- }
-
- crossDefs := []CrossFileDef{
- {
- QualifiedName: "myapp/repo.GetUser",
- ShortName: "GetUser",
- Label: "Function",
- DefModuleQN: "myapp/repo",
- ReturnTypes: "*User",
- },
- {
- QualifiedName: "myapp/repo.User",
- ShortName: "User",
- Label: "Type",
- DefModuleQN: "myapp/repo",
- },
- {
- QualifiedName: "myapp/repo.User.Name",
- ShortName: "Name",
- Label: "Method",
- DefModuleQN: "myapp/repo",
- ReceiverType: "myapp/repo.User",
- },
- }
-
- imports := []Import{
- {LocalName: "repo", ModulePath: "myapp/repo"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // Should resolve user.Name() via return type propagation
- found := false
- for _, rc := range resolved {
- if contains(rc.CallerQN, "showUser") && contains(rc.CalleeQN, "Name") {
- found = true
- break
- }
- }
- if !found {
- t.Errorf("expected cross-file resolution of user.Name() via return type propagation")
- }
-}
-
-func TestGoLSP_SelectReceive(t *testing.T) {
- source := `package main
-
-type Msg struct{}
-
-func (m *Msg) Process() {}
-
-func worker(ch chan *Msg, done chan bool) {
- select {
- case msg := <-ch:
- msg.Process()
- case <-done:
- return
- }
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "worker", "Process")
-}
-
-func TestGoLSP_StructFieldAccess(t *testing.T) {
- source := `package main
-
-type User struct {
- Name string
- Age int
- Profile *Profile
-}
-
-type Profile struct {
- Bio string
-}
-
-func (p *Profile) Summary() string { return "" }
-
-func showUser(u *User) {
- _ = u.Name
- p := u.Profile
- p.Summary()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // p := u.Profile should give p type *Profile, then p.Summary() should resolve
- requireResolvedCall(t, result, "showUser", "Summary")
-}
-
-func TestGoLSP_PointerValueReceivers(t *testing.T) {
- source := `package main
-
-type Conn struct{}
-
-func (c *Conn) Close() {}
-func (c Conn) Status() string { return "" }
-
-func usePointer(c *Conn) {
- c.Close()
- c.Status()
-}
-
-func useValue(c Conn) {
- c.Status()
- c.Close()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // Pointer receiver can call both pointer and value methods
- requireResolvedCall(t, result, "usePointer", "Close")
- requireResolvedCall(t, result, "usePointer", "Status")
- // Value receiver calls should also resolve (Go auto-takes address)
- requireResolvedCall(t, result, "useValue", "Status")
- requireResolvedCall(t, result, "useValue", "Close")
-}
-
-func TestGoLSP_Diagnostics(t *testing.T) {
- source := `package main
-
-import "unknownpkg"
-
-func doStuff() {
- unknownpkg.Foo()
- x := getUnknown()
- x.Bar()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f] reason=%q", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- // Check that we get diagnostics (confidence 0, non-empty reason)
- var diagnostics []ResolvedCall
- for _, rc := range result.ResolvedCalls {
- if rc.Confidence == 0 && rc.Reason != "" {
- diagnostics = append(diagnostics, rc)
- }
- }
- if len(diagnostics) == 0 {
- t.Errorf("expected at least one diagnostic (lsp_unresolved), got none")
- }
-
- // Verify diagnostics have meaningful reasons
- for _, d := range diagnostics {
- if d.Strategy != "lsp_unresolved" {
- t.Errorf("diagnostic should have strategy lsp_unresolved, got %q", d.Strategy)
- }
- t.Logf(" diagnostic: %s -> %s reason=%q", d.CallerQN, d.CalleeQN, d.Reason)
- }
-}
-
-func TestGoLSP_VariadicArgs(t *testing.T) {
- source := `package main
-
-type Logger struct{}
-
-func (l *Logger) Info(msg string) {}
-
-func logAll(loggers ...*Logger) {
- for _, l := range loggers {
- l.Info("hello")
- }
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // loggers is ...*Logger → [](*Logger), range gives l:*Logger, l.Info() resolves
- rc := requireResolvedCall(t, result, "logAll", "Info")
- if rc.Confidence == 0 {
- t.Fatalf("expected high-confidence resolution, got diagnostic: reason=%q", rc.Reason)
- }
-}
-
-func TestGoLSP_NamedReturns(t *testing.T) {
- source := `package main
-
-type Conn struct{}
-
-func (c *Conn) Close() {}
-
-func open() (conn *Conn, err error) {
- conn = &Conn{}
- conn.Close()
- return
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // conn is *Conn via named return, conn.Close() should resolve
- rc2 := requireResolvedCall(t, result, "open", "Close")
- if rc2.Confidence == 0 {
- t.Fatalf("expected high-confidence resolution, got diagnostic: reason=%q", rc2.Reason)
- }
-}
-
-func TestGoLSP_TypeAlias(t *testing.T) {
- source := `package main
-
-type Base struct{}
-
-func (b *Base) DoWork() {}
-
-type Alias = Base
-
-func useAlias(a *Alias) {
- a.DoWork()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f] reason=%q", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- rc := requireResolvedCall(t, result, "useAlias", "DoWork")
- if rc.Confidence == 0 {
- t.Fatalf("expected high-confidence resolution, got diagnostic: reason=%q", rc.Reason)
- }
-}
-
-func TestGoLSP_InterfaceSatisfaction(t *testing.T) {
- // Use unique method names that no stdlib type has, so satisfaction
- // checking finds exactly one implementer.
- source := `package main
-
-type DataProcessor interface {
- ProcessChunk(data []byte) (int, error)
- Finalize() error
-}
-
-type MyProcessor struct{}
-
-func (p *MyProcessor) ProcessChunk(data []byte) (int, error) { return 0, nil }
-func (p *MyProcessor) Finalize() error { return nil }
-
-func runProcessor(dp DataProcessor) {
- dp.ProcessChunk([]byte("hello"))
- dp.Finalize()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- // dp.ProcessChunk() on DataProcessor interface — MyProcessor is the only implementer
- rc := findResolvedCall(t, result, "runProcessor", "ProcessChunk")
- if rc == nil {
- t.Fatal("expected resolved call for runProcessor -> ProcessChunk")
- }
- if rc.Strategy != "lsp_interface_resolve" {
- t.Errorf("strategy: %s (expected lsp_interface_resolve)", rc.Strategy)
- }
- if rc.Confidence < 0.89 {
- t.Errorf("expected confidence >= 0.89, got %.2f", rc.Confidence)
- }
-
- // dp.Finalize() should also resolve
- rc2 := findResolvedCall(t, result, "runProcessor", "Finalize")
- if rc2 == nil {
- t.Fatal("expected resolved call for runProcessor -> Finalize")
- }
- if rc2.Strategy != "lsp_interface_resolve" {
- t.Errorf("strategy: %s (expected lsp_interface_resolve)", rc2.Strategy)
- }
-}
-
-// ============================================================================
-// Gap 1: Package-level var/const declarations
-// ============================================================================
-
-func TestGoLSP_PackageLevelVar(t *testing.T) {
- source := `package main
-
-type Database struct{}
-
-func (d *Database) Query(sql string) string { return "" }
-
-func NewDatabase() *Database { return &Database{} }
-
-var db = NewDatabase()
-
-func handler() {
- db.Query("SELECT 1")
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "handler", "Query")
-}
-
-func TestGoLSP_PackageLevelConst(t *testing.T) {
- source := `package main
-
-type Logger struct{}
-
-func (l *Logger) Info(msg string) {}
-
-func NewLogger() *Logger { return &Logger{} }
-
-var logger = NewLogger()
-
-func doWork() {
- logger.Info("starting")
-}
-`
- result := extractGoWithRegistry(t, source)
- requireResolvedCall(t, result, "doWork", "Info")
-}
-
-// ============================================================================
-// Gap 2: If-statement initializer
-// ============================================================================
-
-func TestGoLSP_IfInit(t *testing.T) {
- source := `package main
-
-type MyError struct{}
-
-func (e *MyError) Error() string { return "" }
-func (e *MyError) Code() int { return 0 }
-
-func getError() *MyError { return nil }
-
-func handle() {
- if err := getError(); err != nil {
- err.Code()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "handle", "Code")
-}
-
-// ============================================================================
-// Gap 3: Embedded struct field promotion
-// ============================================================================
-
-func TestGoLSP_EmbeddedFieldPromotion(t *testing.T) {
- source := `package main
-
-type Inner struct {
- Name string
-}
-
-type Outer struct {
- Inner
-}
-
-type Processor struct{}
-
-func (p *Processor) Process(name string) {}
-
-func doWork() {
- o := &Outer{}
- p := &Processor{}
- p.Process(o.Name)
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "doWork", "Process")
-}
-
-// ============================================================================
-// Gap 4: For-statement C-style init
-// ============================================================================
-
-func TestGoLSP_ForInit(t *testing.T) {
- source := `package main
-
-type Counter struct{}
-
-func (c *Counter) Value() int { return 0 }
-
-func NewCounter() *Counter { return &Counter{} }
-
-func loop() {
- for c := NewCounter(); c.Value() < 10; {
- c.Value()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "loop", "Value")
-}
-
-// ============================================================================
-// Gap 5: Type conversions
-// ============================================================================
-
-func TestGoLSP_TypeConversion(t *testing.T) {
- source := `package main
-
-type MyString string
-
-func (s MyString) Upper() string { return "" }
-
-func convert() {
- s := MyString("hello")
- s.Upper()
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "convert", "Upper")
-}
-
-// ============================================================================
-// Gap 6: Var declarations with multiple names
-// ============================================================================
-
-func TestGoLSP_MultiNameVar(t *testing.T) {
- source := `package main
-
-type Config struct{}
-
-func (c *Config) Get(key string) string { return "" }
-
-var cfg1, cfg2 *Config
-
-func readConfig() {
- cfg1.Get("port")
- cfg2.Get("host")
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- calls := findAllResolvedCalls(t, result, "readConfig", "Get")
- if len(calls) < 2 {
- t.Errorf("expected at least 2 Get calls resolved, got %d", len(calls))
- }
-}
-
-// ============================================================================
-// Gap 7: Switch-statement initializer
-// ============================================================================
-
-func TestGoLSP_SwitchInit(t *testing.T) {
- source := `package main
-
-type Validator struct{}
-
-func (v *Validator) Check() bool { return true }
-
-func NewValidator() *Validator { return &Validator{} }
-
-func validate() {
- switch v := NewValidator(); v.Check() {
- case true:
- v.Check()
- }
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- requireResolvedCall(t, result, "validate", "Check")
-}
-
-func TestGoLSP_InterfaceMethodDispatch_SingleFile(t *testing.T) {
- // Interface defined in same file, variable typed as interface, method called on it.
- source := `package main
-
-type Binder interface {
- Bind(target any) error
-}
-
-type DefaultBinder struct{}
-
-func (d *DefaultBinder) Bind(target any) error { return nil }
-
-func process(b Binder) {
- b.Bind("hello")
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f reason=%q]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- // Should resolve interface call — either lsp_interface_resolve (single impl)
- // or lsp_interface_dispatch (fallback)
- rc := findResolvedCall(t, result, "process", "Bind")
- if rc == nil {
- t.Fatal("expected resolved call for process -> Bind")
- }
- if rc.Strategy != "lsp_interface_resolve" && rc.Strategy != "lsp_interface_dispatch" {
- t.Errorf("expected lsp_interface_resolve or lsp_interface_dispatch, got %q", rc.Strategy)
- }
- t.Logf("Interface dispatch: %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
-}
-
-func TestGoLSP_InterfaceMethodDispatch_FieldChain(t *testing.T) {
- // Reproduces echo pattern: c.echo.Binder.Bind() where Binder is an interface field.
- source := `package main
-
-type Binder interface {
- Bind(target any) error
-}
-
-type DefaultBinder struct{}
-func (d *DefaultBinder) Bind(target any) error { return nil }
-
-type App struct {
- Binder Binder
-}
-
-type Context struct {
- app *App
-}
-
-func (c *Context) process() {
- c.app.Binder.Bind("hello")
-}
-`
- result := extractGoWithRegistry(t, source)
-
- t.Logf("ResolvedCalls (%d):", len(result.ResolvedCalls))
- for _, rc := range result.ResolvedCalls {
- t.Logf(" %s -> %s [%s %.2f reason=%q]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- rc := findResolvedCall(t, result, "process", "Bind")
- if rc == nil {
- t.Fatal("expected resolved call for process -> Bind (field chain interface dispatch)")
- }
- if rc.Strategy != "lsp_interface_resolve" && rc.Strategy != "lsp_interface_dispatch" {
- t.Errorf("expected lsp_interface_resolve or lsp_interface_dispatch, got %q", rc.Strategy)
- }
-}
-
-func TestGoLSP_InterfaceMethodDispatch_CrossFile(t *testing.T) {
- // Interface from another package, method called on interface-typed parameter.
- source := `package main
-
-import "myapp/svc"
-
-func handler(b svc.Binder) {
- b.Bind("data")
-}
-`
- moduleQN := "test.main"
-
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main.handler",
- ShortName: "handler",
- Label: "Function",
- DefModuleQN: moduleQN,
- },
- }
-
- crossDefs := []CrossFileDef{
- {
- QualifiedName: "myapp/svc.Binder",
- ShortName: "Binder",
- Label: "Interface",
- DefModuleQN: "myapp/svc",
- IsInterface: true,
- },
- {
- QualifiedName: "myapp/svc.DefaultBinder",
- ShortName: "DefaultBinder",
- Label: "Type",
- DefModuleQN: "myapp/svc",
- },
- {
- QualifiedName: "myapp/svc.DefaultBinder.Bind",
- ShortName: "Bind",
- Label: "Method",
- DefModuleQN: "myapp/svc",
- ReceiverType: "myapp/svc.DefaultBinder",
- },
- }
-
- imports := []Import{
- {LocalName: "svc", ModulePath: "myapp/svc"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f reason=%q]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- // Should get interface dispatch
- var found *ResolvedCall
- for i, rc := range resolved {
- if contains(rc.CallerQN, "handler") && contains(rc.CalleeQN, "Bind") && rc.Confidence > 0 {
- found = &resolved[i]
- break
- }
- }
- if found == nil {
- t.Fatal("expected resolved call for handler -> Bind")
- }
- if found.Strategy != "lsp_interface_resolve" && found.Strategy != "lsp_interface_dispatch" {
- t.Errorf("expected lsp_interface_resolve or lsp_interface_dispatch, got %q", found.Strategy)
- }
-}
-
-func TestGoLSP_InterfaceMethodDispatch_CrossFile_FieldChain(t *testing.T) {
- // Emulates echo pattern: c.echo.Binder.Bind() where types come from cross-file defs.
- // Context is local, App and Binder are from another package.
- source := `package main
-
-import "myapp/echo"
-
-type Context struct {
- echo *echo.Echo
-}
-
-func (c *Context) process() {
- c.echo.Binder.Bind("hello")
-}
-`
- moduleQN := "test.main"
-
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main.Context",
- ShortName: "Context",
- Label: "Type",
- DefModuleQN: moduleQN,
- },
- {
- QualifiedName: "test.main.Context.process",
- ShortName: "process",
- Label: "Method",
- DefModuleQN: moduleQN,
- ReceiverType: "test.main.Context",
- },
- }
-
- crossDefs := []CrossFileDef{
- // Echo struct with Binder field (interface type)
- {
- QualifiedName: "myapp/echo.Echo",
- ShortName: "Echo",
- Label: "Type",
- DefModuleQN: "myapp/echo",
- FieldDefs: "Binder:Binder", // key: struct field name:type
- },
- // Binder interface
- {
- QualifiedName: "myapp/echo.Binder",
- ShortName: "Binder",
- Label: "Interface",
- DefModuleQN: "myapp/echo",
- IsInterface: true,
- },
- // Concrete implementer
- {
- QualifiedName: "myapp/echo.DefaultBinder",
- ShortName: "DefaultBinder",
- Label: "Type",
- DefModuleQN: "myapp/echo",
- },
- {
- QualifiedName: "myapp/echo.DefaultBinder.Bind",
- ShortName: "Bind",
- Label: "Method",
- DefModuleQN: "myapp/echo",
- ReceiverType: "myapp/echo.DefaultBinder",
- },
- }
-
- imports := []Import{
- {LocalName: "echo", ModulePath: "myapp/echo"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f reason=%q]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- // Should resolve to interface dispatch (either lsp_interface_resolve or lsp_interface_dispatch)
- var found *ResolvedCall
- for i, rc := range resolved {
- if contains(rc.CallerQN, "process") && contains(rc.CalleeQN, "Bind") && rc.Confidence > 0 {
- found = &resolved[i]
- break
- }
- }
- if found == nil {
- t.Fatal("expected resolved call for process -> Bind via c.echo.Binder.Bind() field chain")
- }
- t.Logf("Resolved: %s -> %s [%s %.2f]", found.CallerQN, found.CalleeQN, found.Strategy, found.Confidence)
- // Accept any LSP strategy — the key is that it resolves at all
- if found.Confidence < 0.8 {
- t.Errorf("expected high confidence (>=0.8), got %.2f", found.Confidence)
- }
-}
-
-func TestGoLSP_ConcreteMethodDispatch_CrossFile_MapIndex(t *testing.T) {
- // Emulates echo vhost pattern: vh.ServeHTTP() where vh comes from map[string]*Echo
- source := `package main
-
-import "myapp/echo"
-
-func dispatch(vhosts map[string]*echo.Echo, host string) {
- if vh, ok := vhosts[host]; ok {
- vh.ServeHTTP(nil, nil)
- }
-}
-`
- moduleQN := "test.main"
-
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main.dispatch",
- ShortName: "dispatch",
- Label: "Function",
- DefModuleQN: moduleQN,
- },
- }
-
- crossDefs := []CrossFileDef{
- {
- QualifiedName: "myapp/echo.Echo",
- ShortName: "Echo",
- Label: "Type",
- DefModuleQN: "myapp/echo",
- },
- {
- QualifiedName: "myapp/echo.Echo.ServeHTTP",
- ShortName: "ServeHTTP",
- Label: "Method",
- DefModuleQN: "myapp/echo",
- ReceiverType: "myapp/echo.Echo",
- },
- }
-
- imports := []Import{
- {LocalName: "echo", ModulePath: "myapp/echo"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f reason=%q]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- // Should resolve vh.ServeHTTP to lsp_type_dispatch
- var found *ResolvedCall
- for i, rc := range resolved {
- if contains(rc.CallerQN, "dispatch") && contains(rc.CalleeQN, "ServeHTTP") && rc.Confidence > 0 {
- found = &resolved[i]
- break
- }
- }
- if found == nil {
- t.Fatal("expected resolved call for dispatch -> ServeHTTP via map index")
- }
- if found.Strategy != "lsp_type_dispatch" {
- t.Errorf("expected lsp_type_dispatch, got %q", found.Strategy)
- }
-}
-
-func TestGoLSP_StdlibInterfaceMethodDispatch_CrossFile(t *testing.T) {
- // Emulates common Go pattern: ctx.Done() where ctx is context.Context parameter.
- // context.Context is a stdlib interface — its methods should resolve via interface dispatch.
- source := `package main
-
-import "context"
-
-func process(ctx context.Context) {
- <-ctx.Done()
- ctx.Err()
-}
-`
- moduleQN := "test.main"
-
- fileDefs := []CrossFileDef{
- {
- QualifiedName: "test.main.process",
- ShortName: "process",
- Label: "Function",
- DefModuleQN: moduleQN,
- },
- }
-
- // No cross-file defs — stdlib is pre-registered
- var crossDefs []CrossFileDef
-
- imports := []Import{
- {LocalName: "context", ModulePath: "context"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f reason=%q]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence, rc.Reason)
- }
-
- // Should resolve ctx.Done() — either lsp_interface_dispatch or lsp_interface_resolve
- var foundDone, foundErr *ResolvedCall
- for i, rc := range resolved {
- if contains(rc.CallerQN, "process") && contains(rc.CalleeQN, "Done") && rc.Confidence > 0 {
- foundDone = &resolved[i]
- }
- if contains(rc.CallerQN, "process") && contains(rc.CalleeQN, "Err") && rc.Confidence > 0 {
- foundErr = &resolved[i]
- }
- }
- if foundDone == nil {
- t.Error("expected resolved call for process -> Done via ctx.Done()")
- } else {
- t.Logf("Done: %s -> %s [%s %.2f]", foundDone.CallerQN, foundDone.CalleeQN, foundDone.Strategy, foundDone.Confidence)
- }
- if foundErr == nil {
- t.Error("expected resolved call for process -> Err via ctx.Err()")
- } else {
- t.Logf("Err: %s -> %s [%s %.2f]", foundErr.CallerQN, foundErr.CalleeQN, foundErr.Strategy, foundErr.Confidence)
- }
-}
-
-func TestGoLSP_LocalInterface_SingleImplementer_Resolve(t *testing.T) {
- // When a project-local interface has exactly one implementer,
- // calls through the interface should resolve to the concrete method via lsp_interface_resolve.
- source := `package main
-
-import "myapp/svc"
-
-func process(s svc.Store) {
- s.Get("key")
- s.Put("key", "val")
-}
-`
- moduleQN := "test.main"
-
- fileDefs := []CrossFileDef{
- {QualifiedName: "test.main.process", ShortName: "process", Label: "Function", DefModuleQN: moduleQN},
- }
-
- // Register interface with method_names via IsInterface + MethodNames
- crossDefs := []CrossFileDef{
- {QualifiedName: "myapp/svc.Store", ShortName: "Store", Label: "Interface",
- DefModuleQN: "myapp/svc", IsInterface: true, MethodNames: "Get|Put"},
- // Single concrete implementer
- {QualifiedName: "myapp/svc.RedisStore", ShortName: "RedisStore", Label: "Class", DefModuleQN: "myapp/svc"},
- {QualifiedName: "myapp/svc.RedisStore.Get", ShortName: "Get", Label: "Method",
- DefModuleQN: "myapp/svc", ReceiverType: "myapp/svc.RedisStore"},
- {QualifiedName: "myapp/svc.RedisStore.Put", ShortName: "Put", Label: "Method",
- DefModuleQN: "myapp/svc", ReceiverType: "myapp/svc.RedisStore"},
- }
-
- imports := []Import{
- {LocalName: "svc", ModulePath: "myapp/svc"},
- }
-
- resolved := RunGoLSPCrossFile([]byte(source), moduleQN, fileDefs, crossDefs, imports, nil)
-
- t.Logf("Resolved calls (%d):", len(resolved))
- for _, rc := range resolved {
- t.Logf(" %s -> %s [%s %.2f]", rc.CallerQN, rc.CalleeQN, rc.Strategy, rc.Confidence)
- }
-
- var foundGet, foundPut *ResolvedCall
- for i, rc := range resolved {
- if contains(rc.CallerQN, "process") && contains(rc.CalleeQN, "Get") && rc.Confidence > 0 {
- foundGet = &resolved[i]
- }
- if contains(rc.CallerQN, "process") && contains(rc.CalleeQN, "Put") && rc.Confidence > 0 {
- foundPut = &resolved[i]
- }
- }
-
- // Single implementer of Store → should resolve to concrete method via lsp_interface_resolve
- if foundGet == nil {
- t.Fatal("expected resolved call for process -> Get")
- }
- t.Logf("Get: %s -> %s [%s %.2f]", foundGet.CallerQN, foundGet.CalleeQN, foundGet.Strategy, foundGet.Confidence)
- if foundGet.Strategy != "lsp_interface_resolve" {
- t.Errorf("Get: expected lsp_interface_resolve, got %q", foundGet.Strategy)
- }
- if foundGet.CalleeQN != "myapp/svc.RedisStore.Get" {
- t.Errorf("Get: expected callee myapp/svc.RedisStore.Get, got %q", foundGet.CalleeQN)
- }
-
- if foundPut == nil {
- t.Fatal("expected resolved call for process -> Put")
- }
- t.Logf("Put: %s -> %s [%s %.2f]", foundPut.CallerQN, foundPut.CalleeQN, foundPut.Strategy, foundPut.Confidence)
- if foundPut.Strategy != "lsp_interface_resolve" {
- t.Errorf("Put: expected lsp_interface_resolve, got %q", foundPut.Strategy)
- }
- if foundPut.CalleeQN != "myapp/svc.RedisStore.Put" {
- t.Errorf("Put: expected callee myapp/svc.RedisStore.Put, got %q", foundPut.CalleeQN)
- }
-}
diff --git a/internal/cbm/lz4.go b/internal/cbm/lz4.go
deleted file mode 100644
index 98dd3a526..000000000
--- a/internal/cbm/lz4.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package cbm
-
-// int cbm_lz4_compress_hc(const char *src, int srcLen, char *dst, int dstCap);
-// int cbm_lz4_decompress(const char *src, int srcLen, char *dst, int originalLen);
-// int cbm_lz4_bound(int inputSize);
-import "C"
-import "unsafe"
-
-// LZ4CompressHC compresses src using LZ4 HC (level 9).
-// Returns the compressed data. If the input is empty, returns nil.
-func LZ4CompressHC(src []byte) []byte {
- n := len(src)
- if n == 0 {
- return nil
- }
- bound := int(C.cbm_lz4_bound(C.int(n)))
- dst := make([]byte, bound)
- written := int(C.cbm_lz4_compress_hc(
- (*C.char)(unsafe.Pointer(&src[0])),
- C.int(n),
- (*C.char)(unsafe.Pointer(&dst[0])),
- C.int(bound),
- ))
- if written <= 0 {
- // Compression failed (shouldn't happen with valid input)
- return nil
- }
- return dst[:written]
-}
-
-// LZ4Decompress decompresses src into a buffer of originalLen bytes.
-// Returns the decompressed data. Panics if originalLen is wrong.
-func LZ4Decompress(src []byte, originalLen int) []byte {
- if len(src) == 0 || originalLen == 0 {
- return nil
- }
- dst := make([]byte, originalLen)
- result := int(C.cbm_lz4_decompress(
- (*C.char)(unsafe.Pointer(&src[0])),
- C.int(len(src)),
- (*C.char)(unsafe.Pointer(&dst[0])),
- C.int(originalLen),
- ))
- if result < 0 {
- return nil
- }
- return dst[:result]
-}
diff --git a/internal/cbm/lz4_test.go b/internal/cbm/lz4_test.go
deleted file mode 100644
index 519464679..000000000
--- a/internal/cbm/lz4_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package cbm
-
-import (
- "bytes"
- "crypto/rand"
- "testing"
-)
-
-func TestLZ4RoundTrip(t *testing.T) {
- inputs := []struct {
- name string
- data []byte
- }{
- {"empty", nil},
- {"small", []byte("hello world")},
- {"repeated", bytes.Repeat([]byte("ABCD"), 10000)},
- {"source_code", []byte(`package main
-import "fmt"
-func main() {
- for i := 0; i < 100; i++ {
- fmt.Println("Hello, World!", i)
- }
-}
-`)},
- }
-
- for _, tc := range inputs {
- t.Run(tc.name, func(t *testing.T) {
- compressed := LZ4CompressHC(tc.data)
- if len(tc.data) == 0 {
- if compressed != nil {
- t.Fatal("expected nil for empty input")
- }
- return
- }
- if len(compressed) == 0 {
- t.Fatal("compression returned empty")
- }
-
- decompressed := LZ4Decompress(compressed, len(tc.data))
- if !bytes.Equal(decompressed, tc.data) {
- t.Fatalf("roundtrip mismatch: got %d bytes, want %d", len(decompressed), len(tc.data))
- }
- })
- }
-}
-
-func TestLZ4CompressionRatio(t *testing.T) {
- // Source code should compress well (>2x)
- src := bytes.Repeat([]byte("func handleRequest(w http.ResponseWriter, r *http.Request) {\n"), 1000)
- compressed := LZ4CompressHC(src)
- ratio := float64(len(src)) / float64(len(compressed))
- t.Logf("ratio=%.1fx compressed=%d original=%d", ratio, len(compressed), len(src))
- if ratio < 2.0 {
- t.Fatalf("expected >2x compression on repetitive source, got %.1fx", ratio)
- }
-}
-
-func TestLZ4DecompressWrongLen(t *testing.T) {
- src := []byte("test data for decompression")
- compressed := LZ4CompressHC(src)
-
- // Wrong originalLen — should return nil (safe decompress detects mismatch)
- result := LZ4Decompress(compressed, len(src)+100)
- // LZ4_decompress_safe will decompress what it can; result length may differ
- // The key safety property: it won't crash or buffer overflow
- _ = result
-}
-
-func TestLZ4RandomData(t *testing.T) {
- // Random data is incompressible — LZ4 should still handle it
- data := make([]byte, 4096)
- if _, err := rand.Read(data); err != nil {
- t.Fatal(err)
- }
- compressed := LZ4CompressHC(data)
- if compressed == nil {
- t.Fatal("compression failed on random data")
- }
- decompressed := LZ4Decompress(compressed, len(data))
- if !bytes.Equal(decompressed, data) {
- t.Fatal("roundtrip mismatch on random data")
- }
-}
diff --git a/internal/cbm/regression_test.go b/internal/cbm/regression_test.go
deleted file mode 100644
index a190e04a2..000000000
--- a/internal/cbm/regression_test.go
+++ /dev/null
@@ -1,1282 +0,0 @@
-package cbm
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// =====================================================================
-// Group A: OOP Languages
-// =====================================================================
-
-// --- Java ---
-func TestJavaClass_Regression(t *testing.T) {
- src := []byte("public class Animal { private String name; public String getName() { return name; } }")
- r, err := ExtractFile(src, lang.Java, "t", "Animal.java")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Animal")
-}
-
-func TestJavaMethod_Regression(t *testing.T) {
- src := []byte("public class Svc { public void doWork() {} public int compute(int x) { return x; } }")
- r, err := ExtractFile(src, lang.Java, "t", "Svc.java")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Method"), "doWork")
- assertHasName(t, defsWithLabel(r, "Method"), "compute")
-}
-
-func TestJavaInterface_Regression(t *testing.T) {
- src := []byte("public interface Repository { void save(Object o); Object findById(long id); }")
- r, err := ExtractFile(src, lang.Java, "t", "Repo.java")
- if err != nil {
- t.Fatal(err)
- }
- defs := r.Definitions
- found := false
- for _, d := range defs {
- if d.Name == "Repository" {
- found = true
- }
- }
- if !found {
- t.Error("interface Repository not found")
- }
-}
-
-// --- PHP ---
-func TestPHPClass_Regression(t *testing.T) {
- src := []byte("<?php\nclass User { public string $name; public function getName(): string { return $this->name; } }")
- r, err := ExtractFile(src, lang.PHP, "t", "User.php")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "User")
- assertHasName(t, defsWithLabel(r, "Method"), "getName")
-}
-
-func TestPHPFunction_Regression(t *testing.T) {
- src := []byte("<?php\nfunction greet(string $name): string { return 'Hello ' . $name; }")
- r, err := ExtractFile(src, lang.PHP, "t", "helpers.php")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-// --- Ruby ---
-func TestRubyClass_Regression(t *testing.T) {
- src := []byte("class Animal\n def initialize(name)\n @name = name\n end\n def speak\n puts @name\n end\nend\n")
- r, err := ExtractFile(src, lang.Ruby, "t", "animal.rb")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Animal")
- assertHasName(t, defsWithLabel(r, "Method"), "speak")
-}
-
-func TestRubyModule_Regression(t *testing.T) {
- src := []byte("module Greetable\n def greet\n \"Hello\"\n end\nend\n")
- r, err := ExtractFile(src, lang.Ruby, "t", "greetable.rb")
- if err != nil {
- t.Fatal(err)
- }
- defs := r.Definitions
- found := false
- for _, d := range defs {
- if d.Name == "Greetable" {
- found = true
- }
- }
- if !found {
- t.Error("module Greetable not found")
- }
-}
-
-// --- C# ---
-func TestCSharpClass_Regression(t *testing.T) {
- src := []byte("namespace App { public class Service { public void Run() {} public int Compute(int x) => x * 2; } }")
- r, err := ExtractFile(src, lang.CSharp, "t", "Service.cs")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Service")
- assertHasName(t, defsWithLabel(r, "Method"), "Run")
-}
-
-func TestCSharpInterface_Regression(t *testing.T) {
- src := []byte("public interface IService { void Execute(); string GetStatus(); }")
- r, err := ExtractFile(src, lang.CSharp, "t", "IService.cs")
- if err != nil {
- t.Fatal(err)
- }
- defs := r.Definitions
- found := false
- for _, d := range defs {
- if d.Name == "IService" {
- found = true
- }
- }
- if !found {
- t.Error("interface IService not found")
- }
-}
-
-// --- Swift ---
-func TestSwiftClass_Regression(t *testing.T) {
- src := []byte("class Vehicle {\n var speed: Int = 0\n func accelerate() { speed += 10 }\n func stop() { speed = 0 }\n}\n")
- r, err := ExtractFile(src, lang.Swift, "t", "Vehicle.swift")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Vehicle")
- assertHasName(t, defsWithLabel(r, "Method"), "accelerate")
-}
-
-func TestSwiftStruct_Regression(t *testing.T) {
- src := []byte("struct Point {\n var x: Double\n var y: Double\n func distance() -> Double { return (x*x + y*y).squareRoot() }\n}\n")
- r, err := ExtractFile(src, lang.Swift, "t", "Point.swift")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Method"), "distance")
-}
-
-// --- Kotlin ---
-func TestKotlinFunction_Regression(t *testing.T) {
- src := []byte("fun greet(name: String): String = \"Hello $name\"\nfun main() { println(greet(\"World\")) }\n")
- r, err := ExtractFile(src, lang.Kotlin, "t", "main.kt")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestKotlinClass_Regression(t *testing.T) {
- src := []byte("class User(val name: String) {\n fun display(): String = \"User: $name\"\n}\n")
- r, err := ExtractFile(src, lang.Kotlin, "t", "User.kt")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "User")
-}
-
-// --- Scala ---
-func TestScalaFunction_Regression(t *testing.T) {
- src := []byte("object Main {\n def greet(name: String): String = s\"Hello $name\"\n def main(args: Array[String]): Unit = println(greet(\"World\"))\n}\n")
- r, err := ExtractFile(src, lang.Scala, "t", "Main.scala")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Method"), "greet")
-}
-
-func TestScalaClass_Regression(t *testing.T) {
- src := []byte("class Animal(val name: String) {\n def speak(): String = s\"I am $name\"\n}\n")
- r, err := ExtractFile(src, lang.Scala, "t", "Animal.scala")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Animal")
-}
-
-// --- Objective-C ---
-func TestObjCInterface_Regression(t *testing.T) {
- src := []byte("@interface Animal : NSObject\n- (NSString *)name;\n- (void)speak;\n@end\n")
- r, err := ExtractFile(src, lang.ObjectiveC, "t", "Animal.h")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from ObjC interface")
- }
-}
-
-func TestObjCImplementation_Regression(t *testing.T) {
- src := []byte("@implementation Animal\n- (NSString *)name { return @\"Animal\"; }\n- (void)speak { NSLog(@\"...\"); }\n@end\n")
- r, err := ExtractFile(src, lang.ObjectiveC, "t", "Animal.m")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from ObjC impl")
- }
-}
-
-// --- Dart ---
-func TestDartClass_Regression(t *testing.T) {
- src := []byte("class Animal {\n String name;\n Animal(this.name);\n String speak() => 'I am $name';\n}\n")
- r, err := ExtractFile(src, lang.Dart, "t", "animal.dart")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Animal")
- assertHasName(t, defsWithLabel(r, "Method"), "speak")
-}
-
-func TestDartTopLevelFunction_Regression(t *testing.T) {
- src := []byte("void main() {\n print('Hello');\n}\nString greet(String name) => 'Hello $name';\n")
- r, err := ExtractFile(src, lang.Dart, "t", "main.dart")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "main")
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-// --- Groovy ---
-func TestGroovyClass_Regression(t *testing.T) {
- src := []byte("class Greeter {\n String name\n String greet() { \"Hello, $name\" }\n static void main(args) { println new Greeter(name:'World').greet() }\n}\n")
- r, err := ExtractFile(src, lang.Groovy, "t", "Greeter.groovy")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Greeter")
- assertHasName(t, defsWithLabel(r, "Method"), "greet")
-}
-
-// =====================================================================
-// Group B: Systems Languages
-// =====================================================================
-
-// --- Rust ---
-func TestRustFunction_Regression(t *testing.T) {
- src := []byte("fn main() { println!(\"Hello\"); }\npub fn add(a: i32, b: i32) -> i32 { a + b }\n")
- r, err := ExtractFile(src, lang.Rust, "t", "main.rs")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "main")
- assertHasName(t, defsWithLabel(r, "Function"), "add")
-}
-
-func TestRustStruct_Regression(t *testing.T) {
- src := []byte("pub struct Point { pub x: f64, pub y: f64 }\nimpl Point { pub fn new(x: f64, y: f64) -> Self { Point { x, y } } }\n")
- r, err := ExtractFile(src, lang.Rust, "t", "point.rs")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Point")
- assertHasName(t, defsWithLabel(r, "Method"), "new")
-}
-
-func TestRustEnum_Regression(t *testing.T) {
- src := []byte("pub enum Direction { North, South, East, West }\n")
- r, err := ExtractFile(src, lang.Rust, "t", "dir.rs")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition for Rust enum")
- }
-}
-
-// --- Go ---
-func TestGoFunction_Regression(t *testing.T) {
- src := []byte("package main\nfunc Greet(name string) string { return \"Hello, \" + name }\nfunc main() { Greet(\"World\") }\n")
- r, err := ExtractFile(src, lang.Go, "t", "main.go")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "Greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestGoStruct_Regression(t *testing.T) {
- src := []byte("package main\ntype Server struct { Host string; Port int }\nfunc (s *Server) Start() error { return nil }\n")
- r, err := ExtractFile(src, lang.Go, "t", "server.go")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Server")
- assertHasName(t, defsWithLabel(r, "Method"), "Start")
-}
-
-func TestGoInterface_Regression(t *testing.T) {
- src := []byte("package main\ntype Handler interface { ServeHTTP() error; Close() }\n")
- r, err := ExtractFile(src, lang.Go, "t", "handler.go")
- if err != nil {
- t.Fatal(err)
- }
- defs := r.Definitions
- found := false
- for _, d := range defs {
- if d.Name == "Handler" {
- found = true
- }
- }
- if !found {
- t.Error("interface Handler not found")
- }
-}
-
-// --- Zig ---
-func TestZigFunction_Regression(t *testing.T) {
- src := []byte("pub fn add(a: i32, b: i32) i32 { return a + b; }\npub fn main() void { _ = add(1, 2); }\n")
- r, err := ExtractFile(src, lang.Zig, "t", "main.zig")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "add")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestZigStruct_Regression(t *testing.T) {
- src := []byte("const Point = struct { x: f32, y: f32, pub fn dist(self: Point) f32 { return self.x + self.y; } };\n")
- r, err := ExtractFile(src, lang.Zig, "t", "point.zig")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Zig struct")
- }
-}
-
-// --- C ---
-func TestCFunction_Regression(t *testing.T) {
- src := []byte("#include <stdio.h>\nint add(int a, int b) { return a + b; }\nint main() { printf(\"%d\\n\", add(1,2)); return 0; }\n")
- r, err := ExtractFile(src, lang.C, "t", "main.c")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "add")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestCStruct_Regression(t *testing.T) {
- src := []byte("struct Point { int x; int y; };\nvoid print_point(struct Point p) { /* ... */ }\n")
- r, err := ExtractFile(src, lang.C, "t", "point.c")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "print_point")
-}
-
-// --- C++ ---
-func TestCppFunction_Regression(t *testing.T) {
- src := []byte("#include <string>\nstd::string greet(const std::string& name) { return \"Hello \" + name; }\nint main() { return 0; }\n")
- r, err := ExtractFile(src, lang.CPP, "t", "main.cpp")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from C++ file")
- }
-}
-
-func TestCppClass_Regression(t *testing.T) {
- src := []byte("class Animal {\npublic:\n std::string name;\n Animal(std::string n) : name(n) {}\n void speak() { /* ... */ }\n};\n")
- r, err := ExtractFile(src, lang.CPP, "t", "Animal.cpp")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from C++ class")
- }
-}
-
-// --- COBOL ---
-func TestCOBOLParagraph_Regression(t *testing.T) {
- src := []byte("IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\nPROCEDURE DIVISION.\n DISPLAY-GREETING.\n DISPLAY 'HELLO WORLD'.\n STOP RUN.\n")
- r, err := ExtractFile(src, lang.COBOL, "t", "hello.cbl")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from COBOL")
- }
-}
-
-// --- Verilog ---
-func TestVerilogModule_Regression(t *testing.T) {
- src := []byte("module adder(input a, input b, output sum);\n assign sum = a + b;\nendmodule\n")
- r, err := ExtractFile(src, lang.Verilog, "t", "adder.v")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Verilog")
- }
-}
-
-// --- CUDA ---
-func TestCUDAKernel_Regression(t *testing.T) {
- src := []byte("__global__ void vectorAdd(float *a, float *b, float *c, int n) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i < n) c[i] = a[i] + b[i];\n}\nint main() { return 0; }\n")
- r, err := ExtractFile(src, lang.CUDA, "t", "vector.cu")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from CUDA file")
- }
-}
-
-// =====================================================================
-// Group C: Dynamic Languages
-// =====================================================================
-
-// --- Python ---
-func TestPythonFunction_Regression(t *testing.T) {
- src := []byte("def greet(name: str) -> str:\n return f'Hello {name}'\n\ndef main():\n print(greet('World'))\n")
- r, err := ExtractFile(src, lang.Python, "t", "hello.py")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestPythonClass_Regression(t *testing.T) {
- src := []byte("class Animal:\n def __init__(self, name: str):\n self.name = name\n def speak(self) -> str:\n return f'I am {self.name}'\n")
- r, err := ExtractFile(src, lang.Python, "t", "animal.py")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Animal")
- assertHasName(t, defsWithLabel(r, "Method"), "speak")
-}
-
-func TestPythonDecorator_Regression(t *testing.T) {
- src := []byte("class Router:\n @staticmethod\n def route(path: str):\n def decorator(func): return func\n return decorator\n")
- r, err := ExtractFile(src, lang.Python, "t", "router.py")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Router")
-}
-
-// --- JavaScript ---
-func TestJavaScriptFunction_Regression(t *testing.T) {
- src := []byte("function greet(name) { return 'Hello ' + name; }\nconst add = (a, b) => a + b;\nmodule.exports = { greet, add };\n")
- r, err := ExtractFile(src, lang.JavaScript, "t", "utils.js")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-func TestJavaScriptClass_Regression(t *testing.T) {
- src := []byte("class Animal {\n constructor(name) { this.name = name; }\n speak() { return `I am ${this.name}`; }\n}\nmodule.exports = Animal;\n")
- r, err := ExtractFile(src, lang.JavaScript, "t", "Animal.js")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Animal")
- assertHasName(t, defsWithLabel(r, "Method"), "speak")
-}
-
-// --- TypeScript ---
-func TestTypeScriptFunction_Regression(t *testing.T) {
- src := []byte("export function greet(name: string): string { return `Hello ${name}`; }\nexport const add = (a: number, b: number): number => a + b;\n")
- r, err := ExtractFile(src, lang.TypeScript, "t", "utils.ts")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-func TestTypeScriptInterface_Regression(t *testing.T) {
- src := []byte("export interface Repository<T> { findById(id: number): T; save(entity: T): void; delete(id: number): void; }\n")
- r, err := ExtractFile(src, lang.TypeScript, "t", "repo.ts")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from TypeScript interface")
- }
-}
-
-func TestTypeScriptClass_Regression(t *testing.T) {
- src := []byte("export class UserService {\n private users: Map<number, string> = new Map();\n add(id: number, name: string): void { this.users.set(id, name); }\n get(id: number): string | undefined { return this.users.get(id); }\n}\n")
- r, err := ExtractFile(src, lang.TypeScript, "t", "UserService.ts")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "UserService")
-}
-
-// --- TSX ---
-func TestTSXComponent_Regression(t *testing.T) {
- src := []byte("import React from 'react';\ninterface Props { name: string; }\nexport function Greeting({ name }: Props) {\n return <div>Hello {name}</div>;\n}\nexport default Greeting;\n")
- r, err := ExtractFile(src, lang.TSX, "t", "Greeting.tsx")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "Greeting")
-}
-
-// --- Lua ---
-func TestLuaFunction_Regression(t *testing.T) {
- src := []byte("local function greet(name)\n return 'Hello ' .. name\nend\nlocal function main()\n print(greet('World'))\nend\nmain()\n")
- r, err := ExtractFile(src, lang.Lua, "t", "main.lua")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestLuaTableMethod_Regression(t *testing.T) {
- src := []byte("local M = {}\nfunction M.create(name)\n return { name = name }\nend\nfunction M.greet(self)\n return 'Hi ' .. self.name\nend\nreturn M\n")
- r, err := ExtractFile(src, lang.Lua, "t", "module.lua")
- if err != nil {
- t.Fatal(err)
- }
- if len(defsWithLabel(r, "Function")) < 1 {
- t.Error("expected >=1 Function from Lua table method")
- }
-}
-
-// --- Bash ---
-func TestBashFunction_Regression(t *testing.T) {
- src := []byte("#!/usr/bin/env bash\ngreet() {\n echo \"Hello $1\"\n}\nbuild_project() {\n go build ./...\n}\ngreet World\n")
- r, err := ExtractFile(src, lang.Bash, "t", "build.sh")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "build_project")
-}
-
-// --- Nix ---
-func TestNixFunction_Regression(t *testing.T) {
- src := []byte("{ pkgs ? import <nixpkgs> {} }:\nlet\n greet = name: \"Hello ${name}\";\n build = src: pkgs.stdenv.mkDerivation { inherit src; };\nin\n{ inherit greet build; }\n")
- r, err := ExtractFile(src, lang.Nix, "t", "default.nix")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Nix file")
- }
-}
-
-// --- EmacsLisp (critical: must not be broken by CommonLisp fix) ---
-func TestEmacsLispDefun_Regression(t *testing.T) {
- src := []byte("(defun greet (name)\n (message \"Hello %s\" name))\n(defun main ()\n (greet \"World\"))\n")
- r, err := ExtractFile(src, lang.EmacsLisp, "t", "init.el")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-func TestEmacsLispDefvar_Regression(t *testing.T) {
- src := []byte("(defvar my-count 0 \"A counter.\")\n(defcustom my-name \"World\" \"The name.\"\n :type 'string)\n")
- r, err := ExtractFile(src, lang.EmacsLisp, "t", "vars.el")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from EmacsLisp vars")
- }
-}
-
-// --- R ---
-func TestRFunction_Regression(t *testing.T) {
- src := []byte("greet <- function(name) {\n paste(\"Hello\", name)\n}\nmain <- function() {\n print(greet(\"World\"))\n}\n")
- r, err := ExtractFile(src, lang.R, "t", "main.R")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-// --- Perl ---
-func TestPerlFunction_Regression(t *testing.T) {
- src := []byte("sub greet {\n my ($name) = @_;\n return \"Hello $name\";\n}\nsub main {\n print greet('World'), \"\\n\";\n}\nmain();\n")
- r, err := ExtractFile(src, lang.Perl, "t", "main.pl")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-// =====================================================================
-// Group D: Functional Languages
-// =====================================================================
-
-// --- Haskell ---
-func TestHaskellFunction_Regression(t *testing.T) {
- src := []byte("module Main where\ngreet :: String -> String\ngreet name = \"Hello \" ++ name\nmain :: IO ()\nmain = putStrLn (greet \"World\")\n")
- r, err := ExtractFile(src, lang.Haskell, "t", "Main.hs")
- if err != nil {
- t.Fatal(err)
- }
- // greet (with args) uses prod_id 151 with inherited field_name — always extracted
- // main = ... (no args) uses prod_id 77 with no field_name — not extracted (known limitation)
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-func TestHaskellDataType_Regression(t *testing.T) {
- src := []byte("data Shape = Circle Double | Rectangle Double Double\narea :: Shape -> Double\narea (Circle r) = pi * r * r\narea (Rectangle w h) = w * h\n")
- r, err := ExtractFile(src, lang.Haskell, "t", "Shape.hs")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Haskell data type")
- }
-}
-
-// --- Erlang ---
-func TestErlangFunction_Regression(t *testing.T) {
- src := []byte("-module(hello).\n-export([greet/1, main/0]).\ngreet(Name) -> io:format(\"Hello ~s~n\", [Name]).\nmain() -> greet(\"World\").\n")
- r, err := ExtractFile(src, lang.Erlang, "t", "hello.erl")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-// --- Elm ---
-func TestElmFunction_Regression(t *testing.T) {
- src := []byte("module Main exposing (..)\nimport Html exposing (text)\ngreet : String -> String\ngreet name = \"Hello \" ++ name\nmain = text (greet \"World\")\n")
- r, err := ExtractFile(src, lang.Elm, "t", "Main.elm")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
- assertHasName(t, defsWithLabel(r, "Function"), "main")
-}
-
-// --- Elixir ---
-func TestElixirFunction_Regression(t *testing.T) {
- src := []byte("defmodule Greeter do\n def greet(name) do\n \"Hello #{name}\"\n end\n def main do\n IO.puts(greet(\"World\"))\n end\nend\n")
- r, err := ExtractFile(src, lang.Elixir, "t", "greeter.ex")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "Greeter")
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-// --- F# ---
-func TestFSharpFunction_Regression(t *testing.T) {
- src := []byte("module Greeter\nlet greet name = sprintf \"Hello %s\" name\nlet main argv =\n printfn \"%s\" (greet \"World\")\n 0\n")
- r, err := ExtractFile(src, lang.FSharp, "t", "Greeter.fs")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from F# module")
- }
-}
-
-// --- Clojure ---
-func TestClojureFunction_Regression(t *testing.T) {
- // Clojure uses list_lit for all forms including defn — no dedicated defn node type.
- // FunctionNodeTypes is empty, so no function definitions are extracted (known limitation).
- // The test just verifies extraction completes without error.
- src := []byte("(ns greeter.core)\n(defn greet [name]\n (str \"Hello \" name))\n(defn -main [& args]\n (println (greet \"World\")))\n")
- _, err := ExtractFile(src, lang.Clojure, "t", "core.clj")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-// --- OCaml ---
-func TestOCamlFunction_Regression(t *testing.T) {
- src := []byte("let greet name = Printf.sprintf \"Hello %s\" name\nlet () = print_endline (greet \"World\")\n")
- r, err := ExtractFile(src, lang.OCaml, "t", "main.ml")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Function"), "greet")
-}
-
-// =====================================================================
-// Group E: Config / Markup Languages
-// =====================================================================
-
-// --- YAML ---
-func TestYAMLMapping_Regression(t *testing.T) {
- src := []byte("server:\n host: localhost\n port: 8080\ndatabase:\n url: postgres://localhost/mydb\n")
- r, err := ExtractFile(src, lang.YAML, "t", "config.yaml")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(r, "Variable")
- if len(vars) < 1 {
- t.Errorf("expected >=1 Variable from YAML, got 0")
- }
-}
-
-// --- Dockerfile ---
-func TestDockerfileInstruction_Regression(t *testing.T) {
- src := []byte("FROM golang:1.21 AS builder\nWORKDIR /app\nCOPY . .\nRUN go build -o server ./cmd/server\nFROM alpine:3.18\nCOPY --from=builder /app/server /usr/local/bin/server\nEXPOSE 8080\nCMD [\"server\"]\n")
- r, err := ExtractFile(src, lang.Dockerfile, "t", "Dockerfile")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Dockerfile")
- }
-}
-
-// --- HTML ---
-func TestHTMLElements_Regression(t *testing.T) {
- src := []byte("<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello</h1><p>World</p></body></html>")
- r, err := ExtractFile(src, lang.HTML, "t", "index.html")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from HTML")
- }
-}
-
-// --- SQL ---
-func TestSQLTable_Regression(t *testing.T) {
- src := []byte("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE);\nCREATE INDEX idx_users_email ON users(email);\n")
- r, err := ExtractFile(src, lang.SQL, "t", "schema.sql")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from SQL")
- }
-}
-
-func TestSQLFunction_Regression(t *testing.T) {
- src := []byte("CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$ SELECT COUNT(*) FROM users; $$ LANGUAGE SQL;\n")
- r, err := ExtractFile(src, lang.SQL, "t", "funcs.sql")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from SQL function")
- }
-}
-
-// --- Meson ---
-func TestMesonProject_Regression(t *testing.T) {
- src := []byte("project('myapp', 'c', version: '1.0.0')\nexecutable('myapp', 'main.c', install: true)\n")
- r, err := ExtractFile(src, lang.Meson, "t", "meson.build")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from meson.build")
- }
-}
-
-// --- CSS ---
-func TestCSSRules_Regression(t *testing.T) {
- src := []byte(".container { display: flex; width: 100%; }\n.button { background: #007bff; color: white; border: none; }\n@media (max-width: 768px) { .container { flex-direction: column; } }\n")
- r, err := ExtractFile(src, lang.CSS, "t", "styles.css")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from CSS")
- }
-}
-
-// --- HCL (Terraform) ---
-func TestHCLResource_Regression(t *testing.T) {
- src := []byte("resource \"aws_instance\" \"web\" {\n ami = \"ami-12345678\"\n instance_type = \"t3.micro\"\n tags = { Name = \"web-server\" }\n}\n")
- r, err := ExtractFile(src, lang.HCL, "t", "main.tf")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from HCL/Terraform")
- }
-}
-
-// --- SCSS ---
-func TestSCSSRules_Regression(t *testing.T) {
- src := []byte("$primary: #007bff;\n.container {\n width: 100%;\n .button {\n background: $primary;\n &:hover { opacity: 0.8; }\n }\n}\n")
- r, err := ExtractFile(src, lang.SCSS, "t", "styles.scss")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from SCSS")
- }
-}
-
-// --- TOML (critical: must not be broken by config lang changes) ---
-func TestTOMLBasic_Regression(t *testing.T) {
- src := []byte("[server]\nhost = \"localhost\"\nport = 8080\n\n[database]\nurl = \"postgres://localhost/db\"\nmax_connections = 10\n")
- r, err := ExtractFile(src, lang.TOML, "t", "config.toml")
- if err != nil {
- t.Fatal(err)
- }
- assertHasName(t, defsWithLabel(r, "Class"), "server")
- assertHasName(t, defsWithLabel(r, "Class"), "database")
- assertHasName(t, defsWithLabel(r, "Variable"), "host")
- assertHasName(t, defsWithLabel(r, "Variable"), "port")
-}
-
-// --- CMake ---
-func TestCMakeFunction_Regression(t *testing.T) {
- src := []byte("cmake_minimum_required(VERSION 3.16)\nproject(MyApp VERSION 1.0)\nadd_executable(myapp main.cpp)\ntarget_compile_features(myapp PRIVATE cxx_std_17)\n")
- r, err := ExtractFile(src, lang.CMake, "t", "CMakeLists.txt")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from CMakeLists.txt")
- }
-}
-
-// --- JSON ---
-func TestJSONObject_Regression(t *testing.T) {
- src := []byte("{\"name\": \"myapp\", \"version\": \"1.0.0\", \"scripts\": {\"build\": \"go build\", \"test\": \"go test ./...\"}}")
- r, err := ExtractFile(src, lang.JSON, "t", "config.json")
- if err != nil {
- t.Fatal(err)
- }
- vars := defsWithLabel(r, "Variable")
- assertHasName(t, vars, "name")
- assertHasName(t, vars, "version")
-}
-
-// --- Protobuf ---
-func TestProtobufMessage_Regression(t *testing.T) {
- src := []byte("syntax = \"proto3\";\npackage user;\nmessage User { int64 id = 1; string name = 2; string email = 3; }\nservice UserService { rpc GetUser(User) returns (User); }\n")
- r, err := ExtractFile(src, lang.Protobuf, "t", "user.proto")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Protobuf")
- }
-}
-
-// --- GraphQL ---
-func TestGraphQLType_Regression(t *testing.T) {
- src := []byte("type User {\n id: ID!\n name: String!\n email: String!\n}\ntype Query {\n user(id: ID!): User\n users: [User!]!\n}\n")
- r, err := ExtractFile(src, lang.GraphQL, "t", "schema.graphql")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from GraphQL schema")
- }
-}
-
-// --- Svelte ---
-func TestSvelteComponent_Regression(t *testing.T) {
- src := []byte("<script>\n let name = 'World';\n function greet() {\n return `Hello ${name}`;\n }\n</script>\n<h1>{greet()}</h1>\n")
- r, err := ExtractFile(src, lang.Svelte, "t", "App.svelte")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Svelte component")
- }
-}
-
-// --- Vue ---
-func TestVueComponent_Regression(t *testing.T) {
- src := []byte("<template><div>{{ message }}</div></template>\n<script>\nexport default {\n name: 'App',\n data() { return { message: 'Hello World' }; },\n methods: { greet() { return this.message; } }\n};\n</script>\n")
- r, err := ExtractFile(src, lang.Vue, "t", "App.vue")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from Vue component")
- }
-}
-
-// --- GLSL ---
-func TestGLSLShader_Regression(t *testing.T) {
- src := []byte("#version 330 core\nvoid main() {\n gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n}\nvec3 transform(vec3 pos, mat4 mvp) {\n return (mvp * vec4(pos, 1.0)).xyz;\n}\n")
- r, err := ExtractFile(src, lang.GLSL, "t", "vertex.glsl")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Definitions) < 1 {
- t.Error("expected >=1 definition from GLSL shader")
- }
-}
-
-// --- Julia ---
-func TestJuliaFunction_Regression(t *testing.T) {
- src := []byte("function hello()\n println(\"Hello, World!\")\nend\n")
- r, err := ExtractFile(src, lang.Julia, "t", "hello.jl")
- if err != nil {
- t.Fatal(err)
- }
- // If Julia extraction works, verify the function name
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "hello")
- }
- // If len(fns) == 0, Julia extraction is broken — tracked by TestJuliaFunctionExtraction
-}
-
-// --- VimScript ---
-func TestVimScriptFunction_Regression(t *testing.T) {
- src := []byte("function! SayHello()\n echo 'Hello'\nendfunction\n")
- r, err := ExtractFile(src, lang.VimScript, "t", "plugin.vim")
- if err != nil {
- t.Fatal(err)
- }
- // If VimScript extraction works, verify the function name
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "SayHello")
- }
- // If len(fns) == 0, VimScript extraction is broken — tracked by TestVimScriptFunctionExtraction
-}
-
-// =====================================================================
-// Group H: Scientific/Math Languages
-// =====================================================================
-
-// --- MATLAB ---
-func TestMATLABFunction_Regression(t *testing.T) {
- src := []byte("function result = factorial(n)\n if n <= 1\n result = 1;\n else\n result = n * factorial(n - 1);\n end\nend\n")
- r, err := ExtractFile(src, lang.MATLAB, "t", "factorial.matlab")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "factorial")
- }
-}
-
-func TestMATLABParse_Regression(t *testing.T) {
- src := []byte("x = 1;\ny = x + 2;\n")
- _, err := ExtractFile(src, lang.MATLAB, "t", "simple.matlab")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-// --- Lean 4 ---
-func TestLeanDef_Regression(t *testing.T) {
- src := []byte("def hello : String := \"Hello\"\n")
- r, err := ExtractFile(src, lang.Lean, "t", "Hello.lean")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "hello")
- }
-}
-
-func TestLeanParse_Regression(t *testing.T) {
- src := []byte("theorem add_comm (a b : Nat) : a + b = b + a := by omega\n")
- _, err := ExtractFile(src, lang.Lean, "t", "Comm.lean")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-// --- FORM ---
-func TestFORMProcedure_Regression(t *testing.T) {
- src := []byte("#procedure myproc(x)\n id `x' = 0;\n#endprocedure\n")
- r, err := ExtractFile(src, lang.FORM, "t", "calc.frm")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "myproc")
- }
-}
-
-func TestFORMParse_Regression(t *testing.T) {
- src := []byte("Symbols x, y;\nLocal F = x + y;\nPrint;\n.end\n")
- _, err := ExtractFile(src, lang.FORM, "t", "example.frm")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestFORMCall_Regression(t *testing.T) {
- src := []byte("#procedure myproc(x)\n id `x' = 0;\n#endprocedure\n#procedure caller()\n #call myproc(1)\n#endprocedure\n")
- r, err := ExtractFile(src, lang.FORM, "t", "calc.frm")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Calls) == 0 {
- t.Fatal("expected at least one call extracted from #call myproc(1), got none")
- }
- found := false
- for _, c := range r.Calls {
- if c.CalleeName == "myproc" {
- found = true
- break
- }
- }
- if !found {
- t.Fatalf("expected callee 'myproc' in calls, got: %+v", r.Calls)
- }
-}
-
-// --- Magma ---
-func TestMagmaFunction_Regression(t *testing.T) {
- src := []byte("function Factorial(n)\n if n le 1 then\n return 1;\n end if;\n return n * Factorial(n - 1);\nend function;\n")
- r, err := ExtractFile(src, lang.Magma, "t", "fact.mag")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "Factorial")
- }
-}
-
-func TestMagmaProcedure_Regression(t *testing.T) {
- src := []byte("procedure PrintHello()\n print \"Hello\";\nend procedure;\n")
- r, err := ExtractFile(src, lang.Magma, "t", "hello.mag")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) > 0 {
- assertHasName(t, fns, "PrintHello")
- }
-}
-
-func TestMagmaParse_Regression(t *testing.T) {
- src := []byte("x := 42;\ny := x + 1;\n")
- _, err := ExtractFile(src, lang.Magma, "t", "simple.mag")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestMagmaImport_Regression(t *testing.T) {
- src := []byte("load \"utils.mag\";\nload \"lib/helpers.mag\";\n")
- r, err := ExtractFile(src, lang.Magma, "t", "main.mag")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Imports) < 2 {
- t.Fatalf("expected at least 2 imports, got %d", len(r.Imports))
- }
-}
-
-func TestMagmaCall_Regression(t *testing.T) {
- src := []byte("function Foo(x)\n y := Bar(x);\n return y;\nend function;\n")
- r, err := ExtractFile(src, lang.Magma, "t", "calls.mag")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Calls) == 0 {
- t.Fatal("expected calls to be extracted, got 0")
- }
- found := false
- for _, c := range r.Calls {
- if c.CalleeName == "Bar" {
- found = true
- }
- }
- if !found {
- t.Errorf("expected call to 'Bar', got calls: %v", r.Calls)
- }
-}
-
-// --- MATLAB Calls ---
-func TestMATLABCall_Regression(t *testing.T) {
- src := []byte("function y = foo(x)\n y = inv(x);\n disp hello\nend\n")
- r, err := ExtractFile(src, lang.MATLAB, "t", "foo.matlab")
- if err != nil {
- t.Fatal(err)
- }
- // Should extract function_call "inv" and command "disp"
- if len(r.Calls) == 0 {
- t.Fatal("expected calls to be extracted, got 0")
- }
- foundInv := false
- foundDisp := false
- for _, c := range r.Calls {
- if c.CalleeName == "inv" {
- foundInv = true
- }
- if c.CalleeName == "disp" {
- foundDisp = true
- }
- }
- if !foundInv {
- t.Errorf("expected call to 'inv', got calls: %v", r.Calls)
- }
- if !foundDisp {
- t.Errorf("expected call to 'disp', got calls: %v", r.Calls)
- }
-}
-
-// --- Lean Calls ---
-func TestLeanCall_Regression(t *testing.T) {
- src := []byte("def fib : Nat → Nat\n | 0 => 1\n | 1 => 1\n | n + 2 => fib (n + 1) + fib n\n")
- r, err := ExtractFile(src, lang.Lean, "t", "Fib.lean")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Calls) == 0 {
- t.Fatal("expected calls to be extracted, got 0")
- }
- found := false
- for _, c := range r.Calls {
- if c.CalleeName == "fib" {
- found = true
- }
- }
- if !found {
- t.Errorf("expected call to 'fib', got calls: %v", r.Calls)
- }
-}
-
-func TestLeanTypeAnnotationNotCall_Regression(t *testing.T) {
- // "List Nat" in a binder type should not produce a "List" call.
- // "IO.println" in the body should be extracted.
- src := []byte("def listLen (xs : List Nat) : Nat := 0\ndef greet : IO Unit := IO.println \"hi\"\n")
- r, err := ExtractFile(src, lang.Lean, "t", "Types.lean")
- if err != nil {
- t.Fatal(err)
- }
- // "List" in explicit_binder type should be filtered
- for _, c := range r.Calls {
- if c.CalleeName == "List" {
- t.Errorf("type-position apply %q (binder type) should not be extracted as a call", c.CalleeName)
- }
- }
- // IO.println in the body should be present
- foundPrintln := false
- for _, c := range r.Calls {
- if c.CalleeName == "IO.println" || c.CalleeName == "println" {
- foundPrintln = true
- }
- }
- if !foundPrintln {
- t.Errorf("expected call to IO.println/println, got calls: %v", r.Calls)
- }
-}
-
-// --- Wolfram ---
-func TestWolframFunction_Regression(t *testing.T) {
- src := []byte("f[x_] := x^2\ng[x_] = x + 1\n")
- r, err := ExtractFile(src, lang.Wolfram, "t", "funcs.wl")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) < 2 {
- t.Fatalf("expected at least 2 functions, got %d: %v", len(fns), fns)
- }
- assertHasName(t, fns, "f")
- assertHasName(t, fns, "g")
-}
-
-func TestWolframCall_Regression(t *testing.T) {
- src := []byte("f[x_] := g[x] + h[x]\n")
- r, err := ExtractFile(src, lang.Wolfram, "t", "calls.wl")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Calls) == 0 {
- t.Fatal("expected calls to be extracted, got 0")
- }
- foundG := false
- foundH := false
- for _, c := range r.Calls {
- if c.CalleeName == "g" {
- foundG = true
- }
- if c.CalleeName == "h" {
- foundH = true
- }
- }
- if !foundG {
- t.Errorf("expected call to 'g', got calls: %v", r.Calls)
- }
- if !foundH {
- t.Errorf("expected call to 'h', got calls: %v", r.Calls)
- }
- // "f" should NOT appear as a call (it's the definition LHS)
- for _, c := range r.Calls {
- if c.CalleeName == "f" {
- t.Errorf("'f' should not be a call (it's a definition LHS), but found in calls")
- }
- }
-}
-
-func TestWolframCallerAttribution_Regression(t *testing.T) {
- // Calls inside a function body should have the enclosing function as caller,
- // not the file path (module QN). This verifies func_kinds_wolfram is wired
- // into func_kinds_for_lang so cbm_find_enclosing_func returns the def node.
- src := []byte("f[x_] := g[x] + h[x]\n")
- r, err := ExtractFile(src, lang.Wolfram, "t", "caller.wl")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Calls) == 0 {
- t.Fatal("expected calls, got 0")
- }
- for _, c := range r.Calls {
- if c.CalleeName == "g" || c.CalleeName == "h" {
- // enclosing_func_qn must NOT be the module path (file path)
- if c.EnclosingFuncQN == "" || c.EnclosingFuncQN == "t.caller" {
- t.Errorf("call to %q: enclosing_func_qn is file path %q, want function QN", c.CalleeName, c.EnclosingFuncQN)
- }
- }
- }
-}
-
-func TestWolframParse_Regression(t *testing.T) {
- src := []byte("x = 42;\ny = x + 1;\n")
- _, err := ExtractFile(src, lang.Wolfram, "t", "simple.wl")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestWolframImport_Regression(t *testing.T) {
- src := []byte("<< \"utils.wl\"\nNeeds[\"Package`\"]\n")
- r, err := ExtractFile(src, lang.Wolfram, "t", "main.wl")
- if err != nil {
- t.Fatal(err)
- }
- if len(r.Imports) == 0 {
- t.Fatalf("expected imports, got 0")
- }
-}
-
-func TestWolframNestedDef_Regression(t *testing.T) {
- // set_delayed (non-top) inside Module should also be extracted
- src := []byte("main[x_] := Module[{localF}, localF[t_] := t + 1; localF[x]]\n")
- r, err := ExtractFile(src, lang.Wolfram, "t", "nested.wl")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- assertHasName(t, fns, "main")
- assertHasName(t, fns, "localF")
-}
-
-func TestMagmaDisambiguation_Regression(t *testing.T) {
- // Magma code with 'end function;' should be extractable as Magma
- src := []byte(`function Factorial(n)
- if n le 1 then
- return 1;
- end if;
- return n * Factorial(n - 1);
-end function;
-`)
- r, err := ExtractFile(src, lang.Magma, "t", "test.m")
- if err != nil {
- t.Fatal(err)
- }
- fns := defsWithLabel(r, "Function")
- if len(fns) == 0 {
- t.Fatal("expected at least 1 function from Magma code")
- }
- assertHasName(t, fns, "Factorial")
-}
diff --git a/internal/cbm/scale_debug_test.go b/internal/cbm/scale_debug_test.go
deleted file mode 100644
index 305689400..000000000
--- a/internal/cbm/scale_debug_test.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package cbm
-
-import (
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "testing"
- _ "github.com/mattn/go-sqlite3"
-)
-
-func TestWriteDB_MultiPage(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "test.db")
- N := 192
- nodes := make([]DumpNode, N)
- for i := range nodes {
- nodes[i] = DumpNode{
- ID: int64(i + 1), Project: "p", Label: "Function",
- Name: fmt.Sprintf("f%04d", i), QualifiedName: fmt.Sprintf("p.f%04d", i),
- FilePath: fmt.Sprintf("pkg%d/file.go", i%10), StartLine: i, EndLine: i + 1, Properties: "{}",
- }
- }
- // Also save to /tmp for sqlite3 inspection
- fixedPath := "/tmp/cbm_debug.db"
- _ = WriteDB(fixedPath, "p", "/r", "2026-01-01T00:00:00Z", nodes, nil)
- t.Logf("saved copy to %s", fixedPath)
- if err := WriteDB(path, "p", "/r", "2026-01-01T00:00:00Z", nodes, nil); err != nil {
- t.Fatalf("WriteDB: %v", err)
- }
- db, _ := sql.Open("sqlite3", path)
- defer db.Close()
-
- // Dump all rowids
- rows, _ := db.Query("SELECT rowid FROM nodes ORDER BY rowid")
- var rowids []int64
- for rows.Next() {
- var r int64; rows.Scan(&r); rowids = append(rowids, r)
- }
- rows.Close()
- t.Logf("rowids count: %d", len(rowids))
-
- // Find gaps or duplicates
- seen := map[int64]int{}
- for _, r := range rowids {
- seen[r]++
- }
- for r, c := range seen {
- if c > 1 {
- t.Logf("duplicate rowid %d (count %d)", r, c)
- }
- }
- // Find unexpected rowids
- for _, r := range rowids {
- if r < 1 || r > int64(N) {
- t.Logf("unexpected rowid: %d", r)
- }
- }
-
- // Compare with COUNT(*)
- var countStar int
- db.QueryRow("SELECT COUNT(*) FROM nodes").Scan(&countStar)
- t.Logf("COUNT(*) = %d, len(rowids) = %d", countStar, len(rowids))
-
- // Try reading the last few rows by rowid
- for _, rid := range []int64{190, 191, 192, 193, 194} {
- var id int64; var name string
- err := db.QueryRow("SELECT id, name FROM nodes WHERE rowid = ?", rid).Scan(&id, &name)
- if err != nil {
- t.Logf("rowid %d: %v", rid, err)
- } else {
- t.Logf("rowid %d: id=%d name=%q", rid, id, name)
- }
- }
-
- // Read raw page bytes and check nodes root page from sqlite_master
- var nodesRoot int
- db.QueryRow("SELECT rootpage FROM sqlite_master WHERE name='nodes'").Scan(&nodesRoot)
- t.Logf("nodes root page: %d", nodesRoot)
-
- // Integrity check
- var integrity string
- db.QueryRow("PRAGMA integrity_check").Scan(&integrity)
- t.Logf("integrity_check: %s", integrity)
-
- // Check which plan COUNT(*) uses
- planRows, _ := db.Query("EXPLAIN QUERY PLAN SELECT COUNT(*) FROM nodes")
- for planRows.Next() {
- var id, parent, notused int
- var detail string
- planRows.Scan(&id, &parent, &notused, &detail)
- t.Logf("PLAN: %s", detail)
- }
- planRows.Close()
-
- // Count entries per index
- var cnt int
- for _, idx := range []string{"idx_nodes_label", "idx_nodes_name", "idx_nodes_file"} {
- db.QueryRow("SELECT COUNT(*) FROM nodes INDEXED BY " + idx).Scan(&cnt)
- t.Logf("%s count: %d", idx, cnt)
- }
-
- // Dump sqlite_master
- masterRows, _ := db.Query("SELECT rowid, type, name, rootpage, length(sql) FROM sqlite_master ORDER BY rowid")
- for masterRows.Next() {
- var rid, rootpage int
- var typ, name string
- var sqlLen sql.NullInt64
- masterRows.Scan(&rid, &typ, &name, &rootpage, &sqlLen)
- t.Logf("master[%d]: type=%s name=%s rootpage=%d sql_len=%v", rid, typ, name, rootpage, sqlLen)
- }
- masterRows.Close()
-
- // Also try NOT INDEXED count
- var cntNoIdx int
- db.QueryRow("SELECT COUNT(*) FROM nodes NOT INDEXED").Scan(&cntNoIdx)
- t.Logf("COUNT(*) NOT INDEXED = %d", cntNoIdx)
-
- // Raw page inspection — ALL pages
- raw, _ := os.ReadFile(path)
- pageSize := 4096
- totalPages := len(raw) / pageSize
- t.Logf("total pages in file: %d", totalPages)
- for pn := 1; pn <= totalPages; pn++ {
- off := (pn - 1) * pageSize
- if off+12 > len(raw) { continue }
- pg := raw[off:off+pageSize]
- hdr := 0
- if pn == 1 { hdr = 100 }
- flag := pg[hdr]
- cellCount := int(pg[hdr+3])<<8 | int(pg[hdr+4])
- contentOff := int(pg[hdr+5])<<8 | int(pg[hdr+6])
- flagName := "unknown"
- switch flag {
- case 0x0D: flagName = "leaf_table"
- case 0x05: flagName = "interior_table"
- case 0x0A: flagName = "leaf_index"
- case 0x02: flagName = "interior_index"
- }
- if cellCount > 0 || flag == 0x05 || flag == 0x02 {
- t.Logf("Page %d: %s(0x%02x) cells=%d content_off=%d", pn, flagName, flag, cellCount, contentOff)
- }
- if flag == 0x05 || flag == 0x02 {
- rc := int(pg[hdr+8])<<24 | int(pg[hdr+9])<<16 | int(pg[hdr+10])<<8 | int(pg[hdr+11])
- t.Logf(" right_child=%d", rc)
- }
- }
-}
diff --git a/internal/cbm/sqlite_writer_bridge.go b/internal/cbm/sqlite_writer_bridge.go
deleted file mode 100644
index b8e0a2569..000000000
--- a/internal/cbm/sqlite_writer_bridge.go
+++ /dev/null
@@ -1,129 +0,0 @@
-package cbm
-
-/*
-#include "sqlite_writer.h"
-#include <stdlib.h>
-#include <string.h>
-*/
-import "C"
-import (
- "fmt"
- "runtime"
- "runtime/debug"
- "unsafe"
-)
-
-// DumpNode is the Go-side representation of CBMDumpNode.
-type DumpNode struct {
- ID int64
- Project string
- Label string
- Name string
- QualifiedName string
- FilePath string
- StartLine int
- EndLine int
- Properties string // JSON
-}
-
-// DumpEdge is the Go-side representation of CBMDumpEdge.
-type DumpEdge struct {
- ID int64
- Project string
- SourceID int64
- TargetID int64
- Type string
- Properties string // JSON
- URLPath string // pre-extracted from properties
-}
-
-// WriteDB constructs a SQLite .db file directly from sorted in-memory data.
-// No SQL parser, no INSERTs, no B-tree rebalancing.
-func WriteDB(path, project, rootPath, indexedAt string, nodes []DumpNode, edges []DumpEdge) error {
- cPath := C.CString(path)
- defer C.free(unsafe.Pointer(cPath))
- cProject := C.CString(project)
- defer C.free(unsafe.Pointer(cProject))
- cRootPath := C.CString(rootPath)
- defer C.free(unsafe.Pointer(cRootPath))
- cIndexedAt := C.CString(indexedAt)
- defer C.free(unsafe.Pointer(cIndexedAt))
-
- // Track all CString allocations for cleanup.
- allStrings := make([]*C.char, 0, len(nodes)*5+len(edges)*3)
-
- // Allocate node array in C memory (CGo rules: can't pass Go ptrs containing ptrs).
- nodeSize := C.size_t(C.sizeof_CBMDumpNode)
- var cNodes *C.CBMDumpNode
- if len(nodes) > 0 {
- cNodes = (*C.CBMDumpNode)(C.malloc(nodeSize * C.size_t(len(nodes))))
- for i, n := range nodes {
- cN := (*C.CBMDumpNode)(unsafe.Add(unsafe.Pointer(cNodes), uintptr(i)*uintptr(nodeSize)))
- cN.id = C.int64_t(n.ID)
- cN.project = cProject
- cN.label = C.CString(n.Label)
- allStrings = append(allStrings, cN.label)
- cN.name = C.CString(n.Name)
- allStrings = append(allStrings, cN.name)
- cN.qualified_name = C.CString(n.QualifiedName)
- allStrings = append(allStrings, cN.qualified_name)
- cN.file_path = C.CString(n.FilePath)
- allStrings = append(allStrings, cN.file_path)
- cN.start_line = C.int(n.StartLine)
- cN.end_line = C.int(n.EndLine)
- cN.properties = C.CString(n.Properties)
- allStrings = append(allStrings, cN.properties)
- }
- }
-
- // Allocate edge array in C memory.
- edgeSize := C.size_t(C.sizeof_CBMDumpEdge)
- var cEdges *C.CBMDumpEdge
- if len(edges) > 0 {
- cEdges = (*C.CBMDumpEdge)(C.malloc(edgeSize * C.size_t(len(edges))))
- for i, e := range edges {
- cE := (*C.CBMDumpEdge)(unsafe.Add(unsafe.Pointer(cEdges), uintptr(i)*uintptr(edgeSize)))
- cE.id = C.int64_t(e.ID)
- cE.project = cProject
- cE.source_id = C.int64_t(e.SourceID)
- cE.target_id = C.int64_t(e.TargetID)
- cE._type = C.CString(e.Type)
- allStrings = append(allStrings, cE._type)
- cE.properties = C.CString(e.Properties)
- allStrings = append(allStrings, cE.properties)
- cE.url_path = C.CString(e.URLPath)
- allStrings = append(allStrings, cE.url_path)
- }
- }
-
- // Save counts before releasing Go slices.
- nodeCount := len(nodes)
- edgeCount := len(edges)
-
- // Release Go slices — all data is now in C memory.
- // This frees ~1.5GB for Linux kernel-scale indexes.
- nodes = nil //nolint:ineffassign // intentional: release Go heap before C call
- edges = nil //nolint:ineffassign // intentional: release Go heap before C call
- runtime.GC()
- debug.FreeOSMemory()
-
- rc := C.cbm_write_db(cPath, cProject, cRootPath, cIndexedAt,
- cNodes, C.int(nodeCount),
- cEdges, C.int(edgeCount))
-
- // Free all C allocations.
- for _, s := range allStrings {
- C.free(unsafe.Pointer(s))
- }
- if cNodes != nil {
- C.free(unsafe.Pointer(cNodes))
- }
- if cEdges != nil {
- C.free(unsafe.Pointer(cEdges))
- }
-
- if rc != 0 {
- return fmt.Errorf("cbm_write_db returned %d", rc)
- }
- return nil
-}
diff --git a/internal/cbm/sqlite_writer_test.go b/internal/cbm/sqlite_writer_test.go
deleted file mode 100644
index a48be2a50..000000000
--- a/internal/cbm/sqlite_writer_test.go
+++ /dev/null
@@ -1,258 +0,0 @@
-package cbm
-
-import (
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "testing"
-
- _ "github.com/mattn/go-sqlite3"
-)
-
-func TestWriteDB_MinimalData(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "test.db")
-
- nodes := []DumpNode{
- {ID: 1, Project: "test", Label: "Module", Name: "main", QualifiedName: "test.main", FilePath: "main.go", StartLine: 1, EndLine: 10, Properties: "{}"},
- {ID: 2, Project: "test", Label: "Function", Name: "hello", QualifiedName: "test.main.hello", FilePath: "main.go", StartLine: 3, EndLine: 5, Properties: "{}"},
- }
- edges := []DumpEdge{
- {ID: 1, Project: "test", SourceID: 1, TargetID: 2, Type: "DEFINES", Properties: "{}", URLPath: ""},
- }
-
- err := WriteDB(path, "test", "/tmp/test", "2026-03-14T00:00:00Z", nodes, edges)
- if err != nil {
- t.Fatalf("WriteDB: %v", err)
- }
-
- // Verify file exists
- info, err := os.Stat(path)
- if err != nil {
- t.Fatalf("stat: %v", err)
- }
- if info.Size() == 0 {
- t.Fatal("db file is empty")
- }
- t.Logf("db size: %d bytes", info.Size())
-
- // Open with SQLite and run integrity check
- db, err := sql.Open("sqlite3", path)
- if err != nil {
- t.Fatalf("open db: %v", err)
- }
- defer db.Close()
-
- var integrity string
- if err := db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil {
- t.Fatalf("integrity_check: %v", err)
- }
- if integrity != "ok" {
- t.Fatalf("integrity_check = %q, want 'ok'", integrity)
- }
-
- // Verify nodes
- var nodeCount int
- if err := db.QueryRow("SELECT COUNT(*) FROM nodes").Scan(&nodeCount); err != nil {
- t.Fatalf("count nodes: %v", err)
- }
- if nodeCount != 2 {
- t.Errorf("node count = %d, want 2", nodeCount)
- }
-
- // Verify edges
- var edgeCount int
- if err := db.QueryRow("SELECT COUNT(*) FROM edges").Scan(&edgeCount); err != nil {
- t.Fatalf("count edges: %v", err)
- }
- if edgeCount != 1 {
- t.Errorf("edge count = %d, want 1", edgeCount)
- }
-
- // Verify project
- var projName, rootPath string
- if err := db.QueryRow("SELECT name, root_path FROM projects").Scan(&projName, &rootPath); err != nil {
- t.Fatalf("query project: %v", err)
- }
- if projName != "test" || rootPath != "/tmp/test" {
- t.Errorf("project = (%q, %q), want ('test', '/tmp/test')", projName, rootPath)
- }
-
- // Verify node content
- var qn, label string
- if err := db.QueryRow("SELECT qualified_name, label FROM nodes WHERE id=2").Scan(&qn, &label); err != nil {
- t.Fatalf("query node: %v", err)
- }
- if qn != "test.main.hello" || label != "Function" {
- t.Errorf("node 2 = (%q, %q), want ('test.main.hello', 'Function')", qn, label)
- }
-
- // Verify edge content
- var srcID, tgtID int64
- var edgeType string
- if err := db.QueryRow("SELECT source_id, target_id, type FROM edges WHERE id=1").Scan(&srcID, &tgtID, &edgeType); err != nil {
- t.Fatalf("query edge: %v", err)
- }
- if srcID != 1 || tgtID != 2 || edgeType != "DEFINES" {
- t.Errorf("edge 1 = (%d, %d, %q), want (1, 2, 'DEFINES')", srcID, tgtID, edgeType)
- }
-}
-
-func TestWriteDB_ScaleAndIndexes(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "scale.db")
-
- // 100 nodes across multiple files/labels, 200 edges with varied types
- nodes := make([]DumpNode, 100)
- labels := []string{"Function", "Method", "Class", "Module", "Variable"}
- files := []string{"alpha.go", "beta.go", "gamma.py", "delta.ts", "epsilon.rs"}
- for i := range nodes {
- nodes[i] = DumpNode{
- ID: int64(i + 1),
- Project: "proj",
- Label: labels[i%len(labels)],
- Name: fmt.Sprintf("sym_%03d", i),
- QualifiedName: fmt.Sprintf("proj.pkg.sym_%03d", i),
- FilePath: files[i%len(files)],
- StartLine: i*10 + 1,
- EndLine: i*10 + 9,
- Properties: "{}",
- }
- }
-
- // Build unique (source, target, type) edges
- edgeTypes := []string{"CALLS", "DEFINES", "IMPORTS", "IMPLEMENTS", "USES"}
- type edgeKey struct{ s, t int64; ty string }
- seen := map[edgeKey]bool{}
- var edges []DumpEdge
- edgeID := int64(1)
- for i := 0; len(edges) < 200 && i < 10000; i++ {
- src := int64(i%100) + 1
- tgt := int64((i*7+3)%100) + 1
- if tgt == src {
- tgt = (tgt%100) + 1
- }
- ty := edgeTypes[i%len(edgeTypes)]
- key := edgeKey{src, tgt, ty}
- if seen[key] {
- continue
- }
- seen[key] = true
- urlPath := ""
- props := fmt.Sprintf(`{"weight":%d}`, i)
- if len(edges)%20 == 0 {
- urlPath = fmt.Sprintf("/api/v1/resource/%d", len(edges))
- props = fmt.Sprintf(`{"weight":%d,"url_path":"%s"}`, i, urlPath)
- }
- edges = append(edges, DumpEdge{
- ID: edgeID,
- Project: "proj",
- SourceID: src,
- TargetID: tgt,
- Type: ty,
- Properties: props,
- URLPath: urlPath,
- })
- edgeID++
- }
- edgeCount := len(edges)
-
- if err := WriteDB(path, "proj", "/repo", "2026-03-14T12:00:00Z", nodes, edges); err != nil {
- t.Fatalf("WriteDB: %v", err)
- }
-
- db, err := sql.Open("sqlite3", path)
- if err != nil {
- t.Fatalf("open: %v", err)
- }
- defer db.Close()
-
- // Integrity check
- var integrity string
- if err := db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil {
- t.Fatalf("integrity_check: %v", err)
- }
- if integrity != "ok" {
- t.Fatalf("integrity_check = %q, want 'ok'", integrity)
- }
-
- // Row counts
- var nc, ec int
- db.QueryRow("SELECT COUNT(*) FROM nodes").Scan(&nc)
- db.QueryRow("SELECT COUNT(*) FROM edges").Scan(&ec)
- if nc != 100 {
- t.Errorf("nodes = %d, want 100", nc)
- }
- if ec != edgeCount {
- t.Errorf("edges = %d, want %d", ec, edgeCount)
- }
-
- // Index queries (exercise each index)
- var cnt int
- db.QueryRow("SELECT COUNT(*) FROM nodes WHERE project='proj' AND label='Function'").Scan(&cnt)
- if cnt != 20 {
- t.Errorf("label=Function count = %d, want 20", cnt)
- }
-
- db.QueryRow("SELECT COUNT(*) FROM nodes WHERE project='proj' AND name='sym_042'").Scan(&cnt)
- if cnt != 1 {
- t.Errorf("name=sym_042 count = %d, want 1", cnt)
- }
-
- db.QueryRow("SELECT COUNT(*) FROM nodes WHERE project='proj' AND file_path='alpha.go'").Scan(&cnt)
- if cnt != 20 {
- t.Errorf("file=alpha.go count = %d, want 20", cnt)
- }
-
- db.QueryRow("SELECT COUNT(*) FROM edges WHERE source_id=1 AND type='CALLS'").Scan(&cnt)
- if cnt == 0 {
- // At least some edges should match
- }
-
- db.QueryRow("SELECT COUNT(*) FROM edges WHERE project='proj' AND type='DEFINES'").Scan(&cnt)
- if cnt == 0 {
- t.Errorf("type=DEFINES count = 0, expected some")
- }
-
- // url_path_gen generated column
- db.QueryRow("SELECT COUNT(*) FROM edges WHERE project='proj' AND url_path_gen IS NOT NULL").Scan(&cnt)
- if cnt == 0 {
- t.Errorf("url_path non-null count = 0, expected some")
- }
-
- // Unique constraint: verify qualified_name lookup
- var nid int64
- if err := db.QueryRow("SELECT id FROM nodes WHERE project='proj' AND qualified_name='proj.pkg.sym_050'").Scan(&nid); err != nil {
- t.Fatalf("qn lookup: %v", err)
- }
- if nid != 51 {
- t.Errorf("qn lookup id = %d, want 51", nid)
- }
-
- t.Logf("scale test passed: %d nodes, %d edges", nc, ec)
-}
-
-func TestWriteDB_Empty(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "empty.db")
-
- err := WriteDB(path, "test", "/tmp/test", "2026-03-14T00:00:00Z", nil, nil)
- if err != nil {
- t.Fatalf("WriteDB empty: %v", err)
- }
-
- db, err := sql.Open("sqlite3", path)
- if err != nil {
- t.Fatalf("open: %v", err)
- }
- defer db.Close()
-
- var integrity string
- if err := db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil {
- t.Fatalf("integrity_check: %v", err)
- }
- if integrity != "ok" {
- t.Fatalf("integrity_check = %q, want 'ok'", integrity)
- }
-}
diff --git a/internal/cypher/ast.go b/internal/cypher/ast.go
deleted file mode 100644
index ad76b3bdb..000000000
--- a/internal/cypher/ast.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package cypher
-
-// Query represents a parsed Cypher query.
-type Query struct {
- Match *MatchClause
- Where *WhereClause
- Return *ReturnClause
-}
-
-// MatchClause holds the MATCH pattern.
-type MatchClause struct {
- Pattern *Pattern
-}
-
-// Pattern is a sequence of alternating nodes and relationships.
-type Pattern struct {
- Elements []PatternElement
-}
-
-// PatternElement is either a NodePattern or a RelPattern.
-type PatternElement interface {
- patternElement()
-}
-
-// NodePattern matches a graph node with optional label and inline properties.
-type NodePattern struct {
- Variable string // e.g. "f"
- Label string // e.g. "Function" (optional)
- Props map[string]string // inline property filters (optional)
-}
-
-func (*NodePattern) patternElement() {}
-
-// RelPattern matches a graph relationship with optional types, direction, and hops.
-type RelPattern struct {
- Variable string // (optional)
- Types []string // relationship types, e.g. ["CALLS", "HTTP_CALLS"]
- Direction string // "outbound", "inbound", "any"
- MinHops int // for variable-length, default 1
- MaxHops int // for variable-length, default 1 (0 means unbounded)
-}
-
-func (*RelPattern) patternElement() {}
-
-// WhereClause holds filter conditions joined by AND/OR.
-type WhereClause struct {
- Conditions []Condition
- Operator string // "AND" or "OR"
-}
-
-// Condition is a single property comparison.
-type Condition struct {
- Variable string // "f"
- Property string // "name"
- Operator string // "=", "=~", "CONTAINS", "STARTS WITH", ">", "<", ">=", "<="
- Value string // the comparison value
-}
-
-// ReturnClause specifies which data to return from the query.
-type ReturnClause struct {
- Items []ReturnItem
- OrderBy string // "f.name" (optional)
- OrderDir string // "ASC" or "DESC"
- Limit int // 0 means no limit
- Distinct bool
-}
-
-// ReturnItem is a single item in the RETURN clause.
-type ReturnItem struct {
- Variable string // "f"
- Property string // "name" (empty = return whole node)
- Alias string // "AS call_count" (optional)
- Func string // "COUNT" (optional aggregation)
-}
diff --git a/internal/cypher/cypher_test.go b/internal/cypher/cypher_test.go
deleted file mode 100644
index f1a2861e6..000000000
--- a/internal/cypher/cypher_test.go
+++ /dev/null
@@ -1,1015 +0,0 @@
-package cypher
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// --- Lexer tests ---
-
-func TestLexBasicQuery(t *testing.T) {
- tokens, err := Lex(`MATCH (f:Function) WHERE f.name = "Hello" RETURN f.name`)
- if err != nil {
- t.Fatalf("lex: %v", err)
- }
-
- expected := []TokenType{
- TokMatch, TokLParen, TokIdent, TokColon, TokIdent, TokRParen,
- TokWhere, TokIdent, TokDot, TokIdent, TokEQ, TokString,
- TokReturn, TokIdent, TokDot, TokIdent, TokEOF,
- }
-
- if len(tokens) != len(expected) {
- t.Fatalf("expected %d tokens, got %d", len(expected), len(tokens))
- }
- for i, tok := range tokens {
- if tok.Type != expected[i] {
- t.Errorf("token[%d]: expected type %d, got %d (%q)", i, expected[i], tok.Type, tok.Value)
- }
- }
-}
-
-func TestLexRegexOperator(t *testing.T) {
- tokens, err := Lex(`f.name =~ ".*Handler"`)
- if err != nil {
- t.Fatalf("lex: %v", err)
- }
- // f, ., name, =~, ".*Handler"
- if tokens[3].Type != TokRegex {
- t.Errorf("expected TokRegex, got type %d (%q)", tokens[3].Type, tokens[3].Value)
- }
-}
-
-func TestLexVariableLengthPath(t *testing.T) {
- tokens, err := Lex(`[:CALLS*1..3]`)
- if err != nil {
- t.Fatalf("lex: %v", err)
- }
- expected := []TokenType{
- TokLBracket, TokColon, TokIdent, TokStar, TokNumber, TokDotDot, TokNumber, TokRBracket, TokEOF,
- }
- if len(tokens) != len(expected) {
- t.Fatalf("expected %d tokens, got %d", len(expected), len(tokens))
- }
- for i, tok := range tokens {
- if tok.Type != expected[i] {
- t.Errorf("token[%d]: expected type %d, got %d (%q)", i, expected[i], tok.Type, tok.Value)
- }
- }
-}
-
-// --- Parser tests ---
-
-func TestParseNodePattern(t *testing.T) {
- q, err := Parse(`MATCH (f:Function {name: "Hello"}) RETURN f`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if q.Match == nil || q.Match.Pattern == nil {
- t.Fatal("expected match pattern")
- }
- elems := q.Match.Pattern.Elements
- if len(elems) != 1 {
- t.Fatalf("expected 1 element, got %d", len(elems))
- }
- node, ok := elems[0].(*NodePattern)
- if !ok {
- t.Fatalf("expected *NodePattern, got %T", elems[0])
- }
- if node.Variable != "f" {
- t.Errorf("expected variable 'f', got %q", node.Variable)
- }
- if node.Label != "Function" {
- t.Errorf("expected label 'Function', got %q", node.Label)
- }
- if node.Props["name"] != "Hello" {
- t.Errorf("expected prop name='Hello', got %q", node.Props["name"])
- }
-}
-
-func TestParseRelationship(t *testing.T) {
- q, err := Parse(`MATCH (f)-[:CALLS]->(g) RETURN f.name, g.name`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- elems := q.Match.Pattern.Elements
- if len(elems) != 3 {
- t.Fatalf("expected 3 elements (node-rel-node), got %d", len(elems))
- }
- rel, ok := elems[1].(*RelPattern)
- if !ok {
- t.Fatalf("expected *RelPattern, got %T", elems[1])
- }
- if len(rel.Types) != 1 || rel.Types[0] != "CALLS" {
- t.Errorf("expected CALLS type, got %v", rel.Types)
- }
- if rel.Direction != "outbound" {
- t.Errorf("expected outbound, got %q", rel.Direction)
- }
- if rel.MinHops != 1 || rel.MaxHops != 1 {
- t.Errorf("expected hops 1..1, got %d..%d", rel.MinHops, rel.MaxHops)
- }
-}
-
-func TestParseVariableLength(t *testing.T) {
- q, err := Parse(`MATCH (f)-[:CALLS*1..3]->(g) RETURN g.name`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- rel, ok := q.Match.Pattern.Elements[1].(*RelPattern)
- if !ok {
- t.Fatalf("expected *RelPattern, got %T", q.Match.Pattern.Elements[1])
- }
- if rel.MinHops != 1 {
- t.Errorf("expected minHops=1, got %d", rel.MinHops)
- }
- if rel.MaxHops != 3 {
- t.Errorf("expected maxHops=3, got %d", rel.MaxHops)
- }
-}
-
-func TestParseWhereRegex(t *testing.T) {
- q, err := Parse(`MATCH (f:Function) WHERE f.name =~ ".*Handler" RETURN f.name`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if q.Where == nil {
- t.Fatal("expected WHERE clause")
- }
- if len(q.Where.Conditions) != 1 {
- t.Fatalf("expected 1 condition, got %d", len(q.Where.Conditions))
- }
- c := q.Where.Conditions[0]
- if c.Operator != "=~" {
- t.Errorf("expected =~, got %q", c.Operator)
- }
- if c.Value != ".*Handler" {
- t.Errorf("expected '.*Handler', got %q", c.Value)
- }
-}
-
-func TestParseReturnWithCount(t *testing.T) {
- q, err := Parse(`MATCH (f)-[:CALLS]->(g) RETURN f.name, COUNT(g) AS cnt ORDER BY cnt DESC LIMIT 10`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if q.Return == nil {
- t.Fatal("expected RETURN clause")
- }
- if len(q.Return.Items) != 2 {
- t.Fatalf("expected 2 return items, got %d", len(q.Return.Items))
- }
-
- // First item: f.name
- if q.Return.Items[0].Variable != "f" || q.Return.Items[0].Property != "name" {
- t.Errorf("expected f.name, got %s.%s", q.Return.Items[0].Variable, q.Return.Items[0].Property)
- }
-
- // Second item: COUNT(g) AS cnt
- if q.Return.Items[1].Func != "COUNT" {
- t.Errorf("expected COUNT, got %q", q.Return.Items[1].Func)
- }
- if q.Return.Items[1].Variable != "g" {
- t.Errorf("expected variable 'g', got %q", q.Return.Items[1].Variable)
- }
- if q.Return.Items[1].Alias != "cnt" {
- t.Errorf("expected alias 'cnt', got %q", q.Return.Items[1].Alias)
- }
-
- // ORDER BY
- if q.Return.OrderBy != "cnt" {
- t.Errorf("expected ORDER BY cnt, got %q", q.Return.OrderBy)
- }
- if q.Return.OrderDir != "DESC" {
- t.Errorf("expected DESC, got %q", q.Return.OrderDir)
- }
- if q.Return.Limit != 10 {
- t.Errorf("expected LIMIT 10, got %d", q.Return.Limit)
- }
-}
-
-func TestParseBidirectional(t *testing.T) {
- q, err := Parse(`MATCH (f:Function)-[:CALLS]-(g) RETURN f.name, g.name`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- rel, ok := q.Match.Pattern.Elements[1].(*RelPattern)
- if !ok {
- t.Fatalf("expected *RelPattern, got %T", q.Match.Pattern.Elements[1])
- }
- if rel.Direction != "any" {
- t.Errorf("expected 'any' direction, got %q", rel.Direction)
- }
-}
-
-func TestParseInbound(t *testing.T) {
- q, err := Parse(`MATCH (f:Function)<-[:CALLS]-(g) RETURN f.name`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- rel, ok := q.Match.Pattern.Elements[1].(*RelPattern)
- if !ok {
- t.Fatalf("expected *RelPattern, got %T", q.Match.Pattern.Elements[1])
- }
- if rel.Direction != "inbound" {
- t.Errorf("expected inbound, got %q", rel.Direction)
- }
-}
-
-func TestParseMultipleRelTypes(t *testing.T) {
- q, err := Parse(`MATCH (f)-[:CALLS|HTTP_CALLS]->(g) RETURN g.name`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- rel, ok := q.Match.Pattern.Elements[1].(*RelPattern)
- if !ok {
- t.Fatalf("expected *RelPattern, got %T", q.Match.Pattern.Elements[1])
- }
- if len(rel.Types) != 2 {
- t.Fatalf("expected 2 types, got %d", len(rel.Types))
- }
- if rel.Types[0] != "CALLS" || rel.Types[1] != "HTTP_CALLS" {
- t.Errorf("expected [CALLS, HTTP_CALLS], got %v", rel.Types)
- }
-}
-
-func TestParseWhereStartsWith(t *testing.T) {
- q, err := Parse(`MATCH (f:Function) WHERE f.name STARTS WITH "Send" RETURN f`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- c := q.Where.Conditions[0]
- if c.Operator != "STARTS WITH" {
- t.Errorf("expected 'STARTS WITH', got %q", c.Operator)
- }
- if c.Value != "Send" {
- t.Errorf("expected 'Send', got %q", c.Value)
- }
-}
-
-func TestParseWhereContains(t *testing.T) {
- q, err := Parse(`MATCH (f:Function) WHERE f.name CONTAINS "Handler" RETURN f`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- c := q.Where.Conditions[0]
- if c.Operator != "CONTAINS" {
- t.Errorf("expected CONTAINS, got %q", c.Operator)
- }
-}
-
-func TestParseWhereNumericComparison(t *testing.T) {
- q, err := Parse(`MATCH (f:Function) WHERE f.start_line > 10 RETURN f`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- c := q.Where.Conditions[0]
- if c.Operator != ">" {
- t.Errorf("expected '>', got %q", c.Operator)
- }
- if c.Value != "10" {
- t.Errorf("expected '10', got %q", c.Value)
- }
-}
-
-func TestParseWhereAnd(t *testing.T) {
- q, err := Parse(`MATCH (f) WHERE f.label = "Function" AND f.name = "Foo" RETURN f`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if len(q.Where.Conditions) != 2 {
- t.Fatalf("expected 2 conditions, got %d", len(q.Where.Conditions))
- }
- if q.Where.Operator != "AND" {
- t.Errorf("expected AND, got %q", q.Where.Operator)
- }
-}
-
-func TestParseDistinct(t *testing.T) {
- q, err := Parse(`MATCH (f:Function) RETURN DISTINCT f.label`)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if !q.Return.Distinct {
- t.Error("expected DISTINCT to be true")
- }
-}
-
-// --- Integration test ---
-
-func setupTestStore(t *testing.T) *store.Store {
- t.Helper()
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatalf("open memory store: %v", err)
- }
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("upsert project: %v", err)
- }
-
- // Create nodes
- idA, _ := s.UpsertNode(&store.Node{
- Project: "test", Label: "Function", Name: "HandleOrder",
- QualifiedName: "test.main.HandleOrder", FilePath: "main.go",
- StartLine: 10, EndLine: 30,
- Properties: map[string]any{"signature": "func HandleOrder(w, r)"},
- })
- idB, _ := s.UpsertNode(&store.Node{
- Project: "test", Label: "Function", Name: "ValidateOrder",
- QualifiedName: "test.service.ValidateOrder", FilePath: "service.go",
- StartLine: 5, EndLine: 20,
- Properties: map[string]any{"signature": "func ValidateOrder(o Order) error"},
- })
- idC, _ := s.UpsertNode(&store.Node{
- Project: "test", Label: "Function", Name: "SubmitOrder",
- QualifiedName: "test.service.SubmitOrder", FilePath: "service.go",
- StartLine: 25, EndLine: 50,
- Properties: map[string]any{"signature": "func SubmitOrder(o Order) error"},
- })
- idD, _ := s.UpsertNode(&store.Node{
- Project: "test", Label: "Module", Name: "main",
- QualifiedName: "test.main", FilePath: "main.go",
- })
- idE, _ := s.UpsertNode(&store.Node{
- Project: "test", Label: "Function", Name: "LogError",
- QualifiedName: "test.util.LogError", FilePath: "util.go",
- StartLine: 1, EndLine: 5,
- })
-
- // Edges: HandleOrder -> ValidateOrder -> SubmitOrder
- // HandleOrder -> LogError
- mustInsertEdge(t, s, &store.Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "CALLS"})
- mustInsertEdge(t, s, &store.Edge{Project: "test", SourceID: idB, TargetID: idC, Type: "CALLS"})
- mustInsertEdge(t, s, &store.Edge{Project: "test", SourceID: idA, TargetID: idE, Type: "CALLS"})
- mustInsertEdge(t, s, &store.Edge{Project: "test", SourceID: idD, TargetID: idA, Type: "DEFINES"})
-
- return s
-}
-
-// mustInsertEdge inserts an edge and fails the test on error.
-func mustInsertEdge(t *testing.T, s *store.Store, edge *store.Edge) {
- t.Helper()
- if _, err := s.InsertEdge(edge); err != nil {
- t.Fatalf("insert edge: %v", err)
- }
-}
-
-func TestExecuteSimpleMatch(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) RETURN f.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 4 {
- t.Errorf("expected 4 functions, got %d", len(result.Rows))
- }
-}
-
-func TestExecuteRelationshipQuery(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function)-[:CALLS]->(g:Function) RETURN f.name, g.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
-
- // HandleOrder -> ValidateOrder, HandleOrder -> LogError, ValidateOrder -> SubmitOrder
- if len(result.Rows) != 3 {
- t.Fatalf("expected 3 rows, got %d", len(result.Rows))
- }
-
- // Verify columns
- if len(result.Columns) != 2 {
- t.Errorf("expected 2 columns, got %d", len(result.Columns))
- }
-
- // Check that HandleOrder -> ValidateOrder is in the results
- found := false
- for _, row := range result.Rows {
- if row["f.name"] == "HandleOrder" && row["g.name"] == "ValidateOrder" {
- found = true
- break
- }
- }
- if !found {
- t.Error("expected HandleOrder -> ValidateOrder in results")
- }
-}
-
-func TestExecuteWhereFilter(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) WHERE f.name = "HandleOrder" RETURN f.name, f.file_path`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["f.name"] != "HandleOrder" {
- t.Errorf("expected HandleOrder, got %v", result.Rows[0]["f.name"])
- }
-}
-
-func TestExecuteWhereRegex(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) WHERE f.name =~ ".*Order" RETURN f.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- // HandleOrder, ValidateOrder, SubmitOrder
- if len(result.Rows) != 3 {
- t.Errorf("expected 3 rows, got %d", len(result.Rows))
- }
-}
-
-func TestExecuteWhereStartsWith(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) WHERE f.name STARTS WITH "Submit" RETURN f.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["f.name"] != "SubmitOrder" {
- t.Errorf("expected SubmitOrder, got %v", result.Rows[0]["f.name"])
- }
-}
-
-func TestExecuteWhereContains(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) WHERE f.name CONTAINS "Order" RETURN f.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 3 {
- t.Errorf("expected 3 rows (HandleOrder, ValidateOrder, SubmitOrder), got %d", len(result.Rows))
- }
-}
-
-func TestExecuteWhereNumeric(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) WHERE f.start_line > 10 RETURN f.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- // SubmitOrder (start_line=25)
- if len(result.Rows) != 1 {
- t.Errorf("expected 1 row, got %d", len(result.Rows))
- }
-}
-
-func TestExecuteVariableLength(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // HandleOrder calls ValidateOrder (hop 1), ValidateOrder calls SubmitOrder (hop 2)
- result, err := exec.Execute(`MATCH (f:Function {name: "HandleOrder"})-[:CALLS*1..2]->(g:Function) RETURN g.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- // Should include ValidateOrder (hop 1), LogError (hop 1), SubmitOrder (hop 2)
- if len(result.Rows) < 2 {
- t.Errorf("expected at least 2 rows for variable-length path, got %d", len(result.Rows))
- }
-}
-
-func TestExecuteWithLimit(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) RETURN f.name LIMIT 2`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 2 {
- t.Errorf("expected 2 rows, got %d", len(result.Rows))
- }
-}
-
-func TestExecuteWithOrderBy(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) RETURN f.name ORDER BY f.name ASC`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) < 2 {
- t.Fatalf("expected at least 2 rows, got %d", len(result.Rows))
- }
- // First should be HandleOrder (alphabetically first)
- firstName := result.Rows[0]["f.name"]
- if firstName != "HandleOrder" {
- t.Errorf("expected first row 'HandleOrder', got %v", firstName)
- }
-}
-
-func TestExecuteCountAggregation(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function)-[:CALLS]->(g:Function) RETURN f.name, COUNT(g) AS call_count ORDER BY call_count DESC`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) < 1 {
- t.Fatalf("expected at least 1 row, got %d", len(result.Rows))
- }
- // HandleOrder calls 2 functions (ValidateOrder, LogError)
- for _, row := range result.Rows {
- if row["f.name"] == "HandleOrder" {
- count, ok := row["call_count"].(int)
- if !ok {
- t.Errorf("expected int count, got %T", row["call_count"])
- } else if count != 2 {
- t.Errorf("expected call_count=2 for HandleOrder, got %d", count)
- }
- }
- }
-}
-
-func TestExecuteInboundRelationship(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // Who calls ValidateOrder?
- result, err := exec.Execute(`MATCH (f:Function)<-[:CALLS]-(g:Function) WHERE f.name = "ValidateOrder" RETURN g.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 caller, got %d", len(result.Rows))
- }
- if result.Rows[0]["g.name"] != "HandleOrder" {
- t.Errorf("expected HandleOrder, got %v", result.Rows[0]["g.name"])
- }
-}
-
-func TestExecuteDistinct(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) RETURN DISTINCT f.label`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Errorf("expected 1 distinct label, got %d", len(result.Rows))
- }
- if result.Rows[0]["f.label"] != "Function" {
- t.Errorf("expected 'Function', got %v", result.Rows[0]["f.label"])
- }
-}
-
-func TestExecuteInlinePropertyFilter(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function {name: "SubmitOrder"}) RETURN f.name, f.qualified_name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["f.name"] != "SubmitOrder" {
- t.Errorf("expected SubmitOrder, got %v", result.Rows[0]["f.name"])
- }
-}
-
-func TestExecuteNoResults(t *testing.T) {
- s := setupTestStore(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (f:Function) WHERE f.name = "NonExistent" RETURN f.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 0 {
- t.Errorf("expected 0 rows, got %d", len(result.Rows))
- }
-}
-
-func TestParseError(t *testing.T) {
- _, err := Parse(`NOT A VALID QUERY`)
- if err == nil {
- t.Error("expected parse error for invalid query")
- }
-}
-
-// --- Edge property tests (Feature 2) ---
-
-func setupTestStoreWithHTTPCalls(t *testing.T) *store.Store {
- t.Helper()
- s := setupTestStore(t)
-
- // Add HTTP_CALLS edge with confidence
- callerNode, _ := s.FindNodeByQN("test", "test.main.HandleOrder")
- targetNode, _ := s.FindNodeByQN("test", "test.service.SubmitOrder")
- if callerNode == nil || targetNode == nil {
- t.Fatal("expected test nodes to exist")
- }
- mustInsertEdge(t, s, &store.Edge{
- Project: "test",
- SourceID: callerNode.ID,
- TargetID: targetNode.ID,
- Type: "HTTP_CALLS",
- Properties: map[string]any{
- "url_path": "/api/orders",
- "confidence": 0.85,
- "method": "POST",
- },
- })
- return s
-}
-
-func TestExecuteEdgePropertyAccess(t *testing.T) {
- s := setupTestStoreWithHTTPCalls(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a:Function)-[r:HTTP_CALLS]->(b:Function) RETURN a.name, b.name, r.url_path, r.confidence`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- row := result.Rows[0]
- if row["a.name"] != "HandleOrder" {
- t.Errorf("a.name = %v, want HandleOrder", row["a.name"])
- }
- if row["b.name"] != "SubmitOrder" {
- t.Errorf("b.name = %v, want SubmitOrder", row["b.name"])
- }
- if row["r.url_path"] != "/api/orders" {
- t.Errorf("r.url_path = %v, want /api/orders", row["r.url_path"])
- }
- conf, ok := row["r.confidence"].(float64)
- if !ok {
- t.Errorf("r.confidence type = %T, want float64", row["r.confidence"])
- } else if conf != 0.85 {
- t.Errorf("r.confidence = %v, want 0.85", conf)
- }
-}
-
-func TestExecuteEdgePropertyInWhere(t *testing.T) {
- s := setupTestStoreWithHTTPCalls(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // Filter by confidence > 0.8
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.confidence > 0.8 RETURN a.name, b.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
-
- // Filter by confidence > 0.9 — should return nothing
- result2, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.confidence > 0.9 RETURN a.name`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result2.Rows) != 0 {
- t.Errorf("expected 0 rows for confidence > 0.9, got %d", len(result2.Rows))
- }
-}
-
-func TestExecuteEdgeType(t *testing.T) {
- s := setupTestStoreWithHTTPCalls(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) RETURN r.type`)
- if err != nil {
- t.Fatalf("execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["r.type"] != "HTTP_CALLS" {
- t.Errorf("r.type = %v, want HTTP_CALLS", result.Rows[0]["r.type"])
- }
-}
-
-// --- Comprehensive edge property filtering tests ---
-
-// setupTestStoreMultiEdge creates a store with two HTTP_CALLS edges to test filtering.
-func setupTestStoreMultiEdge(t *testing.T) *store.Store {
- t.Helper()
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
-
- project := "testproj"
- if err := s.UpsertProject(project, "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- srcID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "SendOrder",
- QualifiedName: "testproj.caller.SendOrder",
- FilePath: "caller/client.go",
- })
-
- tgtID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "HandleOrder",
- QualifiedName: "testproj.handler.HandleOrder",
- FilePath: "handler/routes.go",
- })
-
- tgt2ID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "HandleHealth",
- QualifiedName: "testproj.handler.HandleHealth",
- FilePath: "handler/health.go",
- })
-
- mustInsertEdge(t, s, &store.Edge{
- Project: project, SourceID: srcID, TargetID: tgtID,
- Type: "HTTP_CALLS",
- Properties: map[string]any{
- "url_path": "/api/orders",
- "confidence": 0.85,
- "method": "POST",
- },
- })
-
- mustInsertEdge(t, s, &store.Edge{
- Project: project, SourceID: srcID, TargetID: tgt2ID,
- Type: "HTTP_CALLS",
- Properties: map[string]any{
- "url_path": "/health",
- "confidence": 0.45,
- },
- })
-
- return s
-}
-
-func TestEdgePropertyFilterContains(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.url_path CONTAINS 'orders' RETURN a.name, b.name, r.url_path`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
-
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
-
- row := result.Rows[0]
- if row["a.name"] != "SendOrder" {
- t.Errorf("a.name = %v, want SendOrder", row["a.name"])
- }
- if row["b.name"] != "HandleOrder" {
- t.Errorf("b.name = %v, want HandleOrder", row["b.name"])
- }
- if row["r.url_path"] != "/api/orders" {
- t.Errorf("r.url_path = %v, want /api/orders", row["r.url_path"])
- }
-}
-
-func TestEdgePropertyFilterNumericGTE(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.confidence >= 0.6 RETURN a.name, b.name, r.confidence LIMIT 20`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
-
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row (only high-confidence edge), got %d", len(result.Rows))
- }
-
- row := result.Rows[0]
- if row["b.name"] != "HandleOrder" {
- t.Errorf("b.name = %v, want HandleOrder (high confidence)", row["b.name"])
- }
-}
-
-func TestEdgePropertyReturnWithoutFilter(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence LIMIT 20`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
-
- if len(result.Rows) < 2 {
- t.Fatalf("expected at least 2 rows, got %d", len(result.Rows))
- }
-
- foundOrders := false
- foundHealth := false
- for _, row := range result.Rows {
- urlPath, _ := row["r.url_path"].(string)
- if urlPath == "/api/orders" {
- foundOrders = true
- }
- if urlPath == "/health" {
- foundHealth = true
- }
- }
- if !foundOrders {
- t.Error("missing row with url_path=/api/orders")
- }
- if !foundHealth {
- t.Error("missing row with url_path=/health")
- }
-}
-
-func TestEdgePropertyFilterEquals(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.method = 'POST' RETURN a.name, b.name`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
-
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["b.name"] != "HandleOrder" {
- t.Errorf("b.name = %v, want HandleOrder", result.Rows[0]["b.name"])
- }
-}
-
-func TestEdgePropertyFilterStartsWith(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.url_path STARTS WITH '/api' RETURN a.name, b.name, r.url_path`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
-
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row (only /api/orders starts with /api), got %d", len(result.Rows))
- }
- if result.Rows[0]["r.url_path"] != "/api/orders" {
- t.Errorf("r.url_path = %v, want /api/orders", result.Rows[0]["r.url_path"])
- }
-}
-
-func TestCombinedNodeAndEdgeFilter(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // Filter on both node property (early) and edge property (late)
- result, err := exec.Execute(`MATCH (a:Function)-[r:HTTP_CALLS]->(b:Function) WHERE a.name = 'SendOrder' AND r.confidence >= 0.6 RETURN b.name, r.url_path`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
-
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["b.name"] != "HandleOrder" {
- t.Errorf("b.name = %v, want HandleOrder", result.Rows[0]["b.name"])
- }
- if result.Rows[0]["r.url_path"] != "/api/orders" {
- t.Errorf("r.url_path = %v, want /api/orders", result.Rows[0]["r.url_path"])
- }
-}
-
-func TestEdgePropertyFilterNoMatch(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // No edge has method = 'DELETE'
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.method = 'DELETE' RETURN a.name`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
- if len(result.Rows) != 0 {
- t.Errorf("expected 0 rows, got %d", len(result.Rows))
- }
-}
-
-func TestEdgePropertyFilterNumericLT(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // Only the health edge (0.45) should match confidence < 0.5
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.confidence < 0.5 RETURN b.name, r.confidence`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["b.name"] != "HandleHealth" {
- t.Errorf("b.name = %v, want HandleHealth", result.Rows[0]["b.name"])
- }
-}
-
-func TestEdgePropertyFilterRegex(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // Regex match on url_path
- result, err := exec.Execute(`MATCH (a)-[r:HTTP_CALLS]->(b) WHERE r.url_path =~ "/api/.*" RETURN b.name`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
- if len(result.Rows) != 1 {
- t.Fatalf("expected 1 row, got %d", len(result.Rows))
- }
- if result.Rows[0]["b.name"] != "HandleOrder" {
- t.Errorf("b.name = %v, want HandleOrder", result.Rows[0]["b.name"])
- }
-}
-
-func TestApplyLimitRespectsExplicit(t *testing.T) {
- rows := make([]map[string]any, 300)
- for i := range rows {
- rows[i] = map[string]any{"i": i}
- }
-
- // No explicit limit — should use maxRows default (200)
- got := applyLimit(rows, 0, 200)
- if len(got) != 200 {
- t.Errorf("no limit: expected 200 rows, got %d", len(got))
- }
-
- // Explicit limit below maxRows
- got = applyLimit(rows, 50, 200)
- if len(got) != 50 {
- t.Errorf("limit=50: expected 50 rows, got %d", len(got))
- }
-
- // Explicit limit above maxRows — must be respected (not silently capped)
- got = applyLimit(rows, 250, 200)
- if len(got) != 250 {
- t.Errorf("limit=250: expected 250 rows, got %d", len(got))
- }
-
- // Explicit limit above total rows — returns all
- got = applyLimit(rows, 500, 200)
- if len(got) != 300 {
- t.Errorf("limit=500: expected 300 rows (all), got %d", len(got))
- }
-}
-
-func TestEdgeBuiltinPropertyFilter(t *testing.T) {
- s := setupTestStoreMultiEdge(t)
- defer s.Close()
-
- exec := &Executor{Store: s}
- // Filter on built-in edge property r.type
- result, err := exec.Execute(`MATCH (a)-[r]->(b) WHERE r.type = 'HTTP_CALLS' RETURN a.name, b.name LIMIT 20`)
- if err != nil {
- t.Fatalf("Execute: %v", err)
- }
- if len(result.Rows) != 2 {
- t.Fatalf("expected 2 rows (both HTTP_CALLS edges), got %d", len(result.Rows))
- }
-}
diff --git a/internal/cypher/executor.go b/internal/cypher/executor.go
deleted file mode 100644
index 632172222..000000000
--- a/internal/cypher/executor.go
+++ /dev/null
@@ -1,1472 +0,0 @@
-package cypher
-
-import (
- "context"
- "database/sql"
- "fmt"
- "regexp"
- "sort"
- "strconv"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-const defaultMaxRows = 200
-const absoluteMaxRows = 10000
-
-// Executor runs Cypher execution plans against a store.
-type Executor struct {
- Store *store.Store
- MaxRows int // 0 means defaultMaxRows
- regexCache map[string]*regexp.Regexp
- ctx context.Context // set by Execute, used for DB queries
- expandLimit int // binding cap for current query (set per-execution)
-}
-
-func (e *Executor) maxRows() int {
- if e.MaxRows <= 0 {
- return defaultMaxRows
- }
- if e.MaxRows > absoluteMaxRows {
- return absoluteMaxRows
- }
- return e.MaxRows
-}
-
-// bindingCap returns the maximum number of bindings to keep during expansion.
-// For aggregation queries (COUNT), we need all bindings for correct counts,
-// so the cap is much higher. For non-aggregation queries, cap at maxRows*2.
-func (e *Executor) bindingCap(ret *ReturnClause) int {
- if ret != nil {
- for _, item := range ret.Items {
- if item.Func == "COUNT" {
- return absoluteMaxRows * 10 // 100k cap for aggregation
- }
- }
- }
- return e.maxRows() * 2
-}
-
-// Result holds the tabular output of a query.
-type Result struct {
- Columns []string `json:"columns"`
- Rows []map[string]any `json:"rows"`
-}
-
-// binding maps variable names to matched nodes and edges.
-type binding struct {
- nodes map[string]*store.Node
- edges map[string]*store.Edge
-}
-
-func newBinding() binding {
- return binding{
- nodes: make(map[string]*store.Node),
- edges: make(map[string]*store.Edge),
- }
-}
-
-// Execute parses, plans, and executes a Cypher query across all projects.
-func (e *Executor) Execute(query string) (*Result, error) {
- if e.ctx == nil {
- e.ctx = context.Background()
- }
- q, err := Parse(query)
- if err != nil {
- return nil, fmt.Errorf("parse: %w", err)
- }
- plan, err := BuildPlan(q)
- if err != nil {
- return nil, fmt.Errorf("plan: %w", err)
- }
- return e.executePlan(plan)
-}
-
-func (e *Executor) executePlan(plan *Plan) (*Result, error) {
- // Fast path: push COUNT aggregation to SQL when pattern is fusible.
- if result, ok := e.tryAggregateSQL(plan); ok {
- return result, nil
- }
-
- projects, err := e.Store.ListProjects()
- if err != nil {
- return nil, fmt.Errorf("list projects: %w", err)
- }
-
- bindingCap := e.bindingCap(plan.ReturnSpec)
- e.expandLimit = bindingCap
- var allBindings []binding
- for _, proj := range projects {
- bindings, err := e.executeStepsForProject(proj.Name, plan.Steps)
- if err != nil {
- continue // skip projects that error
- }
- allBindings = append(allBindings, bindings...)
- if len(allBindings) > bindingCap {
- allBindings = allBindings[:bindingCap]
- break
- }
- }
-
- return e.projectResults(allBindings, plan.ReturnSpec)
-}
-
-// tryAggregateSQL attempts to push a COUNT aggregation query entirely to SQL.
-// Returns (result, true) if the pattern is fusible, (nil, false) otherwise.
-// Fusible pattern: ScanNodes + ExpandRelationship (fixed-length 1 hop) with
-// RETURN containing COUNT and group-by items that map to SQL columns.
-func (e *Executor) tryAggregateSQL(plan *Plan) (*Result, bool) {
- if plan.ReturnSpec == nil {
- return nil, false
- }
-
- countItem, groupItems := classifyCountItems(plan.ReturnSpec.Items)
- if countItem == nil {
- return nil, false
- }
-
- scan, expand, filter, ok := parseFusibleSteps(plan.Steps)
- if !ok {
- return nil, false
- }
-
- if !validatePushability(scan, expand, filter, groupItems) {
- return nil, false
- }
-
- projects, err := e.Store.ListProjects()
- if err != nil {
- return nil, false
- }
-
- sqlCtx := newAggregateSQLContext(scan, expand, groupItems)
- cols := buildColumnNames(plan.ReturnSpec.Items)
- countCol := cols[len(cols)-1] // COUNT column is last
-
- allRows := make([]map[string]any, 0)
- for _, proj := range projects {
- projRows := e.executeAggregateForProject(proj.Name, &sqlCtx, scan, expand, filter, groupItems, countCol)
- allRows = append(allRows, projRows...)
- }
-
- // ORDER BY
- if plan.ReturnSpec.OrderBy != "" {
- orderCol := resolveOrderColumn(plan.ReturnSpec.OrderBy, plan.ReturnSpec.Items, cols)
- sortRows(allRows, orderCol, plan.ReturnSpec.OrderDir)
- }
-
- // LIMIT
- allRows = applyLimit(allRows, plan.ReturnSpec.Limit, e.maxRows())
-
- return &Result{Columns: cols, Rows: allRows}, true
-}
-
-// classifyCountItems separates return items into the COUNT item and group-by items.
-func classifyCountItems(items []ReturnItem) (countItem *ReturnItem, groupItems []ReturnItem) {
- for i := range items {
- item := &items[i]
- if item.Func == "COUNT" {
- countItem = item
- } else {
- groupItems = append(groupItems, *item)
- }
- }
- return
-}
-
-// parseFusibleSteps identifies the ScanNodes + optional FilterWhere + ExpandRelationship
-// pattern from plan steps. Returns (nil, nil, nil, false) if the pattern is not fusible.
-func parseFusibleSteps(steps []PlanStep) (*ScanNodes, *ExpandRelationship, *FilterWhere, bool) {
- switch len(steps) {
- case 2:
- s, ok1 := steps[0].(*ScanNodes)
- ex, ok2 := steps[1].(*ExpandRelationship)
- if !ok1 || !ok2 {
- return nil, nil, nil, false
- }
- return s, ex, nil, true
- case 3:
- s, ok1 := steps[0].(*ScanNodes)
- f, ok2 := steps[1].(*FilterWhere)
- ex, ok3 := steps[2].(*ExpandRelationship)
- if !ok1 || !ok3 {
- return nil, nil, nil, false
- }
- var filter *FilterWhere
- if ok2 {
- filter = f
- }
- return s, ex, filter, true
- default:
- return nil, nil, nil, false
- }
-}
-
-// validatePushability checks if the scan/expand/filter/group combination
-// can be pushed entirely to SQL.
-func validatePushability(scan *ScanNodes, expand *ExpandRelationship, filter *FilterWhere, groupItems []ReturnItem) bool {
- if expand.MinHops != 1 || expand.MaxHops != 1 {
- return false
- }
- if len(expand.EdgeTypes) == 0 {
- return false
- }
- if len(scan.Props) > 0 || len(expand.ToProps) > 0 {
- return false
- }
-
- for _, gi := range groupItems {
- if gi.Property == "" {
- return false
- }
- if _, ok := sqlPushableColumns[gi.Property]; !ok {
- return false
- }
- }
-
- if filter != nil {
- for _, c := range filter.Conditions {
- if _, ok := sqlPushableColumns[c.Property]; !ok {
- return false
- }
- switch c.Operator {
- case "=", "CONTAINS", "STARTS WITH":
- // OK
- default:
- return false
- }
- }
- }
- return true
-}
-
-// aggregateSQLContext holds pre-computed SQL fragments for aggregate queries.
-type aggregateSQLContext struct {
- srcCol, tgtCol string
- selectParts []string
- groupByParts []string
- srcAlias, tgtAlias string
-}
-
-// newAggregateSQLContext pre-computes direction-dependent columns and
-// SELECT/GROUP BY parts for the aggregate SQL query.
-func newAggregateSQLContext(scan *ScanNodes, expand *ExpandRelationship, groupItems []ReturnItem) aggregateSQLContext {
- dir := expand.Direction
- if dir == "" {
- dir = "outbound"
- }
- var srcCol, tgtCol string
- if dir == "outbound" {
- srcCol, tgtCol = "source_id", "target_id"
- } else {
- srcCol, tgtCol = "target_id", "source_id"
- }
-
- srcAlias, tgtAlias := "src", "tgt"
- selectParts := make([]string, 0, len(groupItems)+1)
- groupByParts := make([]string, 0, len(groupItems))
- for _, gi := range groupItems {
- col := sqlPushableColumns[gi.Property]
- alias := tgtAlias
- if gi.Variable == scan.Variable {
- alias = srcAlias
- }
- selectParts = append(selectParts, alias+"."+col)
- groupByParts = append(groupByParts, alias+"."+col)
- }
- selectParts = append(selectParts, "COUNT(*) as cnt")
-
- return aggregateSQLContext{
- srcCol: srcCol, tgtCol: tgtCol,
- selectParts: selectParts, groupByParts: groupByParts,
- srcAlias: srcAlias, tgtAlias: tgtAlias,
- }
-}
-
-// executeAggregateForProject runs the aggregate SQL query for a single project.
-func (e *Executor) executeAggregateForProject(
- project string, ctx *aggregateSQLContext,
- scan *ScanNodes, expand *ExpandRelationship, filter *FilterWhere,
- groupItems []ReturnItem, countCol string,
-) []map[string]any {
- query, args := buildProjectAggregateSQL(project, ctx, scan, expand, filter)
-
- rows, qErr := e.Store.DB().QueryContext(e.ctx, query, args...)
- if qErr != nil {
- return nil
- }
- defer rows.Close()
-
- var result []map[string]any
- for rows.Next() {
- vals := make([]any, len(groupItems)+1)
- ptrs := make([]any, len(groupItems)+1)
- for i := range vals {
- ptrs[i] = &vals[i]
- }
- if sErr := rows.Scan(ptrs...); sErr != nil {
- continue
- }
- row := make(map[string]any)
- for i, gi := range groupItems {
- col := gi.Variable + "." + gi.Property
- if gi.Alias != "" {
- col = gi.Alias
- }
- if b, ok := vals[i].([]byte); ok {
- row[col] = string(b)
- } else {
- row[col] = vals[i]
- }
- }
- switch v := vals[len(vals)-1].(type) {
- case int64:
- row[countCol] = int(v)
- default:
- row[countCol] = v
- }
- result = append(result, row)
- }
- _ = rows.Err()
- return result
-}
-
-// buildProjectAggregateSQL constructs the SQL query and args for one project.
-func buildProjectAggregateSQL(
- project string, ctx *aggregateSQLContext,
- scan *ScanNodes, expand *ExpandRelationship, filter *FilterWhere,
-) (query string, args []any) {
- var sb strings.Builder
- args = make([]any, 0, 10)
-
- sb.WriteString("SELECT ")
- sb.WriteString(strings.Join(ctx.selectParts, ", "))
- sb.WriteString(" FROM edges e")
- fmt.Fprintf(&sb, " JOIN nodes %s ON %s.id = e.%s", ctx.srcAlias, ctx.srcAlias, ctx.srcCol)
- fmt.Fprintf(&sb, " JOIN nodes %s ON %s.id = e.%s", ctx.tgtAlias, ctx.tgtAlias, ctx.tgtCol)
- sb.WriteString(" WHERE e.project = ?")
- args = append(args, project)
-
- // Edge type filter
- typePlaceholders := make([]string, len(expand.EdgeTypes))
- for i, et := range expand.EdgeTypes {
- typePlaceholders[i] = "?"
- args = append(args, et)
- }
- sb.WriteString(" AND e.type IN (" + strings.Join(typePlaceholders, ",") + ")")
-
- // Label filters
- if scan.Label != "" {
- fmt.Fprintf(&sb, " AND %s.label = ?", ctx.srcAlias)
- args = append(args, scan.Label)
- }
- if expand.ToLabel != "" {
- fmt.Fprintf(&sb, " AND %s.label = ?", ctx.tgtAlias)
- args = append(args, expand.ToLabel)
- }
-
- // Push-down WHERE conditions
- if filter != nil {
- appendFilterConditions(&sb, &args, filter, scan.Variable, ctx.srcAlias, ctx.tgtAlias)
- }
-
- sb.WriteString(" GROUP BY " + strings.Join(ctx.groupByParts, ", "))
- query = sb.String()
- return
-}
-
-// appendFilterConditions appends WHERE conditions to the SQL query builder.
-func appendFilterConditions(sb *strings.Builder, args *[]any, filter *FilterWhere, scanVar, srcAlias, tgtAlias string) {
- for _, c := range filter.Conditions {
- col := sqlPushableColumns[c.Property]
- alias := tgtAlias
- if c.Variable == scanVar {
- alias = srcAlias
- }
- switch c.Operator {
- case "=":
- fmt.Fprintf(sb, " AND %s.%s = ?", alias, col)
- *args = append(*args, c.Value)
- case "CONTAINS":
- fmt.Fprintf(sb, " AND %s.%s LIKE ?", alias, col)
- *args = append(*args, "%"+c.Value+"%")
- case "STARTS WITH":
- fmt.Fprintf(sb, " AND %s.%s LIKE ?", alias, col)
- *args = append(*args, c.Value+"%")
- }
- }
-}
-
-//nolint:gocognit // step dispatch with fusion/push-down is inherently branchy
-func (e *Executor) executeStepsForProject(project string, steps []PlanStep) ([]binding, error) {
- var bindings []binding
-
- for i, step := range steps {
- var err error
- switch s := step.(type) {
- case *ScanNodes:
- // Fast path: ScanNodes followed by ExpandRelationship can be fused
- // into a single SQL JOIN, avoiding N+1 queries.
- if i+1 < len(steps) {
- if expand, ok := steps[i+1].(*ExpandRelationship); ok && canFuseJoin(s, expand) {
- bindings, err = e.execJoinScanExpand(project, s, expand)
- if err != nil {
- return nil, err
- }
- // Mark next step as consumed by incrementing i via a skip flag
- // We'll handle this below.
- steps[i+1] = &fusedExpandMarker{}
- break
- }
- }
-
- // Check if the next step is a FilterWhere that can be pushed down
- var pushDown *FilterWhere
- if i+1 < len(steps) {
- if fw, ok := steps[i+1].(*FilterWhere); ok {
- pushDown = fw
- }
- }
- bindings, err = e.execScan(project, s, pushDown)
- case *ExpandRelationship:
- bindings, err = e.execExpand(s, bindings)
- case *fusedExpandMarker:
- continue // already handled by JOIN fusion
- case *FilterWhere:
- // Skip if this was already consumed by push-down
- if i > 0 {
- if _, wasScan := steps[i-1].(*ScanNodes); wasScan {
- continue // already handled in execScan
- }
- }
- bindings, err = e.execFilter(s, bindings)
- default:
- return nil, fmt.Errorf("unknown step type: %T", step)
- }
- if err != nil {
- return nil, err
- }
- isLastStep := i == len(steps)-1
- _, isExpand := step.(*ExpandRelationship)
- if isLastStep || isExpand {
- stepCap := e.expandLimit
- if stepCap <= 0 {
- stepCap = e.maxRows() * 2
- }
- if len(bindings) > stepCap {
- bindings = bindings[:stepCap]
- }
- }
- }
-
- return bindings, nil
-}
-
-// fusedExpandMarker is a placeholder step marking an ExpandRelationship
-// that was already handled by JOIN fusion with the preceding ScanNodes.
-type fusedExpandMarker struct{}
-
-func (*fusedExpandMarker) stepType() string { return "fused" }
-
-// canFuseJoin returns true if a ScanNodes + ExpandRelationship pair can be
-// replaced by a single SQL JOIN. Requirements: fixed-length (1 hop), known
-// edge types, standard direction, no inline property filters on source.
-func canFuseJoin(scan *ScanNodes, expand *ExpandRelationship) bool {
- if expand.MinHops != 1 || expand.MaxHops != 1 {
- return false // variable-length paths need BFS
- }
- if len(expand.EdgeTypes) == 0 {
- return false // untyped edges: keep generic path
- }
- if len(scan.Props) > 0 {
- return false // inline property filters on source not supported in JOIN
- }
- if expand.Direction != "outbound" && expand.Direction != "inbound" && expand.Direction != "" {
- return false
- }
- return true
-}
-
-// execJoinScanExpand executes a fused ScanNodes→ExpandRelationship step using
-// a single SQL JOIN, avoiding N+1 queries.
-func (e *Executor) execJoinScanExpand(project string, scan *ScanNodes, expand *ExpandRelationship) ([]binding, error) {
- // Build type filter: type IN (?, ?, ...)
- typePlaceholders := make([]string, len(expand.EdgeTypes))
- args := make([]any, 0, len(expand.EdgeTypes)+2)
- args = append(args, project)
- for i, et := range expand.EdgeTypes {
- typePlaceholders[i] = "?"
- args = append(args, et)
- }
- typeFilter := strings.Join(typePlaceholders, ",")
-
- // Determine join direction
- var srcCol, tgtCol string
- dir := expand.Direction
- if dir == "" {
- dir = "outbound"
- }
- if dir == "outbound" {
- srcCol, tgtCol = "source_id", "target_id"
- } else {
- srcCol, tgtCol = "target_id", "source_id"
- }
-
- // Build label filters
- var srcLabelClause, tgtLabelClause string
- if scan.Label != "" {
- srcLabelClause = " AND src.label = ?"
- args = append(args, scan.Label)
- }
- if expand.ToLabel != "" {
- tgtLabelClause = " AND tgt.label = ?"
- args = append(args, expand.ToLabel)
- }
-
- query := fmt.Sprintf(`
- SELECT
- src.id, src.project, src.label, src.name, src.qualified_name, src.file_path, src.start_line, src.end_line, src.properties,
- tgt.id, tgt.project, tgt.label, tgt.name, tgt.qualified_name, tgt.file_path, tgt.start_line, tgt.end_line, tgt.properties,
- e.id, e.project, e.source_id, e.target_id, e.type, e.properties
- FROM edges e
- JOIN nodes src ON src.id = e.%s
- JOIN nodes tgt ON tgt.id = e.%s
- WHERE e.project = ? AND e.type IN (%s)%s%s
- LIMIT ?`,
- srcCol, tgtCol, typeFilter, srcLabelClause, tgtLabelClause)
-
- sqlLimit := e.expandLimit
- if sqlLimit <= 0 {
- sqlLimit = e.maxRows() * 2
- }
- args = append(args, sqlLimit)
-
- rows, err := e.Store.DB().QueryContext(e.ctx, query, args...)
- if err != nil {
- return nil, fmt.Errorf("join scan+expand: %w", err)
- }
- defer rows.Close()
-
- var bindings []binding
- for rows.Next() {
- var srcN, tgtN store.Node
- var srcProps, tgtProps string
- var edge store.Edge
- var edgeProps string
-
- if err := rows.Scan(
- &srcN.ID, &srcN.Project, &srcN.Label, &srcN.Name, &srcN.QualifiedName, &srcN.FilePath, &srcN.StartLine, &srcN.EndLine, &srcProps,
- &tgtN.ID, &tgtN.Project, &tgtN.Label, &tgtN.Name, &tgtN.QualifiedName, &tgtN.FilePath, &tgtN.StartLine, &tgtN.EndLine, &tgtProps,
- &edge.ID, &edge.Project, &edge.SourceID, &edge.TargetID, &edge.Type, &edgeProps,
- ); err != nil {
- return nil, err
- }
- srcN.Properties = store.UnmarshalProps(srcProps)
- tgtN.Properties = store.UnmarshalProps(tgtProps)
- edge.Properties = store.UnmarshalProps(edgeProps)
-
- // Apply target inline property filters
- if len(expand.ToProps) > 0 && !nodeMatchesProps(&tgtN, expand.ToProps) {
- continue
- }
-
- b := newBinding()
- if scan.Variable != "" {
- b.nodes[scan.Variable] = &srcN
- }
- if expand.ToVar != "" {
- b.nodes[expand.ToVar] = &tgtN
- }
- if expand.RelVar != "" {
- b.edges[expand.RelVar] = &edge
- }
- bindings = append(bindings, b)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- return bindings, nil
-}
-
-// sqlPushableColumns are node properties that map directly to SQL columns.
-var sqlPushableColumns = map[string]string{
- "name": "name",
- "qualified_name": "qualified_name",
- "label": "label",
- "file_path": "file_path",
-}
-
-func (e *Executor) execScan(project string, s *ScanNodes, pushDown *FilterWhere) ([]binding, error) {
- // Build dynamic SQL query with optional push-down conditions
- query := `SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties FROM nodes WHERE project=?`
- args := []any{project}
-
- if s.Label != "" {
- query += " AND label=?"
- args = append(args, s.Label)
- }
-
- // Push down WHERE conditions into SQL where possible
- var unpushedConditions []Condition
- if pushDown != nil {
- for _, c := range pushDown.Conditions {
- col, canPush := sqlPushableColumns[c.Property]
- if !canPush {
- unpushedConditions = append(unpushedConditions, c)
- continue
- }
- switch c.Operator {
- case "=":
- query += " AND " + col + "=?"
- args = append(args, c.Value)
- case "CONTAINS":
- query += " AND " + col + " LIKE ?"
- args = append(args, "%"+c.Value+"%")
- case "STARTS WITH":
- query += " AND " + col + " LIKE ?"
- args = append(args, c.Value+"%")
- default:
- // =~, numeric comparisons: can't push to SQL easily
- unpushedConditions = append(unpushedConditions, c)
- }
- }
- }
-
- rows, err := e.Store.DB().QueryContext(e.ctx, query, args...)
- if err != nil {
- return nil, fmt.Errorf("scan nodes: %w", err)
- }
- defer rows.Close()
-
- var nodes []*store.Node
- for rows.Next() {
- n, scanErr := scanNodeFromRows(rows)
- if scanErr != nil {
- return nil, scanErr
- }
- nodes = append(nodes, n)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- // Apply inline property filters
- if len(s.Props) > 0 {
- nodes = filterNodesByProps(nodes, s.Props)
- }
-
- bindings := make([]binding, 0, len(nodes))
- for _, n := range nodes {
- // Apply unpushed conditions in Go
- if len(unpushedConditions) > 0 {
- b := newBinding()
- b.nodes[s.Variable] = n
- match, evalErr := e.evaluateConditions(b, unpushedConditions, "AND")
- if evalErr != nil {
- return nil, evalErr
- }
- if !match {
- continue
- }
- }
- b := newBinding()
- if s.Variable != "" {
- b.nodes[s.Variable] = n
- }
- bindings = append(bindings, b)
- }
- return bindings, nil
-}
-
-// scanNodeFromRows scans a single node from sql.Rows.
-func scanNodeFromRows(rows *sql.Rows) (*store.Node, error) {
- var n store.Node
- var props string
- if err := rows.Scan(&n.ID, &n.Project, &n.Label, &n.Name, &n.QualifiedName, &n.FilePath, &n.StartLine, &n.EndLine, &props); err != nil {
- return nil, err
- }
- n.Properties = store.UnmarshalProps(props)
- return &n, nil
-}
-
-func (e *Executor) execExpand(s *ExpandRelationship, bindings []binding) ([]binding, error) {
- if len(bindings) == 0 {
- return nil, nil
- }
-
- isVariableLength := s.MinHops != 1 || s.MaxHops != 1
-
- if isVariableLength {
- // Variable-length: use BFS per binding (already uses recursive CTE)
- result := make([]binding, 0, len(bindings))
- for _, b := range bindings {
- fromNode, ok := b.nodes[s.FromVar]
- if !ok {
- continue
- }
- expanded, err := e.expandVariableLength(b, fromNode, s)
- if err != nil {
- return nil, err
- }
- result = append(result, expanded...)
- if len(result) > e.maxRows()*2 {
- result = result[:e.maxRows()*2]
- break
- }
- }
- return result, nil
- }
-
- // Fixed-length (1 hop): batch all source IDs, 2 queries total
- return e.expandFixedLengthBatch(s, bindings)
-}
-
-// expandFixedLengthBatch performs fixed-length (1 hop) expansion for all bindings
-// in just 2 SQL queries: one for edges, one for target nodes.
-func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []binding) ([]binding, error) {
- sourceIDs := collectSourceIDs(s.FromVar, bindings)
- if len(sourceIDs) == 0 {
- return nil, nil
- }
-
- direction := s.Direction
- if direction == "" {
- direction = "outbound"
- }
-
- edgesByNode, err := e.fetchEdgesForDirection(sourceIDs, s.EdgeTypes, direction)
- if err != nil {
- return nil, err
- }
-
- nodeMap, err := e.Store.FindNodesByIDs(collectTargetIDs(edgesByNode, direction))
- if err != nil {
- return nil, err
- }
-
- expandCap := e.expandLimit
- if expandCap <= 0 {
- expandCap = e.maxRows() * 2
- }
- return buildExpandedBindings(bindings, s, edgesByNode, nodeMap, direction, expandCap), nil
-}
-
-// collectSourceIDs extracts unique node IDs from bindings for the given variable.
-func collectSourceIDs(fromVar string, bindings []binding) []int64 {
- sourceIDs := make([]int64, 0, len(bindings))
- idSeen := make(map[int64]bool, len(bindings))
- for _, b := range bindings {
- fromNode, ok := b.nodes[fromVar]
- if !ok {
- continue
- }
- if !idSeen[fromNode.ID] {
- idSeen[fromNode.ID] = true
- sourceIDs = append(sourceIDs, fromNode.ID)
- }
- }
- return sourceIDs
-}
-
-// fetchEdgesForDirection fetches edges for the given source IDs and direction.
-func (e *Executor) fetchEdgesForDirection(sourceIDs []int64, edgeTypes []string, direction string) (map[int64][]*store.Edge, error) {
- switch direction {
- case "inbound":
- return e.Store.FindEdgesByTargetIDs(sourceIDs, edgeTypes)
- case "any":
- outEdges, err := e.Store.FindEdgesBySourceIDs(sourceIDs, edgeTypes)
- if err != nil {
- return nil, err
- }
- inEdges, err := e.Store.FindEdgesByTargetIDs(sourceIDs, edgeTypes)
- if err != nil {
- return nil, err
- }
- for id, edges := range inEdges {
- outEdges[id] = append(outEdges[id], edges...)
- }
- return outEdges, nil
- default: // "outbound" or unspecified
- return e.Store.FindEdgesBySourceIDs(sourceIDs, edgeTypes)
- }
-}
-
-// collectTargetIDs extracts all target node IDs from edge batches.
-func collectTargetIDs(edgesByNode map[int64][]*store.Edge, direction string) []int64 {
- targetIDSet := make(map[int64]bool)
- for _, edges := range edgesByNode {
- for _, edge := range edges {
- if direction == "any" {
- targetIDSet[edge.SourceID] = true
- targetIDSet[edge.TargetID] = true
- } else {
- targetIDSet[edgeTargetID(edge, 0, direction)] = true
- }
- }
- }
- targetIDs := make([]int64, 0, len(targetIDSet))
- for id := range targetIDSet {
- targetIDs = append(targetIDs, id)
- }
- return targetIDs
-}
-
-// buildExpandedBindings creates result bindings by matching edges to target nodes.
-func buildExpandedBindings(bindings []binding, s *ExpandRelationship, edgesByNode map[int64][]*store.Edge, nodeMap map[int64]*store.Node, direction string, maxRows int) []binding {
- result := make([]binding, 0, len(bindings))
- for _, b := range bindings {
- fromNode, ok := b.nodes[s.FromVar]
- if !ok {
- continue
- }
- edges := edgesByNode[fromNode.ID]
- seen := make(map[int64]bool)
-
- for _, edge := range edges {
- targetID := edgeTargetID(edge, fromNode.ID, direction)
- if seen[targetID] {
- continue
- }
- seen[targetID] = true
-
- node, exists := nodeMap[targetID]
- if !exists || (s.ToLabel != "" && node.Label != s.ToLabel) {
- continue
- }
- if len(s.ToProps) > 0 && !nodeMatchesProps(node, s.ToProps) {
- continue
- }
- newB := copyBinding(b)
- if s.ToVar != "" {
- newB.nodes[s.ToVar] = node
- }
- if s.RelVar != "" {
- newB.edges[s.RelVar] = edge
- }
- result = append(result, newB)
- }
-
- if len(result) > maxRows*2 {
- result = result[:maxRows*2]
- break
- }
- }
- return result
-}
-
-func (e *Executor) expandVariableLength(b binding, fromNode *store.Node, s *ExpandRelationship) ([]binding, error) {
- maxDepth := s.MaxHops
- if maxDepth == 0 {
- maxDepth = 10 // cap unbounded at 10
- }
-
- direction := s.Direction
- if direction == "" {
- direction = "outbound"
- }
-
- edgeTypes := s.EdgeTypes
- if len(edgeTypes) == 0 {
- edgeTypes = []string{"CALLS"} // default
- }
-
- bfsResult, err := e.Store.BFS(fromNode.ID, direction, edgeTypes, maxDepth, e.maxRows())
- if err != nil {
- return nil, fmt.Errorf("bfs: %w", err)
- }
-
- result := make([]binding, 0, len(bfsResult.Visited))
- for _, nh := range bfsResult.Visited {
- if nh.Hop < s.MinHops {
- continue
- }
- if s.MaxHops > 0 && nh.Hop > s.MaxHops {
- continue
- }
- if s.ToLabel != "" && nh.Node.Label != s.ToLabel {
- continue
- }
- if len(s.ToProps) > 0 && !nodeMatchesProps(nh.Node, s.ToProps) {
- continue
- }
- newB := copyBinding(b)
- if s.ToVar != "" {
- newB.nodes[s.ToVar] = nh.Node
- }
- // Note: variable-length BFS doesn't bind individual edges
- result = append(result, newB)
- }
- return result, nil
-}
-
-// edgeTargetID returns the ID of the node on the "other end" of the edge relative to nodeID.
-func edgeTargetID(edge *store.Edge, nodeID int64, direction string) int64 {
- switch direction {
- case "inbound":
- return edge.SourceID
- case "any":
- if edge.SourceID == nodeID {
- return edge.TargetID
- }
- return edge.SourceID
- default:
- return edge.TargetID
- }
-}
-
-func (e *Executor) execFilter(s *FilterWhere, bindings []binding) ([]binding, error) {
- var result []binding
- for _, b := range bindings {
- match, err := e.evaluateConditions(b, s.Conditions, s.Operator)
- if err != nil {
- return nil, err
- }
- if match {
- result = append(result, b)
- }
- }
- return result, nil
-}
-
-func (e *Executor) evaluateConditions(b binding, conditions []Condition, op string) (bool, error) {
- if op == "OR" {
- for _, c := range conditions {
- ok, err := e.evaluateCondition(b, c)
- if err != nil {
- return false, err
- }
- if ok {
- return true, nil
- }
- }
- return false, nil
- }
- // AND (default)
- for _, c := range conditions {
- ok, err := e.evaluateCondition(b, c)
- if err != nil {
- return false, err
- }
- if !ok {
- return false, nil
- }
- }
- return true, nil
-}
-
-// compiledRegex returns a compiled regex for the pattern, using a cache
-// to avoid recompiling the same pattern on every binding.
-func (e *Executor) compiledRegex(pattern string) (*regexp.Regexp, error) {
- if e.regexCache == nil {
- e.regexCache = make(map[string]*regexp.Regexp)
- }
- if re, ok := e.regexCache[pattern]; ok {
- return re, nil
- }
- re, err := regexp.Compile(pattern)
- if err != nil {
- return nil, err
- }
- e.regexCache[pattern] = re
- return re, nil
-}
-
-func (e *Executor) evaluateCondition(b binding, c Condition) (bool, error) {
- // Try node first, then edge
- var actual any
- if node, ok := b.nodes[c.Variable]; ok {
- actual = getNodeProperty(node, c.Property)
- } else if edge, ok := b.edges[c.Variable]; ok {
- actual = getEdgeProperty(edge, c.Property)
- } else {
- return false, nil
- }
-
- switch c.Operator {
- case "=":
- return fmt.Sprintf("%v", actual) == c.Value, nil
- case "=~":
- s, ok := actual.(string)
- if !ok {
- return false, nil
- }
- re, err := e.compiledRegex(c.Value)
- if err != nil {
- return false, fmt.Errorf("regex %q: %w", c.Value, err)
- }
- return re.MatchString(s), nil
- case "CONTAINS":
- s, ok := actual.(string)
- if !ok {
- return false, nil
- }
- return strings.Contains(s, c.Value), nil
- case "STARTS WITH":
- s, ok := actual.(string)
- if !ok {
- return false, nil
- }
- return strings.HasPrefix(s, c.Value), nil
- case ">", "<", ">=", "<=":
- return compareNumeric(actual, c.Value, c.Operator)
- default:
- return false, fmt.Errorf("unsupported operator: %s", c.Operator)
- }
-}
-
-func compareNumeric(actual any, expected, op string) (bool, error) {
- expectedNum, err := strconv.ParseFloat(expected, 64)
- if err != nil {
- return false, fmt.Errorf("invalid numeric value %q: %w", expected, err)
- }
- var actualNum float64
- switch v := actual.(type) {
- case int:
- actualNum = float64(v)
- case int64:
- actualNum = float64(v)
- case float64:
- actualNum = v
- case string:
- n, parseErr := strconv.ParseFloat(v, 64)
- if parseErr != nil {
- return false, fmt.Errorf("cannot compare %q as number: %w", v, parseErr)
- }
- actualNum = n
- default:
- return false, nil
- }
-
- switch op {
- case ">":
- return actualNum > expectedNum, nil
- case "<":
- return actualNum < expectedNum, nil
- case ">=":
- return actualNum >= expectedNum, nil
- case "<=":
- return actualNum <= expectedNum, nil
- default:
- return false, nil
- }
-}
-
-func getNodeProperty(n *store.Node, prop string) any {
- switch prop {
- case "name":
- return n.Name
- case "qualified_name":
- return n.QualifiedName
- case "label":
- return n.Label
- case "file_path":
- return n.FilePath
- case "start_line":
- return n.StartLine
- case "end_line":
- return n.EndLine
- case "id":
- return n.ID
- case "project":
- return n.Project
- default:
- if n.Properties != nil {
- if v, ok := n.Properties[prop]; ok {
- return v
- }
- }
- return nil
- }
-}
-
-// getEdgeProperty returns a property value from an edge.
-func getEdgeProperty(edge *store.Edge, prop string) any {
- switch prop {
- case "type":
- return edge.Type
- case "id":
- return edge.ID
- case "source_id":
- return edge.SourceID
- case "target_id":
- return edge.TargetID
- default:
- if edge.Properties != nil {
- if v, ok := edge.Properties[prop]; ok {
- return v
- }
- }
- return nil
- }
-}
-
-func (e *Executor) projectResults(bindings []binding, ret *ReturnClause) (*Result, error) {
- if ret == nil {
- return e.defaultProjection(bindings)
- }
-
- // Check if we have a COUNT aggregation
- hasCount := false
- for _, item := range ret.Items {
- if item.Func == "COUNT" {
- hasCount = true
- break
- }
- }
-
- if hasCount {
- return e.aggregateResults(bindings, ret)
- }
-
- return e.simpleProjection(bindings, ret)
-}
-
-func (e *Executor) defaultProjection(bindings []binding) (*Result, error) {
- if len(bindings) == 0 {
- return &Result{Columns: []string{}, Rows: []map[string]any{}}, nil
- }
-
- // Collect all variable names from nodes and edges
- varSet := make(map[string]bool)
- edgeVarSet := make(map[string]bool)
- for _, b := range bindings {
- for k := range b.nodes {
- varSet[k] = true
- }
- for k := range b.edges {
- edgeVarSet[k] = true
- }
- }
- cols := make([]string, 0, len(varSet)*3+len(edgeVarSet))
- for k := range varSet {
- cols = append(cols, k+".name", k+".qualified_name", k+".label")
- }
- for k := range edgeVarSet {
- cols = append(cols, k+".type")
- }
- sort.Strings(cols)
-
- rows := make([]map[string]any, 0, len(bindings))
- for _, b := range bindings {
- row := make(map[string]any)
- for varName, node := range b.nodes {
- row[varName+".name"] = node.Name
- row[varName+".qualified_name"] = node.QualifiedName
- row[varName+".label"] = node.Label
- }
- for varName, edge := range b.edges {
- row[varName+".type"] = edge.Type
- }
- rows = append(rows, row)
- }
-
- if len(rows) > e.maxRows() {
- rows = rows[:e.maxRows()]
- }
-
- return &Result{Columns: cols, Rows: rows}, nil
-}
-
-func (e *Executor) simpleProjection(bindings []binding, ret *ReturnClause) (*Result, error) {
- cols := buildColumnNames(ret.Items)
-
- seen := make(map[string]bool)
- rows := make([]map[string]any, 0, len(bindings))
- for _, b := range bindings {
- row := buildProjectionRow(b, ret.Items, cols)
-
- // DISTINCT check
- if ret.Distinct {
- key := fmt.Sprintf("%v", row)
- if seen[key] {
- continue
- }
- seen[key] = true
- }
-
- rows = append(rows, row)
- }
-
- // ORDER BY
- if ret.OrderBy != "" {
- orderCol := resolveOrderColumn(ret.OrderBy, ret.Items, cols)
- sortRows(rows, orderCol, ret.OrderDir)
- }
-
- // LIMIT
- rows = applyLimit(rows, ret.Limit, e.maxRows())
-
- return &Result{Columns: cols, Rows: rows}, nil
-}
-
-// buildColumnNames builds column names from return items.
-func buildColumnNames(items []ReturnItem) []string {
- cols := make([]string, 0, len(items))
- for _, item := range items {
- col := item.Variable
- if item.Property != "" {
- col = item.Variable + "." + item.Property
- }
- if item.Alias != "" {
- col = item.Alias
- }
- cols = append(cols, col)
- }
- return cols
-}
-
-// buildProjectionRow builds a single result row from a binding.
-func buildProjectionRow(b binding, items []ReturnItem, cols []string) map[string]any {
- row := make(map[string]any)
- for i, item := range items {
- row[cols[i]] = resolveItemValue(b, item)
- }
- return row
-}
-
-// resolveItemValue resolves a return item value from a binding (node or edge).
-func resolveItemValue(b binding, item ReturnItem) any {
- if node, ok := b.nodes[item.Variable]; ok {
- return resolveNodeItemValue(node, item.Property)
- }
- if edge, ok := b.edges[item.Variable]; ok {
- return resolveEdgeItemValue(edge, item.Property)
- }
- return nil
-}
-
-// resolveNodeItemValue resolves a node return item: full node map or single property.
-func resolveNodeItemValue(node *store.Node, property string) any {
- if property == "" {
- return map[string]any{
- "name": node.Name,
- "qualified_name": node.QualifiedName,
- "label": node.Label,
- "file_path": node.FilePath,
- "start_line": node.StartLine,
- "end_line": node.EndLine,
- }
- }
- return getNodeProperty(node, property)
-}
-
-// resolveEdgeItemValue resolves an edge return item: full edge map or single property.
-func resolveEdgeItemValue(edge *store.Edge, property string) any {
- if property == "" {
- return map[string]any{
- "type": edge.Type,
- "source_id": edge.SourceID,
- "target_id": edge.TargetID,
- }
- }
- return getEdgeProperty(edge, property)
-}
-
-// resolveOrderColumn maps an ORDER BY field to the actual column name.
-func resolveOrderColumn(orderBy string, items []ReturnItem, cols []string) string {
- // 1. Try alias match
- for i, item := range items {
- if item.Alias == orderBy {
- return cols[i]
- }
- }
- // 2. Try matching aggregate expression (e.g. "COUNT(r)")
- for i, item := range items {
- if item.Func == "COUNT" {
- expr := "COUNT(" + item.Variable + ")"
- if orderBy == expr {
- return cols[i]
- }
- }
- }
- // 3. Try matching variable.property to column name
- for i, item := range items {
- varProp := item.Variable
- if item.Property != "" {
- varProp += "." + item.Property
- }
- if orderBy == varProp {
- return cols[i]
- }
- }
- return orderBy
-}
-
-// applyLimit caps result rows. Explicit LIMIT values from the Cypher query are
-// respected; when no LIMIT is specified (limit <= 0), maxRows is used as default.
-func applyLimit(rows []map[string]any, limit, maxRows int) []map[string]any {
- if limit <= 0 {
- limit = maxRows
- }
- if len(rows) > limit {
- return rows[:limit]
- }
- return rows
-}
-
-func (e *Executor) aggregateResults(bindings []binding, ret *ReturnClause) (*Result, error) {
- groupItems, countItem := splitAggregateItems(ret.Items)
- groups, order := buildGroups(bindings, groupItems)
-
- // Build columns
- cols := buildColumnNames(ret.Items)
-
- // Build result rows
- countCol := countItem.Alias
- if countCol == "" {
- countCol = "COUNT(" + countItem.Variable + ")"
- }
-
- rows := make([]map[string]any, 0, len(order))
- for _, key := range order {
- g := groups[key]
- row := g.row
- row[countCol] = g.count
- rows = append(rows, row)
- }
-
- // ORDER BY
- if ret.OrderBy != "" {
- orderCol := resolveOrderColumn(ret.OrderBy, ret.Items, cols)
- sortRows(rows, orderCol, ret.OrderDir)
- }
-
- // LIMIT
- rows = applyLimit(rows, ret.Limit, e.maxRows())
-
- return &Result{Columns: cols, Rows: rows}, nil
-}
-
-// splitAggregateItems separates return items into group-by items and the COUNT item.
-func splitAggregateItems(items []ReturnItem) (groupItems []ReturnItem, countItem ReturnItem) {
- for _, item := range items {
- if item.Func == "COUNT" {
- countItem = item
- } else {
- groupItems = append(groupItems, item)
- }
- }
- return groupItems, countItem
-}
-
-type groupEntry struct {
- key string
- row map[string]any
- count int
-}
-
-// buildGroups groups bindings by non-COUNT items and counts occurrences.
-func buildGroups(bindings []binding, groupItems []ReturnItem) (groups map[string]*groupEntry, order []string) {
- groups = make(map[string]*groupEntry)
-
- for _, b := range bindings {
- row := make(map[string]any)
- keyParts := make([]string, 0, len(groupItems))
- for _, item := range groupItems {
- col := item.Variable
- if item.Property != "" {
- col = item.Variable + "." + item.Property
- }
- if item.Alias != "" {
- col = item.Alias
- }
- val := resolveItemValue(b, item)
- row[col] = val
- keyParts = append(keyParts, fmt.Sprintf("%v", val))
- }
- key := strings.Join(keyParts, "\x00")
- if g, ok := groups[key]; ok {
- g.count++
- } else {
- groups[key] = &groupEntry{key: key, row: row, count: 1}
- order = append(order, key)
- }
- }
- return groups, order
-}
-
-// sortRows sorts rows by the given column.
-func sortRows(rows []map[string]any, col, dir string) {
- sort.SliceStable(rows, func(i, j int) bool {
- a, b := rows[i][col], rows[j][col]
- cmp := compareValues(a, b)
- if dir == "DESC" {
- return cmp > 0
- }
- return cmp < 0
- })
-}
-
-func compareValues(a, b any) int {
- // Try numeric
- aNum, aOK := toFloat(a)
- bNum, bOK := toFloat(b)
- if aOK && bOK {
- if aNum < bNum {
- return -1
- }
- if aNum > bNum {
- return 1
- }
- return 0
- }
- // Fall back to string
- aStr := fmt.Sprintf("%v", a)
- bStr := fmt.Sprintf("%v", b)
- if aStr < bStr {
- return -1
- }
- if aStr > bStr {
- return 1
- }
- return 0
-}
-
-func toFloat(v any) (float64, bool) {
- switch n := v.(type) {
- case int:
- return float64(n), true
- case int64:
- return float64(n), true
- case float64:
- return n, true
- default:
- return 0, false
- }
-}
-
-// copyBinding makes a shallow copy of a binding.
-func copyBinding(b binding) binding {
- c := newBinding()
- for k, v := range b.nodes {
- c.nodes[k] = v
- }
- for k, v := range b.edges {
- c.edges[k] = v
- }
- return c
-}
-
-// filterNodesByProps filters nodes by inline property key-value pairs.
-func filterNodesByProps(nodes []*store.Node, props map[string]string) []*store.Node {
- var filtered []*store.Node
- for _, n := range nodes {
- if nodeMatchesProps(n, props) {
- filtered = append(filtered, n)
- }
- }
- return filtered
-}
-
-// nodeMatchesProps checks if a node matches all given property filters.
-func nodeMatchesProps(n *store.Node, props map[string]string) bool {
- for key, val := range props {
- actual := getNodeProperty(n, key)
- if fmt.Sprintf("%v", actual) != val {
- return false
- }
- }
- return true
-}
diff --git a/internal/cypher/lexer.go b/internal/cypher/lexer.go
deleted file mode 100644
index de171862e..000000000
--- a/internal/cypher/lexer.go
+++ /dev/null
@@ -1,289 +0,0 @@
-package cypher
-
-import (
- "fmt"
- "strings"
- "unicode"
-)
-
-// TokenType classifies a lexer token.
-type TokenType int
-
-const (
- // Keywords
- TokMatch TokenType = iota // MATCH
- TokWhere // WHERE
- TokReturn // RETURN
- TokOrder // ORDER
- TokBy // BY
- TokLimit // LIMIT
- TokAnd // AND
- TokOr // OR
- TokAs // AS
- TokDistinct // DISTINCT
- TokCount // COUNT
- TokContains // CONTAINS
- TokStarts // STARTS
- TokWith // WITH
- TokNot // NOT
- TokAsc // ASC
- TokDesc // DESC
-
- // Symbols
- TokLParen // (
- TokRParen // )
- TokLBracket // [
- TokRBracket // ]
- TokDash // -
- TokGT // >
- TokLT // <
- TokColon // :
- TokDot // .
- TokLBrace // {
- TokRBrace // }
- TokStar // *
- TokComma // ,
- TokEQ // =
- TokRegex // =~
- TokGTE // >=
- TokLTE // <=
- TokPipe // |
- TokDotDot // ..
-
- // Literals
- TokIdent // identifier
- TokString // "..." or '...'
- TokNumber // integer
-
- TokEOF // end of input
-)
-
-// Token is a single lexer token.
-type Token struct {
- Type TokenType
- Value string
- Pos int // byte offset in the input
-}
-
-func (t Token) String() string {
- return fmt.Sprintf("Token(%d, %q, pos=%d)", t.Type, t.Value, t.Pos)
-}
-
-// keywords maps uppercase keyword strings to their token type.
-var keywords = map[string]TokenType{
- "MATCH": TokMatch,
- "WHERE": TokWhere,
- "RETURN": TokReturn,
- "ORDER": TokOrder,
- "BY": TokBy,
- "LIMIT": TokLimit,
- "AND": TokAnd,
- "OR": TokOr,
- "AS": TokAs,
- "DISTINCT": TokDistinct,
- "COUNT": TokCount,
- "CONTAINS": TokContains,
- "STARTS": TokStarts,
- "WITH": TokWith,
- "NOT": TokNot,
- "ASC": TokAsc,
- "DESC": TokDesc,
-}
-
-// singleCharTokens maps single-character symbols to their token type.
-var singleCharTokens = map[byte]TokenType{
- '(': TokLParen,
- ')': TokRParen,
- '[': TokLBracket,
- ']': TokRBracket,
- '{': TokLBrace,
- '}': TokRBrace,
- '*': TokStar,
- ',': TokComma,
- '|': TokPipe,
- ':': TokColon,
- '-': TokDash,
-}
-
-// Lexer tokenizes a Cypher query string.
-type Lexer struct {
- input string
- pos int
- tokens []Token
-}
-
-// Lex tokenizes the input string into a slice of tokens.
-func Lex(input string) ([]Token, error) {
- l := &Lexer{input: input}
- if err := l.tokenize(); err != nil {
- return nil, err
- }
- return l.tokens, nil
-}
-
-func (l *Lexer) tokenize() error {
- for l.pos < len(l.input) {
- ch := l.input[l.pos]
-
- if l.skipWhitespaceAndComments(ch) {
- continue
- }
-
- if err := l.lexNextToken(ch); err != nil {
- return err
- }
- }
-
- l.tokens = append(l.tokens, Token{Type: TokEOF, Value: "", Pos: l.pos})
- return nil
-}
-
-// skipWhitespaceAndComments skips whitespace and // or /* */ comments.
-// Returns true if something was skipped (caller should continue the loop).
-func (l *Lexer) skipWhitespaceAndComments(ch byte) bool {
- if unicode.IsSpace(rune(ch)) {
- l.pos++
- return true
- }
- if ch == '/' && l.pos+1 < len(l.input) && l.input[l.pos+1] == '/' {
- for l.pos < len(l.input) && l.input[l.pos] != '\n' {
- l.pos++
- }
- return true
- }
- if ch == '/' && l.pos+1 < len(l.input) && l.input[l.pos+1] == '*' {
- l.pos += 2
- for l.pos+1 < len(l.input) {
- if l.input[l.pos] == '*' && l.input[l.pos+1] == '/' {
- l.pos += 2
- break
- }
- l.pos++
- }
- return true
- }
- return false
-}
-
-// lexNextToken dispatches a single token starting at l.pos.
-func (l *Lexer) lexNextToken(ch byte) error {
- // Single-character tokens
- if tok, ok := singleCharTokens[ch]; ok {
- l.emit(tok, string(ch))
- l.pos++
- return nil
- }
-
- switch {
- case ch == '.':
- l.lexDot()
- case ch == '>':
- l.lexTwoChar('=', TokGTE, TokGT, ">")
- case ch == '<':
- l.lexTwoChar('=', TokLTE, TokLT, "<")
- case ch == '=':
- l.lexTwoChar('~', TokRegex, TokEQ, "=")
- case ch == '"' || ch == '\'':
- return l.lexString(ch)
- case isDigit(ch):
- l.lexNumber()
- case isIdentStart(ch):
- l.lexIdent()
- default:
- return fmt.Errorf("unexpected char %q at pos %d", string(ch), l.pos)
- }
- return nil
-}
-
-// lexDot handles '.' and '..' tokens.
-func (l *Lexer) lexDot() {
- if l.pos+1 < len(l.input) && l.input[l.pos+1] == '.' {
- l.emit(TokDotDot, "..")
- l.pos += 2
- } else {
- l.emit(TokDot, ".")
- l.pos++
- }
-}
-
-// lexTwoChar handles two-character tokens like >=, <=, =~.
-// If the next char matches second, emit the compound token; otherwise emit the single token.
-func (l *Lexer) lexTwoChar(second byte, compoundTok, singleTok TokenType, singleVal string) {
- if l.pos+1 < len(l.input) && l.input[l.pos+1] == second {
- l.emit(compoundTok, singleVal+string(second))
- l.pos += 2
- } else {
- l.emit(singleTok, singleVal)
- l.pos++
- }
-}
-
-func (l *Lexer) emit(typ TokenType, val string) {
- l.tokens = append(l.tokens, Token{Type: typ, Value: val, Pos: l.pos})
-}
-
-func (l *Lexer) lexString(quote byte) error {
- start := l.pos
- l.pos++ // skip opening quote
- var sb strings.Builder
- for l.pos < len(l.input) {
- ch := l.input[l.pos]
- if ch == '\\' && l.pos+1 < len(l.input) {
- l.pos++
- sb.WriteByte(l.input[l.pos])
- l.pos++
- continue
- }
- if ch == quote {
- l.tokens = append(l.tokens, Token{Type: TokString, Value: sb.String(), Pos: start})
- l.pos++ // skip closing quote
- return nil
- }
- sb.WriteByte(ch)
- l.pos++
- }
- return fmt.Errorf("unterminated string at pos %d", start)
-}
-
-func (l *Lexer) lexNumber() {
- start := l.pos
- for l.pos < len(l.input) && isDigit(l.input[l.pos]) {
- l.pos++
- }
- // Handle decimal point (e.g. 0.9, 3.14) — but not ".." (range operator)
- if l.pos < len(l.input) && l.input[l.pos] == '.' {
- if l.pos+1 < len(l.input) && l.input[l.pos+1] != '.' && isDigit(l.input[l.pos+1]) {
- l.pos++ // consume '.'
- for l.pos < len(l.input) && isDigit(l.input[l.pos]) {
- l.pos++
- }
- }
- }
- l.tokens = append(l.tokens, Token{Type: TokNumber, Value: l.input[start:l.pos], Pos: start})
-}
-
-func (l *Lexer) lexIdent() {
- start := l.pos
- for l.pos < len(l.input) && isIdentPart(l.input[l.pos]) {
- l.pos++
- }
- word := l.input[start:l.pos]
- upper := strings.ToUpper(word)
- if tok, ok := keywords[upper]; ok {
- l.tokens = append(l.tokens, Token{Type: tok, Value: upper, Pos: start})
- } else {
- l.tokens = append(l.tokens, Token{Type: TokIdent, Value: word, Pos: start})
- }
-}
-
-func isDigit(ch byte) bool {
- return ch >= '0' && ch <= '9'
-}
-
-func isIdentStart(ch byte) bool {
- return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'
-}
-
-func isIdentPart(ch byte) bool {
- return isIdentStart(ch) || isDigit(ch)
-}
diff --git a/internal/cypher/parser.go b/internal/cypher/parser.go
deleted file mode 100644
index 184192d81..000000000
--- a/internal/cypher/parser.go
+++ /dev/null
@@ -1,613 +0,0 @@
-package cypher
-
-import (
- "fmt"
- "strconv"
-)
-
-// Parser converts a token stream into an AST.
-type Parser struct {
- tokens []Token
- pos int
-}
-
-// Parse tokenizes and parses a Cypher query string into an AST.
-func Parse(input string) (*Query, error) {
- tokens, err := Lex(input)
- if err != nil {
- return nil, fmt.Errorf("lex: %w", err)
- }
- p := &Parser{tokens: tokens}
- return p.parseQuery()
-}
-
-func (p *Parser) peek() Token {
- if p.pos >= len(p.tokens) {
- return Token{Type: TokEOF}
- }
- return p.tokens[p.pos]
-}
-
-func (p *Parser) advance() Token {
- t := p.peek()
- p.pos++
- return t
-}
-
-func (p *Parser) expect(typ TokenType) error {
- t := p.advance()
- if t.Type != typ {
- return fmt.Errorf("expected token %d, got %d (%q) at pos %d", typ, t.Type, t.Value, t.Pos)
- }
- return nil
-}
-
-func (p *Parser) parseQuery() (*Query, error) {
- q := &Query{}
-
- // MATCH clause (required)
- if p.peek().Type != TokMatch {
- return nil, fmt.Errorf("expected MATCH at pos %d, got %q", p.peek().Pos, p.peek().Value)
- }
- m, err := p.parseMatch()
- if err != nil {
- return nil, err
- }
- q.Match = m
-
- // WHERE clause (optional)
- if p.peek().Type == TokWhere {
- w, err := p.parseWhere()
- if err != nil {
- return nil, err
- }
- q.Where = w
- }
-
- // RETURN clause (optional but common)
- if p.peek().Type == TokReturn {
- r, err := p.parseReturn()
- if err != nil {
- return nil, err
- }
- q.Return = r
- }
-
- return q, nil
-}
-
-func (p *Parser) parseMatch() (*MatchClause, error) {
- if err := p.expect(TokMatch); err != nil {
- return nil, err
- }
- pat, err := p.parsePattern()
- if err != nil {
- return nil, fmt.Errorf("match pattern: %w", err)
- }
- return &MatchClause{Pattern: pat}, nil
-}
-
-func (p *Parser) parsePattern() (*Pattern, error) {
- pat := &Pattern{}
-
- // First element must be a node
- node, err := p.parseNodePattern()
- if err != nil {
- return nil, err
- }
- pat.Elements = append(pat.Elements, node)
-
- // Parse alternating rel-node pairs
- for p.isRelStart() {
- rel, nextNode, err := p.parseRelAndNode()
- if err != nil {
- return nil, err
- }
- pat.Elements = append(pat.Elements, rel, nextNode)
- }
-
- return pat, nil
-}
-
-// isRelStart checks whether the next tokens begin a relationship pattern.
-// Patterns: -[...]-> or <-[...]- or -[...]-
-func (p *Parser) isRelStart() bool {
- t := p.peek()
- return t.Type == TokDash || t.Type == TokLT
-}
-
-func (p *Parser) parseRelAndNode() (*RelPattern, *NodePattern, error) {
- rel := &RelPattern{MinHops: 1, MaxHops: 1}
-
- // Determine direction by looking at leading token
- // Possibilities:
- // -[...]->(node) outbound
- // <-[...]-(node) inbound
- // -[...]-(node) any
-
- leadingArrow := false
- if p.peek().Type == TokLT {
- leadingArrow = true
- p.advance() // consume <
- }
-
- // Expect dash
- if err := p.expect(TokDash); err != nil {
- return nil, nil, fmt.Errorf("expected '-' in relationship: %w", err)
- }
-
- // Optional bracket section [...]
- if p.peek().Type == TokLBracket {
- if err := p.parseRelBracket(rel); err != nil {
- return nil, nil, err
- }
- }
-
- // Expect dash
- if err := p.expect(TokDash); err != nil {
- return nil, nil, fmt.Errorf("expected '-' after relationship: %w", err)
- }
-
- // Check trailing arrow
- trailingArrow := false
- if p.peek().Type == TokGT {
- trailingArrow = true
- p.advance() // consume >
- }
-
- // Determine direction
- switch {
- case !leadingArrow && trailingArrow:
- rel.Direction = "outbound"
- case leadingArrow && !trailingArrow:
- rel.Direction = "inbound"
- default:
- rel.Direction = "any"
- }
-
- // Parse the next node
- node, err := p.parseNodePattern()
- if err != nil {
- return nil, nil, err
- }
-
- return rel, node, nil
-}
-
-func (p *Parser) parseRelBracket(rel *RelPattern) error {
- p.advance() // consume [
-
- // Optional variable name
- if p.peek().Type == TokIdent {
- rel.Variable = p.advance().Value
- }
-
- // Optional :TYPE or :TYPE1|TYPE2
- if p.peek().Type == TokColon {
- p.advance() // consume :
- types, err := p.parseRelTypes()
- if err != nil {
- return err
- }
- rel.Types = types
- }
-
- // Optional *min..max for variable-length
- if p.peek().Type == TokStar {
- p.advance() // consume *
- if err := p.parseHopRange(rel); err != nil {
- return err
- }
- }
-
- // Expect ]
- if err := p.expect(TokRBracket); err != nil {
- return fmt.Errorf("expected ']' to close relationship: %w", err)
- }
-
- return nil
-}
-
-func (p *Parser) parseRelTypes() ([]string, error) {
- var types []string
- t := p.advance()
- if t.Type != TokIdent {
- return nil, fmt.Errorf("expected relationship type name, got %q at pos %d", t.Value, t.Pos)
- }
- types = append(types, t.Value)
-
- // Handle TYPE1|TYPE2
- for p.peek().Type == TokPipe {
- p.advance() // consume |
- t = p.advance()
- if t.Type != TokIdent {
- return nil, fmt.Errorf("expected relationship type after '|', got %q at pos %d", t.Value, t.Pos)
- }
- types = append(types, t.Value)
- }
- return types, nil
-}
-
-func (p *Parser) parseHopRange(rel *RelPattern) error {
- // Possibilities after *:
- // *1..3 min=1, max=3
- // *..3 min=1, max=3
- // *1.. min=1, max=0 (unbounded)
- // *3 min=1, max=3 (shorthand)
- // (empty) min=1, max=0 (unbounded)
-
- switch p.peek().Type {
- case TokNumber:
- n, _ := strconv.Atoi(p.advance().Value)
- if p.peek().Type == TokDotDot {
- // *N..M or *N..
- rel.MinHops = n
- p.advance() // consume ..
- if p.peek().Type == TokNumber {
- m, _ := strconv.Atoi(p.advance().Value)
- rel.MaxHops = m
- } else {
- rel.MaxHops = 0 // unbounded
- }
- } else {
- // *N (shorthand for *1..N)
- rel.MinHops = 1
- rel.MaxHops = n
- }
- case TokDotDot:
- // *..M
- p.advance() // consume ..
- rel.MinHops = 1
- if p.peek().Type == TokNumber {
- m, _ := strconv.Atoi(p.advance().Value)
- rel.MaxHops = m
- } else {
- rel.MaxHops = 0
- }
- default:
- // Just * with no range: unbounded
- rel.MinHops = 1
- rel.MaxHops = 0
- }
-
- return nil
-}
-
-func (p *Parser) parseNodePattern() (*NodePattern, error) {
- if err := p.expect(TokLParen); err != nil {
- return nil, fmt.Errorf("expected '(' for node pattern: %w", err)
- }
-
- node := &NodePattern{}
-
- // Optional variable name
- if p.peek().Type == TokIdent {
- node.Variable = p.advance().Value
- }
-
- // Optional :Label
- if p.peek().Type == TokColon {
- p.advance() // consume :
- t := p.advance()
- if t.Type != TokIdent {
- return nil, fmt.Errorf("expected label name after ':', got %q at pos %d", t.Value, t.Pos)
- }
- node.Label = t.Value
- }
-
- // Optional {key: "val", ...}
- if p.peek().Type == TokLBrace {
- props, err := p.parseInlineProps()
- if err != nil {
- return nil, err
- }
- node.Props = props
- }
-
- if err := p.expect(TokRParen); err != nil {
- return nil, fmt.Errorf("expected ')' to close node pattern: %w", err)
- }
-
- return node, nil
-}
-
-func (p *Parser) parseInlineProps() (map[string]string, error) {
- p.advance() // consume {
- props := make(map[string]string)
-
- for p.peek().Type != TokRBrace {
- if len(props) > 0 {
- if err := p.expect(TokComma); err != nil {
- return nil, fmt.Errorf("expected ',' between properties: %w", err)
- }
- }
-
- // key
- keyTok := p.advance()
- if keyTok.Type != TokIdent {
- return nil, fmt.Errorf("expected property key, got %q at pos %d", keyTok.Value, keyTok.Pos)
- }
-
- // :
- if err := p.expect(TokColon); err != nil {
- return nil, fmt.Errorf("expected ':' after property key: %w", err)
- }
-
- // value (string)
- valTok := p.advance()
- if valTok.Type != TokString {
- return nil, fmt.Errorf("expected string value for property %q, got %q at pos %d", keyTok.Value, valTok.Value, valTok.Pos)
- }
-
- props[keyTok.Value] = valTok.Value
- }
-
- p.advance() // consume }
- return props, nil
-}
-
-func (p *Parser) parseWhere() (*WhereClause, error) {
- p.advance() // consume WHERE
- w := &WhereClause{Operator: "AND"}
-
- cond, err := p.parseCondition()
- if err != nil {
- return nil, err
- }
- w.Conditions = append(w.Conditions, cond)
-
- for p.peek().Type == TokAnd || p.peek().Type == TokOr {
- op := p.advance()
- if op.Type == TokOr {
- w.Operator = "OR"
- }
- cond, err := p.parseCondition()
- if err != nil {
- return nil, err
- }
- w.Conditions = append(w.Conditions, cond)
- }
-
- return w, nil
-}
-
-func (p *Parser) parseCondition() (Condition, error) {
- c := Condition{}
-
- // variable.property
- varTok := p.advance()
- if varTok.Type != TokIdent {
- return c, fmt.Errorf("expected variable name in condition, got %q at pos %d", varTok.Value, varTok.Pos)
- }
- c.Variable = varTok.Value
-
- if err := p.expect(TokDot); err != nil {
- return c, fmt.Errorf("expected '.' after variable in condition: %w", err)
- }
-
- propTok := p.advance()
- if propTok.Type != TokIdent {
- return c, fmt.Errorf("expected property name in condition, got %q at pos %d", propTok.Value, propTok.Pos)
- }
- c.Property = propTok.Value
-
- // Operator
- op := p.peek()
- switch op.Type {
- case TokEQ:
- c.Operator = "="
- p.advance()
- case TokRegex:
- c.Operator = "=~"
- p.advance()
- case TokGT:
- c.Operator = ">"
- p.advance()
- case TokLT:
- c.Operator = "<"
- p.advance()
- case TokGTE:
- c.Operator = ">="
- p.advance()
- case TokLTE:
- c.Operator = "<="
- p.advance()
- case TokContains:
- c.Operator = "CONTAINS"
- p.advance()
- case TokStarts:
- // STARTS WITH
- p.advance() // consume STARTS
- if p.peek().Type != TokWith {
- return c, fmt.Errorf("expected WITH after STARTS at pos %d", p.peek().Pos)
- }
- p.advance() // consume WITH
- c.Operator = "STARTS WITH"
- default:
- return c, fmt.Errorf("expected comparison operator, got %q at pos %d", op.Value, op.Pos)
- }
-
- // Value (string or number)
- valTok := p.advance()
- switch valTok.Type {
- case TokString:
- c.Value = valTok.Value
- case TokNumber:
- c.Value = valTok.Value
- default:
- return c, fmt.Errorf("expected value in condition, got %q at pos %d", valTok.Value, valTok.Pos)
- }
-
- return c, nil
-}
-
-func (p *Parser) parseReturn() (*ReturnClause, error) {
- p.advance() // consume RETURN
- r := &ReturnClause{OrderDir: "ASC"}
-
- // Optional DISTINCT
- if p.peek().Type == TokDistinct {
- r.Distinct = true
- p.advance()
- }
-
- // Parse return items
- item, err := p.parseReturnItem()
- if err != nil {
- return nil, err
- }
- r.Items = append(r.Items, item)
-
- for p.peek().Type == TokComma {
- p.advance() // consume ,
- item, err := p.parseReturnItem()
- if err != nil {
- return nil, err
- }
- r.Items = append(r.Items, item)
- }
-
- // Optional ORDER BY
- if p.peek().Type == TokOrder {
- orderBy, orderDir, err := p.parseOrderBy()
- if err != nil {
- return nil, err
- }
- r.OrderBy = orderBy
- r.OrderDir = orderDir
- }
-
- // Optional LIMIT
- if p.peek().Type == TokLimit {
- p.advance() // consume LIMIT
- numTok := p.advance()
- if numTok.Type != TokNumber {
- return nil, fmt.Errorf("expected number after LIMIT, got %q", numTok.Value)
- }
- n, _ := strconv.Atoi(numTok.Value)
- r.Limit = n
- }
-
- return r, nil
-}
-
-func (p *Parser) parseReturnItem() (ReturnItem, error) {
- item := ReturnItem{}
-
- // Check for COUNT(variable)
- if p.peek().Type == TokCount {
- return p.parseCountItem()
- }
-
- // variable or variable.property
- varTok := p.advance()
- if varTok.Type != TokIdent {
- return item, fmt.Errorf("expected variable in RETURN item, got %q at pos %d", varTok.Value, varTok.Pos)
- }
- item.Variable = varTok.Value
-
- if p.peek().Type == TokDot {
- p.advance() // consume .
- propTok := p.advance()
- if propTok.Type != TokIdent {
- return item, fmt.Errorf("expected property after '.', got %q", propTok.Value)
- }
- item.Property = propTok.Value
- }
-
- // Optional AS alias
- if p.peek().Type == TokAs {
- p.advance() // consume AS
- aliasTok := p.advance()
- if aliasTok.Type != TokIdent {
- return item, fmt.Errorf("expected alias after AS, got %q", aliasTok.Value)
- }
- item.Alias = aliasTok.Value
- }
-
- return item, nil
-}
-
-// parseCountItem parses a COUNT(variable) [AS alias] expression.
-func (p *Parser) parseCountItem() (ReturnItem, error) {
- item := ReturnItem{}
- p.advance() // consume COUNT
- item.Func = "COUNT"
- if err := p.expect(TokLParen); err != nil {
- return item, fmt.Errorf("expected '(' after COUNT: %w", err)
- }
- varTok := p.advance()
- if varTok.Type != TokIdent {
- return item, fmt.Errorf("expected variable in COUNT(), got %q", varTok.Value)
- }
- item.Variable = varTok.Value
- if err := p.expect(TokRParen); err != nil {
- return item, fmt.Errorf("expected ')' after COUNT variable: %w", err)
- }
-
- // Optional AS alias
- if p.peek().Type == TokAs {
- p.advance() // consume AS
- aliasTok := p.advance()
- if aliasTok.Type != TokIdent {
- return item, fmt.Errorf("expected alias after AS, got %q", aliasTok.Value)
- }
- item.Alias = aliasTok.Value
- }
-
- return item, nil
-}
-
-// parseOrderBy parses ORDER BY <field|COUNT(var)> [ASC|DESC].
-func (p *Parser) parseOrderBy() (orderBy, orderDir string, err error) {
- p.advance() // consume ORDER
- if err := p.expect(TokBy); err != nil {
- return "", "", fmt.Errorf("expected BY after ORDER: %w", err)
- }
-
- orderField, err := p.parseOrderField()
- if err != nil {
- return "", "", err
- }
-
- // Optional ASC/DESC
- dir := ""
- if p.peek().Type == TokAsc {
- dir = "ASC"
- p.advance()
- } else if p.peek().Type == TokDesc {
- dir = "DESC"
- p.advance()
- }
- return orderField, dir, nil
-}
-
-// parseOrderField parses the field expression in ORDER BY: either COUNT(var) or var[.prop].
-func (p *Parser) parseOrderField() (string, error) {
- if p.peek().Type == TokCount {
- p.advance() // consume COUNT
- if err := p.expect(TokLParen); err != nil {
- return "", fmt.Errorf("expected '(' after COUNT in ORDER BY: %w", err)
- }
- varTok := p.advance()
- if varTok.Type != TokIdent {
- return "", fmt.Errorf("expected variable in COUNT(), got %q", varTok.Value)
- }
- if err := p.expect(TokRParen); err != nil {
- return "", fmt.Errorf("expected ')' after COUNT variable in ORDER BY: %w", err)
- }
- return "COUNT(" + varTok.Value + ")", nil
- }
-
- orderTok := p.advance()
- if orderTok.Type != TokIdent {
- return "", fmt.Errorf("expected field name for ORDER BY, got %q", orderTok.Value)
- }
- field := orderTok.Value
- if p.peek().Type == TokDot {
- p.advance() // consume .
- propTok := p.advance()
- field += "." + propTok.Value
- }
- return field, nil
-}
diff --git a/internal/cypher/planner.go b/internal/cypher/planner.go
deleted file mode 100644
index f409abf92..000000000
--- a/internal/cypher/planner.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package cypher
-
-import "fmt"
-
-// Plan represents an execution plan for a parsed Cypher query.
-type Plan struct {
- Steps []PlanStep
- ReturnSpec *ReturnClause
-}
-
-// PlanStep is a single step in the execution plan.
-type PlanStep interface {
- stepType() string
-}
-
-// ScanNodes finds nodes matching label and/or inline property filters.
-type ScanNodes struct {
- Variable string
- Label string
- Props map[string]string // inline property filters
-}
-
-func (*ScanNodes) stepType() string { return "scan" }
-
-// ExpandRelationship follows edges from bound nodes to match target nodes.
-type ExpandRelationship struct {
- FromVar string // source variable (already bound)
- ToVar string // target variable (to bind)
- RelVar string // optional relationship variable (to bind edge)
- ToLabel string // optional label filter on target
- ToProps map[string]string
- EdgeTypes []string // required edge types
- Direction string // "outbound", "inbound", "any"
- MinHops int
- MaxHops int
-}
-
-func (*ExpandRelationship) stepType() string { return "expand" }
-
-// FilterWhere applies WHERE conditions to the bindings.
-type FilterWhere struct {
- Conditions []Condition
- Operator string // "AND" or "OR"
-}
-
-func (*FilterWhere) stepType() string { return "filter" }
-
-// asNodePattern safely type-asserts a PatternElement to *NodePattern.
-func asNodePattern(el PatternElement) (*NodePattern, error) {
- np, ok := el.(*NodePattern)
- if !ok {
- return nil, fmt.Errorf("expected *NodePattern, got %T", el)
- }
- return np, nil
-}
-
-// asRelPattern safely type-asserts a PatternElement to *RelPattern.
-func asRelPattern(el PatternElement) (*RelPattern, error) {
- rp, ok := el.(*RelPattern)
- if !ok {
- return nil, fmt.Errorf("expected *RelPattern, got %T", el)
- }
- return rp, nil
-}
-
-// BuildPlan converts a parsed Query AST into an execution Plan.
-func BuildPlan(q *Query) (*Plan, error) {
- plan := &Plan{ReturnSpec: q.Return}
-
- elements := q.Match.Pattern.Elements
- if len(elements) == 0 {
- return plan, nil
- }
-
- // First element is always a node pattern
- firstNode, err := asNodePattern(elements[0])
- if err != nil {
- return nil, fmt.Errorf("first pattern element: %w", err)
- }
- plan.Steps = append(plan.Steps, &ScanNodes{
- Variable: firstNode.Variable,
- Label: firstNode.Label,
- Props: firstNode.Props,
- })
-
- // Optimization: push WHERE conditions that reference only the first
- // scan variable BEFORE any expand steps. This dramatically reduces the
- // number of bindings that need to be expanded.
- earlyFilters, lateFilters := splitWhereFilters(q.Where, firstNode.Variable, len(elements) > 1)
-
- // Insert early filter right after scan
- if len(earlyFilters) > 0 {
- plan.Steps = append(plan.Steps, &FilterWhere{
- Conditions: earlyFilters,
- Operator: "AND",
- })
- }
-
- // Process relationship-node pairs
- for i := 1; i+1 < len(elements); i += 2 {
- rel, err := asRelPattern(elements[i])
- if err != nil {
- return nil, fmt.Errorf("element[%d]: %w", i, err)
- }
- targetNode, err := asNodePattern(elements[i+1])
- if err != nil {
- return nil, fmt.Errorf("element[%d]: %w", i+1, err)
- }
- fromNode, err := asNodePattern(elements[i-1])
- if err != nil {
- return nil, fmt.Errorf("element[%d]: %w", i-1, err)
- }
-
- plan.Steps = append(plan.Steps, &ExpandRelationship{
- FromVar: fromNode.Variable,
- ToVar: targetNode.Variable,
- RelVar: rel.Variable,
- ToLabel: targetNode.Label,
- ToProps: targetNode.Props,
- EdgeTypes: rel.Types,
- Direction: rel.Direction,
- MinHops: rel.MinHops,
- MaxHops: rel.MaxHops,
- })
- }
-
- // Late WHERE filter (conditions referencing expand variables)
- if len(lateFilters) > 0 {
- plan.Steps = append(plan.Steps, &FilterWhere{
- Conditions: lateFilters,
- Operator: q.Where.Operator,
- })
- } else if q.Where != nil && len(earlyFilters) == 0 {
- // No split happened — add all conditions at the end
- plan.Steps = append(plan.Steps, &FilterWhere{
- Conditions: q.Where.Conditions,
- Operator: q.Where.Operator,
- })
- }
-
- return plan, nil
-}
-
-// splitWhereFilters separates WHERE conditions into early (scan-only) and late filters.
-func splitWhereFilters(where *WhereClause, scanVar string, hasExpand bool) (early, late []Condition) {
- if where == nil {
- return nil, nil
- }
-
- if hasExpand && where.Operator == "AND" {
- for _, c := range where.Conditions {
- if c.Variable == scanVar {
- early = append(early, c)
- } else {
- late = append(late, c)
- }
- }
- return early, late
- }
- // Can't split OR conditions or when there's no expand
- return nil, where.Conditions
-}
diff --git a/internal/discover/discover.go b/internal/discover/discover.go
deleted file mode 100644
index a02500b6a..000000000
--- a/internal/discover/discover.go
+++ /dev/null
@@ -1,465 +0,0 @@
-package discover
-
-import (
- "bufio"
- "context"
- "io"
- "log/slog"
- "os"
- "path/filepath"
- "regexp"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// IGNORE_PATTERNS are directory names to skip during discovery.
-var IGNORE_PATTERNS = map[string]bool{
- // VCS / IDE
- ".git": true, ".hg": true, ".svn": true, ".worktrees": true,
- ".idea": true, ".vs": true, ".vscode": true, ".eclipse": true, ".claude": true,
- // Python
- ".cache": true, ".eggs": true, ".env": true, ".mypy_cache": true, ".nox": true,
- ".pytest_cache": true, ".ruff_cache": true, ".tox": true, ".venv": true,
- "__pycache__": true, "env": true, "htmlcov": true, "site-packages": true, "venv": true,
- // JS/TS
- ".npm": true, ".nyc_output": true, ".pnpm-store": true, ".yarn": true,
- "bower_components": true, "coverage": true, "node_modules": true,
- // JS/TS framework caches
- ".next": true, ".nuxt": true, ".svelte-kit": true, ".angular": true,
- ".turbo": true, ".parcel-cache": true, ".docusaurus": true, ".expo": true,
- // Build artifacts
- "dist": true, "obj": true, "Pods": true, "target": true, "temp": true, "tmp": true,
- // Build system caches
- ".terraform": true, ".serverless": true,
- "bazel-bin": true, "bazel-out": true, "bazel-testlogs": true,
- // Language-specific caches
- ".cargo": true, ".stack-work": true, ".dart_tool": true,
- "zig-cache": true, "zig-out": true,
- ".metals": true, ".bloop": true, ".bsp": true,
- ".ccls-cache": true, ".clangd": true,
- "elm-stuff": true, "_opam": true, ".cpcache": true, ".shadow-cljs": true,
- // Deploy/hosting
- ".vercel": true, ".netlify": true,
- // Misc
- ".qdrant_code_embeddings": true, ".tmp": true, "vendor": true,
-}
-
-// IGNORE_SUFFIXES are file suffixes that are never source files.
-var IGNORE_SUFFIXES = map[string]bool{
- // Temp/compiled
- ".tmp": true, "~": true, ".pyc": true, ".pyo": true,
- ".o": true, ".a": true, ".so": true, ".dll": true, ".class": true,
- // Images
- ".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
- ".ico": true, ".bmp": true, ".tiff": true, ".webp": true, ".svg": true,
- // Binaries
- ".wasm": true, ".node": true, ".exe": true, ".bin": true, ".dat": true,
- // Databases
- ".db": true, ".sqlite": true, ".sqlite3": true,
- // Fonts
- ".woff": true, ".woff2": true, ".ttf": true, ".eot": true, ".otf": true,
-}
-
-// IndexMode controls how aggressively files are filtered during discovery.
-type IndexMode string
-
-const (
- ModeFull IndexMode = "full" // default: parse everything supported
- ModeFast IndexMode = "fast" // aggressive filtering for speed
-)
-
-// FileInfo represents a discovered source file.
-type FileInfo struct {
- Path string // absolute path
- RelPath string // relative to repo root
- Language lang.Language // detected language
- Size int64 // file size in bytes
-}
-
-// Options configures file discovery.
-type Options struct {
- IgnoreFile string // path to .cgrignore file (optional)
- Mode IndexMode // indexing mode (full or fast)
- MaxFileSize int64 // max file size in bytes (0 = no limit)
-}
-
-// fastIgnoreDirs are additional directories skipped in fast mode.
-var fastIgnoreDirs = map[string]bool{
- "generated": true, "gen": true, "auto-generated": true,
- "fixtures": true, "testdata": true, "test_data": true,
- "__tests__": true, "__mocks__": true, "__snapshots__": true,
- "__fixtures__": true, "__test__": true,
- "docs": true, "doc": true, "documentation": true,
- "examples": true, "example": true, "samples": true, "sample": true,
- "assets": true, "static": true, "public": true, "media": true,
- "third_party": true, "thirdparty": true, "3rdparty": true, "external": true,
- "migrations": true, "seeds": true,
- "e2e": true, "integration": true,
- "locale": true, "locales": true, "i18n": true, "l10n": true,
- "scripts": true, "tools": true, "hack": true,
- // Generic dirs moved from IGNORE_PATTERNS (cause false exclusions in Go, CMake, Maven)
- "bin": true, "build": true, "out": true,
-}
-
-// fastIgnoreSuffixes are additional file extensions skipped in fast mode.
-var fastIgnoreSuffixes = map[string]bool{
- // Archives
- ".zip": true, ".tar": true, ".gz": true, ".bz2": true, ".xz": true,
- ".rar": true, ".7z": true, ".jar": true, ".war": true, ".ear": true,
- // Media/audio/video
- ".mp3": true, ".mp4": true, ".avi": true, ".mov": true, ".wav": true,
- ".flac": true, ".ogg": true, ".mkv": true, ".webm": true,
- // Documents
- ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true,
- ".ppt": true, ".pptx": true, ".odt": true, ".ods": true,
- // Source maps
- ".map": true,
- // Minified bundles
- ".min.js": true, ".min.css": true,
- // Certificates/keys
- ".pem": true, ".crt": true, ".key": true, ".cer": true, ".p12": true,
- // Serialized data
- ".pb": true, ".proto": true, ".avro": true, ".parquet": true,
- // Compiled/intermediate
- ".beam": true, ".elc": true, ".rlib": true,
- // Coverage/profiling
- ".coverage": true, ".prof": true, ".out": true,
- // Patches
- ".patch": true, ".diff": true,
-}
-
-// fastIgnoreFilenames are specific filenames skipped in fast mode.
-var fastIgnoreFilenames = map[string]bool{
- "LICENSE": true, "LICENSE.txt": true, "LICENSE.md": true, "LICENSE-MIT": true, "LICENSE-APACHE": true,
- "LICENCE": true, "LICENCE.txt": true, "LICENCE.md": true,
- "CHANGELOG": true, "CHANGELOG.md": true, "CHANGES.md": true,
- "HISTORY": true, "HISTORY.md": true,
- "AUTHORS": true, "AUTHORS.md": true, "CONTRIBUTORS": true, "CONTRIBUTORS.md": true,
- "CODEOWNERS": true,
- "go.sum": true, "yarn.lock": true, "pnpm-lock.yaml": true, "Pipfile.lock": true,
- "poetry.lock": true, "Gemfile.lock": true, "Cargo.lock": true, "mix.lock": true,
- "flake.lock": true, "pubspec.lock": true, "composer.lock": true,
- "configure": true, "Makefile.in": true, "config.guess": true, "config.sub": true,
- "package-lock.json": true,
-}
-
-// fastIgnorePatterns are suffix/contains patterns skipped in fast mode.
-var fastIgnorePatterns = []string{
- ".d.ts", // TypeScript declaration files
- ".bundle.", // bundled files
- ".chunk.", // code-split chunks
- ".generated.", // generated code
- ".pb.go", // protobuf generated Go
- "_pb2.py", // protobuf generated Python
- ".pb2.py", // protobuf generated Python (alt)
- "_grpc.pb.go", // gRPC generated Go
- "_string.go", // stringer generated Go
- "mock_", // mock files prefix
- "_mock.", // mock files suffix
- "_test_helpers.", // test helpers
- ".stories.", // Storybook stories
- ".spec.", // spec/test files
- ".test.", // test files
-}
-
-// isWorktreeDir reports whether dir is a git worktree or submodule checkout.
-// These contain a .git *file* (not directory) whose first line starts with "gitdir:".
-func isWorktreeDir(dir string) bool {
- gitPath := filepath.Join(dir, ".git")
- fi, err := os.Lstat(gitPath)
- if err != nil || fi.IsDir() {
- return false
- }
- f, err := os.Open(gitPath)
- if err != nil {
- return false
- }
- defer f.Close()
- buf := make([]byte, 7)
- n, _ := f.Read(buf)
- return n == 7 && string(buf) == "gitdir:"
-}
-
-// shouldSkipDir returns true if the directory should be skipped during discovery.
-func shouldSkipDir(name, rel string, extraIgnore []string, mode IndexMode) bool {
- if IGNORE_PATTERNS[name] {
- return true
- }
- if mode == ModeFast {
- // Skip all dot-directories not already in IGNORE_PATTERNS
- if strings.HasPrefix(name, ".") {
- return true
- }
- if fastIgnoreDirs[name] {
- return true
- }
- }
- for _, pattern := range extraIgnore {
- if matched, _ := filepath.Match(pattern, name); matched {
- return true
- }
- if matched, _ := filepath.Match(pattern, rel); matched {
- return true
- }
- }
- return false
-}
-
-// shouldSkipFile returns true if the file should be skipped in fast mode.
-func shouldSkipFile(name, path string, size int64, opts *Options) bool {
- // File size limit (both modes)
- if opts != nil && opts.MaxFileSize > 0 && size > opts.MaxFileSize {
- return true
- }
- if opts == nil || opts.Mode != ModeFast {
- return false
- }
- // Fast-mode filename filter
- if fastIgnoreFilenames[name] {
- return true
- }
- // Fast-mode suffix filter
- for suffix := range fastIgnoreSuffixes {
- if strings.HasSuffix(path, suffix) {
- return true
- }
- }
- // Fast-mode pattern filter (contains/suffix patterns)
- for _, pattern := range fastIgnorePatterns {
- if strings.Contains(path, pattern) {
- return true
- }
- }
- return false
-}
-
-// hasIgnoredSuffix returns true if path ends with any suffix in IGNORE_SUFFIXES.
-func hasIgnoredSuffix(path string) bool {
- for suffix := range IGNORE_SUFFIXES {
- if strings.HasSuffix(path, suffix) {
- return true
- }
- }
- return false
-}
-
-// Objective-C markers adapted from GitHub Linguist heuristics.yml
-var objcMarkers = regexp.MustCompile(`@interface|@implementation|@protocol|@property|#import\s+[<"]|@selector|@encode|@synthesize|@dynamic`)
-
-// MATLAB markers adapted from GitHub Linguist heuristics.yml
-var matlabMarkers = regexp.MustCompile(`(?m)^\s*function\b|^\s*classdef\b|^\s*%%|^\s*%[^{]`)
-
-// Magma markers — semicolons after end-blocks and procedure/intrinsic keywords are unique to Magma
-var magmaMarkers = regexp.MustCompile(`(?m)end\s+(function|procedure|intrinsic)\s*;|\bintrinsic\s+\w+\s*\(|\bprocedure\s+\w+\s*\(|end\s+if\s*;|end\s+for\s*;|end\s+while\s*;`)
-
-// disambiguateM determines whether a .m file is MATLAB, Objective-C, or Magma.
-// Returns the detected language and true, or ("", false) if undetermined.
-func disambiguateM(path string) (lang.Language, bool) {
- f, err := os.Open(path)
- if err != nil {
- return lang.MATLAB, true // default to MATLAB on error
- }
- defer f.Close()
-
- // Read first 4KB for heuristics
- buf := make([]byte, 4096)
- n, err := io.ReadAtLeast(f, buf, 1)
- if err != nil && n == 0 {
- return lang.MATLAB, true
- }
- head := string(buf[:n])
-
- if objcMarkers.MatchString(head) {
- return lang.ObjectiveC, true
- }
- // Check Magma before MATLAB — both use 'function' keyword but Magma has 'end function;'
- if magmaMarkers.MatchString(head) {
- return lang.Magma, true
- }
- if matlabMarkers.MatchString(head) {
- return lang.MATLAB, true
- }
- // Default to MATLAB (more common for .m in scientific codebases)
- return lang.MATLAB, true
-}
-
-// classifyFile checks if a file is a supported source file and returns its FileInfo.
-// Returns nil if the file should be skipped.
-func classifyFile(path, rel string, info os.FileInfo, opts *Options) *FileInfo {
- if hasIgnoredSuffix(path) {
- return nil
- }
- if shouldSkipFile(info.Name(), path, info.Size(), opts) {
- return nil
- }
-
- ext := filepath.Ext(path)
-
- // .m files are ambiguous: MATLAB vs Objective-C
- if ext == ".m" {
- ml, ok := disambiguateM(path)
- if ok {
- return &FileInfo{
- Path: path,
- RelPath: filepath.ToSlash(rel),
- Language: ml,
- Size: info.Size(),
- }
- }
- }
-
- l, ok := lang.LanguageForExtension(ext)
- if !ok {
- l, ok = lang.LanguageForFilename(info.Name())
- }
- if !ok {
- return nil
- }
-
- if l == lang.JSON && isIgnoredJSON(info.Name()) {
- return nil
- }
- if l == lang.JSON && info.Size() > 100*1024 {
- slog.Warn("discover.skip_large_json", "path", rel, "size", info.Size())
- return nil
- }
-
- return &FileInfo{
- Path: path,
- RelPath: filepath.ToSlash(rel),
- Language: l,
- Size: info.Size(),
- }
-}
-
-// Discover walks a repository and returns all source files.
-func Discover(ctx context.Context, repoPath string, opts *Options) ([]FileInfo, error) {
- repoPath, err := filepath.Abs(repoPath)
- if err != nil {
- return nil, err
- }
-
- if err := ctx.Err(); err != nil {
- return nil, err
- }
-
- var extraIgnore []string
- if opts != nil && opts.IgnoreFile != "" {
- extraIgnore, _ = loadIgnoreFile(opts.IgnoreFile)
- } else {
- ignPath := filepath.Join(repoPath, ".cgrignore")
- extraIgnore, _ = loadIgnoreFile(ignPath)
- }
-
- var files []FileInfo
-
- mode := ModeFull
- if opts != nil && opts.Mode != "" {
- mode = opts.Mode
- }
-
- // Load gitignore + cbmignore matchers (nil-safe for non-git repos)
- matchers := loadIgnoreMatchers(repoPath)
-
- err = filepath.Walk(repoPath, func(path string, info os.FileInfo, walkErr error) error {
- if err := ctx.Err(); err != nil {
- return err
- }
- if walkErr != nil {
- return filepath.SkipDir
- }
-
- // Skip symlinks — prevents duplicate indexing
- if info.Mode()&os.ModeSymlink != 0 {
- return nil
- }
-
- rel, _ := filepath.Rel(repoPath, path)
-
- if info.IsDir() {
- // Hardcoded patterns first (fast O(1) map lookup)
- if shouldSkipDir(info.Name(), rel, extraIgnore, mode) {
- return filepath.SkipDir
- }
- // Detect worktree/submodule checkouts (.git file with "gitdir:" pointer)
- if rel != "." && isWorktreeDir(path) {
- slog.Debug("discover.skip_worktree", "dir", rel)
- return filepath.SkipDir
- }
- // Then gitignore + cbmignore (skip root — library panics on base==path)
- if rel != "." && matchers.shouldIgnore(path, true) {
- slog.Debug("discover.gitignore_skip", "dir", rel)
- return filepath.SkipDir
- }
- return nil
- }
-
- // Gitignore + cbmignore check for files
- if matchers.shouldIgnore(path, false) {
- return nil
- }
-
- if fi := classifyFile(path, rel, info, opts); fi != nil {
- files = append(files, *fi)
- }
- return nil
- })
-
- return files, err
-}
-
-// ignoredJSONFiles are JSON filenames to skip (tool configs, lock files, specs).
-var ignoredJSONFiles = map[string]bool{
- "package.json": true,
- "package-lock.json": true,
- "tsconfig.json": true,
- "jsconfig.json": true,
- "composer.json": true,
- "composer.lock": true,
- "yarn.lock": true,
- "openapi.json": true,
- "swagger.json": true,
- "jest.config.json": true,
- ".eslintrc.json": true,
- ".prettierrc.json": true,
- ".babelrc.json": true,
- "tslint.json": true,
- "angular.json": true,
- "firebase.json": true,
- "renovate.json": true,
- "lerna.json": true,
- "turbo.json": true,
- ".stylelintrc.json": true,
- "pnpm-lock.json": true,
- "deno.json": true,
- "biome.json": true,
- "devcontainer.json": true,
- ".devcontainer.json": true,
- "launch.json": true,
- "settings.json": true,
- "extensions.json": true,
- "tasks.json": true,
-}
-
-func isIgnoredJSON(name string) bool {
- return ignoredJSONFiles[name]
-}
-
-func loadIgnoreFile(path string) ([]string, error) {
- f, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- var patterns []string
- scanner := bufio.NewScanner(f)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line != "" && !strings.HasPrefix(line, "#") {
- patterns = append(patterns, line)
- }
- }
- return patterns, scanner.Err()
-}
diff --git a/internal/discover/discover_test.go b/internal/discover/discover_test.go
deleted file mode 100644
index bab05ee7a..000000000
--- a/internal/discover/discover_test.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package discover
-
-import (
- "context"
- "errors"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-func TestDiscoverBasic(t *testing.T) {
- dir := t.TempDir()
-
- // Create a Go file and a Python file
- if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, "app.py"), []byte("def main(): pass\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- ctx := context.Background()
- files, err := Discover(ctx, dir, nil)
- if err != nil {
- t.Fatalf("Discover: %v", err)
- }
-
- if len(files) != 2 {
- t.Fatalf("expected 2 files, got %d", len(files))
- }
-
- // Verify file info is populated
- for _, f := range files {
- if f.Path == "" {
- t.Error("expected non-empty Path")
- }
- if f.RelPath == "" {
- t.Error("expected non-empty RelPath")
- }
- if f.Language == "" {
- t.Error("expected non-empty Language")
- }
- }
-}
-
-func TestDisambiguateM(t *testing.T) {
- dir := t.TempDir()
-
- tests := []struct {
- name string
- content string
- want lang.Language
- }{
- {"objc", "@interface Foo\n@end\n", lang.ObjectiveC},
- {"matlab_function", "function y = foo(x)\n y = x^2;\nend\n", lang.MATLAB},
- {"matlab_comment", "% This is MATLAB\nx = 1;\n", lang.MATLAB},
- {"magma_end_function", "function Fact(n)\n return n;\nend function;\n", lang.Magma},
- {"magma_procedure", "procedure DoStuff(~x)\n x := 1;\nend procedure;\n", lang.Magma},
- {"magma_intrinsic", "intrinsic IsSmall(x :: RngIntElt) -> BoolElt\n", lang.Magma},
- {"magma_end_if", "if n le 1 then\n return 1;\nend if;\n", lang.Magma},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- path := filepath.Join(dir, tt.name+".m")
- if err := os.WriteFile(path, []byte(tt.content), 0o600); err != nil {
- t.Fatal(err)
- }
- got, ok := disambiguateM(path)
- if !ok {
- t.Fatal("disambiguateM returned ok=false")
- }
- if got != tt.want {
- t.Errorf("disambiguateM(%s) = %s, want %s", tt.name, got, tt.want)
- }
- })
- }
-}
-
-func TestDiscoverSkipsWorktrees(t *testing.T) {
- dir := t.TempDir()
-
- if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- // .worktrees/ contains duplicated source trees from git worktrees
- wtDir := filepath.Join(dir, ".worktrees", "feature-branch", "src")
- if err := os.MkdirAll(wtDir, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(wtDir, "app.go"), []byte("package app\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- files, err := Discover(context.Background(), dir, nil)
- if err != nil {
- t.Fatalf("Discover: %v", err)
- }
-
- if len(files) != 1 {
- t.Fatalf("expected 1 file (skipping .worktrees), got %d", len(files))
- }
- if filepath.Base(files[0].Path) != "main.go" {
- t.Errorf("expected main.go, got %s", files[0].Path)
- }
-}
-
-func TestDiscoverSkipsWorktreeCheckout(t *testing.T) {
- dir := t.TempDir()
-
- if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- // Create a worktree-like directory with a .git file containing "gitdir:"
- wtDir := filepath.Join(dir, "feature-branch")
- if err := os.MkdirAll(filepath.Join(wtDir, "src"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(wtDir, "src", "lib.go"), []byte("package lib\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(wtDir, ".git"), []byte("gitdir: /repo/.git/worktrees/feature-branch\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- files, err := Discover(context.Background(), dir, nil)
- if err != nil {
- t.Fatalf("Discover: %v", err)
- }
-
- if len(files) != 1 {
- t.Fatalf("expected 1 file (skipping worktree checkout), got %d", len(files))
- }
- if filepath.Base(files[0].Path) != "main.go" {
- t.Errorf("expected main.go, got %s", files[0].Path)
- }
-}
-
-func TestDiscoverDoesNotSkipDirWithNonGitdirDotGitFile(t *testing.T) {
- dir := t.TempDir()
-
- if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- // Create a directory with a .git file that does NOT start with "gitdir:"
- subDir := filepath.Join(dir, "subproject")
- if err := os.MkdirAll(subDir, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(subDir, "lib.go"), []byte("package lib\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(subDir, ".git"), []byte("not a gitdir pointer\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- files, err := Discover(context.Background(), dir, nil)
- if err != nil {
- t.Fatalf("Discover: %v", err)
- }
-
- if len(files) != 2 {
- t.Fatalf("expected 2 files (subdir NOT skipped), got %d", len(files))
- }
-}
-
-func TestDiscoverCancellation(t *testing.T) {
- dir := t.TempDir()
-
- // Create a file so the directory isn't empty
- if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- ctx, cancel := context.WithCancel(context.Background())
- cancel() // pre-cancel
-
- _, err := Discover(ctx, dir, nil)
- if !errors.Is(err, context.Canceled) {
- t.Fatalf("expected context.Canceled, got %v", err)
- }
-}
diff --git a/internal/discover/gitignore.go b/internal/discover/gitignore.go
deleted file mode 100644
index 87297cbf0..000000000
--- a/internal/discover/gitignore.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package discover
-
-import (
- "os"
- "path/filepath"
- "strings"
- "sync"
-
- gitignore "github.com/boyter/gocodewalker/go-gitignore"
-)
-
-// ignoreMatchers holds the layered ignore matchers for a repository.
-// Evaluation order: hardcoded patterns (fastest) → gitignore → cbmignore.
-type ignoreMatchers struct {
- gitignore *repoMatcher // .gitignore hierarchy + .git/info/exclude (nil for non-git repos)
- cbmignore gitignore.GitIgnore // .cbmignore at repo root (nil if absent)
-}
-
-// loadIgnoreMatchers loads all gitignore-style matchers for the repository.
-// .gitignore is loaded only for git repos (presence of .git dir).
-// .cbmignore stacks on top — patterns there additionally exclude from indexing.
-//
-// All files are read and closed immediately — no file handle leaks.
-// This is critical for Windows where open handles prevent t.TempDir() cleanup.
-func loadIgnoreMatchers(repoPath string) ignoreMatchers {
- var m ignoreMatchers
-
- // .gitignore — only for git repos
- gitDir := filepath.Join(repoPath, ".git")
- if info, err := os.Stat(gitDir); err == nil && info.IsDir() {
- m.gitignore = newRepoMatcher(repoPath)
- }
-
- // .cbmignore — repo-root file with gitignore-style patterns
- m.cbmignore = safeLoadGitignore(filepath.Join(repoPath, ".cbmignore"))
-
- return m
-}
-
-// shouldIgnore checks if a path should be ignored by gitignore or cbmignore.
-// absPath must be absolute; isDir indicates whether the path is a directory.
-func (m *ignoreMatchers) shouldIgnore(absPath string, isDir bool) bool {
- if m.gitignore != nil {
- if m.gitignore.shouldIgnore(absPath, isDir) {
- return true
- }
- }
- if m.cbmignore != nil {
- if match := m.cbmignore.Absolute(absPath, isDir); match != nil && match.Ignore() {
- return true
- }
- }
- return false
-}
-
-// safeLoadGitignore reads a gitignore-style file and returns a GitIgnore matcher.
-// The file is read completely and closed immediately — no handle leak.
-// Returns nil if the file doesn't exist or can't be read.
-func safeLoadGitignore(path string) gitignore.GitIgnore {
- content, err := os.ReadFile(path)
- if err != nil {
- return nil
- }
- base := filepath.Dir(path)
- return gitignore.New(strings.NewReader(string(content)), base, nil)
-}
-
-// repoMatcher implements gitignore-style matching across a repository's
-// .gitignore hierarchy. It replaces the library's repository type to avoid
-// file handle leaks (the library's NewWithErrors opens files but never closes them).
-//
-// Pattern matching uses the library's ignore.Relative() — only the hierarchy
-// walker and file loading are reimplemented.
-type repoMatcher struct {
- base string
- exclude gitignore.GitIgnore // .git/info/exclude patterns
- mu sync.Mutex // protects cache
- cache map[string]gitignore.GitIgnore // dir path → loaded .gitignore (nil = no file)
-}
-
-func newRepoMatcher(base string) *repoMatcher {
- m := &repoMatcher{
- base: base,
- cache: make(map[string]gitignore.GitIgnore),
- }
- m.exclude = safeLoadGitignore(filepath.Join(base, ".git", "info", "exclude"))
- return m
-}
-
-// loadDir loads the .gitignore for a directory, caching the result.
-func (m *repoMatcher) loadDir(dir string) gitignore.GitIgnore {
- m.mu.Lock()
- defer m.mu.Unlock()
- if gi, ok := m.cache[dir]; ok {
- return gi // may be nil (cached miss)
- }
- gi := safeLoadGitignore(filepath.Join(dir, ".gitignore"))
- m.cache[dir] = gi
- return gi
-}
-
-// shouldIgnore checks if an absolute path should be ignored according to
-// the repository's .gitignore hierarchy, following standard git precedence:
-// - child .gitignore overrides parent .gitignore
-// - negation patterns (!) in child override matching patterns in parent
-// - .git/info/exclude is checked last (lowest priority)
-func (m *repoMatcher) shouldIgnore(absPath string, isDir bool) bool {
- if !strings.HasPrefix(absPath, m.base) {
- return false
- }
- if absPath == m.base {
- return false
- }
-
- rel, err := filepath.Rel(m.base, absPath)
- if err != nil {
- return false
- }
- rel = filepath.ToSlash(rel)
- if rel == "." {
- return false
- }
-
- return m.matchRel(rel, isDir)
-}
-
-// matchRel implements the core gitignore hierarchy matching algorithm.
-// Mirrors the logic in the library's repository.Relative().
-func (m *repoMatcher) matchRel(rel string, isDir bool) bool {
- rel = filepath.ToSlash(filepath.Clean(rel))
- if rel == "." {
- return false
- }
-
- // First: is the parent directory ignored?
- // An ignored parent means the child is also ignored.
- parent, local := splitPath(rel)
- if parent != "" {
- if m.matchRel(parent, true) {
- return true
- }
- }
-
- // Walk from the file's directory up to the repo root,
- // checking .gitignore at each level. First match wins.
- dir := parent
- curLocal := local
- for {
- absDir := filepath.Join(m.base, filepath.FromSlash(dir))
- if dir == "" {
- absDir = m.base
- }
- gi := m.loadDir(absDir)
- if gi != nil {
- if match := gi.Relative(curLocal, isDir); match != nil {
- return match.Ignore()
- }
- }
-
- if dir == "" {
- break
- }
-
- // Walk up: prepend the current directory component to local
- var last string
- dir, last = splitPath(dir)
- curLocal = last + "/" + curLocal
- }
-
- // Finally check .git/info/exclude (lowest priority)
- if m.exclude != nil {
- if match := m.exclude.Relative(rel, isDir); match != nil {
- return match.Ignore()
- }
- }
-
- return false
-}
-
-// splitPath splits a forward-slash path into parent and last component.
-// "a/b/c" → ("a/b", "c"), "a" → ("", "a"), "" → ("", "")
-func splitPath(p string) (parent, last string) {
- if p == "" {
- return "", ""
- }
- i := strings.LastIndex(p, "/")
- if i < 0 {
- return "", p
- }
- return p[:i], p[i+1:]
-}
diff --git a/internal/discover/gitignore_test.go b/internal/discover/gitignore_test.go
deleted file mode 100644
index c6b856c7d..000000000
--- a/internal/discover/gitignore_test.go
+++ /dev/null
@@ -1,378 +0,0 @@
-package discover
-
-import (
- "context"
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-// initGitRepo creates a minimal .git directory to make the temp dir look like a git repo.
-func initGitRepo(t *testing.T, dir string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Join(dir, ".git", "info"), 0o755); err != nil {
- t.Fatal(err)
- }
-}
-
-func writeFile(t *testing.T, path, content string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-func discoverRelPaths(t *testing.T, dir string) map[string]bool {
- t.Helper()
- files, err := Discover(context.Background(), dir, nil)
- if err != nil {
- t.Fatal(err)
- }
- m := make(map[string]bool, len(files))
- for _, f := range files {
- m[f.RelPath] = true
- }
- return m
-}
-
-func TestGitignoreBasicPatterns(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, ".gitignore"), "*.log\nbuild/\n")
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
- writeFile(t, filepath.Join(dir, "app.log"), "log data\n")
- writeFile(t, filepath.Join(dir, "build", "out.go"), "package build\n")
-
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- if found["app.log"] {
- t.Error("app.log should be ignored by *.log pattern")
- }
- if found["build/out.go"] {
- t.Error("build/out.go should be ignored by build/ pattern")
- }
-}
-
-func TestGitignoreNegation(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, ".gitignore"), "*.log\n!important.log\n")
- writeFile(t, filepath.Join(dir, "debug.log"), "debug\n")
- writeFile(t, filepath.Join(dir, "important.log"), "keep me\n")
- // .log isn't a supported language, so add a Go file to prove discovery works
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
-
- files, err := Discover(context.Background(), dir, nil)
- if err != nil {
- t.Fatal(err)
- }
-
- found := make(map[string]bool)
- for _, f := range files {
- found[f.RelPath] = true
- }
-
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- // Note: .log files aren't a supported language, so they won't appear in Discover
- // results regardless. The gitignore negation is still effective — we test it
- // via the matcher directly.
- m := loadIgnoreMatchers(dir)
- if !m.shouldIgnore(filepath.Join(dir, "debug.log"), false) {
- t.Error("debug.log should be ignored")
- }
- if m.shouldIgnore(filepath.Join(dir, "important.log"), false) {
- t.Error("important.log should NOT be ignored (negated)")
- }
-}
-
-func TestGitignoreGlobstar(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, ".gitignore"), "**/vendor/\n")
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
- writeFile(t, filepath.Join(dir, "vendor", "lib.go"), "package vendor\n")
- writeFile(t, filepath.Join(dir, "src", "vendor", "dep.go"), "package vendor\n")
-
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- // vendor/ is also in IGNORE_PATTERNS, but the gitignore globstar should catch nested ones
- if found["src/vendor/dep.go"] {
- t.Error("src/vendor/dep.go should be ignored by **/vendor/ pattern")
- }
-}
-
-func TestGitignoreNested(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, ".gitignore"), "*.txt\n")
- writeFile(t, filepath.Join(dir, "subdir", ".gitignore"), "!readme.txt\n")
- writeFile(t, filepath.Join(dir, "top.txt"), "top\n")
- writeFile(t, filepath.Join(dir, "subdir", "readme.txt"), "readme\n")
- writeFile(t, filepath.Join(dir, "subdir", "notes.txt"), "notes\n")
-
- // Test via matchers since .txt isn't a supported language
- m := loadIgnoreMatchers(dir)
-
- if !m.shouldIgnore(filepath.Join(dir, "top.txt"), false) {
- t.Error("top.txt should be ignored by root *.txt")
- }
- if m.shouldIgnore(filepath.Join(dir, "subdir", "readme.txt"), false) {
- t.Error("subdir/readme.txt should NOT be ignored (negated by subdir/.gitignore)")
- }
- if !m.shouldIgnore(filepath.Join(dir, "subdir", "notes.txt"), false) {
- t.Error("subdir/notes.txt should be ignored by root *.txt")
- }
-}
-
-func TestGitignoreExcludeFile(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- // Pattern only in .git/info/exclude
- writeFile(t, filepath.Join(dir, ".git", "info", "exclude"), "*.secret\n")
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
-
- m := loadIgnoreMatchers(dir)
- if !m.shouldIgnore(filepath.Join(dir, "config.secret"), false) {
- t.Error("config.secret should be ignored by .git/info/exclude")
- }
- if m.shouldIgnore(filepath.Join(dir, "main.go"), false) {
- t.Error("main.go should not be ignored")
- }
-}
-
-func TestGitignoreNonGitRepo(t *testing.T) {
- dir := t.TempDir()
- // No .git directory
-
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
-
- m := loadIgnoreMatchers(dir)
- if m.gitignore != nil {
- t.Error("gitignore should be nil for non-git repo")
- }
-
- // Discovery should still work with hardcoded patterns
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered in non-git repo")
- }
-}
-
-func TestGitignoreDirOnly(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, ".gitignore"), "logs/\n")
- writeFile(t, filepath.Join(dir, "logs", "app.go"), "package logs\n")
-
- m := loadIgnoreMatchers(dir)
- // Directory should be ignored
- if !m.shouldIgnore(filepath.Join(dir, "logs"), true) {
- t.Error("logs/ directory should be ignored")
- }
- // File named "logs" should NOT be ignored (trailing slash = dir-only)
- if m.shouldIgnore(filepath.Join(dir, "logs"), false) {
- t.Error("file named 'logs' should NOT be ignored by 'logs/' pattern")
- }
-}
-
-func TestCBMIgnoreBasic(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- // .cbmignore with patterns that stack on top of .gitignore
- writeFile(t, filepath.Join(dir, ".cbmignore"), "generated/\n*.pb.go\n")
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
- writeFile(t, filepath.Join(dir, "generated", "types.go"), "package generated\n")
- writeFile(t, filepath.Join(dir, "api.pb.go"), "package api\n")
-
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- if found["generated/types.go"] {
- t.Error("generated/types.go should be ignored by .cbmignore")
- }
- if found["api.pb.go"] {
- t.Error("api.pb.go should be ignored by .cbmignore")
- }
-}
-
-func TestCBMIgnoreStacksOnGitignore(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- // .gitignore ignores *.log
- writeFile(t, filepath.Join(dir, ".gitignore"), "*.log\n")
- // .cbmignore additionally ignores docs/
- writeFile(t, filepath.Join(dir, ".cbmignore"), "docs/\n")
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
- writeFile(t, filepath.Join(dir, "docs", "api.go"), "package docs\n")
-
- m := loadIgnoreMatchers(dir)
-
- // Both matchers should work
- if !m.shouldIgnore(filepath.Join(dir, "app.log"), false) {
- t.Error("app.log should be ignored by .gitignore")
- }
- if !m.shouldIgnore(filepath.Join(dir, "docs"), true) {
- t.Error("docs/ should be ignored by .cbmignore")
- }
- if m.shouldIgnore(filepath.Join(dir, "main.go"), false) {
- t.Error("main.go should not be ignored")
- }
-
- // End-to-end via Discover
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- if found["docs/api.go"] {
- t.Error("docs/api.go should be ignored by .cbmignore")
- }
-}
-
-func TestCBMIgnoreWithoutGitRepo(t *testing.T) {
- dir := t.TempDir()
- // No .git — but .cbmignore should still work
-
- writeFile(t, filepath.Join(dir, ".cbmignore"), "scratch/\n")
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
- writeFile(t, filepath.Join(dir, "scratch", "tmp.go"), "package scratch\n")
-
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- if found["scratch/tmp.go"] {
- t.Error("scratch/tmp.go should be ignored by .cbmignore")
- }
-}
-
-func TestSymlinkedFilesSkipped(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("symlinks require elevated privileges on Windows")
- }
-
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, "real.go"), "package main\n")
- if err := os.Symlink(filepath.Join(dir, "real.go"), filepath.Join(dir, "link.go")); err != nil {
- t.Fatal(err)
- }
-
- found := discoverRelPaths(t, dir)
- if !found["real.go"] {
- t.Error("real.go should be discovered")
- }
- // filepath.Walk uses Lstat, so symlinked files show ModeSymlink
- // Our check should skip them
- if found["link.go"] {
- t.Error("link.go (symlink) should be skipped")
- }
-}
-
-func TestSymlinkedDirsSkipped(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("symlinks require elevated privileges on Windows")
- }
-
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- writeFile(t, filepath.Join(dir, "src", "main.go"), "package main\n")
- if err := os.Symlink(filepath.Join(dir, "src"), filepath.Join(dir, "src-link")); err != nil {
- t.Fatal(err)
- }
-
- found := discoverRelPaths(t, dir)
- if !found["src/main.go"] {
- t.Error("src/main.go should be discovered")
- }
- // filepath.Walk does NOT follow symlinked dirs, so src-link/ contents won't appear.
- // The symlinked dir entry itself should be skipped by our ModeSymlink check.
- if found["src-link/main.go"] {
- t.Error("src-link/main.go should not appear")
- }
-}
-
-func TestNewIgnorePatterns(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- // Create directories that should now be in IGNORE_PATTERNS
- dirs := []string{".next", ".terraform", "zig-cache", ".cargo", "elm-stuff", "bazel-out"}
- for _, d := range dirs {
- writeFile(t, filepath.Join(dir, d, "file.go"), "package x\n")
- }
- writeFile(t, filepath.Join(dir, "main.go"), "package main\n")
-
- found := discoverRelPaths(t, dir)
- if !found["main.go"] {
- t.Error("main.go should be discovered")
- }
- for _, d := range dirs {
- if found[d+"/file.go"] {
- t.Errorf("%s/file.go should be ignored by IGNORE_PATTERNS", d)
- }
- }
-}
-
-func TestGenericDirsNotIgnoredInFullMode(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- // bin, build, out were moved to fastIgnoreDirs — should be discovered in full mode
- dirs := []string{"bin", "build", "out"}
- for _, d := range dirs {
- writeFile(t, filepath.Join(dir, d, "main.go"), "package "+d+"\n")
- }
-
- found := discoverRelPaths(t, dir)
- for _, d := range dirs {
- if !found[d+"/main.go"] {
- t.Errorf("%s/main.go should be discovered in full mode", d)
- }
- }
-}
-
-func TestGenericDirsIgnoredInFastMode(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
-
- dirs := []string{"bin", "build", "out"}
- for _, d := range dirs {
- writeFile(t, filepath.Join(dir, d, "main.go"), "package "+d+"\n")
- }
-
- files, err := Discover(context.Background(), dir, &Options{Mode: ModeFast})
- if err != nil {
- t.Fatal(err)
- }
- found := make(map[string]bool, len(files))
- for _, f := range files {
- found[f.RelPath] = true
- }
-
- for _, d := range dirs {
- if found[d+"/main.go"] {
- t.Errorf("%s/main.go should be ignored in fast mode", d)
- }
- }
-}
diff --git a/internal/fqn/fqn.go b/internal/fqn/fqn.go
deleted file mode 100644
index 41baa96fe..000000000
--- a/internal/fqn/fqn.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package fqn
-
-import (
- "path/filepath"
- "strings"
-)
-
-// Compute returns the canonical qualified name for a node.
-// Format: <project>.<rel_path_parts_dotted>.<name>
-// Examples:
-// - myproject.cmd.server.main.HandleRequest
-// - myproject.pkg.service.ProcessOrder
-func Compute(project, relPath, name string) string {
- // Remove file extension
- relPath = strings.TrimSuffix(relPath, filepath.Ext(relPath))
- // Convert path separators to dots
- parts := strings.Split(filepath.ToSlash(relPath), "/")
-
- // For Python __init__.py, drop the __init__ part
- if len(parts) > 0 && parts[len(parts)-1] == "__init__" {
- parts = parts[:len(parts)-1]
- }
- // For JS/TS index files
- if len(parts) > 0 && parts[len(parts)-1] == "index" {
- parts = parts[:len(parts)-1]
- }
-
- all := append([]string{project}, parts...)
- if name != "" {
- all = append(all, name)
- }
- return strings.Join(all, ".")
-}
-
-// ModuleQN returns the qualified name for a module (file without function name).
-func ModuleQN(project, relPath string) string {
- return Compute(project, relPath, "")
-}
-
-// FolderQN returns the qualified name for a folder.
-func FolderQN(project, relDir string) string {
- parts := strings.Split(filepath.ToSlash(relDir), "/")
- all := append([]string{project}, parts...)
- return strings.Join(all, ".")
-}
diff --git a/internal/httplink/config.go b/internal/httplink/config.go
deleted file mode 100644
index e43857f71..000000000
--- a/internal/httplink/config.go
+++ /dev/null
@@ -1,90 +0,0 @@
-package httplink
-
-import (
- "os"
- "path/filepath"
- "strings"
-
- "gopkg.in/yaml.v3"
-)
-
-// LinkerConfig holds user-overridable HTTP linker settings.
-// Loaded from .cgrconfig in the project root.
-type LinkerConfig struct {
- HTTPLinker HTTPLinkerConfig `yaml:"http_linker"`
-}
-
-// HTTPLinkerConfig holds HTTP linker-specific settings.
-type HTTPLinkerConfig struct {
- // ExcludePaths are route paths to exclude from HTTP_CALLS matching.
- // These are added to (not replacing) the built-in defaultExcludePaths.
- ExcludePaths []string `yaml:"exclude_paths"`
-
- // MinConfidence is the minimum confidence score for creating HTTP_CALLS edges.
- // Default: 0.25 (includes speculative matches).
- MinConfidence *float64 `yaml:"min_confidence"`
-
- // FuzzyMatching enables/disables fuzzy URL matching.
- // Default: true.
- FuzzyMatching *bool `yaml:"fuzzy_matching"`
-}
-
-// DefaultConfig returns the default linker configuration.
-func DefaultConfig() *LinkerConfig {
- return &LinkerConfig{}
-}
-
-// LoadConfig reads .cgrconfig from the given directory.
-// Returns default config if the file doesn't exist.
-func LoadConfig(dir string) *LinkerConfig {
- cfg := DefaultConfig()
-
- path := filepath.Join(dir, ".cgrconfig")
- data, err := os.ReadFile(path)
- if err != nil {
- return cfg // file not found or unreadable — use defaults
- }
-
- if err := yaml.Unmarshal(data, cfg); err != nil {
- return DefaultConfig() // invalid YAML — use defaults
- }
-
- return cfg
-}
-
-// EffectiveMinConfidence returns the configured minimum confidence,
-// or the default (0.25) if not set.
-func (c *LinkerConfig) EffectiveMinConfidence() float64 {
- if c.HTTPLinker.MinConfidence != nil {
- return *c.HTTPLinker.MinConfidence
- }
- return 0.25
-}
-
-// EffectiveFuzzyMatching returns the configured fuzzy matching setting,
-// or the default (true) if not set.
-func (c *LinkerConfig) EffectiveFuzzyMatching() bool {
- if c.HTTPLinker.FuzzyMatching != nil {
- return *c.HTTPLinker.FuzzyMatching
- }
- return true
-}
-
-// AllExcludePaths returns the combined list of default + user-configured exclude paths.
-func (c *LinkerConfig) AllExcludePaths() []string {
- combined := make([]string, 0, len(defaultExcludePaths)+len(c.HTTPLinker.ExcludePaths))
- combined = append(combined, defaultExcludePaths...)
- combined = append(combined, c.HTTPLinker.ExcludePaths...)
- return combined
-}
-
-// isPathExcluded checks if a route path matches any of the given exclusion paths.
-func isPathExcluded(path string, excludePaths []string) bool {
- normalized := strings.ToLower(strings.TrimRight(path, "/"))
- for _, excluded := range excludePaths {
- if strings.EqualFold(normalized, strings.TrimRight(excluded, "/")) {
- return true
- }
- }
- return false
-}
diff --git a/internal/httplink/config_test.go b/internal/httplink/config_test.go
deleted file mode 100644
index 194d2adfa..000000000
--- a/internal/httplink/config_test.go
+++ /dev/null
@@ -1,112 +0,0 @@
-package httplink
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestLoadConfigDefault(t *testing.T) {
- cfg := LoadConfig("/nonexistent/path")
- if cfg.EffectiveMinConfidence() != 0.25 {
- t.Errorf("expected default min_confidence 0.25, got %f", cfg.EffectiveMinConfidence())
- }
- if !cfg.EffectiveFuzzyMatching() {
- t.Error("expected default fuzzy_matching true")
- }
- paths := cfg.AllExcludePaths()
- if len(paths) != len(defaultExcludePaths) {
- t.Errorf("expected %d default paths, got %d", len(defaultExcludePaths), len(paths))
- }
-}
-
-func TestLoadConfigFromFile(t *testing.T) {
- dir := t.TempDir()
- configContent := `
-http_linker:
- exclude_paths:
- - /debug
- - /internal/status
- min_confidence: 0.5
- fuzzy_matching: false
-`
- if err := os.WriteFile(filepath.Join(dir, ".cgrconfig"), []byte(configContent), 0o600); err != nil {
- t.Fatal(err)
- }
-
- cfg := LoadConfig(dir)
- if cfg.EffectiveMinConfidence() != 0.5 {
- t.Errorf("expected min_confidence 0.5, got %f", cfg.EffectiveMinConfidence())
- }
- if cfg.EffectiveFuzzyMatching() {
- t.Error("expected fuzzy_matching false")
- }
- paths := cfg.AllExcludePaths()
- expectedLen := len(defaultExcludePaths) + 2
- if len(paths) != expectedLen {
- t.Errorf("expected %d total paths, got %d", expectedLen, len(paths))
- }
-}
-
-func TestLoadConfigInvalidYAML(t *testing.T) {
- dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, ".cgrconfig"), []byte("not: [valid: yaml"), 0o600); err != nil {
- t.Fatal(err)
- }
- cfg := LoadConfig(dir)
- // Should fall back to defaults
- if cfg.EffectiveMinConfidence() != 0.25 {
- t.Errorf("expected default on invalid yaml, got %f", cfg.EffectiveMinConfidence())
- }
-}
-
-func TestIsPathExcluded(t *testing.T) {
- paths := []string{"/health", "/debug", "/internal/status"}
-
- tests := []struct {
- path string
- want bool
- }{
- {"/health", true},
- {"/health/", true},
- {"/HEALTH", true},
- {"/debug", true},
- {"/internal/status", true},
- {"/api/orders", false},
- {"/healthcheck", false},
- }
- for _, tt := range tests {
- got := isPathExcluded(tt.path, paths)
- if got != tt.want {
- t.Errorf("isPathExcluded(%q) = %v, want %v", tt.path, got, tt.want)
- }
- }
-}
-
-func TestAllExcludePathsMerge(t *testing.T) {
- cfg := DefaultConfig()
- cfg.HTTPLinker.ExcludePaths = []string{"/custom1", "/custom2"}
-
- paths := cfg.AllExcludePaths()
-
- // Should contain all defaults + custom
- if len(paths) != len(defaultExcludePaths)+2 {
- t.Errorf("expected %d paths, got %d", len(defaultExcludePaths)+2, len(paths))
- }
-
- // Verify defaults are first
- for i, dp := range defaultExcludePaths {
- if paths[i] != dp {
- t.Errorf("paths[%d] = %q, want %q", i, paths[i], dp)
- }
- }
-
- // Verify custom paths are appended
- customStart := len(defaultExcludePaths)
- if paths[customStart] != "/custom1" {
- t.Errorf("paths[%d] = %q, want /custom1", customStart, paths[customStart])
- }
- if paths[customStart+1] != "/custom2" {
- t.Errorf("paths[%d] = %q, want /custom2", customStart+1, paths[customStart+1])
- }
-}
diff --git a/internal/httplink/httplink.go b/internal/httplink/httplink.go
deleted file mode 100644
index 1684b4883..000000000
--- a/internal/httplink/httplink.go
+++ /dev/null
@@ -1,2002 +0,0 @@
-package httplink
-
-import (
- "bufio"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "regexp"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// RouteHandler represents a discovered HTTP route handler.
-type RouteHandler struct {
- Path string
- Method string
- FunctionName string
- QualifiedName string
- HandlerRef string // resolved handler function reference (e.g. "h.CreateOrder")
- ResolvedHandlerQN string // set by createRegistrationCallEdges — actual handler QN
- Protocol string // "ws", "sse", or "" (standard HTTP)
-}
-
-// HTTPCallSite represents a discovered HTTP call site.
-type HTTPCallSite struct {
- Path string
- Method string // best-effort: "GET", "POST", etc. or "" if unknown
- SourceName string
- SourceQualifiedName string
- SourceLabel string // "Function", "Method", or "Module"
- IsAsync bool // true when source uses async dispatch keywords
-}
-
-// HTTPLink represents a matched HTTP call from caller to handler.
-type HTTPLink struct {
- CallerQN string
- CallerLabel string
- HandlerQN string
- URLPath string
- EdgeType string // "HTTP_CALLS" or "ASYNC_CALLS"
-}
-
-// SourceReader returns the full source bytes for a file by relative path.
-type SourceReader func(relPath string) []byte
-
-// SourceLineReader returns specific lines from a file by relative path.
-type SourceLineReader func(relPath string, startLine, endLine int) string
-
-// Linker discovers cross-service HTTP calls and creates HTTP_CALLS edges.
-type Linker struct {
- store store.StoreBackend
- project string
- config *LinkerConfig
- routesByFunc map[string][]int // funcQN → indices into routes slice
- extraCallSites []HTTPCallSite // injected from pipeline (e.g., InfraFile URLs)
- sourceReader SourceReader // RAM source reader (nil → disk fallback)
- sourceLines SourceLineReader // RAM line reader (nil → disk fallback)
- httpKeywordFiles map[string]uint64 // relPath → AC bitmask (files containing HTTP/async keywords)
- routeKeywordFiles map[string]uint64 // relPath → AC bitmask (files containing route registration keywords)
-}
-
-// New creates a new HTTP Linker.
-func New(s store.StoreBackend, project string) *Linker {
- return &Linker{store: s, project: project, config: DefaultConfig()}
-}
-
-// SetConfig sets the linker configuration. If cfg is nil, defaults are used.
-func (l *Linker) SetConfig(cfg *LinkerConfig) {
- if cfg != nil {
- l.config = cfg
- }
-}
-
-// AddCallSites allows the pipeline to inject additional call sites from infra files.
-func (l *Linker) AddCallSites(sites []HTTPCallSite) {
- l.extraCallSites = append(l.extraCallSites, sites...)
-}
-
-// SetSourceReader sets callbacks for reading source from RAM instead of disk.
-func (l *Linker) SetSourceReader(full SourceReader, lines SourceLineReader) {
- l.sourceReader = full
- l.sourceLines = lines
-}
-
-// SetHTTPKeywordFiles sets the pre-screened file filter from AC scanning.
-// Only files in this map will have their functions scanned for HTTP call sites.
-// The bitmask encodes which keyword categories matched (httpClient vs asyncDispatch).
-func (l *Linker) SetHTTPKeywordFiles(files map[string]uint64) {
- l.httpKeywordFiles = files
-}
-
-// SetRouteKeywordFiles sets the pre-screened file filter for route discovery.
-// Only files in this map will have their function source read for route patterns.
-func (l *Linker) SetRouteKeywordFiles(files map[string]uint64) {
- l.routeKeywordFiles = files
-}
-
-// HTTPClientKeywords returns the HTTP client keyword patterns for AC automaton building.
-func HTTPClientKeywords() []string {
- return httpClientKeywords
-}
-
-// AsyncDispatchKeywords returns the async dispatch keyword patterns for AC automaton building.
-func AsyncDispatchKeywords() []string {
- return asyncDispatchKeywords
-}
-
-// RouteKeywords returns keywords that indicate route registration in source code.
-// Used for AC pre-screening to avoid reading source for files with no routes.
-func RouteKeywords() []string {
- return routeKeywords
-}
-
-// routeKeywords are patterns indicating route registration in source code.
-// Files not containing any of these can skip source-based route discovery.
-var routeKeywords = []string{
- // Go gin/chi: .GET("/path"), .POST("/path"), .Group("/prefix"), .Route("/prefix"
- ".GET(", ".POST(", ".PUT(", ".DELETE(", ".PATCH(",
- ".Get(", ".Post(", ".Put(", ".Delete(", ".Patch(",
- ".Group(", ".Route(",
- // Express.js: app.get("/path"), router.post("/path"), .use("/prefix"
- ".get(", ".post(", ".put(", ".delete(", ".patch(",
- ".use(",
- // PHP Laravel: Route::get, Route::post
- "Route::get", "Route::post", "Route::put", "Route::delete", "Route::patch",
- // Kotlin Ktor: get("/path") {, post("/path") {
- // (covered by .get(/.post( above)
- // Python decorators (in properties, but file-level patterns for module scan)
- "@app.", "@router.",
- // Java Spring annotations (in properties, but useful for file screening)
- "@GetMapping", "@PostMapping", "@PutMapping", "@DeleteMapping", "@PatchMapping",
- "@RequestMapping",
- // Rust Actix: #[get("/path")]
- "#[get(", "#[post(", "#[put(", "#[delete(", "#[patch(",
- // C# ASP.NET: [HttpGet("/path")], [Route("/path")]
- "[HttpGet", "[HttpPost", "[HttpPut", "[HttpDelete", "[HttpPatch",
- "[Route(",
- // WebSocket
- ".websocket(", "webSocket(", "@MessageMapping",
-}
-
-// regex patterns for route and URL discovery
-var (
- // Python decorators: @app.post("/path"), @router.get(""), @router.get("/path")
- pyRouteRe = regexp.MustCompile(`@\w+\.(get|post|put|delete|patch)\(\s*["']([^"']*)["']`)
-
- // Go gin/chi routes: .POST("/path"), .Get("/path"), .POST("", handler)
- goRouteRe = regexp.MustCompile(`\.(GET|POST|PUT|DELETE|PATCH|Get|Post|Put|Delete|Patch)\(\s*["']([^"']*)["']`)
-
- // Go gin group: .Group("/prefix")
- goGroupRe = regexp.MustCompile(`(\w+)\s*(?::=|=)\s*\w+\.Group\(\s*["']([^"']+)["']`)
-
- // Go gin/chi route handler reference: captures the last argument (handler, not middleware)
- // .POST("/path", h.CreateOrder) or .Get("/path", handler)
- goRouteHandlerRe = regexp.MustCompile(`\.(GET|POST|PUT|DELETE|PATCH|Get|Post|Put|Delete|Patch)\s*\(\s*"[^"]*"\s*(?:,\s*[\w.]+)*,\s*([\w.]+)\s*\)`)
-
- // Go chi: r.Route("/prefix", func(r chi.Router) { ... })
- goChiRouteRe = regexp.MustCompile(`\.Route\(\s*"([^"]+)"\s*,\s*func`)
-
- // Express.js routes: captures (receiver).(method)("path") — filtered by allowlist
- expressRouteRe = regexp.MustCompile(`(\w+)\.(get|post|put|delete|patch)\(\s*["'` + "`" + `]([^"'` + "`" + `]+)["'` + "`" + `]`)
-
- // Express.js handler reference: captures (receiver).(method)("path", ..., handler)
- expressHandlerRe = regexp.MustCompile(`(\w+)\.(get|post|put|delete|patch)\(\s*["'` + "`" + `][^"'` + "`" + `]+["'` + "`" + `]\s*(?:,\s*[\w.]+)*,\s*([\w.]+)\s*\)`)
-
- // Java Spring annotations: @GetMapping("/path"), @PostMapping, @RequestMapping
- springMappingRe = regexp.MustCompile(`@(Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["']([^"']+)["']`)
-
- // Rust Actix annotations: #[get("/path")], #[post("/path")]
- actixRouteRe = regexp.MustCompile(`#\[(get|post|put|delete|patch)\(\s*"([^"]+)"`)
-
- // PHP Laravel routes: Route::get("/path", Route::post("/path"
- laravelRouteRe = regexp.MustCompile(`Route::(get|post|put|delete|patch)\(\s*["']([^"']+)["']`)
-
- // C# ASP.NET route attributes: [HttpGet("/path")], [Route("/path")]
- aspnetRouteRe = regexp.MustCompile(`\[(Http(?:Get|Post|Put|Delete|Patch))\(\s*"([^"]+)"`)
- aspnetRouteAttrRe = regexp.MustCompile(`\[Route\(\s*"([^"]+)"`)
-
- // Kotlin Ktor routes: get("/path") {, post("/path") {
- ktorRouteRe = regexp.MustCompile(`\b(get|post|put|delete|patch)\(\s*"([^"]+)"\s*\)`)
-
- // Laravel handler: Route::get("/path", [Controller::class, "method"]) or "Controller@method"
- laravelHandlerArrayRe = regexp.MustCompile(`Route::(get|post|put|delete|patch)\(\s*["'][^"']+["']\s*,\s*\[(\w+)::class\s*,\s*["'](\w+)["']\]`)
- laravelHandlerAtRe = regexp.MustCompile(`Route::(get|post|put|delete|patch)\(\s*["'][^"']+["']\s*,\s*["'](\w+)@(\w+)["']`)
-
- // URL patterns in source: https://host/path or http://host/path — captures domain and path
- urlRe = regexp.MustCompile(`https?://([a-zA-Z0-9.\-]+)(/[a-zA-Z0-9_/:.\-]+)`)
-
- // Path-only patterns: "/api/something" (quoted paths starting with /)
- pathRe = regexp.MustCompile(`["'](/[a-zA-Z0-9_/:.\-]{2,})["']`)
-
- // Python WebSocket routes: @app.websocket("/path"), @app.websocket("")
- pyWSRouteRe = regexp.MustCompile(`@\w+\.websocket\(\s*["']([^"']*)["']`)
-
- // Spring WebSocket: @MessageMapping("/path")
- springWSRe = regexp.MustCompile(`@MessageMapping\(\s*["']([^"']+)["']`)
-
- // Kotlin Ktor WebSocket: webSocket("/path") {
- ktorWSRe = regexp.MustCompile(`\bwebSocket\(\s*"([^"]+)"\s*\)`)
-
- // FastAPI prefix: app.include_router(var, prefix="/prefix")
- fastAPIIncludeRe = regexp.MustCompile(`\.include_router\(\s*(\w+)\s*,\s*prefix\s*=\s*["']([^"']+)["']`)
-
- // Python import: from module.path import var_name
- pyImportRe = regexp.MustCompile(`from\s+([\w.]+)\s+import\s+(\w+)`)
-
- // Express prefix: app.use("/prefix", routerVar)
- expressUseRe = regexp.MustCompile(`\.use\(\s*["'` + "`" + `]([^"'` + "`" + `]+)["'` + "`" + `]\s*,\s*(\w+)`)
-
- // JS/TS import patterns for router variable resolution
- jsRequireRe = regexp.MustCompile(`(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*["']([^"']+)["']`)
- jsImportRe = regexp.MustCompile(`import\s+(\w+)\s+from\s+["']([^"']+)["']`)
-
- // Path param normalizers
- colonParamRe = regexp.MustCompile(`:[a-zA-Z_]+`)
- braceParamRe = regexp.MustCompile(`\{[a-zA-Z_]+\}`)
-)
-
-// expressReceiverAllowlist restricts Express route matching to known router variable names.
-// Prevents false positives from req.get("Header"), res.get("key"), map.get("key"), etc.
-var expressReceiverAllowlist = map[string]bool{
- "app": true, "router": true, "server": true, "api": true,
- "routes": true, "express": true, "route": true,
-}
-
-// Run executes the HTTP linking pass.
-func (l *Linker) Run() ([]HTTPLink, error) {
- proj, err := l.store.GetProject(l.project)
- if err != nil {
- return nil, fmt.Errorf("get project: %w", err)
- }
- rootPath := proj.RootPath
-
- // Load config from project root if using defaults
- if l.config.HTTPLinker.MinConfidence == nil &&
- l.config.HTTPLinker.FuzzyMatching == nil &&
- len(l.config.HTTPLinker.ExcludePaths) == 0 {
- l.config = LoadConfig(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) // Go gin
- l.resolveFastAPIPrefixes(routes, rootPath) // Python FastAPI
- l.resolveExpressPrefixes(routes, rootPath) // JS/TS Express
-
- // Resolve handler references first so insertRouteNodes can use the actual handler QN
- l.createRegistrationCallEdges(routes)
-
- // Insert Route nodes and HANDLES edges (uses ResolvedHandlerQN from above)
- l.insertRouteNodes(routes, rootPath)
-
- callSites := l.discoverCallSites(rootPath)
- callSites = append(callSites, l.extraCallSites...)
- slog.Info("httplink.callsites", "count", len(callSites))
-
- links := l.matchAndLink(routes, callSites)
- slog.Info("httplink.links", "count", len(links))
-
- return links, nil
-}
-
-// insertRouteNodes creates Route nodes for each discovered route handler and
-// HANDLES edges from the handler function to the Route node.
-func (l *Linker) insertRouteNodes(routes []RouteHandler, rootPath string) {
- for i := range routes {
- l.insertSingleRouteNode(&routes[i], rootPath)
- }
- slog.Info("httplink.route_nodes", "count", len(routes))
-}
-
-// insertSingleRouteNode creates a Route node and HANDLES edge for one route handler.
-func (l *Linker) insertSingleRouteNode(rh *RouteHandler, rootPath string) {
- normalMethod := rh.Method
- if normalMethod == "" {
- normalMethod = "ANY"
- }
- normalPath := strings.ReplaceAll(rh.Path, "/", "_")
- normalPath = strings.Trim(normalPath, "_")
- routeQN := rh.QualifiedName + ".route." + normalMethod + "." + normalPath
- routeName := normalMethod + " " + rh.Path
-
- // Use resolved handler QN if available, otherwise fall back to registering function
- handlerQN := rh.QualifiedName
- if rh.ResolvedHandlerQN != "" {
- handlerQN = rh.ResolvedHandlerQN
- }
-
- // Look up handler node BEFORE creating Route — we need its file_path
- handlerNode, _ := l.store.FindNodeByQN(l.project, handlerQN)
-
- routeProps := l.buildRouteProps(rh, handlerNode, rootPath)
-
- // Inherit file_path and line range from handler function
- var filePath string
- var startLine, endLine int
- if handlerNode != nil {
- if handlerNode.FilePath != "" {
- filePath = handlerNode.FilePath
- }
- startLine = handlerNode.StartLine
- endLine = handlerNode.EndLine
- }
-
- routeID, err := l.store.UpsertNode(&store.Node{
- Project: l.project,
- Label: "Route",
- Name: routeName,
- QualifiedName: routeQN,
- FilePath: filePath,
- StartLine: startLine,
- EndLine: endLine,
- Properties: routeProps,
- })
- if err != nil || routeID == 0 {
- return
- }
-
- l.linkHandlerToRoute(handlerNode, routeID, routeQN)
-}
-
-// buildRouteProps constructs the properties map for a Route node, including protocol detection.
-func (l *Linker) buildRouteProps(rh *RouteHandler, handlerNode *store.Node, rootPath string) map[string]any {
- handlerQN := rh.QualifiedName
- if rh.ResolvedHandlerQN != "" {
- handlerQN = rh.ResolvedHandlerQN
- }
-
- routeProps := map[string]any{
- "method": rh.Method,
- "path": rh.Path,
- "handler": handlerQN,
- }
-
- // Protocol from route extraction (Python websocket, Spring MessageMapping, Ktor webSocket)
- if rh.Protocol != "" {
- routeProps["protocol"] = rh.Protocol
- return routeProps
- }
-
- // Detect protocol from handler source if not already set
- if handlerNode != nil && handlerNode.FilePath != "" && handlerNode.StartLine > 0 {
- handlerSource := l.readLines(rootPath, handlerNode.FilePath, handlerNode.StartLine, handlerNode.EndLine)
- if protocol := detectProtocol(handlerSource); protocol != "" {
- routeProps["protocol"] = protocol
- }
- }
-
- return routeProps
-}
-
-// linkHandlerToRoute creates HANDLES edge and marks handler as entry point.
-func (l *Linker) linkHandlerToRoute(handlerNode *store.Node, routeID int64, routeQN string) {
- if handlerNode == nil {
- return
- }
-
- if _, edgeErr := l.store.InsertEdge(&store.Edge{
- Project: l.project,
- SourceID: handlerNode.ID,
- TargetID: routeID,
- Type: "HANDLES",
- }); edgeErr != nil {
- // FK failures expected: LastInsertId() can return stale IDs for upserted Route nodes
- slog.Info("httplink.handles_edge.skip", "route", routeQN)
- }
-
- // Mark handler as entry point (for dead code detection)
- if handlerNode.Properties == nil {
- handlerNode.Properties = map[string]any{}
- }
- handlerNode.Properties["is_entry_point"] = true
- if _, upsertErr := l.store.UpsertNode(handlerNode); upsertErr != nil {
- slog.Warn("httplink.entry_point.err", "err", upsertErr)
- }
-}
-
-// isTestNode returns true if the node is from a test file.
-// Checks the is_test property set during pipeline pass 1, with a file path heuristic fallback.
-func isTestNode(n *store.Node) bool {
- if isTest, ok := n.Properties["is_test"].(bool); ok && isTest {
- return true
- }
- // Fallback: common test path patterns
- fp := filepath.ToSlash(n.FilePath)
- return containsTestSegment(fp, "test") ||
- containsTestSegment(fp, "tests") ||
- containsTestSegment(fp, "__tests__") ||
- strings.Contains(fp, "_test.") ||
- strings.Contains(fp, ".test.") ||
- strings.Contains(fp, ".spec.")
-}
-
-// containsTestSegment checks if a path contains a directory segment named seg.
-// Matches both "seg/..." (at start) and ".../seg/..." (mid-path).
-func containsTestSegment(fp, seg string) bool {
- return strings.HasPrefix(fp, seg+"/") || strings.Contains(fp, "/"+seg+"/")
-}
-
-// discoverRoutes finds route handler registrations from Function nodes.
-//
-//nolint:gocognit,cyclop // WHY: inherent complexity from multi-framework route discovery
-func (l *Linker) discoverRoutes(rootPath string) []RouteHandler {
- var routes []RouteHandler
-
- funcs, err := l.store.FindNodesByLabel(l.project, "Function")
- if err != nil {
- slog.Warn("httplink.routes.funcs.err", "err", err)
- return routes
- }
-
- methods, err := l.store.FindNodesByLabel(l.project, "Method")
- if err != nil {
- slog.Warn("httplink.routes.methods.err", "err", err)
- } else {
- funcs = append(funcs, methods...)
- }
-
- // Track which PHP files have Function/Method nodes (for dedup in module scan)
- phpFilesWithFuncs := map[string]bool{}
-
- for _, f := range funcs {
- // Skip test files — test fixtures should not produce Route nodes
- if isTestNode(f) {
- continue
- }
-
- // Python: check decorators property
- routes = append(routes, extractPythonRoutes(f)...)
-
- // Java: check annotation-based decorators (Spring)
- routes = append(routes, extractJavaRoutes(f)...)
-
- // Rust: check attribute decorators (Actix)
- routes = append(routes, extractRustRoutes(f)...)
-
- // C# ASP.NET: check attribute decorators
- routes = append(routes, extractASPNetRoutes(f)...)
-
- // Source-based route discovery (Go gin, Express.js, PHP Laravel, Kotlin Ktor)
- // Skip source reads for files that AC pre-screening excluded.
- if f.FilePath != "" && f.StartLine > 0 && f.EndLine > 0 &&
- (l.routeKeywordFiles == nil || l.routeKeywordFiles[f.FilePath] != 0) {
- source := l.readLines(rootPath, f.FilePath, f.StartLine, f.EndLine)
- if source != "" {
- routes = append(routes, extractGoRoutes(f, source)...)
- routes = append(routes, extractExpressRoutes(f, source)...)
- routes = append(routes, extractLaravelRoutes(f, source)...)
- routes = append(routes, extractKtorRoutes(f, source)...)
- }
- }
-
- if strings.HasSuffix(f.FilePath, ".php") {
- phpFilesWithFuncs[f.FilePath] = true
- }
- }
-
- // Module-level route scanning: some frameworks register routes at file top level
- // (not inside any function body). Scan modules for route patterns.
- modules, err := l.store.FindNodesByLabel(l.project, "Module")
- if err != nil {
- slog.Warn("httplink.routes.modules.err", "err", err)
- return routes
- }
-
- for _, m := range modules {
- // Skip test files
- if isTestNode(m) {
- continue
- }
-
- isPHP := strings.HasSuffix(m.FilePath, ".php")
- isJSTS := strings.HasSuffix(m.FilePath, ".js") ||
- strings.HasSuffix(m.FilePath, ".ts") ||
- strings.HasSuffix(m.FilePath, ".mjs") ||
- strings.HasSuffix(m.FilePath, ".mts")
-
- if !isPHP && !isJSTS {
- continue
- }
- // Skip files that AC pre-screening excluded
- if l.routeKeywordFiles != nil && l.routeKeywordFiles[m.FilePath] == 0 {
- continue
- }
- // For PHP: skip files where routes were already extracted from function bodies
- if isPHP && phpFilesWithFuncs[m.FilePath] {
- continue
- }
- sourceBytes := l.readFull(rootPath, m.FilePath)
- source := string(sourceBytes)
- if source == "" {
- continue
- }
- if isPHP {
- routes = append(routes, extractLaravelRoutes(m, source)...)
- }
- if isJSTS {
- routes = append(routes, extractExpressRoutes(m, source)...)
- }
- }
-
- return routes
-}
-
-// extractPythonRoutes extracts route handlers from Python decorator metadata.
-func extractPythonRoutes(f *store.Node) []RouteHandler {
- var routes []RouteHandler
-
- decs, ok := f.Properties["decorators"]
- if !ok {
- return routes
- }
-
- // decorators is stored as []any (JSON deserialized)
- decList, ok := decs.([]any)
- if !ok {
- return routes
- }
-
- for _, d := range decList {
- decStr, ok := d.(string)
- if !ok {
- continue
- }
- // Standard HTTP routes
- matches := pyRouteRe.FindAllStringSubmatch(decStr, -1)
- for _, m := range matches {
- routes = append(routes, RouteHandler{
- Path: m[2],
- Method: strings.ToUpper(m[1]),
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- // WebSocket routes: @app.websocket("/path")
- if wm := pyWSRouteRe.FindStringSubmatch(decStr); wm != nil {
- routes = append(routes, RouteHandler{
- Path: wm[1],
- Method: "WS",
- Protocol: "ws",
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- }
-
- return routes
-}
-
-// extractGoRoutes extracts route registrations from Go source code (gin/chi patterns).
-// Resolves gin group prefixes and chi r.Route("/prefix", func...) blocks.
-func extractGoRoutes(f *store.Node, source string) []RouteHandler {
- routes := make([]RouteHandler, 0, 4)
-
- // Build a map of variable name → group prefix from gin Group() calls
- groupPrefixes := map[string]string{}
- for _, gm := range goGroupRe.FindAllStringSubmatch(source, -1) {
- groupPrefixes[gm[1]] = gm[2]
- }
-
- // Chi Route() prefix stack for nested r.Route("/prefix", func...) blocks
- type chiBlock struct {
- prefix string
- depth int
- }
- var chiStack []chiBlock
- braceDepth := 0
-
- lines := strings.Split(source, "\n")
- for _, line := range lines {
- // Detect chi .Route("/prefix", func...) blocks
- if cm := goChiRouteRe.FindStringSubmatch(line); cm != nil {
- chiStack = append(chiStack, chiBlock{prefix: cm[1], depth: braceDepth})
- }
-
- // Track brace depth
- braceDepth += strings.Count(line, "{") - strings.Count(line, "}")
-
- // Pop closed chi blocks
- for len(chiStack) > 0 && braceDepth <= chiStack[len(chiStack)-1].depth {
- chiStack = chiStack[:len(chiStack)-1]
- }
-
- rm := goRouteRe.FindStringSubmatch(line)
- if rm == nil {
- continue
- }
- method := strings.ToUpper(rm[1])
- path := rm[2]
-
- // Apply chi prefix stack if active, otherwise try gin group resolution
- if len(chiStack) > 0 {
- var fullPrefix string
- for _, block := range chiStack {
- fullPrefix = strings.TrimRight(fullPrefix, "/") + "/" + strings.TrimLeft(block.prefix, "/")
- }
- if path == "/" || path == "" {
- path = fullPrefix
- } else {
- path = strings.TrimRight(fullPrefix, "/") + "/" + strings.TrimLeft(path, "/")
- }
- } else {
- path = resolveGroupPrefix(line, rm[1], path, groupPrefixes)
- }
-
- // Capture handler reference (last argument) for CALLS edge creation
- var handlerRef string
- if hm := goRouteHandlerRe.FindStringSubmatch(line); hm != nil {
- handlerRef = hm[2]
- }
-
- routes = append(routes, RouteHandler{
- Path: path,
- Method: method,
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- HandlerRef: handlerRef,
- })
- }
-
- return routes
-}
-
-// resolveGroupPrefix resolves a router group prefix for a route line.
-// It finds the receiver variable (e.g., "contracts" in "contracts.POST")
-// and looks up its group prefix.
-func resolveGroupPrefix(line, method, path string, groupPrefixes map[string]string) string {
- idx := strings.Index(line, "."+method+"(")
- if idx <= 0 {
- return path
- }
- prefix := strings.TrimSpace(line[:idx])
- parts := strings.Fields(prefix)
- if len(parts) == 0 {
- return path
- }
- receiver := parts[len(parts)-1]
- gp, ok := groupPrefixes[receiver]
- if !ok {
- return path
- }
- resolved := strings.TrimRight(gp, "/") + "/" + strings.TrimLeft(path, "/")
- if resolved == "/" {
- return gp
- }
- return resolved
-}
-
-// extractExpressRoutes extracts route registrations from JS/TS source (Express/Koa patterns).
-// Uses receiver allowlist to avoid false positives from req.get(), res.get(), etc.
-func extractExpressRoutes(f *store.Node, source string) []RouteHandler {
- routes := make([]RouteHandler, 0, 4)
- for _, line := range strings.Split(source, "\n") {
- rm := expressRouteRe.FindStringSubmatch(line)
- if rm == nil {
- continue
- }
- // rm[1]=receiver, rm[2]=method, rm[3]=path
- receiver := strings.ToLower(rm[1])
- if !expressReceiverAllowlist[receiver] {
- continue
- }
-
- // Express overloads .get(): with 1 arg it's a config getter (app.get('trust proxy')),
- // with 2+ args it's a route (app.get('/path', handler)). Only .get() has this
- // overload — .post/.put/.delete/.patch are always routes.
- if strings.EqualFold(rm[2], "get") {
- // Check if there's a comma after the closing quote — indicates a callback/handler arg
- matchEnd := strings.Index(line, rm[0]) + len(rm[0])
- rest := strings.TrimSpace(line[matchEnd:])
- if !strings.HasPrefix(rest, ",") {
- continue // Single-arg app.get('setting') — config getter, skip
- }
- }
-
- var handlerRef string
- hm := expressHandlerRe.FindStringSubmatch(line)
- if hm != nil {
- handlerRef = hm[3] // group 3 after adding receiver capture
- }
-
- routes = append(routes, RouteHandler{
- Path: rm[3],
- Method: strings.ToUpper(rm[2]),
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- HandlerRef: handlerRef,
- })
- }
- return routes
-}
-
-// extractJavaRoutes extracts routes from Java Spring annotations in decorators.
-func extractJavaRoutes(f *store.Node) []RouteHandler {
- var routes []RouteHandler
- decs, ok := f.Properties["decorators"]
- if !ok {
- return routes
- }
- decList, ok := decs.([]any)
- if !ok {
- return routes
- }
- for _, d := range decList {
- decStr, ok := d.(string)
- if !ok {
- continue
- }
- // Standard Spring HTTP mappings
- matches := springMappingRe.FindAllStringSubmatch(decStr, -1)
- for _, m := range matches {
- method := strings.ToUpper(m[1])
- if method == "REQUEST" {
- method = "" // RequestMapping doesn't specify method
- }
- routes = append(routes, RouteHandler{
- Path: m[2],
- Method: method,
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- // Spring WebSocket: @MessageMapping("/path")
- if wm := springWSRe.FindStringSubmatch(decStr); wm != nil {
- routes = append(routes, RouteHandler{
- Path: wm[1],
- Method: "WS",
- Protocol: "ws",
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- }
- return routes
-}
-
-// extractRustRoutes extracts routes from Rust Actix attribute decorators.
-func extractRustRoutes(f *store.Node) []RouteHandler {
- var routes []RouteHandler
- decs, ok := f.Properties["decorators"]
- if !ok {
- return routes
- }
- decList, ok := decs.([]any)
- if !ok {
- return routes
- }
- for _, d := range decList {
- decStr, ok := d.(string)
- if !ok {
- continue
- }
- matches := actixRouteRe.FindAllStringSubmatch(decStr, -1)
- for _, m := range matches {
- routes = append(routes, RouteHandler{
- Path: m[2],
- Method: strings.ToUpper(m[1]),
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- }
- return routes
-}
-
-// extractLaravelRoutes extracts route registrations from PHP Laravel source.
-func extractLaravelRoutes(f *store.Node, source string) []RouteHandler {
- routes := make([]RouteHandler, 0, 4)
- for _, line := range strings.Split(source, "\n") {
- rm := laravelRouteRe.FindStringSubmatch(line)
- if rm == nil {
- continue
- }
-
- // Try to extract handler reference from [Controller::class, "method"] or "Controller@method"
- var handlerRef string
- if am := laravelHandlerArrayRe.FindStringSubmatch(line); am != nil {
- handlerRef = am[3] // method name from [Controller::class, "method"]
- } else if atm := laravelHandlerAtRe.FindStringSubmatch(line); atm != nil {
- handlerRef = atm[3] // method name from "Controller@method"
- }
-
- routes = append(routes, RouteHandler{
- Path: rm[2],
- Method: strings.ToUpper(rm[1]),
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- HandlerRef: handlerRef,
- })
- }
- return routes
-}
-
-// extractASPNetRoutes extracts route handlers from C# ASP.NET attribute metadata.
-func extractASPNetRoutes(f *store.Node) []RouteHandler {
- var routes []RouteHandler
-
- decs, ok := f.Properties["decorators"]
- if !ok {
- return routes
- }
-
- decList, ok := decs.([]any)
- if !ok {
- return routes
- }
-
- for _, d := range decList {
- decStr, ok := d.(string)
- if !ok {
- continue
- }
- // [HttpGet("/path")] pattern
- matches := aspnetRouteRe.FindAllStringSubmatch(decStr, -1)
- for _, m := range matches {
- method := strings.TrimPrefix(m[1], "Http")
- routes = append(routes, RouteHandler{
- Path: m[2],
- Method: strings.ToUpper(method),
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- // [Route("/path")] pattern
- routeMatches := aspnetRouteAttrRe.FindAllStringSubmatch(decStr, -1)
- for _, m := range routeMatches {
- routes = append(routes, RouteHandler{
- Path: m[1],
- Method: "",
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- }
- return routes
-}
-
-// extractKtorRoutes extracts route handlers from Kotlin Ktor source code.
-func extractKtorRoutes(f *store.Node, source string) []RouteHandler {
- routes := make([]RouteHandler, 0, 4)
- for _, line := range strings.Split(source, "\n") {
- // Standard HTTP routes
- if rm := ktorRouteRe.FindStringSubmatch(line); rm != nil {
- routes = append(routes, RouteHandler{
- Path: rm[2],
- Method: strings.ToUpper(rm[1]),
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- continue
- }
- // WebSocket routes: webSocket("/path") {
- if wm := ktorWSRe.FindStringSubmatch(line); wm != nil {
- routes = append(routes, RouteHandler{
- Path: wm[1],
- Method: "WS",
- Protocol: "ws",
- FunctionName: f.Name,
- QualifiedName: f.QualifiedName,
- })
- }
- }
- return routes
-}
-
-// discoverCallSites finds HTTP URL references in Module constants and Function source.
-func (l *Linker) discoverCallSites(rootPath string) []HTTPCallSite {
- var sites []HTTPCallSite
-
- // Module constants
- modules, err := l.store.FindNodesByLabel(l.project, "Module")
- if err != nil {
- slog.Warn("httplink.callsites.modules.err", "err", err)
- } else {
- for _, m := range modules {
- sites = append(sites, extractModuleCallSites(m)...)
- }
- }
-
- // Function/Method source — skip files that AC pre-screening excluded
- funcs, err := l.store.FindNodesByLabel(l.project, "Function")
- if err != nil {
- slog.Warn("httplink.callsites.funcs.err", "err", err)
- } else {
- for _, f := range funcs {
- if l.httpKeywordFiles != nil {
- if _, ok := l.httpKeywordFiles[f.FilePath]; !ok {
- continue
- }
- }
- sites = append(sites, l.extractFunctionCallSites(f, rootPath)...)
- }
- }
-
- methods, err := l.store.FindNodesByLabel(l.project, "Method")
- if err != nil {
- slog.Warn("httplink.callsites.methods.err", "err", err)
- } else {
- for _, f := range methods {
- if l.httpKeywordFiles != nil {
- if _, ok := l.httpKeywordFiles[f.FilePath]; !ok {
- continue
- }
- }
- sites = append(sites, l.extractFunctionCallSites(f, rootPath)...)
- }
- }
-
- return sites
-}
-
-// extractModuleCallSites extracts HTTP paths from module constants.
-func extractModuleCallSites(m *store.Node) []HTTPCallSite {
- var sites []HTTPCallSite
-
- constants, ok := m.Properties["constants"]
- if !ok {
- return sites
- }
-
- constList, ok := constants.([]any)
- if !ok {
- return sites
- }
-
- for _, c := range constList {
- cStr, ok := c.(string)
- if !ok {
- continue
- }
- paths := extractURLPaths(cStr)
- for _, p := range paths {
- sites = append(sites, HTTPCallSite{
- Path: p,
- SourceName: m.Name,
- SourceQualifiedName: m.QualifiedName,
- SourceLabel: "Module",
- })
- }
- }
-
- return sites
-}
-
-// detectHTTPMethod tries to find the HTTP method used near a URL path in source code.
-func detectHTTPMethod(source string) string {
- upper := strings.ToUpper(source)
- for _, verb := range []string{"POST", "PUT", "DELETE", "PATCH", "GET"} {
- // Python: requests.post(, httpx.post(
- if strings.Contains(upper, "REQUESTS."+verb+"(") || strings.Contains(upper, "HTTPX."+verb+"(") {
- return verb
- }
- // Go: "POST" near http.NewRequest
- if strings.Contains(upper, `"`+verb+`"`) && strings.Contains(upper, "HTTP.") {
- return verb
- }
- // JS: method: "POST", method: 'POST'
- if strings.Contains(upper, "METHOD") && strings.Contains(upper, verb) {
- return verb
- }
- // Java: HttpMethod.POST, .method(POST
- if strings.Contains(upper, "HTTPMETHOD."+verb) {
- return verb
- }
- // Rust: reqwest::Client::new().post(, .get(
- if strings.Contains(source, "."+strings.ToLower(verb)+"(") {
- return verb
- }
- // PHP: curl CURLOPT_CUSTOMREQUEST
- if strings.Contains(upper, "CURLOPT") && strings.Contains(upper, verb) {
- return verb
- }
- }
- return ""
-}
-
-// httpClientKeywords are patterns indicating actual HTTP client usage.
-// A function must contain at least one of these to be considered an HTTP call site.
-var httpClientKeywords = []string{
- // Python
- "requests.get", "requests.post", "requests.put", "requests.delete", "requests.patch",
- "httpx.", "aiohttp.", "urllib.request",
- // Go
- "http.Get", "http.Post", "http.NewRequest", "client.Do(",
- // JavaScript/TypeScript
- "fetch(", "axios.", ".ajax(",
- // Java
- "HttpClient", "RestTemplate", "WebClient", "OkHttpClient",
- "HttpURLConnection", "openConnection(",
- // Rust
- "reqwest::", "hyper::", "surf::", "ureq::",
- // PHP
- "curl_exec", "curl_init", "Guzzle", "Http::get", "Http::post",
- // Scala
- "sttp.", "http4s", "HttpClient", "wsClient",
- // C++
- "curl_easy", "cpr::Get", "cpr::Post", "httplib::",
- // Lua
- "socket.http", "http.request", "curl.",
- // C#
- "HttpClient", "WebClient", "RestClient", "HttpWebRequest",
- // Kotlin
- "OkHttpClient", "HttpClient", "ktor.client",
- // Generic
- "send_request", "http_client",
-}
-
-// asyncDispatchKeywords indicate cross-service async dispatch via HTTP.
-// Functions containing these keywords create ASYNC_CALLS edges instead of HTTP_CALLS.
-var asyncDispatchKeywords = []string{
- // Cloud Tasks (GCP) — task body contains HTTP URL
- "CreateTask", "create_task",
- // Pub/Sub publish (GCP) — push subscriptions deliver via HTTP
- "topic.Publish", "publisher.publish", "topic.publish",
- // AWS SQS/SNS — SQS + Lambda/HTTP, SNS + HTTP subscription
- "sqs.send_message", "sns.publish",
- // RabbitMQ — exchange → HTTP consumer
- "basic_publish",
- // Kafka — consumer often fronted by HTTP
- "producer.send", "producer.Send",
-}
-
-// wsPatterns indicate WebSocket usage in handler source.
-var wsPatterns = []string{
- // Go: gorilla/nhooyr websocket
- "websocket.Upgrade", "websocket.Accept", "upgrader.Upgrade",
- // JS/TS: ws library, socket.io
- `ws.on("connection`, `io.on("connection`, "new WebSocket(",
- // Generic
- "WebSocketSession", "wsHandler",
-}
-
-// ssePatterns indicate Server-Sent Events usage in handler source.
-var ssePatterns = []string{
- "text/event-stream",
- "EventSourceResponse",
- "SseEmitter",
- "ServerSentEvent",
- "event-stream",
-}
-
-// detectProtocol checks handler source for WebSocket or SSE patterns.
-// Returns "ws", "sse", or "" (standard HTTP).
-func detectProtocol(source string) string {
- for _, p := range wsPatterns {
- if strings.Contains(source, p) {
- return "ws"
- }
- }
- for _, p := range ssePatterns {
- if strings.Contains(source, p) {
- return "sse"
- }
- }
- return ""
-}
-
-// extractFunctionCallSites extracts HTTP paths from function source code.
-func (l *Linker) extractFunctionCallSites(f *store.Node, rootPath string) []HTTPCallSite {
- sites := make([]HTTPCallSite, 0, 4)
-
- if f.FilePath == "" || f.StartLine <= 0 || f.EndLine <= 0 {
- return sites
- }
-
- // Skip Python dunder methods — they configure, not call
- if strings.HasPrefix(f.Name, "__") && strings.HasSuffix(f.Name, "__") {
- return sites
- }
-
- source := l.readLines(rootPath, f.FilePath, f.StartLine, f.EndLine)
- if source == "" {
- return sites
- }
-
- // Require at least one HTTP client or async dispatch keyword to avoid
- // false positives from functions that merely store URL strings in variables
- hasHTTPClient := false
- for _, kw := range httpClientKeywords {
- if strings.Contains(source, kw) {
- hasHTTPClient = true
- break
- }
- }
-
- hasAsyncDispatch := false
- for _, kw := range asyncDispatchKeywords {
- if strings.Contains(source, kw) {
- hasAsyncDispatch = true
- break
- }
- }
-
- if !hasHTTPClient && !hasAsyncDispatch {
- return sites
- }
-
- // Sync (HTTP client) takes precedence over async dispatch
- isAsync := hasAsyncDispatch && !hasHTTPClient
-
- method := detectHTTPMethod(source)
-
- paths := extractURLPaths(source)
- for _, p := range paths {
- sites = append(sites, HTTPCallSite{
- Path: p,
- Method: method,
- SourceName: f.Name,
- SourceQualifiedName: f.QualifiedName,
- SourceLabel: f.Label,
- IsAsync: isAsync,
- })
- }
-
- return sites
-}
-
-// externalDomains are well-known external API domains whose paths
-// should not be matched against internal route handlers.
-var externalDomains = []string{
- "googleapis.com",
- "google.com",
- "github.com",
- "gitlab.com",
- "docker.com",
- "docker.io",
- "npmjs.org",
- "pypi.org",
- "cloudflare.com",
- "sentry.io",
- "aws.amazon.com",
-}
-
-// defaultExcludePaths are common utility endpoints that produce noise in HTTP_CALLS.
-// These are excluded from route matching by default.
-var defaultExcludePaths = []string{
- "/health",
- "/healthz",
- "/ready",
- "/readyz",
- "/metrics",
- "/favicon.ico",
-}
-
-// isExternalDomain checks if a domain is a well-known external API.
-func isExternalDomain(domain string) bool {
- domain = strings.ToLower(domain)
- for _, ext := range externalDomains {
- if domain == ext || strings.HasSuffix(domain, "."+ext) {
- return true
- }
- }
- return false
-}
-
-// ExtractURLPaths finds URL path segments from text (exported for use by pipeline).
-func ExtractURLPaths(text string) []string {
- return extractURLPaths(text)
-}
-
-// extractURLPaths finds URL path segments from text.
-func extractURLPaths(text string) []string {
- seen := map[string]bool{}
- var paths []string
-
- // Full URLs: extract domain and path, skip external domains
- for _, m := range urlRe.FindAllStringSubmatch(text, -1) {
- domain := m[1]
- p := m[2]
- if isExternalDomain(domain) {
- continue
- }
- if !seen[p] {
- seen[p] = true
- paths = append(paths, p)
- }
- }
-
- // Quoted path literals
- for _, m := range pathRe.FindAllStringSubmatch(text, -1) {
- p := m[1]
- if !seen[p] {
- seen[p] = true
- paths = append(paths, p)
- }
- }
-
- // Try to extract URLs from embedded JSON strings (e.g., Cloud Tasks payloads)
- for _, p := range extractJSONStringPaths(text) {
- if !seen[p] {
- seen[p] = true
- paths = append(paths, p)
- }
- }
-
- return paths
-}
-
-// extractJSONStringPaths tries to JSON-parse the text (or substrings that look
-// like JSON) and extract URL paths from string values within.
-func extractJSONStringPaths(text string) []string {
- seen := make(map[string]bool)
- var paths []string
-
- // Find JSON-like substrings: {...} or [...]
- for _, bounds := range findJSONBounds(text) {
- var parsed any
- if err := json.Unmarshal([]byte(bounds), &parsed); err != nil {
- continue
- }
- var raw []string
- walkJSONForURLs(parsed, &raw)
- for _, p := range raw {
- if !seen[p] {
- seen[p] = true
- paths = append(paths, p)
- }
- }
- }
-
- return paths
-}
-
-// findJSONBounds extracts substrings that look like JSON objects or arrays.
-func findJSONBounds(text string) []string {
- results := make([]string, 0, 4)
- for _, opener := range []byte{'{', '['} {
- closer := byte('}')
- if opener == '[' {
- closer = ']'
- }
- results = append(results, scanJSONBlocks(text, opener, closer)...)
- }
- return results
-}
-
-// scanJSONBlocks scans text for balanced JSON blocks delimited by opener/closer.
-func scanJSONBlocks(text string, opener, closer byte) []string {
- var results []string
- start := strings.IndexByte(text, opener)
- for start >= 0 && start < len(text) {
- end, ok := findBalancedEnd(text, start, opener, closer)
- if !ok {
- break
- }
- candidate := text[start : end+1]
- if len(candidate) > 5 {
- results = append(results, candidate)
- }
- start = end + 1
- next := strings.IndexByte(text[start:], opener)
- if next < 0 {
- break
- }
- start += next
- }
- return results
-}
-
-// findBalancedEnd finds the index of the closing bracket that balances the opener at start.
-// Returns the index and true if found, or 0 and false if unbalanced.
-func findBalancedEnd(text string, start int, opener, closer byte) (int, bool) {
- depth := 0
- inStr := false
- for i := start; i < len(text); i++ {
- ch := text[i]
- if inStr {
- if ch == '\\' {
- i++ // skip escaped char
- continue
- }
- if ch == '"' {
- inStr = false
- }
- continue
- }
- switch ch {
- case '"':
- inStr = true
- case opener:
- depth++
- case closer:
- depth--
- if depth == 0 {
- return i, true
- }
- }
- }
- return 0, false
-}
-
-// walkJSONForURLs recursively walks parsed JSON and extracts URL paths.
-func walkJSONForURLs(v any, out *[]string) {
- switch val := v.(type) {
- case map[string]any:
- for _, child := range val {
- walkJSONForURLs(child, out)
- }
- case []any:
- for _, child := range val {
- walkJSONForURLs(child, out)
- }
- case string:
- // Check if value is a URL or path
- for _, m := range urlRe.FindAllStringSubmatch(val, -1) {
- if !isExternalDomain(m[1]) {
- *out = append(*out, m[2])
- }
- }
- for _, m := range pathRe.FindAllStringSubmatch(`"`+val+`"`, -1) {
- *out = append(*out, m[1])
- }
- }
-}
-
-// matchAndLink matches call site paths to route handler paths and creates edges.
-// Uses multi-signal probabilistic scoring (path Jaccard, depth, method, source type).
-// Only creates edges above the confidence threshold.
-// Pre-caches QN lookups, pre-normalizes paths, and batch-inserts edges.
-func (l *Linker) matchAndLink(routes []RouteHandler, callSites []HTTPCallSite) []HTTPLink { //nolint:gocognit // multi-signal scoring loop is inherently complex
- // Pre-resolve all unique QNs before the nested loop
- qnCache := make(map[string]*store.Node)
- for _, cs := range callSites {
- if _, ok := qnCache[cs.SourceQualifiedName]; !ok {
- n, _ := l.store.FindNodeByQN(l.project, cs.SourceQualifiedName)
- qnCache[cs.SourceQualifiedName] = n // nil cached as "not found"
- }
- }
- for _, rh := range routes {
- if _, ok := qnCache[rh.QualifiedName]; !ok {
- n, _ := l.store.FindNodeByQN(l.project, rh.QualifiedName)
- qnCache[rh.QualifiedName] = n
- }
- }
-
- // Pre-normalize all paths (avoid redundant regex in the inner loop)
- normCalls := make([]string, len(callSites))
- for i, cs := range callSites {
- normCalls[i] = normalizePath(cs.Path)
- }
- normRoutes := make([]string, len(routes))
- for i, rh := range routes {
- normRoutes[i] = normalizePath(rh.Path)
- }
-
- slog.Info("httplink.matchAndLink.stats",
- "routes", len(routes),
- "callsites", len(callSites),
- "cached_qns", len(qnCache))
-
- excludePaths := l.config.AllExcludePaths()
- minConf := l.config.EffectiveMinConfidence()
-
- var pendingEdges []*store.Edge
- var links []HTTPLink
-
- for ci, cs := range callSites {
- callerNode := qnCache[cs.SourceQualifiedName]
- if callerNode == nil {
- continue
- }
- for ri, rh := range routes {
- if sameService(cs.SourceQualifiedName, rh.QualifiedName) {
- continue
- }
- if isPathExcluded(rh.Path, excludePaths) {
- continue
- }
-
- // Multi-signal confidence scoring using pre-normalized paths
- pathScore := pathMatchScorePreNorm(normCalls[ci], normRoutes[ri])
- if pathScore == 0 {
- continue
- }
-
- score := pathScore*sourceWeight(cs.SourceLabel) + methodBonus(cs.Method, rh.Method)
- if score < minConf {
- continue
- }
- if score > 1.0 {
- score = 1.0
- }
-
- edgeType := "HTTP_CALLS"
- if cs.IsAsync {
- edgeType = "ASYNC_CALLS"
- }
-
- handlerNode := qnCache[rh.QualifiedName]
- if handlerNode != nil {
- band := confidenceBand(score)
- props := map[string]any{
- "url_path": cs.Path,
- "confidence": score,
- "confidence_band": band,
- }
- if rh.Method != "" {
- props["method"] = rh.Method
- }
- pendingEdges = append(pendingEdges, &store.Edge{
- Project: l.project,
- SourceID: callerNode.ID,
- TargetID: handlerNode.ID,
- Type: edgeType,
- Properties: props,
- })
- }
-
- links = append(links, HTTPLink{
- CallerQN: cs.SourceQualifiedName,
- CallerLabel: cs.SourceLabel,
- HandlerQN: rh.QualifiedName,
- URLPath: cs.Path,
- EdgeType: edgeType,
- })
- }
- }
-
- if len(pendingEdges) > 0 {
- _ = l.store.InsertEdgeBatch(pendingEdges)
- }
- return links
-}
-
-// normalizePath normalizes a URL path for comparison.
-// numericSegmentRe matches path segments that are pure numeric IDs.
-var numericSegmentRe = regexp.MustCompile(`/\d+(/|$)`)
-
-// uuidSegmentRe matches path segments that are UUIDs.
-var uuidSegmentRe = regexp.MustCompile(`/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(/|$)`)
-
-func normalizePath(path string) string {
- path = strings.TrimRight(path, "/")
- path = colonParamRe.ReplaceAllString(path, "*")
- path = braceParamRe.ReplaceAllString(path, "*")
- // Normalize UUIDs and numeric IDs to wildcards for better matching
- path = uuidSegmentRe.ReplaceAllString(path, "/*$1")
- path = numericSegmentRe.ReplaceAllString(path, "/*$1")
- return strings.ToLower(path)
-}
-
-// matchConfidenceThreshold is the minimum score for an HTTP_CALLS edge.
-// Lowered from 0.45 to 0.25 to include speculative matches with confidence bands.
-const matchConfidenceThreshold = 0.25
-
-// pathMatchScore returns a confidence score (0.0–1.0) for how well callPath
-// matches routePath. Returns 0 if no match.
-//
-// Multi-signal scoring (inspired by RAD/Code2DFD research):
-//
-// confidence = matchBase × (0.5 × jaccard + 0.5 × depthFactor)
-//
-// Where:
-//
-// matchBase: exact=0.95, suffix=0.75, wildcard=0.55
-// jaccard: segment Jaccard similarity (non-wildcard segments)
-// depthFactor: min(matched_segments / 3.0, 1.0) — longer paths = more specific
-func pathMatchScore(callPath, routePath string) float64 {
- normCall := normalizePath(callPath)
- normRoute := normalizePath(routePath)
-
- if normCall == "" || normRoute == "" {
- return 0
- }
-
- // Determine structural match type
- var matchBase float64
- var matchedCallSegs, matchedRouteSegs []string
-
- switch {
- case normCall == normRoute:
- matchBase = 0.95
- matchedCallSegs = splitSegments(normCall)
- matchedRouteSegs = splitSegments(normRoute)
- case strings.HasSuffix(normCall, normRoute):
- matchBase = 0.75
- matchedCallSegs = splitSegments(normRoute) // use the route portion that matched
- matchedRouteSegs = splitSegments(normRoute)
- default:
- // Segment-by-segment wildcard matching
- callParts := strings.Split(normCall, "/")
- routeParts := strings.Split(normRoute, "/")
- if len(callParts) != len(routeParts) {
- return 0
- }
- for i := range callParts {
- if callParts[i] != routeParts[i] && callParts[i] != "*" && routeParts[i] != "*" {
- return 0
- }
- }
- matchBase = 0.55
- matchedCallSegs = splitSegments(normCall)
- matchedRouteSegs = splitSegments(normRoute)
- }
-
- // Jaccard similarity on non-empty, non-wildcard segments
- jaccard := segmentJaccard(matchedCallSegs, matchedRouteSegs)
-
- // Depth factor: more segments = more specific match
- totalSegs := len(matchedRouteSegs)
- depthFactor := float64(totalSegs) / 3.0
- if depthFactor > 1.0 {
- depthFactor = 1.0
- }
-
- score := matchBase * (0.5*jaccard + 0.5*depthFactor)
- if score > 1.0 {
- score = 1.0
- }
- return score
-}
-
-// pathMatchScorePreNorm is like pathMatchScore but accepts already-normalized paths.
-// Avoids redundant normalizePath calls in the hot loop.
-func pathMatchScorePreNorm(normCall, normRoute string) float64 {
- if normCall == "" || normRoute == "" {
- return 0
- }
-
- var matchBase float64
- var matchedCallSegs, matchedRouteSegs []string
-
- switch {
- case normCall == normRoute:
- matchBase = 0.95
- matchedCallSegs = splitSegments(normCall)
- matchedRouteSegs = splitSegments(normRoute)
- case strings.HasSuffix(normCall, normRoute):
- matchBase = 0.75
- matchedCallSegs = splitSegments(normRoute)
- matchedRouteSegs = splitSegments(normRoute)
- default:
- callParts := strings.Split(normCall, "/")
- routeParts := strings.Split(normRoute, "/")
- if len(callParts) != len(routeParts) {
- return 0
- }
- for i := range callParts {
- if callParts[i] != routeParts[i] && callParts[i] != "*" && routeParts[i] != "*" {
- return 0
- }
- }
- matchBase = 0.55
- matchedCallSegs = splitSegments(normCall)
- matchedRouteSegs = splitSegments(normRoute)
- }
-
- jaccard := segmentJaccard(matchedCallSegs, matchedRouteSegs)
- totalSegs := len(matchedRouteSegs)
- depthFactor := float64(totalSegs) / 3.0
- if depthFactor > 1.0 {
- depthFactor = 1.0
- }
-
- score := matchBase * (0.5*jaccard + 0.5*depthFactor)
- if score > 1.0 {
- score = 1.0
- }
- return score
-}
-
-// splitSegments splits a normalized path into non-empty segments.
-func splitSegments(path string) []string {
- var segs []string
- for _, s := range strings.Split(path, "/") {
- if s != "" {
- segs = append(segs, s)
- }
- }
- return segs
-}
-
-// segmentJaccard computes Jaccard similarity on non-wildcard path segments.
-// Wildcards (*) are excluded from both sets since they match anything.
-func segmentJaccard(segsA, segsB []string) float64 {
- setA := make(map[string]bool)
- setB := make(map[string]bool)
- for _, s := range segsA {
- if s != "*" {
- setA[s] = true
- }
- }
- for _, s := range segsB {
- if s != "*" {
- setB[s] = true
- }
- }
-
- if len(setA) == 0 && len(setB) == 0 {
- return 0
- }
-
- intersection := 0
- for k := range setA {
- if setB[k] {
- intersection++
- }
- }
-
- union := len(setA)
- for k := range setB {
- if !setA[k] {
- union++
- }
- }
-
- if union == 0 {
- return 0
- }
- return float64(intersection) / float64(union)
-}
-
-// methodBonus returns a confidence adjustment based on HTTP method matching.
-//
-// +0.10 if both methods are known and match
-// 0.00 if one or both methods are unknown
-// -0.15 if both methods are known and mismatch
-func methodBonus(callMethod, routeMethod string) float64 {
- if callMethod == "" || routeMethod == "" {
- return 0
- }
- if strings.EqualFold(callMethod, routeMethod) {
- return 0.10
- }
- return -0.15
-}
-
-// sourceWeight returns a confidence multiplier based on call site type.
-// Function/Method sources are higher confidence (HTTP client in source code)
-// than Module sources (URL in constants — may be config, not a call).
-func sourceWeight(label string) float64 {
- switch label {
- case "Function", "Method":
- return 1.0
- default:
- return 0.85
- }
-}
-
-// resolveFastAPIPrefixes resolves include_router prefixes for FastAPI routes.
-// Scans Python Module files for app.include_router(var, prefix="/prefix") calls
-// and prepends the prefix to routes from the imported module.
-func (l *Linker) resolveFastAPIPrefixes(routes []RouteHandler, rootPath string) {
- modules, err := l.store.FindNodesByLabel(l.project, "Module")
- if err != nil {
- return
- }
-
- for _, mod := range modules {
- if !strings.HasSuffix(mod.FilePath, ".py") {
- continue
- }
-
- source := l.readFull(rootPath, mod.FilePath)
- if source == nil {
- continue
- }
- srcStr := string(source)
-
- includes := fastAPIIncludeRe.FindAllStringSubmatch(srcStr, -1)
- if len(includes) == 0 {
- continue
- }
-
- // Build import map: var_name → dotted module path
- imports := map[string]string{}
- for _, m := range pyImportRe.FindAllStringSubmatch(srcStr, -1) {
- imports[m[2]] = m[1] // var_name → module.path
- }
-
- for _, inc := range includes {
- varName := inc[1]
- prefix := inc[2]
-
- modulePath, ok := imports[varName]
- if !ok {
- continue
- }
-
- // Convert dotted module path to file path fragment
- fileFrag := strings.ReplaceAll(modulePath, ".", "/")
- normalizedPrefix := strings.TrimRight(prefix, "/")
-
- prefixed := 0
- for i := range routes {
- if strings.HasPrefix(routes[i].Path, normalizedPrefix) {
- continue
- }
- // Match routes whose QN contains the imported module path
- if strings.Contains(routes[i].QualifiedName, fileFrag+".py") ||
- strings.Contains(routes[i].QualifiedName, fileFrag+"/") {
- routes[i].Path = normalizedPrefix + "/" + strings.TrimLeft(routes[i].Path, "/")
- prefixed++
- }
- }
- if prefixed > 0 {
- slog.Info("httplink.fastapi_prefix", "prefix", prefix, "module", modulePath, "routes", prefixed)
- }
- }
- }
-}
-
-// resolveExpressPrefixes resolves app.use("/prefix", router) for Express routes.
-// Scans JS/TS Module files for .use("/prefix", routerVar) calls and prepends
-// the prefix to routes from the imported module.
-func (l *Linker) resolveExpressPrefixes(routes []RouteHandler, rootPath string) {
- modules, err := l.store.FindNodesByLabel(l.project, "Module")
- if err != nil {
- return
- }
-
- for _, mod := range modules {
- if !isJSTSModule(mod.FilePath) {
- continue
- }
-
- source := l.readFull(rootPath, mod.FilePath)
- if source == nil {
- continue
- }
- srcStr := string(source)
-
- uses := expressUseRe.FindAllStringSubmatch(srcStr, -1)
- if len(uses) == 0 {
- continue
- }
-
- imports := buildJSImportMap(srcStr)
- l.applyExpressUsePrefixes(routes, uses, imports)
- }
-}
-
-// isJSTSModule returns true if the file path is a JS/TS module file.
-func isJSTSModule(filePath string) bool {
- return strings.HasSuffix(filePath, ".js") || strings.HasSuffix(filePath, ".ts") ||
- strings.HasSuffix(filePath, ".mjs") || strings.HasSuffix(filePath, ".tsx")
-}
-
-// buildJSImportMap builds a map of var_name to module path from require/import statements.
-func buildJSImportMap(src string) map[string]string {
- imports := map[string]string{}
- for _, m := range jsRequireRe.FindAllStringSubmatch(src, -1) {
- imports[m[1]] = m[2]
- }
- for _, m := range jsImportRe.FindAllStringSubmatch(src, -1) {
- imports[m[1]] = m[2]
- }
- return imports
-}
-
-// applyExpressUsePrefixes applies .use("/prefix", routerVar) prefix resolution to routes.
-func (l *Linker) applyExpressUsePrefixes(routes []RouteHandler, uses [][]string, imports map[string]string) {
- for _, use := range uses {
- prefix := use[1]
- varName := use[2]
-
- modulePath, ok := imports[varName]
- if !ok {
- continue
- }
-
- // Strip leading ./ from relative import
- fileFrag := strings.TrimPrefix(modulePath, "./")
- fileFrag = strings.TrimPrefix(fileFrag, "../")
- normalizedPrefix := strings.TrimRight(prefix, "/")
-
- prefixed := 0
- for i := range routes {
- if strings.HasPrefix(routes[i].Path, normalizedPrefix) {
- continue
- }
- if strings.Contains(routes[i].QualifiedName, fileFrag+".js") ||
- strings.Contains(routes[i].QualifiedName, fileFrag+".ts") ||
- strings.Contains(routes[i].QualifiedName, fileFrag+"/") {
- routes[i].Path = normalizedPrefix + "/" + strings.TrimLeft(routes[i].Path, "/")
- prefixed++
- }
- }
- if prefixed > 0 {
- slog.Info("httplink.express_prefix", "prefix", prefix, "module", modulePath, "routes", prefixed)
- }
- }
-}
-
-// pathsMatch is a convenience wrapper for tests — returns true if score >= threshold.
-func pathsMatch(callPath, routePath string) bool {
- return pathMatchScore(callPath, routePath) >= matchConfidenceThreshold
-}
-
-// sameService checks if two qualified names share the same directory path.
-// It strips the last 2 segments (module file + function/method name) from each
-// QN and compares the remaining directory prefix. If the prefixes are identical,
-// the nodes are in the same deployable unit.
-//
-// Example: "myapp.docker-images.cloud-runs.svcA.module.func" → dir prefix "myapp.docker-images.cloud-runs.svcA"
-//
-// "myapp.docker-images.cloud-runs.svcB.routes.handler" → dir prefix "myapp.docker-images.cloud-runs.svcB"
-// → different prefix → different service → returns false
-func sameService(qn1, qn2 string) bool {
- parts1 := strings.Split(qn1, ".")
- parts2 := strings.Split(qn2, ".")
-
- // Strip last 2 segments (module + name) to get directory path
- const strip = 2
- if len(parts1) <= strip || len(parts2) <= strip {
- return false
- }
- dir1 := strings.Join(parts1[:len(parts1)-strip], ".")
- dir2 := strings.Join(parts2[:len(parts2)-strip], ".")
- 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 funcQN, indices := range l.routesByFunc {
- funcNode, _ := l.store.FindNodeByQN(l.project, funcQN)
- if funcNode == nil {
- continue
- }
-
- callerEdges, _ := l.store.FindEdgesByTargetAndType(funcNode.ID, "CALLS")
- if len(callerEdges) == 0 {
- continue
- }
-
- l.resolveCallerGroupPrefixes(routes, indices, callerEdges, funcNode.Name, rootPath)
- }
-}
-
-// resolveCallerGroupPrefixes checks each caller's source for Group() prefix passing
-// and prepends the prefix to the routes at the given indices.
-func (l *Linker) resolveCallerGroupPrefixes(routes []RouteHandler, indices []int, callerEdges []*store.Edge, funcName, rootPath string) {
- for _, edge := range callerEdges {
- callerNode, _ := l.store.FindNodeByID(edge.SourceID)
- if callerNode == nil || callerNode.FilePath == "" || callerNode.StartLine <= 0 {
- continue
- }
-
- callerSource := l.readLines(rootPath, callerNode.FilePath, callerNode.StartLine, callerNode.EndLine)
- if callerSource == "" {
- continue
- }
-
- // Pattern 1: direct — RegisterRoutes(router.Group("/api"))
- for _, m := range crossFileGroupRe.FindAllStringSubmatch(callerSource, -1) {
- if m[1] == funcName {
- l.prependPrefixToRoutes(routes, indices, m[2])
- break
- }
- }
-
- // Pattern 2: variable-based — v1 := router.Group("/api"); RegisterRoutes(v1)
- l.resolveVarGroupPrefix(routes, indices, callerSource, funcName)
- }
-}
-
-// resolveVarGroupPrefix resolves Group() prefixes passed via intermediate variables.
-func (l *Linker) resolveVarGroupPrefix(routes []RouteHandler, indices []int, callerSource, funcName string) {
- varPrefixes := map[string]string{}
- for _, m := range crossFileGroupVarRe.FindAllStringSubmatch(callerSource, -1) {
- varPrefixes[m[1]] = m[2]
- }
- if len(varPrefixes) == 0 {
- return
- }
- callRe := regexp.MustCompile(regexp.QuoteMeta(funcName) + `\s*\(\s*(\w+)`)
- for _, cm := range callRe.FindAllStringSubmatch(callerSource, -1) {
- if prefix, ok := varPrefixes[cm[1]]; 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 i := range routes {
- rh := &routes[i]
- 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]
-
- // Propagate resolved handler QN back to route for insertRouteNodes
- rh.ResolvedHandlerQN = handler.QualifiedName
-
- _, _ = 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)
- }
-}
-
-// readLines returns specific lines, using sourceLines callback or disk fallback.
-func (l *Linker) readLines(rootPath, relPath string, startLine, endLine int) string {
- if l.sourceLines != nil {
- return l.sourceLines(relPath, startLine, endLine)
- }
- return readSourceLinesDisk(rootPath, relPath, startLine, endLine)
-}
-
-// readFull returns full file content, using sourceReader callback or disk fallback.
-func (l *Linker) readFull(rootPath, relPath string) []byte {
- if l.sourceReader != nil {
- return l.sourceReader(relPath)
- }
- data, err := os.ReadFile(filepath.Join(rootPath, relPath))
- if err != nil {
- return nil
- }
- return data
-}
-
-// readSourceLinesDisk reads specific lines from a file on disk (fallback).
-func readSourceLinesDisk(rootPath, relPath string, startLine, endLine int) string {
- absPath := filepath.Join(rootPath, relPath)
- f, err := os.Open(absPath)
- if err != nil {
- return ""
- }
- defer f.Close()
-
- var lines []string
- scanner := bufio.NewScanner(f)
- lineNum := 0
- for scanner.Scan() {
- lineNum++
- if lineNum >= startLine && lineNum <= endLine {
- lines = append(lines, scanner.Text())
- }
- if lineNum > endLine {
- break
- }
- }
- return strings.Join(lines, "\n")
-}
diff --git a/internal/httplink/httplink_test.go b/internal/httplink/httplink_test.go
deleted file mode 100644
index bbac55f0f..000000000
--- a/internal/httplink/httplink_test.go
+++ /dev/null
@@ -1,1470 +0,0 @@
-package httplink
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func TestNormalizePath(t *testing.T) {
- tests := []struct {
- input string
- want string
- }{
- {"/api/orders/", "/api/orders"},
- {"/api/orders", "/api/orders"},
- {"/api/orders/:id", "/api/orders/*"},
- {"/api/orders/{order_id}", "/api/orders/*"},
- {"/API/Orders", "/api/orders"},
- {"/api/:version/items/:id", "/api/*/items/*"},
- {"/api/{version}/items/{id}", "/api/*/items/*"},
- {"/", ""},
- {"", ""},
- }
- for _, tt := range tests {
- got := normalizePath(tt.input)
- if got != tt.want {
- t.Errorf("normalizePath(%q) = %q, want %q", tt.input, got, tt.want)
- }
- }
-}
-
-func TestPathsMatch(t *testing.T) {
- tests := []struct {
- callPath string
- routePath string
- want bool
- }{
- // Exact match
- {"/api/orders", "/api/orders", true},
- {"/api/orders/", "/api/orders", true},
-
- // Case insensitive
- {"/API/Orders", "/api/orders", true},
-
- // Suffix match (call has host prefix, route is just path)
- {"https://example.com/api/orders", "/api/orders", true},
- {"/api/orders", "/api/orders", true},
-
- // Wildcard params
- {"/api/orders/:id", "/api/orders/{order_id}", true},
- {"/api/orders/123", "/api/orders/:id", true}, // 123 matches * (normalized :id)
-
- // Segment wildcard: :version normalizes to *, matches any segment
- {"/api/:version/items", "/api/v1/items", true},
-
- // Different lengths
- {"/api/orders", "/api/orders/detail", false},
- {"/api", "/api/orders", false},
-
- // Both have wildcards
- {"/api/*/items", "/api/*/items", true},
-
- // No match
- {"/api/users", "/api/orders", false},
- }
- for _, tt := range tests {
- got := pathsMatch(tt.callPath, tt.routePath)
- if got != tt.want {
- t.Errorf("pathsMatch(%q, %q) = %v, want %v", tt.callPath, tt.routePath, got, tt.want)
- }
- }
-}
-
-func TestPathsMatchSuffix(t *testing.T) {
- // Suffix match: normalized call path ends with normalized route path
- got := pathsMatch("/host/prefix/api/orders", "/api/orders")
- if !got {
- t.Error("expected suffix match for /host/prefix/api/orders -> /api/orders")
- }
-}
-
-func TestPathMatchScore(t *testing.T) {
- tests := []struct {
- call string
- route string
- min float64
- max float64
- }{
- // Exact matches: matchBase=0.95, confidence = 0.95 × (0.5×jaccard + 0.5×depthFactor)
- {"/api/orders", "/api/orders", 0.78, 0.82}, // jaccard=1.0, depth=2/3=0.667 → 0.95×0.833 ≈ 0.79
- {"/integrate", "/integrate", 0.60, 0.67}, // jaccard=1.0, depth=1/3=0.333 → 0.95×0.667 ≈ 0.63
- {"/api/v1/orders/items", "/api/v1/orders/items", 0.93, 0.96}, // jaccard=1.0, depth=4/3→1.0 → 0.95×1.0 = 0.95
-
- // Suffix matches: matchBase=0.75
- {"https://host/api/orders", "/api/orders", 0.60, 0.66}, // jaccard=1.0, depth=0.667 → 0.75×0.833 ≈ 0.625
-
- // Numeric IDs normalized to wildcard → exact match with :id (also normalized to *)
- {"/api/orders/123", "/api/orders/:id", 0.90, 0.96}, // both normalize to /api/orders/* → exact match
-
- // No match
- {"/api/users", "/api/orders", 0.0, 0.0},
- {"/", "/api/orders", 0.0, 0.0}, // empty normalized
- {"", "/api/orders", 0.0, 0.0},
- }
- for _, tt := range tests {
- got := pathMatchScore(tt.call, tt.route)
- if got < tt.min || got > tt.max {
- t.Errorf("pathMatchScore(%q, %q) = %.2f, want [%.2f, %.2f]", tt.call, tt.route, got, tt.min, tt.max)
- }
- }
-}
-
-func TestSameService(t *testing.T) {
- tests := []struct {
- qn1 string
- qn2 string
- want bool
- }{
- // Full directory comparison: strip last 2 segments (module+name), compare rest
- // "a.b.c.mod.func" → dir="a.b.c", so same dir = same service
- {"a.b.c.mod.Func1", "a.b.c.mod.Func2", true}, // same dir (a.b.c)
- {"a.b.c.mod.Func1", "a.b.x.mod.Func2", false}, // different dir (a.b.c vs a.b.x)
- {"a.b.c.d.mod.Func", "a.b.c.d.mod.Other", true}, // same deep dir (a.b.c.d)
- {"a.b.c.d.mod.Func", "a.b.c.e.mod.Other", false}, // different deep dir
- {"short.x", "short.y", false}, // only 2 segments → strip leaves empty → false
- {"a.b", "a.b", false}, // 2 segments → not enough to determine
- {"a.b.c", "a.b.c", true}, // 3 segments: dir="a", same
- {"a.b.c", "x.b.c", false}, // 3 segments: dir="a" vs "x"
- // Realistic multi-service QN patterns
- {"myapp.docker-images.cloud-runs.order-service.main.Func", "myapp.docker-images.cloud-runs.order-service.handlers.Other", true},
- {"myapp.docker-images.cloud-runs.order-service.main.Func", "myapp.docker-images.cloud-runs.notification-service.main.health_check", false},
- {"myapp.docker-images.cloud-runs.svcA.sub.mod.Func", "myapp.docker-images.cloud-runs.svcA.sub.mod.Other", true},
- {"myapp.docker-images.cloud-runs.svcA.sub.mod.Func", "myapp.docker-images.cloud-runs.svcB.sub.mod.Other", false},
- }
- for _, tt := range tests {
- got := sameService(tt.qn1, tt.qn2)
- if got != tt.want {
- t.Errorf("sameService(%q, %q) = %v, want %v", tt.qn1, tt.qn2, got, tt.want)
- }
- }
-}
-
-func TestExtractURLPaths(t *testing.T) {
- tests := []struct {
- text string
- want int // expected number of paths
- }{
- {`URL = "https://example.com/api/orders"`, 1},
- {`fetch("http://host/api/v1/items")`, 1},
- {`path = "/api/orders"`, 1},
- {`no urls here`, 0},
- {`both = "https://a.com/api/x" and "/api/y"`, 2},
- }
- for _, tt := range tests {
- got := extractURLPaths(tt.text)
- if len(got) != tt.want {
- t.Errorf("extractURLPaths(%q) returned %d paths, want %d: %v", tt.text, len(got), tt.want, got)
- }
- }
-}
-
-func TestExtractPythonRoutes(t *testing.T) {
- node := &store.Node{
- Name: "create_order",
- QualifiedName: "proj.api.routes.create_order",
- Properties: map[string]any{
- "decorators": []any{
- `@app.post("/api/orders")`,
- },
- },
- }
-
- routes := extractPythonRoutes(node)
- if len(routes) != 1 {
- t.Fatalf("expected 1 route, got %d", len(routes))
- }
- if routes[0].Path != "/api/orders" {
- t.Errorf("path = %q, want /api/orders", routes[0].Path)
- }
- if routes[0].Method != "POST" {
- t.Errorf("method = %q, want POST", routes[0].Method)
- }
- if routes[0].QualifiedName != "proj.api.routes.create_order" {
- t.Errorf("qn = %q, want proj.api.routes.create_order", routes[0].QualifiedName)
- }
-}
-
-func TestExtractPythonRoutesMultiple(t *testing.T) {
- node := &store.Node{
- Name: "handler",
- QualifiedName: "proj.api.handler",
- Properties: map[string]any{
- "decorators": []any{
- `@router.get("/api/items/{item_id}")`,
- `@router.post("/api/items")`,
- },
- },
- }
-
- routes := extractPythonRoutes(node)
- if len(routes) != 2 {
- t.Fatalf("expected 2 routes, got %d", len(routes))
- }
-}
-
-func TestExtractPythonRoutesNoDecorators(t *testing.T) {
- node := &store.Node{
- Name: "helper",
- QualifiedName: "proj.utils.helper",
- Properties: map[string]any{},
- }
-
- routes := extractPythonRoutes(node)
- if len(routes) != 0 {
- t.Errorf("expected 0 routes, got %d", len(routes))
- }
-}
-
-func TestExtractGoRoutes(t *testing.T) {
- source := `
- r.POST("/api/orders", h.CreateOrder)
- r.GET("/api/orders/:id", h.GetOrder)
- `
- node := &store.Node{
- Name: "RegisterRoutes",
- QualifiedName: "proj.api.RegisterRoutes",
- }
-
- routes := extractGoRoutes(node, source)
- if len(routes) != 2 {
- t.Fatalf("expected 2 routes, got %d", len(routes))
- }
- if routes[0].Path != "/api/orders" {
- t.Errorf("route[0].Path = %q, want /api/orders", routes[0].Path)
- }
- if routes[0].Method != "POST" {
- t.Errorf("route[0].Method = %q, want POST", routes[0].Method)
- }
- if routes[1].Path != "/api/orders/:id" {
- t.Errorf("route[1].Path = %q, want /api/orders/:id", routes[1].Path)
- }
-}
-
-func TestReadSourceLines(t *testing.T) {
- dir, err := os.MkdirTemp("", "httplink-test-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- content := "line1\nline2\nline3\nline4\nline5\n"
- path := filepath.Join(dir, "test.go")
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
-
- got := readSourceLinesDisk(dir, "test.go", 2, 4)
- want := "line2\nline3\nline4"
- if got != want {
- t.Errorf("readSourceLines = %q, want %q", got, want)
- }
-}
-
-func TestReadSourceLinesMissingFile(t *testing.T) {
- got := readSourceLinesDisk("/nonexistent", "missing.go", 1, 10)
- if got != "" {
- t.Errorf("expected empty string for missing file, got %q", got)
- }
-}
-
-func TestLinkerRun(t *testing.T) {
- // Set up a temp directory with a Python route handler and a Go caller
- dir, err := os.MkdirTemp("", "httplink-e2e-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Write a Go file that contains a URL constant
- goDir := filepath.Join(dir, "caller")
- if err := os.MkdirAll(goDir, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(goDir, "client.go"), []byte(`package caller
-const OrderURL = "https://api.example.com/api/orders"
-`), 0o600); 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 a Module node with constants containing a URL
- callerID, _ := s.UpsertNode(&store.Node{
- Project: project,
- Label: "Module",
- Name: "client.go",
- QualifiedName: "testproj.caller.client",
- FilePath: "caller/client.go",
- Properties: map[string]any{
- "constants": []any{`OrderURL = "https://api.example.com/api/orders"`},
- },
- })
-
- // Create a Function node with a Python route decorator
- handlerID, _ := s.UpsertNode(&store.Node{
- Project: project,
- Label: "Function",
- Name: "create_order",
- QualifiedName: "testproj.handler.routes.create_order",
- FilePath: "handler/routes.py",
- Properties: map[string]any{
- "decorators": []any{`@app.post("/api/orders")`},
- },
- })
-
- if callerID == 0 || handlerID == 0 {
- t.Fatal("failed to create test nodes")
- }
-
- linker := New(s, project)
- links, err := linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- if len(links) == 0 {
- t.Fatal("expected at least 1 HTTP link, got 0")
- }
-
- // Verify the link
- found := false
- for _, link := range links {
- if link.CallerQN == "testproj.caller.client" && link.HandlerQN == "testproj.handler.routes.create_order" {
- found = true
- t.Logf("link: %s -> %s (path=%s)", link.CallerQN, link.HandlerQN, link.URLPath)
- }
- }
- if !found {
- t.Error("expected link from testproj.caller.client to testproj.handler.routes.create_order")
- for _, link := range links {
- t.Logf(" got: %s -> %s", link.CallerQN, link.HandlerQN)
- }
- }
-
- // Verify edge was created in store
- callerNode, _ := s.FindNodeByQN(project, "testproj.caller.client")
- if callerNode == nil {
- t.Fatal("caller node not found")
- }
- edges, _ := s.FindEdgesBySourceAndType(callerNode.ID, "HTTP_CALLS")
- if len(edges) == 0 {
- t.Error("expected HTTP_CALLS edge in store, got 0")
- }
-}
-
-func TestExtractJSONStringPaths(t *testing.T) {
- tests := []struct {
- name string
- text string
- want int
- }{
- {
- name: "JSON object with URL",
- text: `BODY = '{"target": "https://api.internal.com/api/orders", "method": "POST"}'`,
- want: 1, // /api/orders
- },
- {
- name: "JSON object with path",
- text: `CONFIG = {"endpoint": "/api/v1/process", "timeout": 30}`,
- want: 1, // /api/v1/process
- },
- {
- name: "no JSON",
- text: `plain string without json`,
- want: 0,
- },
- {
- name: "nested JSON with URL",
- text: `{"services": [{"url": "https://svc.example.com/api/health"}]}`,
- want: 1,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := extractJSONStringPaths(tt.text)
- if len(got) != tt.want {
- t.Errorf("extractJSONStringPaths(%q) returned %d paths, want %d: %v", tt.text, len(got), tt.want, got)
- }
- })
- }
-}
-
-func TestRouteNodesCreated(t *testing.T) {
- dir, err := os.MkdirTemp("", "httplink-route-nodes-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- 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 a Function node with a Python route decorator
- _, _ = s.UpsertNode(&store.Node{
- Project: project,
- Label: "Function",
- Name: "create_order",
- QualifiedName: "testproj.handler.routes.create_order",
- FilePath: "handler/routes.py",
- Properties: map[string]any{
- "decorators": []any{`@app.post("/api/orders")`},
- },
- })
-
- linker := New(s, project)
- _, err = linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- // Verify Route node was created
- routeNodes, _ := s.FindNodesByLabel(project, "Route")
- if len(routeNodes) != 1 {
- t.Fatalf("expected 1 Route node, got %d", len(routeNodes))
- }
- rn := routeNodes[0]
- if rn.FilePath != "handler/routes.py" {
- t.Errorf("Route file_path = %q, want 'handler/routes.py'", rn.FilePath)
- }
- if rn.Name != "POST /api/orders" {
- t.Errorf("Route name = %q, want 'POST /api/orders'", rn.Name)
- }
- if rn.Properties["method"] != "POST" {
- t.Errorf("Route method = %v, want POST", rn.Properties["method"])
- }
- if rn.Properties["path"] != "/api/orders" {
- t.Errorf("Route path = %v, want /api/orders", rn.Properties["path"])
- }
-
- // Verify HANDLES edge from handler → Route
- handlerNode, _ := s.FindNodeByQN(project, "testproj.handler.routes.create_order")
- if handlerNode == nil {
- t.Fatal("handler node not found")
- }
- edges, _ := s.FindEdgesBySourceAndType(handlerNode.ID, "HANDLES")
- if len(edges) != 1 {
- t.Errorf("expected 1 HANDLES edge, got %d", len(edges))
- }
-
- // Verify handler marked as entry point
- if handlerNode.Properties["is_entry_point"] != true {
- t.Error("expected handler to be marked as is_entry_point")
- }
-}
-
-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"))
-}
-`), 0o600); 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)
-}
-`), 0o600); 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)
- if _, err := s.InsertEdge(&store.Edge{
- Project: project,
- SourceID: setupID,
- TargetID: regID,
- Type: "CALLS",
- }); err != nil {
- t.Fatal(err)
- }
-
- 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)
-}
-`), 0o600); 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)
-}
-`), 0o600); 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)
- }
-
- 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,
- })
-
- if _, err := s.InsertEdge(&store.Edge{
- Project: project, SourceID: setupID, TargetID: regID, Type: "CALLS",
- }); err != nil {
- t.Fatal(err)
- }
-
- linker := New(s, project)
- if _, runErr := linker.Run(); runErr != nil {
- t.Fatal(runErr)
- }
-
- 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)
-}
-`), 0o600); 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 the registering function
- if _, err := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "RegisterRoutes",
- QualifiedName: "testproj.routes.routes.RegisterRoutes",
- FilePath: "routes/routes.go", StartLine: 3, EndLine: 6,
- }); err != nil {
- t.Fatal(err)
- }
-
- // Create handler functions (as pipeline would)
- if _, err := s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "CreateOrder",
- QualifiedName: "testproj.handlers.handler.CreateOrder",
- FilePath: "handlers/handler.go", StartLine: 10, EndLine: 30,
- }); err != nil {
- t.Fatal(err)
- }
- if _, err := s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "GetOrder",
- QualifiedName: "testproj.handlers.handler.GetOrder",
- FilePath: "handlers/handler.go", StartLine: 32, EndLine: 50,
- }); err != nil {
- t.Fatal(err)
- }
-
- linker := New(s, project)
- if _, runErr := linker.Run(); runErr != nil {
- t.Fatal(runErr)
- }
-
- // 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 TestAsyncDispatchKeywords(t *testing.T) {
- dir, err := os.MkdirTemp("", "httplink-async-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeTestFile(t, dir, "taskworker", "dispatch.go", `package taskworker
-
-func DispatchOrder(orderID string) {
- url := "https://api.internal.com/api/orders"
- client.CreateTask(ctx, url, payload)
-}
-`)
- writeTestFile(t, dir, "synccaller", "caller.go", `package synccaller
-
-func CallOrder() {
- url := "https://api.internal.com/api/orders"
- requests.post(url, data)
-}
-`)
- writeTestFile(t, dir, "bothcaller", "both.go", `package bothcaller
-
-func CallAndDispatch() {
- url := "https://api.internal.com/api/orders"
- requests.post(url, data)
- client.CreateTask(ctx, url, payload)
-}
-`)
-
- 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)
- }
-
- createTestNode(t, s, project, "DispatchOrder", "testproj.taskworker.dispatch.DispatchOrder", "taskworker/dispatch.go", 3, 6)
- createTestNode(t, s, project, "CallOrder", "testproj.synccaller.caller.CallOrder", "synccaller/caller.go", 3, 6)
- createTestNode(t, s, project, "CallAndDispatch", "testproj.bothcaller.both.CallAndDispatch", "bothcaller/both.go", 3, 7)
-
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "create_order",
- QualifiedName: "testproj.handler.routes.create_order",
- FilePath: "handler/routes.py",
- Properties: map[string]any{"decorators": []any{`@app.post("/api/orders")`}},
- })
-
- linker := New(s, project)
- links, err := linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- edgeTypes := map[string]string{}
- for _, link := range links {
- edgeTypes[link.CallerQN] = link.EdgeType
- }
-
- assertEdgeType(t, edgeTypes, "testproj.taskworker.dispatch.DispatchOrder", "ASYNC_CALLS")
- assertEdgeType(t, edgeTypes, "testproj.synccaller.caller.CallOrder", "HTTP_CALLS")
- assertEdgeType(t, edgeTypes, "testproj.bothcaller.both.CallAndDispatch", "HTTP_CALLS")
-
- assertStoredEdgeCounts(t, s, project, "testproj.taskworker.dispatch.DispatchOrder", 1, 0)
- assertStoredEdgeCounts(t, s, project, "testproj.synccaller.caller.CallOrder", 0, 1)
-}
-
-func writeTestFile(t *testing.T, dir, subdir, filename, content string) {
- t.Helper()
- d := filepath.Join(dir, subdir)
- if err := os.MkdirAll(d, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(d, filename), []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-func createTestNode(t *testing.T, s *store.Store, project, name, qn, filePath string, startLine, endLine int) {
- t.Helper()
- _, err := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: name,
- QualifiedName: qn, FilePath: filePath,
- StartLine: startLine, EndLine: endLine,
- })
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func assertEdgeType(t *testing.T, edgeTypes map[string]string, qn, wantType string) {
- t.Helper()
- et, ok := edgeTypes[qn]
- if !ok {
- t.Errorf("expected link from %s", qn)
- return
- }
- if et != wantType {
- t.Errorf("%s edge type = %q, want %q", qn, et, wantType)
- }
-}
-
-func assertStoredEdgeCounts(t *testing.T, s *store.Store, project, qn string, wantAsync, wantHTTP int) {
- t.Helper()
- node, _ := s.FindNodeByQN(project, qn)
- if node == nil {
- t.Errorf("node not found: %s", qn)
- return
- }
- asyncEdges, _ := s.FindEdgesBySourceAndType(node.ID, "ASYNC_CALLS")
- if len(asyncEdges) != wantAsync {
- t.Errorf("%s: ASYNC_CALLS edges = %d, want %d", qn, len(asyncEdges), wantAsync)
- }
- httpEdges, _ := s.FindEdgesBySourceAndType(node.ID, "HTTP_CALLS")
- if len(httpEdges) != wantHTTP {
- t.Errorf("%s: HTTP_CALLS edges = %d, want %d", qn, len(httpEdges), wantHTTP)
- }
-}
-
-func TestExtractFunctionCallSitesAsync(t *testing.T) {
- // Test extractFunctionCallSites directly with a temp file containing async keywords.
- dir, err := os.MkdirTemp("", "httplink-extract-async-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Write a Go file with CreateTask and a URL
- if err := os.MkdirAll(filepath.Join(dir, "worker"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, "worker", "task.go"), []byte(`package worker
-
-func EnqueueJob(ctx context.Context) {
- url := "https://backend.internal.com/api/process"
- client.CreateTask(ctx, &taskspb.CreateTaskRequest{
- HttpRequest: &taskspb.HttpRequest{Url: url},
- })
-}
-`), 0o600); err != nil {
- t.Fatal(err)
- }
-
- node := &store.Node{
- Project: "testproj", Label: "Function", Name: "EnqueueJob",
- QualifiedName: "testproj.worker.task.EnqueueJob",
- FilePath: "worker/task.go", StartLine: 3, EndLine: 7,
- }
-
- sites := (&Linker{}).extractFunctionCallSites(node, dir)
- if len(sites) == 0 {
- t.Fatal("expected at least 1 call site, got 0")
- }
-
- foundAsync := false
- for _, s := range sites {
- if s.IsAsync {
- foundAsync = true
- if s.Path != "/api/process" {
- t.Errorf("async site path = %q, want /api/process", s.Path)
- }
- }
- }
- if !foundAsync {
- t.Error("expected at least one call site with IsAsync=true")
- }
-
- // Also test that a function with only sync keywords gets IsAsync=false
- if err := os.WriteFile(filepath.Join(dir, "worker", "sync.go"), []byte(`package worker
-
-func SyncCall(ctx context.Context) {
- url := "https://backend.internal.com/api/process"
- requests.post(url, data)
-}
-`), 0o600); err != nil {
- t.Fatal(err)
- }
-
- syncNode := &store.Node{
- Project: "testproj", Label: "Function", Name: "SyncCall",
- QualifiedName: "testproj.worker.sync.SyncCall",
- FilePath: "worker/sync.go", StartLine: 3, EndLine: 6,
- }
-
- syncSites := (&Linker{}).extractFunctionCallSites(syncNode, dir)
- if len(syncSites) == 0 {
- t.Fatal("expected at least 1 sync call site, got 0")
- }
- for _, s := range syncSites {
- if s.IsAsync {
- t.Errorf("sync call site should have IsAsync=false, got true (path=%s)", s.Path)
- }
- }
-}
-
-func TestLinkerSkipsSameService(t *testing.T) {
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- dir, err := os.MkdirTemp("", "httplink-same-svc-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- project := "testproj"
- if err := s.UpsertProject(project, dir); err != nil {
- t.Fatal(err)
- }
-
- // Both in the same service (same first 4 QN segments: testproj.cat.sub.svcA)
- _, _ = s.UpsertNode(&store.Node{
- Project: project,
- Label: "Module",
- Name: "client.py",
- QualifiedName: "testproj.cat.sub.svcA.internal.client",
- FilePath: "cat/sub/svcA/internal/client.py",
- Properties: map[string]any{
- "constants": []any{`URL = "https://localhost/api/orders"`},
- },
- })
-
- _, _ = s.UpsertNode(&store.Node{
- Project: project,
- Label: "Function",
- Name: "handle_orders",
- QualifiedName: "testproj.cat.sub.svcA.internal.handle_orders",
- FilePath: "cat/sub/svcA/internal/routes.py",
- Properties: map[string]any{
- "decorators": []any{`@app.get("/api/orders")`},
- },
- })
-
- linker := New(s, project)
- links, err := linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- if len(links) != 0 {
- t.Errorf("expected 0 links (same service), got %d", len(links))
- for _, l := range links {
- t.Logf(" %s -> %s", l.CallerQN, l.HandlerQN)
- }
- }
-}
-
-func TestDetectProtocol(t *testing.T) {
- tests := []struct {
- name string
- source string
- want string
- }{
- {"go websocket upgrade", `err := websocket.Upgrade(w, r, nil, 1024, 1024)`, "ws"},
- {"go websocket accept", `conn, err := websocket.Accept(w, r, nil)`, "ws"},
- {"go upgrader", `conn, err := upgrader.Upgrade(w, r, nil)`, "ws"},
- {"js ws", `ws.on("connection", func)`, "ws"},
- {"js socketio", `io.on("connection", handler)`, "ws"},
- {"sse content type", `w.Header().Set("Content-Type", "text/event-stream")`, "sse"},
- {"python sse", `return EventSourceResponse(generate())`, "sse"},
- {"java sse emitter", `SseEmitter emitter = new SseEmitter()`, "sse"},
- {"java sse event", `ServerSentEvent event = ServerSentEvent.builder()`, "sse"},
- {"no protocol", `return json.Marshal(result)`, ""},
- {"empty", "", ""},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := detectProtocol(tt.source)
- if got != tt.want {
- t.Errorf("detectProtocol() = %q, want %q", got, tt.want)
- }
- })
- }
-}
-
-func TestExtractPythonWSRoutes(t *testing.T) {
- node := &store.Node{
- Name: "ws_handler",
- QualifiedName: "proj.api.ws_handler",
- Properties: map[string]any{
- "decorators": []any{
- `@app.websocket("/ws/chat")`,
- },
- },
- }
-
- routes := extractPythonRoutes(node)
- if len(routes) != 1 {
- t.Fatalf("expected 1 route, got %d", len(routes))
- }
- if routes[0].Path != "/ws/chat" {
- t.Errorf("path = %q, want /ws/chat", routes[0].Path)
- }
- if routes[0].Method != "WS" {
- t.Errorf("method = %q, want WS", routes[0].Method)
- }
- if routes[0].Protocol != "ws" {
- t.Errorf("protocol = %q, want ws", routes[0].Protocol)
- }
-}
-
-func TestExtractSpringWSRoutes(t *testing.T) {
- node := &store.Node{
- Name: "handleChat",
- QualifiedName: "proj.ChatController.handleChat",
- Properties: map[string]any{
- "decorators": []any{
- `@MessageMapping("/chat")`,
- },
- },
- }
-
- routes := extractJavaRoutes(node)
- if len(routes) != 1 {
- t.Fatalf("expected 1 route, got %d", len(routes))
- }
- if routes[0].Path != "/chat" {
- t.Errorf("path = %q, want /chat", routes[0].Path)
- }
- if routes[0].Method != "WS" {
- t.Errorf("method = %q, want WS", routes[0].Method)
- }
- if routes[0].Protocol != "ws" {
- t.Errorf("protocol = %q, want ws", routes[0].Protocol)
- }
-}
-
-func TestExtractKtorWSRoutes(t *testing.T) {
- source := `
- webSocket("/chat") {
- for (frame in incoming) {
- send(frame)
- }
- }
- get("/api/health") {
- call.respond("ok")
- }
-`
- node := &store.Node{
- Name: "configureRouting",
- QualifiedName: "proj.Routing.configureRouting",
- }
-
- routes := extractKtorRoutes(node, source)
- if len(routes) != 2 {
- t.Fatalf("expected 2 routes, got %d", len(routes))
- }
-
- // Check WS route
- wsFound := false
- httpFound := false
- for _, r := range routes {
- if r.Protocol == "ws" && r.Path == "/chat" && r.Method == "WS" {
- wsFound = true
- }
- if r.Path == "/api/health" && r.Method == "GET" {
- httpFound = true
- }
- }
- if !wsFound {
- t.Error("expected WS route for /chat")
- }
- if !httpFound {
- t.Error("expected HTTP route for /api/health")
- }
-}
-
-func TestChiPrefix(t *testing.T) {
- source := `
-func SetupRoutes(r chi.Router) {
- r.Route("/api", func(r chi.Router) {
- r.Get("/health", healthHandler)
- r.Route("/users", func(r chi.Router) {
- r.Get("/", listUsers)
- r.Post("/{id}", updateUser)
- })
- })
-}
-`
- node := &store.Node{
- Name: "SetupRoutes",
- QualifiedName: "proj.SetupRoutes",
- }
-
- routes := extractGoRoutes(node, source)
-
- expectedPaths := map[string]string{
- "/api/health": "GET",
- "/api/users": "GET",
- "/api/users/{id}": "POST",
- }
-
- if len(routes) != len(expectedPaths) {
- t.Fatalf("expected %d routes, got %d", len(expectedPaths), len(routes))
- for _, r := range routes {
- t.Logf(" %s %s", r.Method, r.Path)
- }
- }
-
- for _, r := range routes {
- wantMethod, ok := expectedPaths[r.Path]
- if !ok {
- t.Errorf("unexpected route: %s %s", r.Method, r.Path)
- continue
- }
- if r.Method != wantMethod {
- t.Errorf("route %s: method = %q, want %q", r.Path, r.Method, wantMethod)
- }
- }
-}
-
-func TestChiPrefixMixedWithGin(t *testing.T) {
- // When no chi Route() blocks, gin group resolution should still work
- source := `
-func RegisterRoutes(r *gin.RouterGroup) {
- orders := r.Group("/orders")
- orders.GET("/:id", getOrder)
- orders.POST("", createOrder)
-}
-`
- node := &store.Node{
- Name: "RegisterRoutes",
- QualifiedName: "proj.RegisterRoutes",
- }
-
- routes := extractGoRoutes(node, source)
- if len(routes) != 2 {
- t.Fatalf("expected 2 routes, got %d", len(routes))
- }
-
- for _, r := range routes {
- if !strings.HasPrefix(r.Path, "/orders") {
- t.Errorf("expected /orders prefix, got %s", r.Path)
- }
- }
-}
-
-func TestFastAPIPrefix(t *testing.T) {
- dir, err := os.MkdirTemp("", "httplink-fastapi-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Write Python files: main.py with include_router, orders/routes.py with routes
- if err := os.MkdirAll(filepath.Join(dir, "orders"), 0o755); err != nil {
- t.Fatal(err)
- }
-
- if err := os.WriteFile(filepath.Join(dir, "main.py"), []byte(`
-from orders.routes import order_router
-
-app = FastAPI()
-app.include_router(order_router, prefix="/api/v1/orders")
-`), 0o600); 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 Module for main.py (has the include_router call)
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Module", Name: "main.py",
- QualifiedName: "testproj//main.py",
- FilePath: "main.py",
- })
-
- // Create Function with route in the orders module
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "list_orders",
- QualifiedName: "testproj//orders/routes.py/list_orders",
- FilePath: "orders/routes.py",
- Properties: map[string]any{
- "decorators": []any{`@order_router.get("/")`},
- },
- })
-
- linker := New(s, project)
- _, err = linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- 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/v1/orders/" {
- t.Errorf("expected /api/v1/orders/, got %s", path)
- }
-}
-
-func TestExpressPrefix(t *testing.T) {
- dir, err := os.MkdirTemp("", "httplink-express-*")
- 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, "app.js"), []byte(`
-const orderRouter = require('./routes/orders');
-app.use("/api/orders", orderRouter);
-`), 0o600); 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)
- }
-
- // Module for app.js
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Module", Name: "app.js",
- QualifiedName: "testproj//app.js",
- FilePath: "app.js",
- })
-
- // Function with route in orders module
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "getOrder",
- QualifiedName: "testproj//routes/orders.js/getOrder",
- FilePath: "routes/orders.js",
- StartLine: 1, EndLine: 5,
- })
-
- // Write the routes file with Express route
- if err := os.WriteFile(filepath.Join(dir, "routes", "orders.js"), []byte(`
-router.get("/:id", function(req, res) {
- res.json({id: req.params.id});
-});
-`), 0o600); err != nil {
- t.Fatal(err)
- }
-
- linker := New(s, project)
- _, err = linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- 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/orders/:id" {
- t.Errorf("expected /api/orders/:id, got %s", path)
- }
-}
-
-func TestExpressRouteFiltering(t *testing.T) {
- tests := []struct {
- name string
- line string
- wantMatch bool
- wantMethod string
- wantPath string
- }{
- // Should match (allowlisted receivers)
- {"app.get", `app.get('/api/users', handler)`, true, "GET", "/api/users"},
- {"router.post", `router.post('/orders', handler)`, true, "POST", "/orders"},
- {"server.put", `server.put('/items', handler)`, true, "PUT", "/items"},
- {"api.delete", `api.delete('/users/:id', handler)`, true, "DELETE", "/users/:id"},
- {"routes.patch", `routes.patch('/items/:id', handler)`, true, "PATCH", "/items/:id"},
- // Should NOT match (not in allowlist)
- {"req.get", `req.get('Content-Type')`, false, "", ""},
- {"res.get", `res.get('key')`, false, "", ""},
- {"this.get", `this.get('property')`, false, "", ""},
- {"map.get", `map.get('key')`, false, "", ""},
- {"model.delete", `model.delete('record')`, false, "", ""},
- {"params.get", `params.get('id')`, false, "", ""},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- node := &store.Node{
- Name: "testFunc",
- QualifiedName: "proj.test.testFunc",
- }
- routes := extractExpressRoutes(node, tt.line)
- if tt.wantMatch {
- if len(routes) == 0 {
- t.Errorf("expected route match, got 0 routes")
- return
- }
- if routes[0].Method != tt.wantMethod {
- t.Errorf("method = %q, want %q", routes[0].Method, tt.wantMethod)
- }
- if routes[0].Path != tt.wantPath {
- t.Errorf("path = %q, want %q", routes[0].Path, tt.wantPath)
- }
- } else if len(routes) > 0 {
- t.Errorf("expected no match, got %d routes: %v", len(routes), routes[0].Path)
- }
- })
- }
-}
-
-func TestLaravelModuleLevelRoutes(t *testing.T) {
- dir, err := os.MkdirTemp("", "httplink-laravel-module-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Create a Laravel-style route file with module-level Route:: calls
- if err := os.MkdirAll(filepath.Join(dir, "routes"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, "routes", "api.php"), []byte(`<?php
-
-use App\Http\Controllers\OrderController;
-
-Route::get('/api/orders', [OrderController::class, 'index']);
-Route::post('/api/orders', [OrderController::class, 'store']);
-Route::get('/api/orders/{id}', [OrderController::class, 'show']);
-`), 0o600); 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 Module node for the PHP route file (as pipeline would)
- // No Function/Method nodes — routes are at module level
- _, _ = s.UpsertNode(&store.Node{
- Project: project,
- Label: "Module",
- Name: "api.php",
- QualifiedName: "testproj.routes.api",
- FilePath: "routes/api.php",
- })
-
- linker := New(s, project)
- _, err = linker.Run()
- if err != nil {
- t.Fatalf("Run: %v", err)
- }
-
- routeNodes, _ := s.FindNodesByLabel(project, "Route")
- if len(routeNodes) < 3 {
- t.Fatalf("expected at least 3 Route nodes from module-level Laravel routes, 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)
- }
-
- for _, wantPath := range []string{"/api/orders", "/api/orders/{id}"} {
- if !foundPaths[wantPath] {
- t.Errorf("expected route path %s", wantPath)
- }
- }
-}
-
-func TestIsTestNodeFiltering(t *testing.T) {
- tests := []struct {
- filePath string
- isTest bool
- expected bool
- }{
- {"src/routes/api.js", false, false},
- {"test/app.get.js", false, true},
- {"__tests__/routes.test.ts", false, true},
- {"src/routes/api.js", true, true},
- {"lib/router/index.js", false, false},
- {"tests/fixtures/server.js", false, true},
- {"app/controllers/orders_controller.rb", false, false},
- }
-
- for _, tt := range tests {
- n := &store.Node{
- FilePath: tt.filePath,
- Properties: map[string]any{"is_test": tt.isTest},
- }
- got := isTestNode(n)
- if got != tt.expected {
- t.Errorf("isTestNode(%q, is_test=%v) = %v, want %v", tt.filePath, tt.isTest, got, tt.expected)
- }
- }
-}
diff --git a/internal/httplink/langparity_test.go b/internal/httplink/langparity_test.go
deleted file mode 100644
index b5a214046..000000000
--- a/internal/httplink/langparity_test.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package httplink
-
-import (
- "strings"
- "testing"
-)
-
-func TestHTTPClientKeywordsAllLanguages(t *testing.T) {
- // Each language should have at least one keyword in httpClientKeywords.
- langKeywords := map[string][]string{
- "Python": {"requests.get", "httpx.", "aiohttp."},
- "Go": {"http.Get", "http.Post", "http.NewRequest"},
- "JavaScript": {"fetch(", "axios."},
- "TypeScript": {"fetch(", "axios."},
- "Java": {"HttpClient", "RestTemplate"},
- "Rust": {"reqwest::", "hyper::"},
- "PHP": {"curl_exec", "Guzzle"},
- "Scala": {"sttp.", "http4s"},
- "CPP": {"curl_easy", "cpr::Get"},
- "Lua": {"socket.http", "http.request"},
- "CSharp": {"HttpClient", "WebClient", "RestClient"},
- "Kotlin": {"HttpClient", "OkHttpClient"},
- }
-
- joined := strings.Join(httpClientKeywords, "|")
-
- for langName, keywords := range langKeywords {
- t.Run(langName, func(t *testing.T) {
- found := false
- for _, kw := range keywords {
- if strings.Contains(joined, kw) {
- found = true
- break
- }
- }
- if !found {
- t.Errorf("no HTTP client keywords found for %s; want at least one of %v", langName, keywords)
- }
- })
- }
-}
-
-func TestRouteExtractionNegativeCases(t *testing.T) {
- // Non-route functions should NOT produce spurious route matches.
- tests := []struct {
- name string
- source string
- }{
- {"plain_function", "func processOrder(order Order) error {\n\treturn nil\n}\n"},
- {"math_function", "function calculate(x, y) {\n\treturn x + y;\n}\n"},
- {"utility", "def transform_data(data):\n return data.upper()\n"},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Python route patterns
- matches := pyRouteRe.FindAllStringSubmatch(tt.source, -1)
- if len(matches) > 0 {
- t.Errorf("pyRouteRe matched non-route source: %v", matches)
- }
-
- // Go route patterns
- matches = goRouteRe.FindAllStringSubmatch(tt.source, -1)
- if len(matches) > 0 {
- t.Errorf("goRouteRe matched non-route source: %v", matches)
- }
-
- // Express route patterns
- matches = expressRouteRe.FindAllStringSubmatch(tt.source, -1)
- if len(matches) > 0 {
- t.Errorf("expressRouteRe matched non-route source: %v", matches)
- }
-
- // Spring route patterns
- matches = springMappingRe.FindAllStringSubmatch(tt.source, -1)
- if len(matches) > 0 {
- t.Errorf("springMappingRe matched non-route source: %v", matches)
- }
-
- // Laravel route patterns
- matches = laravelRouteRe.FindAllStringSubmatch(tt.source, -1)
- if len(matches) > 0 {
- t.Errorf("laravelRouteRe matched non-route source: %v", matches)
- }
-
- // Actix route patterns
- matches = actixRouteRe.FindAllStringSubmatch(tt.source, -1)
- if len(matches) > 0 {
- t.Errorf("actixRouteRe matched non-route source: %v", matches)
- }
- })
- }
-}
diff --git a/internal/httplink/similarity.go b/internal/httplink/similarity.go
deleted file mode 100644
index b8509156e..000000000
--- a/internal/httplink/similarity.go
+++ /dev/null
@@ -1,97 +0,0 @@
-package httplink
-
-// levenshteinDistance computes the edit distance between two strings.
-func levenshteinDistance(a, b string) int {
- if a == "" {
- return len(b)
- }
- if b == "" {
- return len(a)
- }
-
- // Use two rows instead of full matrix for space efficiency
- prev := make([]int, len(b)+1)
- curr := make([]int, len(b)+1)
-
- for j := range prev {
- prev[j] = j
- }
-
- for i := 1; i <= len(a); i++ {
- curr[0] = i
- for j := 1; j <= len(b); j++ {
- cost := 1
- if a[i-1] == b[j-1] {
- cost = 0
- }
- curr[j] = min(curr[j-1]+1, min(prev[j]+1, prev[j-1]+cost))
- }
- prev, curr = curr, prev
- }
- return prev[len(b)]
-}
-
-// normalizedLevenshtein returns 1.0 - (distance / maxLen), so 1.0 = identical.
-func normalizedLevenshtein(a, b string) float64 {
- if a == b {
- return 1.0
- }
- maxLen := len(a)
- if len(b) > maxLen {
- maxLen = len(b)
- }
- if maxLen == 0 {
- return 1.0
- }
- dist := levenshteinDistance(a, b)
- return 1.0 - float64(dist)/float64(maxLen)
-}
-
-// ngramOverlap computes the character n-gram overlap coefficient between two strings.
-// Returns |intersection(ngrams(a), ngrams(b))| / min(|ngrams(a)|, |ngrams(b)|).
-func ngramOverlap(a, b string, n int) float64 {
- if len(a) < n || len(b) < n {
- return 0
- }
-
- ngramsA := buildNgrams(a, n)
- ngramsB := buildNgrams(b, n)
-
- intersection := 0
- for ng := range ngramsA {
- if ngramsB[ng] {
- intersection++
- }
- }
-
- minSize := len(ngramsA)
- if len(ngramsB) < minSize {
- minSize = len(ngramsB)
- }
- if minSize == 0 {
- return 0
- }
- return float64(intersection) / float64(minSize)
-}
-
-func buildNgrams(s string, n int) map[string]bool {
- ngrams := make(map[string]bool)
- for i := 0; i <= len(s)-n; i++ {
- ngrams[s[i:i+n]] = true
- }
- return ngrams
-}
-
-// confidenceBand returns the confidence band label for a given score.
-func confidenceBand(score float64) string {
- switch {
- case score >= 0.7:
- return "high"
- case score >= 0.45:
- return "medium"
- case score >= 0.25:
- return "speculative"
- default:
- return ""
- }
-}
diff --git a/internal/httplink/similarity_test.go b/internal/httplink/similarity_test.go
deleted file mode 100644
index c7e5d4f06..000000000
--- a/internal/httplink/similarity_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package httplink
-
-import "testing"
-
-func TestLevenshteinDistance(t *testing.T) {
- tests := []struct {
- a, b string
- want int
- }{
- {"", "", 0},
- {"abc", "", 3},
- {"", "abc", 3},
- {"abc", "abc", 0},
- {"kitten", "sitting", 3},
- {"api/orders", "api/order", 1},
- {"/api/v1/orders", "/api/v2/orders", 1},
- }
- for _, tt := range tests {
- got := levenshteinDistance(tt.a, tt.b)
- if got != tt.want {
- t.Errorf("levenshteinDistance(%q, %q) = %d, want %d", tt.a, tt.b, got, tt.want)
- }
- }
-}
-
-func TestNormalizedLevenshtein(t *testing.T) {
- tests := []struct {
- a, b string
- min float64
- max float64
- }{
- {"abc", "abc", 1.0, 1.0},
- {"", "", 1.0, 1.0},
- {"api/orders", "api/order", 0.88, 0.92},
- {"/api/v1/items", "/api/v2/items", 0.90, 0.94},
- {"completely", "different", 0.0, 0.4},
- }
- for _, tt := range tests {
- got := normalizedLevenshtein(tt.a, tt.b)
- if got < tt.min || got > tt.max {
- t.Errorf("normalizedLevenshtein(%q, %q) = %.3f, want [%.2f, %.2f]", tt.a, tt.b, got, tt.min, tt.max)
- }
- }
-}
-
-func TestNgramOverlap(t *testing.T) {
- tests := []struct {
- a, b string
- n int
- min float64
- max float64
- }{
- {"api/orders", "api/orders", 3, 1.0, 1.0},
- {"api/orders", "api/order", 3, 0.8, 1.0},
- {"abcdef", "ghijkl", 3, 0.0, 0.0},
- {"ab", "cd", 3, 0.0, 0.0}, // too short for trigrams
- }
- for _, tt := range tests {
- got := ngramOverlap(tt.a, tt.b, tt.n)
- if got < tt.min || got > tt.max {
- t.Errorf("ngramOverlap(%q, %q, %d) = %.3f, want [%.2f, %.2f]", tt.a, tt.b, tt.n, got, tt.min, tt.max)
- }
- }
-}
-
-func TestConfidenceBand(t *testing.T) {
- tests := []struct {
- score float64
- want string
- }{
- {0.95, "high"},
- {0.70, "high"},
- {0.69, "medium"},
- {0.45, "medium"},
- {0.44, "speculative"},
- {0.25, "speculative"},
- {0.24, ""},
- {0.0, ""},
- }
- for _, tt := range tests {
- got := confidenceBand(tt.score)
- if got != tt.want {
- t.Errorf("confidenceBand(%.2f) = %q, want %q", tt.score, got, tt.want)
- }
- }
-}
diff --git a/internal/lang/bash.go b/internal/lang/bash.go
deleted file mode 100644
index c7cc662ee..000000000
--- a/internal/lang/bash.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Bash,
- FileExtensions: []string{".sh", ".bash"},
- FunctionNodeTypes: []string{"function_definition"},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"command"},
- ImportNodeTypes: []string{"command"},
-
- BranchingNodeTypes: []string{"if_statement", "while_statement", "for_statement", "case_statement", "elif_clause"},
- VariableNodeTypes: []string{"variable_assignment"},
- AssignmentNodeTypes: []string{"variable_assignment"},
- })
-}
diff --git a/internal/lang/c_lang.go b/internal/lang/c_lang.go
deleted file mode 100644
index 3bac7885c..000000000
--- a/internal/lang/c_lang.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: C,
- FileExtensions: []string{".c"},
- FunctionNodeTypes: []string{
- "function_definition",
- },
- ClassNodeTypes: []string{"struct_specifier", "enum_specifier", "union_specifier"},
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{"translation_unit"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"preproc_include"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "do_statement", "switch_statement", "case_statement"},
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- EnvAccessFunctions: []string{"getenv"},
- })
-}
diff --git a/internal/lang/clojure.go b/internal/lang/clojure.go
deleted file mode 100644
index f7681e7f0..000000000
--- a/internal/lang/clojure.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Clojure,
- FileExtensions: []string{".clj", ".cljs", ".cljc"},
- ModuleNodeTypes: []string{"source"},
- CallNodeTypes: []string{"list_lit"},
- })
-}
diff --git a/internal/lang/cmake.go b/internal/lang/cmake.go
deleted file mode 100644
index b1c333cb3..000000000
--- a/internal/lang/cmake.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: CMake,
- FileExtensions: []string{".cmake"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"normal_command"},
- })
-}
diff --git a/internal/lang/cobol.go b/internal/lang/cobol.go
deleted file mode 100644
index d67420f97..000000000
--- a/internal/lang/cobol.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: COBOL,
- FileExtensions: []string{".cob", ".cbl"},
- FunctionNodeTypes: []string{"program_definition"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_statement"},
- BranchingNodeTypes: []string{
- "if_statement", "evaluate_statement", "perform_statement",
- },
- VariableNodeTypes: []string{"data_description_entry"},
- })
-}
diff --git a/internal/lang/commonlisp.go b/internal/lang/commonlisp.go
deleted file mode 100644
index 104a74664..000000000
--- a/internal/lang/commonlisp.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: CommonLisp,
- FileExtensions: []string{".lisp", ".lsp", ".cl"},
- FunctionNodeTypes: []string{"defun"},
- ModuleNodeTypes: []string{"source"},
- CallNodeTypes: []string{"list_lit"},
- })
-}
diff --git a/internal/lang/cpp.go b/internal/lang/cpp.go
deleted file mode 100644
index 1b2ee4300..000000000
--- a/internal/lang/cpp.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: CPP,
- FileExtensions: []string{".cpp", ".h", ".hpp", ".cc", ".cxx", ".hxx", ".hh", ".ixx", ".cppm", ".ccm"},
- FunctionNodeTypes: []string{
- "function_definition",
- "declaration",
- "field_declaration",
- "template_declaration",
- "lambda_expression",
- },
- ClassNodeTypes: []string{
- "class_specifier",
- "struct_specifier",
- "union_specifier",
- "enum_specifier",
- },
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{
- "translation_unit",
- "namespace_definition",
- "linkage_specification",
- "declaration",
- },
- CallNodeTypes: []string{
- "call_expression",
- "field_expression",
- "subscript_expression",
- "new_expression",
- "delete_expression",
- "binary_expression",
- "unary_expression",
- "update_expression",
- },
- ImportNodeTypes: []string{"preproc_include", "template_function", "declaration"},
- ImportFromTypes: []string{"preproc_include", "template_function", "declaration"},
- PackageIndicators: []string{"CMakeLists.txt", "Makefile", "*.vcxproj", "conanfile.txt"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "for_range_loop", "while_statement", "switch_statement", "case_statement", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- EnvAccessFunctions: []string{"getenv", "std::getenv"},
- })
-}
diff --git a/internal/lang/csharp.go b/internal/lang/csharp.go
deleted file mode 100644
index a10492b07..000000000
--- a/internal/lang/csharp.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: CSharp,
- FileExtensions: []string{".cs"},
- FunctionNodeTypes: []string{
- "destructor_declaration",
- "local_function_statement",
- "function_pointer_type",
- "constructor_declaration",
- "anonymous_method_expression",
- "lambda_expression",
- "method_declaration",
- },
- ClassNodeTypes: []string{
- "class_declaration",
- "struct_declaration",
- "enum_declaration",
- "interface_declaration",
- },
- ModuleNodeTypes: []string{"compilation_unit"},
- CallNodeTypes: []string{"invocation_expression"},
- ImportNodeTypes: []string{"using_directive"},
- ImportFromTypes: []string{"using_directive"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "foreach_statement", "while_statement", "switch_statement", "case_switch_label", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"field_declaration", "local_declaration_statement"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement", "throw_expression"},
- DecoratorNodeTypes: []string{"attribute"},
- EnvAccessFunctions: []string{"Environment.GetEnvironmentVariable"},
- })
-}
diff --git a/internal/lang/css.go b/internal/lang/css.go
deleted file mode 100644
index 87f3710e6..000000000
--- a/internal/lang/css.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: CSS,
- FileExtensions: []string{".css"},
- FunctionNodeTypes: []string{},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"stylesheet"},
- CallNodeTypes: []string{},
- ImportNodeTypes: []string{"import_statement"},
-
- VariableNodeTypes: []string{},
- })
-}
diff --git a/internal/lang/cuda.go b/internal/lang/cuda.go
deleted file mode 100644
index 8a036c8fb..000000000
--- a/internal/lang/cuda.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: CUDA,
- FileExtensions: []string{".cu", ".cuh"},
- FunctionNodeTypes: []string{
- "function_definition", "declaration", "field_declaration",
- "template_declaration", "lambda_expression",
- },
- ClassNodeTypes: []string{
- "class_specifier", "struct_specifier", "union_specifier", "enum_specifier",
- },
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{"translation_unit", "namespace_definition", "linkage_specification", "declaration"},
- CallNodeTypes: []string{
- "call_expression", "field_expression", "subscript_expression",
- "new_expression", "delete_expression",
- },
- ImportNodeTypes: []string{"preproc_include"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "for_range_loop", "while_statement",
- "switch_statement", "case_statement", "try_statement", "catch_clause",
- },
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- EnvAccessFunctions: []string{"getenv", "std::getenv"},
- })
-}
diff --git a/internal/lang/dart.go b/internal/lang/dart.go
deleted file mode 100644
index d017c9e9c..000000000
--- a/internal/lang/dart.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Dart,
- FileExtensions: []string{".dart"},
- FunctionNodeTypes: []string{
- "function_signature", // top-level function: return_type name(params)
- "method_signature", // class method: wraps function_signature
- },
- ClassNodeTypes: []string{
- "class_definition",
- "enum_declaration",
- "mixin_declaration",
- },
- FieldNodeTypes: []string{"declaration"},
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"selector"},
- ImportNodeTypes: []string{"import_or_export"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "while_statement",
- "switch_statement",
- },
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_expression"},
- DecoratorNodeTypes: []string{"annotation"},
- })
-}
diff --git a/internal/lang/dockerfile.go b/internal/lang/dockerfile.go
deleted file mode 100644
index a33abc01d..000000000
--- a/internal/lang/dockerfile.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Dockerfile,
- FileExtensions: []string{".dockerfile", "Dockerfile"},
- ModuleNodeTypes: []string{"source_file"},
- FunctionNodeTypes: []string{},
- ClassNodeTypes: []string{},
- FieldNodeTypes: []string{},
- CallNodeTypes: []string{},
- ImportNodeTypes: []string{},
- VariableNodeTypes: []string{
- "env_instruction",
- "arg_instruction",
- },
- })
-}
diff --git a/internal/lang/elixir.go b/internal/lang/elixir.go
deleted file mode 100644
index 3bcaee9c7..000000000
--- a/internal/lang/elixir.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Elixir,
- FileExtensions: []string{".ex", ".exs"},
- // Elixir uses "call" for everything (homoiconic), but we only want
- // definition forms (def, defp, defmacro) in FunctionNodeTypes.
- // The pipeline has custom Elixir handling to classify call nodes.
- FunctionNodeTypes: []string{
- "call", // classified by pipeline: def/defp → Function, defmodule → Class
- },
- ClassNodeTypes: []string{}, // handled by custom extraction (defmodule)
- ModuleNodeTypes: []string{"source"},
- CallNodeTypes: []string{"call", "dot", "binary_operator"},
- ImportNodeTypes: []string{"call"},
-
- BranchingNodeTypes: []string{
- "call", // if/cond/case are macro calls in Elixir
- },
- VariableNodeTypes: []string{"binary_operator"},
- AssignmentNodeTypes: []string{"binary_operator"},
- EnvAccessFunctions: []string{"System.get_env"},
- })
-}
diff --git a/internal/lang/elm.go b/internal/lang/elm.go
deleted file mode 100644
index ec0aa178e..000000000
--- a/internal/lang/elm.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Elm,
- FileExtensions: []string{".elm"},
- FunctionNodeTypes: []string{"value_declaration", "function_declaration"},
- ClassNodeTypes: []string{"type_declaration", "type_alias_declaration"},
- ModuleNodeTypes: []string{"file"},
- CallNodeTypes: []string{"function_call"},
- ImportNodeTypes: []string{"import"},
- BranchingNodeTypes: []string{"case_of_expr", "if_else_expr"},
- })
-}
diff --git a/internal/lang/emacslisp.go b/internal/lang/emacslisp.go
deleted file mode 100644
index 342620f8d..000000000
--- a/internal/lang/emacslisp.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: EmacsLisp,
- FileExtensions: []string{".el"},
- FunctionNodeTypes: []string{"function_definition", "macro_definition"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"list"},
- })
-}
diff --git a/internal/lang/erlang.go b/internal/lang/erlang.go
deleted file mode 100644
index 2636b5b4c..000000000
--- a/internal/lang/erlang.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Erlang,
- FileExtensions: []string{".erl"},
- FunctionNodeTypes: []string{
- "function_clause",
- },
- ClassNodeTypes: []string{},
- FieldNodeTypes: []string{},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call"},
- ImportNodeTypes: []string{"module_attribute"},
- BranchingNodeTypes: []string{
- "if_expression", "case_expression", "receive_expression",
- },
- VariableNodeTypes: []string{"pp_define", "record_decl"},
- AssignmentNodeTypes: []string{"match_expression"},
- ThrowNodeTypes: []string{"call"},
- })
-}
diff --git a/internal/lang/form.go b/internal/lang/form.go
deleted file mode 100644
index f09a94227..000000000
--- a/internal/lang/form.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: FORM,
- FileExtensions: []string{".frm", ".prc"},
- FunctionNodeTypes: []string{"procedure_definition"},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_statement"},
- ImportNodeTypes: []string{"include_directive"},
- BranchingNodeTypes: []string{"if_statement", "repeat_statement", "do_loop"},
- VariableNodeTypes: []string{"declaration_statement"},
- AssignmentNodeTypes: []string{"substitution_statement"},
- })
-}
diff --git a/internal/lang/fortran.go b/internal/lang/fortran.go
deleted file mode 100644
index b78c01166..000000000
--- a/internal/lang/fortran.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Fortran,
- FileExtensions: []string{".f90", ".f95", ".f03", ".f08"},
- FunctionNodeTypes: []string{"function", "subroutine"},
- ClassNodeTypes: []string{"derived_type_definition"},
- ModuleNodeTypes: []string{"translation_unit"},
- CallNodeTypes: []string{"call_expression", "keyword_argument"},
- ImportNodeTypes: []string{"use_statement", "include_statement"},
- BranchingNodeTypes: []string{
- "if_statement", "do_loop_statement", "where_statement", "select_case_statement",
- },
- VariableNodeTypes: []string{"variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_statement"},
- EnvAccessFunctions: []string{"get_environment_variable"},
- })
-}
diff --git a/internal/lang/fsharp.go b/internal/lang/fsharp.go
deleted file mode 100644
index e641eb14e..000000000
--- a/internal/lang/fsharp.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: FSharp,
- FileExtensions: []string{".fs", ".fsi", ".fsx"},
- FunctionNodeTypes: []string{"function_declaration", "value_declaration"},
- ClassNodeTypes: []string{"type_definition", "exception_definition"},
- ModuleNodeTypes: []string{"file"},
- CallNodeTypes: []string{"application_expression", "dot_expression"},
- ImportNodeTypes: []string{"import_decl", "open_expression"},
- BranchingNodeTypes: []string{
- "if_expression", "for_expression", "while_expression",
- "match_expression", "elif_expression",
- },
- VariableNodeTypes: []string{"value_declaration"},
- AssignmentNodeTypes: []string{"value_declaration"},
- EnvAccessFunctions: []string{"Environment.GetEnvironmentVariable"},
- })
-}
diff --git a/internal/lang/glsl.go b/internal/lang/glsl.go
deleted file mode 100644
index 87877b539..000000000
--- a/internal/lang/glsl.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: GLSL,
- FileExtensions: []string{".glsl", ".vert", ".frag"},
- FunctionNodeTypes: []string{"function_definition"},
- ClassNodeTypes: []string{"struct_specifier", "enum_specifier", "union_specifier"},
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{"translation_unit"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"preproc_include"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "while_statement",
- "do_statement", "switch_statement", "case_statement",
- },
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- })
-}
diff --git a/internal/lang/go_lang.go b/internal/lang/go_lang.go
deleted file mode 100644
index 5101f81ce..000000000
--- a/internal/lang/go_lang.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Go,
- FileExtensions: []string{".go"},
- FunctionNodeTypes: []string{"function_declaration", "method_declaration", "method_elem"},
- ClassNodeTypes: []string{"type_spec", "type_alias"},
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"import_declaration"},
- ImportFromTypes: []string{"import_declaration"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "switch_expression", "select_statement", "case_clause", "default_clause"},
- VariableNodeTypes: []string{"var_declaration", "const_declaration"},
- AssignmentNodeTypes: []string{"assignment_statement", "short_var_declaration"},
- EnvAccessFunctions: []string{"os.Getenv", "os.LookupEnv"},
- })
-}
diff --git a/internal/lang/graphql.go b/internal/lang/graphql.go
deleted file mode 100644
index 6be61d5be..000000000
--- a/internal/lang/graphql.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: GraphQL,
- FileExtensions: []string{".graphql", ".gql"},
- ClassNodeTypes: []string{
- "object_type_definition", "input_object_type_definition",
- "enum_type_definition", "interface_type_definition",
- "union_type_definition", "scalar_type_definition",
- },
- FieldNodeTypes: []string{"field_definition", "input_value_definition"},
- ModuleNodeTypes: []string{"document"},
- })
-}
diff --git a/internal/lang/groovy.go b/internal/lang/groovy.go
deleted file mode 100644
index 02aeadf25..000000000
--- a/internal/lang/groovy.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Groovy,
- FileExtensions: []string{".groovy", ".gradle"},
- FunctionNodeTypes: []string{
- "function_definition", // def greet() {} or void greet() {}
- },
- ClassNodeTypes: []string{
- "class_definition", // class Foo extends Bar {}
- },
- FieldNodeTypes: []string{},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"function_call", "juxt_function_call"},
- ImportNodeTypes: []string{"groovy_import"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "while_statement",
- "switch_statement",
- },
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment"},
- ThrowNodeTypes: []string{"throw_statement"},
- DecoratorNodeTypes: []string{"annotation"},
- })
-}
diff --git a/internal/lang/haskell.go b/internal/lang/haskell.go
deleted file mode 100644
index a1262bdd0..000000000
--- a/internal/lang/haskell.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Haskell,
- FileExtensions: []string{".hs"},
- FunctionNodeTypes: []string{
- "function", // function binding with name, patterns, match
- "signature", // type signature (name :: Type -> Type)
- },
- ClassNodeTypes: []string{
- "class", // type class declaration
- "data_type", // algebraic data type
- "newtype", // newtype declaration
- },
- ModuleNodeTypes: []string{"haskell"},
- CallNodeTypes: []string{"infix", "apply"},
- ImportNodeTypes: []string{"import"},
-
- BranchingNodeTypes: []string{
- "match", // pattern match clause
- "guards", // guard expressions
- "if", // if expression
- "case", // case expression
- "do", // do notation
- "boolean", // guard condition
- },
- VariableNodeTypes: []string{"function"},
- AssignmentNodeTypes: []string{"function"},
- EnvAccessFunctions: []string{"lookupEnv", "getEnv"},
- })
-}
diff --git a/internal/lang/hcl.go b/internal/lang/hcl.go
deleted file mode 100644
index dad5eaec6..000000000
--- a/internal/lang/hcl.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: HCL,
- FileExtensions: []string{".tf", ".hcl"},
- FunctionNodeTypes: []string{},
- ClassNodeTypes: []string{
- "block", // resource, variable, output, data, module blocks
- },
- ModuleNodeTypes: []string{"config_file"},
- CallNodeTypes: []string{"function_call"},
- ImportNodeTypes: []string{},
-
- VariableNodeTypes: []string{"attribute"},
- })
-}
diff --git a/internal/lang/html.go b/internal/lang/html.go
deleted file mode 100644
index 529d6f9da..000000000
--- a/internal/lang/html.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: HTML,
- FileExtensions: []string{".html", ".htm"},
- FunctionNodeTypes: []string{},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"document"},
- CallNodeTypes: []string{},
- ImportNodeTypes: []string{},
-
- VariableNodeTypes: []string{},
- })
-}
diff --git a/internal/lang/ini.go b/internal/lang/ini.go
deleted file mode 100644
index 76d3cd43f..000000000
--- a/internal/lang/ini.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: INI,
- FileExtensions: []string{".ini", ".cfg", ".conf"},
- ModuleNodeTypes: []string{"document"},
- })
-}
diff --git a/internal/lang/java.go b/internal/lang/java.go
deleted file mode 100644
index 27efec70c..000000000
--- a/internal/lang/java.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Java,
- FileExtensions: []string{".java"},
- FunctionNodeTypes: []string{"method_declaration", "constructor_declaration"},
- ClassNodeTypes: []string{
- "class_declaration",
- "interface_declaration",
- "enum_declaration",
- "annotation_type_declaration",
- "record_declaration",
- },
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"method_invocation"},
- ImportNodeTypes: []string{"import_declaration"},
- ImportFromTypes: []string{"import_declaration"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "enhanced_for_statement", "while_statement", "switch_expression", "switch_block_statement_group", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"field_declaration", "local_variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- ThrowsClauseField: "throws",
- DecoratorNodeTypes: []string{"marker_annotation", "annotation"},
- EnvAccessFunctions: []string{"System.getenv", "System.getProperty"},
- })
-}
diff --git a/internal/lang/javascript.go b/internal/lang/javascript.go
deleted file mode 100644
index e2d9dddb6..000000000
--- a/internal/lang/javascript.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: JavaScript,
- FileExtensions: []string{".js", ".jsx"},
- FunctionNodeTypes: []string{
- "function_declaration",
- "generator_function_declaration",
- "function_expression",
- "arrow_function",
- "method_definition",
- },
- ClassNodeTypes: []string{"class_declaration", "class"},
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"import_statement", "lexical_declaration", "export_statement"},
- ImportFromTypes: []string{"import_statement", "lexical_declaration", "export_statement"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "switch_statement", "case_clause", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"lexical_declaration", "variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression", "augmented_assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- EnvAccessMemberPatterns: []string{"process.env"},
- })
-}
diff --git a/internal/lang/json.go b/internal/lang/json.go
deleted file mode 100644
index 0aa92d1c2..000000000
--- a/internal/lang/json.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: JSON,
- FileExtensions: []string{".json"},
- ModuleNodeTypes: []string{"document"},
- })
-}
diff --git a/internal/lang/julia.go b/internal/lang/julia.go
deleted file mode 100644
index 8fda194e7..000000000
--- a/internal/lang/julia.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Julia,
- FileExtensions: []string{".jl"},
- FunctionNodeTypes: []string{"function_definition", "short_function_definition"},
- ClassNodeTypes: []string{"struct_definition", "abstract_definition"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_expression", "broadcast_call_expression"},
- ImportNodeTypes: []string{"import_statement", "using_statement"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "while_statement", "try_statement",
- },
- VariableNodeTypes: []string{"const_statement", "assignment"},
- AssignmentNodeTypes: []string{"assignment", "compound_assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- EnvAccessMemberPatterns: []string{"ENV"},
- })
-}
diff --git a/internal/lang/kotlin.go b/internal/lang/kotlin.go
deleted file mode 100644
index bc219d5af..000000000
--- a/internal/lang/kotlin.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Kotlin,
- FileExtensions: []string{".kt", ".kts"},
- FunctionNodeTypes: []string{
- "function_declaration",
- "secondary_constructor",
- "anonymous_function",
- },
- ClassNodeTypes: []string{
- "class_declaration",
- "object_declaration",
- "companion_object",
- },
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{
- "call_expression",
- "navigation_expression",
- },
- ImportNodeTypes: []string{"import"},
- ImportFromTypes: []string{"import"},
-
- BranchingNodeTypes: []string{"if_expression", "for_statement", "while_statement", "when_expression", "when_entry", "try_expression", "catch_block"},
- VariableNodeTypes: []string{"property_declaration"},
- AssignmentNodeTypes: []string{"assignment", "directly_assignable_expression"},
- ThrowNodeTypes: []string{"throw_expression"},
- DecoratorNodeTypes: []string{"annotation"},
- EnvAccessFunctions: []string{"System.getenv", "System.getProperty"},
- })
-}
diff --git a/internal/lang/lang.go b/internal/lang/lang.go
deleted file mode 100644
index 28a0a49e7..000000000
--- a/internal/lang/lang.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package lang
-
-// Language represents a supported programming language.
-type Language string
-
-const (
- Python Language = "python"
- JavaScript Language = "javascript"
- TypeScript Language = "typescript"
- Go Language = "go"
- Rust Language = "rust"
- Java Language = "java"
- CPP Language = "cpp"
- TSX Language = "tsx"
- CSharp Language = "c-sharp"
- PHP Language = "php"
- Lua Language = "lua"
- Scala Language = "scala"
- Kotlin Language = "kotlin"
- // Programming languages (Tier 1)
- Ruby Language = "ruby"
- C Language = "c"
- Bash Language = "bash"
- Zig Language = "zig"
- Elixir Language = "elixir"
- Haskell Language = "haskell"
- OCaml Language = "ocaml"
- ObjectiveC Language = "objective-c"
- Swift Language = "swift"
- Dart Language = "dart"
- Perl Language = "perl"
- Groovy Language = "groovy"
- Erlang Language = "erlang"
- R Language = "r"
-
- Clojure Language = "clojure"
- FSharp Language = "fsharp"
- Julia Language = "julia"
- VimScript Language = "vimscript"
- Nix Language = "nix"
- CommonLisp Language = "commonlisp"
- Elm Language = "elm"
- Fortran Language = "fortran"
- CUDA Language = "cuda"
- COBOL Language = "cobol"
- Verilog Language = "verilog"
- EmacsLisp Language = "emacslisp"
-
- // Scientific/math languages
- MATLAB Language = "matlab"
- Lean Language = "lean"
- FORM Language = "form"
- Magma Language = "magma"
- Wolfram Language = "wolfram"
-
- // Helper languages (Tier 2)
- HTML Language = "html"
- CSS Language = "css"
- SCSS Language = "scss"
- YAML Language = "yaml"
- TOML Language = "toml"
- HCL Language = "hcl"
- SQL Language = "sql"
- Dockerfile Language = "dockerfile"
- JSON Language = "json"
- XML Language = "xml"
- Markdown Language = "markdown"
- Makefile Language = "makefile"
- CMake Language = "cmake"
- Protobuf Language = "protobuf"
- GraphQL Language = "graphql"
- Vue Language = "vue"
- Svelte Language = "svelte"
- Meson Language = "meson"
- GLSL Language = "glsl"
- INI Language = "ini"
-)
-
-// AllLanguages returns all supported languages.
-func AllLanguages() []Language {
- return []Language{
- Python, JavaScript, TypeScript, TSX, Go, Rust, Java, CPP, CSharp, PHP, Lua, Scala, Kotlin,
- Ruby, C, Bash, Zig, Elixir, Haskell, OCaml, ObjectiveC,
- Swift, Dart, Perl, Groovy, Erlang, R,
- Clojure, FSharp, Julia, VimScript, Nix, CommonLisp, Elm, Fortran,
- CUDA, COBOL, Verilog, EmacsLisp,
- MATLAB, Lean, FORM, Magma, Wolfram,
- HTML, CSS, SCSS, YAML, TOML, HCL, SQL, Dockerfile,
- JSON, XML, Markdown, Makefile, CMake, Protobuf, GraphQL,
- Vue, Svelte, Meson, GLSL, INI,
- }
-}
-
-// LanguageSpec defines the tree-sitter node types for a language.
-type LanguageSpec struct {
- Language Language
- FileExtensions []string
- FunctionNodeTypes []string
- ClassNodeTypes []string
- FieldNodeTypes []string // tree-sitter node kinds for struct/class fields
- ModuleNodeTypes []string
- CallNodeTypes []string
- ImportNodeTypes []string
- ImportFromTypes []string
- PackageIndicators []string
-
- // BranchingNodeTypes lists AST node kinds counted for complexity metric.
- BranchingNodeTypes []string
- // VariableNodeTypes lists module-level variable declaration node kinds.
- VariableNodeTypes []string
- // AssignmentNodeTypes lists assignment expression/statement node kinds.
- AssignmentNodeTypes []string
- // ThrowNodeTypes lists throw/raise statement node kinds.
- ThrowNodeTypes []string
- // ThrowsClauseField is the field name for declared throws (e.g. Java "throws").
- ThrowsClauseField string
- // DecoratorNodeTypes lists decorator/annotation node kinds.
- DecoratorNodeTypes []string
- // EnvAccessFunctions lists function names used to read env vars (e.g. "os.Getenv").
- EnvAccessFunctions []string
- // EnvAccessMemberPatterns lists member access patterns for env vars (e.g. "process.env").
- EnvAccessMemberPatterns []string
-}
-
-// registry maps file extensions to language specs.
-var registry = map[string]*LanguageSpec{}
-
-// Register adds a LanguageSpec to the global registry.
-func Register(spec *LanguageSpec) {
- for _, ext := range spec.FileExtensions {
- registry[ext] = spec
- }
-}
-
-// ForExtension returns the LanguageSpec for a file extension (e.g. ".go").
-func ForExtension(ext string) *LanguageSpec {
- return registry[ext]
-}
-
-// ForLanguage returns the LanguageSpec for a language.
-func ForLanguage(lang Language) *LanguageSpec {
- for _, spec := range registry {
- if spec.Language == lang {
- return spec
- }
- }
- return nil
-}
-
-// LanguageForExtension returns the Language for a file extension.
-func LanguageForExtension(ext string) (Language, bool) {
- spec := registry[ext]
- if spec == nil {
- return "", false
- }
- return spec.Language, true
-}
-
-// filenameToLanguage maps exact filenames to languages (for extensionless files).
-var filenameToLanguage = map[string]Language{
- "Makefile": Makefile,
- "GNUmakefile": Makefile,
- "makefile": Makefile,
- "CMakeLists.txt": CMake,
- "Dockerfile": Dockerfile,
- "meson.build": Meson,
- "meson.options": Meson,
- "meson_options.txt": Meson,
- ".vimrc": VimScript,
-}
-
-// LanguageForFilename returns the Language for an exact filename match.
-func LanguageForFilename(name string) (Language, bool) {
- l, ok := filenameToLanguage[name]
- return l, ok
-}
diff --git a/internal/lang/lang_test.go b/internal/lang/lang_test.go
deleted file mode 100644
index a64b18a92..000000000
--- a/internal/lang/lang_test.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package lang
-
-import "testing"
-
-func TestForExtension(t *testing.T) {
- tests := []struct {
- ext string
- lang Language
- }{
- {".py", Python},
- {".go", Go},
- {".js", JavaScript},
- {".ts", TypeScript},
- {".tsx", TSX},
- {".rs", Rust},
- {".java", Java},
- {".cpp", CPP},
- {".h", CPP},
- {".cs", CSharp},
- {".php", PHP},
- {".lua", Lua},
- {".scala", Scala},
- {".kt", Kotlin},
- {".kts", Kotlin},
- }
- for _, tt := range tests {
- spec := ForExtension(tt.ext)
- if spec == nil {
- t.Errorf("ForExtension(%q) = nil, want %s", tt.ext, tt.lang)
- continue
- }
- if spec.Language != tt.lang {
- t.Errorf("ForExtension(%q).Language = %s, want %s", tt.ext, spec.Language, tt.lang)
- }
- }
-}
-
-func TestForLanguage(t *testing.T) {
- for _, lang := range AllLanguages() {
- spec := ForLanguage(lang)
- if spec == nil {
- t.Errorf("ForLanguage(%s) = nil", lang)
- }
- }
-}
-
-func TestUnknownExtension(t *testing.T) {
- if spec := ForExtension(".xyz"); spec != nil {
- t.Errorf("ForExtension(.xyz) should be nil, got %v", spec)
- }
-}
-
-func TestGoSpec(t *testing.T) {
- spec := ForLanguage(Go)
- if spec == nil {
- t.Fatal("Go spec not registered")
- }
- if len(spec.FunctionNodeTypes) != 3 {
- t.Errorf("Go FunctionNodeTypes: got %d, want 3", len(spec.FunctionNodeTypes))
- }
- // Should contain function_declaration, method_declaration, and method_elem (interface methods)
- found := map[string]bool{}
- for _, nt := range spec.FunctionNodeTypes {
- found[nt] = true
- }
- if !found["function_declaration"] || !found["method_declaration"] || !found["method_elem"] {
- t.Errorf("Go FunctionNodeTypes missing expected types: %v", spec.FunctionNodeTypes)
- }
-}
-
-func TestPythonSpec(t *testing.T) {
- spec := ForLanguage(Python)
- if spec == nil {
- t.Fatal("Python spec not registered")
- }
- if spec.PackageIndicators[0] != "__init__.py" {
- t.Errorf("Python PackageIndicators: got %v, want [__init__.py]", spec.PackageIndicators)
- }
-}
-
-func TestKotlinSpec(t *testing.T) {
- spec := ForLanguage(Kotlin)
- if spec == nil {
- t.Fatal("Kotlin spec not registered")
- }
- // Should have .kt and .kts extensions
- if len(spec.FileExtensions) != 2 {
- t.Errorf("Kotlin FileExtensions: got %d, want 2", len(spec.FileExtensions))
- }
- extSet := map[string]bool{}
- for _, ext := range spec.FileExtensions {
- extSet[ext] = true
- }
- if !extSet[".kt"] || !extSet[".kts"] {
- t.Errorf("Kotlin FileExtensions missing .kt or .kts: %v", spec.FileExtensions)
- }
- // Should contain function_declaration, secondary_constructor, anonymous_function
- if len(spec.FunctionNodeTypes) != 3 {
- t.Errorf("Kotlin FunctionNodeTypes: got %d, want 3", len(spec.FunctionNodeTypes))
- }
- found := map[string]bool{}
- for _, nt := range spec.FunctionNodeTypes {
- found[nt] = true
- }
- if !found["function_declaration"] || !found["secondary_constructor"] || !found["anonymous_function"] {
- t.Errorf("Kotlin FunctionNodeTypes missing expected types: %v", spec.FunctionNodeTypes)
- }
- // Should contain class_declaration, object_declaration, companion_object
- if len(spec.ClassNodeTypes) != 3 {
- t.Errorf("Kotlin ClassNodeTypes: got %d, want 3", len(spec.ClassNodeTypes))
- }
- classFound := map[string]bool{}
- for _, nt := range spec.ClassNodeTypes {
- classFound[nt] = true
- }
- if !classFound["class_declaration"] || !classFound["object_declaration"] || !classFound["companion_object"] {
- t.Errorf("Kotlin ClassNodeTypes missing expected types: %v", spec.ClassNodeTypes)
- }
-}
diff --git a/internal/lang/lean.go b/internal/lang/lean.go
deleted file mode 100644
index 62019188a..000000000
--- a/internal/lang/lean.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Lean,
- FileExtensions: []string{".lean"},
- FunctionNodeTypes: []string{"def", "theorem", "instance", "abbrev"},
- ClassNodeTypes: []string{"structure", "class_inductive", "inductive"},
- ModuleNodeTypes: []string{"module"},
- CallNodeTypes: []string{"apply"},
- ImportNodeTypes: []string{"import"},
- BranchingNodeTypes: []string{"if", "match", "do"},
- VariableNodeTypes: []string{},
- AssignmentNodeTypes: []string{},
- })
-}
diff --git a/internal/lang/lua.go b/internal/lang/lua.go
deleted file mode 100644
index 44bbddc1b..000000000
--- a/internal/lang/lua.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Lua,
- FileExtensions: []string{".lua"},
- FunctionNodeTypes: []string{"function_declaration", "function_definition"},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"chunk"},
- CallNodeTypes: []string{"function_call"},
- ImportNodeTypes: []string{"function_call"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "repeat_statement"},
- VariableNodeTypes: []string{"variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_statement"},
- EnvAccessFunctions: []string{"os.getenv"},
- })
-}
diff --git a/internal/lang/magma.go b/internal/lang/magma.go
deleted file mode 100644
index c0f9004f2..000000000
--- a/internal/lang/magma.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Magma,
- FileExtensions: []string{".mag", ".magma"},
- FunctionNodeTypes: []string{"function_definition", "procedure_definition", "intrinsic_definition"},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"load_statement"},
- BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "repeat_statement", "case_statement"},
- VariableNodeTypes: []string{"assignment_statement"},
- AssignmentNodeTypes: []string{"assignment_statement"},
- })
-}
diff --git a/internal/lang/makefile.go b/internal/lang/makefile.go
deleted file mode 100644
index 22537b85b..000000000
--- a/internal/lang/makefile.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Makefile,
- FileExtensions: []string{".mk"},
- FunctionNodeTypes: []string{"rule"},
- ModuleNodeTypes: []string{"makefile"},
- CallNodeTypes: []string{"function_call"},
- ImportNodeTypes: []string{"include_directive"},
- VariableNodeTypes: []string{"variable_assignment"},
- })
-}
diff --git a/internal/lang/markdown.go b/internal/lang/markdown.go
deleted file mode 100644
index 429208ce3..000000000
--- a/internal/lang/markdown.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Markdown,
- FileExtensions: []string{".md", ".mdx"},
- ModuleNodeTypes: []string{"document"},
- })
-}
diff --git a/internal/lang/matlab.go b/internal/lang/matlab.go
deleted file mode 100644
index 00de6cf88..000000000
--- a/internal/lang/matlab.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: MATLAB,
- FileExtensions: []string{".matlab", ".mlx"},
- FunctionNodeTypes: []string{"function_definition"},
- ClassNodeTypes: []string{"class_definition"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"function_call", "command"},
- ImportNodeTypes: []string{},
- BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "switch_statement", "try_statement"},
- VariableNodeTypes: []string{"assignment"},
- AssignmentNodeTypes: []string{"assignment"},
- })
-}
diff --git a/internal/lang/meson.go b/internal/lang/meson.go
deleted file mode 100644
index 23dbe3b57..000000000
--- a/internal/lang/meson.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Meson,
- FileExtensions: []string{".meson"},
- FunctionNodeTypes: []string{"function_expression"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"function_expression"},
- BranchingNodeTypes: []string{"if_statement", "foreach_statement"},
- VariableNodeTypes: []string{"assignment_statement"},
- })
-}
diff --git a/internal/lang/nix.go b/internal/lang/nix.go
deleted file mode 100644
index dbe118a32..000000000
--- a/internal/lang/nix.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Nix,
- FileExtensions: []string{".nix"},
- FunctionNodeTypes: []string{"function_expression"},
- ModuleNodeTypes: []string{"source_expression"},
- CallNodeTypes: []string{"apply_expression"},
- BranchingNodeTypes: []string{"if_expression"},
- VariableNodeTypes: []string{"binding"},
- EnvAccessFunctions: []string{"builtins.getEnv"},
- })
-}
diff --git a/internal/lang/objc.go b/internal/lang/objc.go
deleted file mode 100644
index e552d4ee6..000000000
--- a/internal/lang/objc.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: ObjectiveC,
- FileExtensions: []string{".m"},
- FunctionNodeTypes: []string{
- "function_definition",
- "method_definition",
- },
- ClassNodeTypes: []string{
- "class_interface",
- "class_implementation",
- "protocol_declaration",
- },
- FieldNodeTypes: []string{"property_declaration"},
- ModuleNodeTypes: []string{"translation_unit"},
- CallNodeTypes: []string{"call_expression", "message_expression"},
- ImportNodeTypes: []string{"preproc_import"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "switch_statement"},
- VariableNodeTypes: []string{"declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- })
-}
diff --git a/internal/lang/ocaml.go b/internal/lang/ocaml.go
deleted file mode 100644
index 3fb663067..000000000
--- a/internal/lang/ocaml.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: OCaml,
- FileExtensions: []string{".ml", ".mli"},
- FunctionNodeTypes: []string{
- "value_definition", // let name args = body (contains let_binding)
- },
- ClassNodeTypes: []string{
- "type_definition", // type color = Red | Green
- "class_definition", // class foo = object ... end
- "module_definition", // module M = struct ... end
- },
- ModuleNodeTypes: []string{"compilation_unit"},
- CallNodeTypes: []string{"application_expression", "infix_expression"},
- ImportNodeTypes: []string{"open_module"},
-
- BranchingNodeTypes: []string{
- "match_expression", // match ... with
- "if_expression", // if ... then ... else
- "match_case", // individual pattern match case
- },
- VariableNodeTypes: []string{"value_definition"},
- AssignmentNodeTypes: []string{"value_definition"},
- EnvAccessFunctions: []string{"Sys.getenv"},
- })
-}
diff --git a/internal/lang/perl.go b/internal/lang/perl.go
deleted file mode 100644
index 16642413c..000000000
--- a/internal/lang/perl.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Perl,
- FileExtensions: []string{".pl", ".pm"},
- FunctionNodeTypes: []string{
- "subroutine_declaration_statement",
- },
- ClassNodeTypes: []string{},
- FieldNodeTypes: []string{},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"ambiguous_function_call_expression", "function_call_expression", "func1op_call_expression"},
- ImportNodeTypes: []string{"use_statement", "require_statement"},
- BranchingNodeTypes: []string{
- "if_statement", "unless_statement", "for_statement",
- "foreach_statement", "while_statement",
- },
- VariableNodeTypes: []string{"variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- EnvAccessFunctions: []string{"$ENV"},
- })
-}
diff --git a/internal/lang/php.go b/internal/lang/php.go
deleted file mode 100644
index 1259b3bec..000000000
--- a/internal/lang/php.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: PHP,
- FileExtensions: []string{".php"},
- FunctionNodeTypes: []string{
- "function_static_declaration",
- "anonymous_function",
- "function_definition",
- "arrow_function",
- "method_declaration",
- },
- ClassNodeTypes: []string{
- "trait_declaration",
- "enum_declaration",
- "interface_declaration",
- "class_declaration",
- },
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{
- "member_call_expression",
- "scoped_call_expression",
- "function_call_expression",
- "nullsafe_member_call_expression",
- },
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "foreach_statement", "while_statement", "switch_statement", "case_statement", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"expression_statement"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_expression"},
- DecoratorNodeTypes: []string{"attribute_group"},
- EnvAccessFunctions: []string{"getenv", "env"},
- })
-}
diff --git a/internal/lang/protobuf.go b/internal/lang/protobuf.go
deleted file mode 100644
index 09f3778dd..000000000
--- a/internal/lang/protobuf.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Protobuf,
- FileExtensions: []string{".proto"},
- ClassNodeTypes: []string{"message", "enum"},
- FieldNodeTypes: []string{"field", "map_field", "oneof_field"},
- ModuleNodeTypes: []string{"source_file"},
- ImportNodeTypes: []string{"import"},
- })
-}
diff --git a/internal/lang/python.go b/internal/lang/python.go
deleted file mode 100644
index 633a8d70e..000000000
--- a/internal/lang/python.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Python,
- FileExtensions: []string{".py"},
- FunctionNodeTypes: []string{"function_definition"},
- ClassNodeTypes: []string{"class_definition"},
- ModuleNodeTypes: []string{"module"},
- CallNodeTypes: []string{"call", "with_statement"},
- ImportNodeTypes: []string{"import_statement"},
- ImportFromTypes: []string{"import_from_statement"},
- PackageIndicators: []string{"__init__.py"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "try_statement", "except_clause", "with_statement", "elif_clause"},
- VariableNodeTypes: []string{"assignment", "augmented_assignment"},
- AssignmentNodeTypes: []string{"assignment", "augmented_assignment"},
- ThrowNodeTypes: []string{"raise_statement"},
- DecoratorNodeTypes: []string{"decorator"},
- EnvAccessFunctions: []string{"os.getenv", "os.environ.get"},
- EnvAccessMemberPatterns: []string{"os.environ"},
- })
-}
diff --git a/internal/lang/r.go b/internal/lang/r.go
deleted file mode 100644
index d579a2c69..000000000
--- a/internal/lang/r.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: R,
- FileExtensions: []string{".r", ".R"},
- FunctionNodeTypes: []string{
- "function_definition",
- },
- ClassNodeTypes: []string{},
- FieldNodeTypes: []string{},
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"call"},
- ImportNodeTypes: []string{"call"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "while_statement",
- },
- VariableNodeTypes: []string{"binary_operator"},
- AssignmentNodeTypes: []string{"binary_operator"},
- EnvAccessFunctions: []string{"Sys.getenv"},
- })
-}
diff --git a/internal/lang/r_lang.go b/internal/lang/r_lang.go
deleted file mode 100644
index 48e87f869..000000000
--- a/internal/lang/r_lang.go
+++ /dev/null
@@ -1 +0,0 @@
-package lang
diff --git a/internal/lang/ruby.go b/internal/lang/ruby.go
deleted file mode 100644
index d84df550e..000000000
--- a/internal/lang/ruby.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Ruby,
- FileExtensions: []string{".rb", ".rake", ".gemspec"},
- FunctionNodeTypes: []string{
- "method",
- "singleton_method",
- },
- ClassNodeTypes: []string{"class", "module"},
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"call", "command_call"},
- ImportNodeTypes: []string{"call"},
-
- BranchingNodeTypes: []string{"if", "unless", "while", "until", "for", "case", "when", "rescue", "elsif"},
- VariableNodeTypes: []string{"assignment"},
- AssignmentNodeTypes: []string{"assignment", "operator_assignment"},
- DecoratorNodeTypes: []string{},
- EnvAccessMemberPatterns: []string{"ENV"},
- })
-}
diff --git a/internal/lang/rust.go b/internal/lang/rust.go
deleted file mode 100644
index 596721aab..000000000
--- a/internal/lang/rust.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Rust,
- FileExtensions: []string{".rs"},
- FunctionNodeTypes: []string{
- "function_item",
- "function_signature_item",
- "closure_expression",
- },
- ClassNodeTypes: []string{
- "struct_item",
- "enum_item",
- "union_item",
- "trait_item",
- "type_item",
- },
- FieldNodeTypes: []string{"field_declaration"},
- ModuleNodeTypes: []string{"source_file", "mod_item"},
- CallNodeTypes: []string{"call_expression", "macro_invocation"},
- ImportNodeTypes: []string{"use_declaration", "extern_crate_declaration"},
- ImportFromTypes: []string{"use_declaration"},
- PackageIndicators: []string{"Cargo.toml"},
-
- BranchingNodeTypes: []string{"if_expression", "for_expression", "while_expression", "loop_expression", "match_expression", "match_arm"},
- VariableNodeTypes: []string{"static_item", "const_item"},
- AssignmentNodeTypes: []string{"assignment_expression", "compound_assignment_expr"},
- EnvAccessFunctions: []string{"env::var", "std::env::var"},
- })
-}
diff --git a/internal/lang/scala.go b/internal/lang/scala.go
deleted file mode 100644
index 73a1de655..000000000
--- a/internal/lang/scala.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Scala,
- FileExtensions: []string{".scala", ".sc"},
- FunctionNodeTypes: []string{"function_definition", "function_declaration"},
- ClassNodeTypes: []string{
- "class_definition",
- "object_definition",
- "trait_definition",
- },
- ModuleNodeTypes: []string{"compilation_unit"},
- CallNodeTypes: []string{
- "call_expression",
- "generic_function",
- "field_expression",
- "infix_expression",
- },
- ImportNodeTypes: []string{"import_declaration"},
- ImportFromTypes: []string{"import_declaration"},
-
- BranchingNodeTypes: []string{"if_expression", "for_expression", "while_expression", "match_expression", "case_clause", "try_expression", "catch_clause"},
- VariableNodeTypes: []string{"val_definition", "var_definition", "val_declaration", "var_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- ThrowNodeTypes: []string{"throw_expression"},
- EnvAccessFunctions: []string{"sys.env", "System.getenv", "System.getProperty"},
- })
-}
diff --git a/internal/lang/scss.go b/internal/lang/scss.go
deleted file mode 100644
index 9dbb902e8..000000000
--- a/internal/lang/scss.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: SCSS,
- FileExtensions: []string{".scss"},
- ModuleNodeTypes: []string{"stylesheet"},
- FunctionNodeTypes: []string{
- "mixin_statement",
- "function_statement",
- },
- ClassNodeTypes: []string{},
- FieldNodeTypes: []string{},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"import_statement", "use_statement"},
- VariableNodeTypes: []string{"declaration"},
- BranchingNodeTypes: []string{"if_statement"},
- })
-}
diff --git a/internal/lang/sql.go b/internal/lang/sql.go
deleted file mode 100644
index 906db0877..000000000
--- a/internal/lang/sql.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: SQL,
- FileExtensions: []string{".sql"},
- ModuleNodeTypes: []string{"program"},
- FunctionNodeTypes: []string{
- "create_function",
- },
- ClassNodeTypes: []string{},
- FieldNodeTypes: []string{"column_definition"},
- CallNodeTypes: []string{"function_call", "invocation"},
- ImportNodeTypes: []string{},
- VariableNodeTypes: []string{
- "create_table",
- "create_view",
- },
- BranchingNodeTypes: []string{"if_statement", "case_expression"},
- })
-}
diff --git a/internal/lang/svelte.go b/internal/lang/svelte.go
deleted file mode 100644
index c7c734272..000000000
--- a/internal/lang/svelte.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Svelte,
- FileExtensions: []string{".svelte"},
- ModuleNodeTypes: []string{"document"},
- BranchingNodeTypes: []string{"if_statement", "each_statement", "await_statement"},
- })
-}
diff --git a/internal/lang/swift.go b/internal/lang/swift.go
deleted file mode 100644
index a6cd8172c..000000000
--- a/internal/lang/swift.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Swift,
- FileExtensions: []string{".swift"},
- FunctionNodeTypes: []string{
- "function_declaration",
- },
- ClassNodeTypes: []string{
- "class_declaration",
- "protocol_declaration",
- "struct_declaration",
- "enum_declaration",
- },
- FieldNodeTypes: []string{"property_declaration"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"import_declaration"},
- BranchingNodeTypes: []string{
- "if_statement", "guard_statement", "for_statement",
- "while_statement", "switch_statement",
- },
- VariableNodeTypes: []string{"property_declaration"},
- AssignmentNodeTypes: []string{"assignment"},
- ThrowNodeTypes: []string{"throw_statement"},
- DecoratorNodeTypes: []string{"attribute"},
- })
-}
diff --git a/internal/lang/toml_lang.go b/internal/lang/toml_lang.go
deleted file mode 100644
index 154224fc5..000000000
--- a/internal/lang/toml_lang.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: TOML,
- FileExtensions: []string{".toml"},
- FunctionNodeTypes: []string{},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"document"},
- CallNodeTypes: []string{},
- ImportNodeTypes: []string{},
-
- VariableNodeTypes: []string{},
- })
-}
diff --git a/internal/lang/tsx.go b/internal/lang/tsx.go
deleted file mode 100644
index 1461cae07..000000000
--- a/internal/lang/tsx.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: TSX,
- FileExtensions: []string{".tsx"},
- FunctionNodeTypes: []string{
- "function_declaration",
- "generator_function_declaration",
- "function_expression",
- "arrow_function",
- "method_definition",
- "function_signature",
- },
- ClassNodeTypes: []string{
- "class_declaration",
- "class",
- "abstract_class_declaration",
- "enum_declaration",
- "interface_declaration",
- "type_alias_declaration",
- "internal_module",
- },
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"import_statement", "lexical_declaration", "export_statement"},
- ImportFromTypes: []string{"import_statement", "lexical_declaration", "export_statement"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "switch_statement", "case_clause", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"lexical_declaration", "variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression", "augmented_assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- DecoratorNodeTypes: []string{"decorator"},
- EnvAccessMemberPatterns: []string{"process.env"},
- })
-}
diff --git a/internal/lang/typescript.go b/internal/lang/typescript.go
deleted file mode 100644
index f93cde1ff..000000000
--- a/internal/lang/typescript.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: TypeScript,
- FileExtensions: []string{".ts"},
- FunctionNodeTypes: []string{
- "function_declaration",
- "generator_function_declaration",
- "function_expression",
- "arrow_function",
- "method_definition",
- "function_signature",
- },
- ClassNodeTypes: []string{
- "class_declaration",
- "class",
- "abstract_class_declaration",
- "enum_declaration",
- "interface_declaration",
- "type_alias_declaration",
- "internal_module",
- },
- ModuleNodeTypes: []string{"program"},
- CallNodeTypes: []string{"call_expression"},
- ImportNodeTypes: []string{"import_statement", "lexical_declaration", "export_statement"},
- ImportFromTypes: []string{"import_statement", "lexical_declaration", "export_statement"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "switch_statement", "case_clause", "try_statement", "catch_clause"},
- VariableNodeTypes: []string{"lexical_declaration", "variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression", "augmented_assignment_expression"},
- ThrowNodeTypes: []string{"throw_statement"},
- DecoratorNodeTypes: []string{"decorator"},
- EnvAccessMemberPatterns: []string{"process.env"},
- })
-}
diff --git a/internal/lang/verilog.go b/internal/lang/verilog.go
deleted file mode 100644
index e8ee0e02d..000000000
--- a/internal/lang/verilog.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Verilog,
- FileExtensions: []string{".v", ".sv"},
- FunctionNodeTypes: []string{"function_declaration", "task_declaration"},
- ClassNodeTypes: []string{"module_declaration", "class_declaration", "interface_declaration"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"system_tf_call", "subroutine_call"},
- BranchingNodeTypes: []string{
- "conditional_statement", "case_statement", "loop_statement",
- },
- VariableNodeTypes: []string{"net_declaration", "data_declaration"},
- AssignmentNodeTypes: []string{"blocking_assignment", "nonblocking_assignment"},
- })
-}
diff --git a/internal/lang/vimscript.go b/internal/lang/vimscript.go
deleted file mode 100644
index 8715ecbdd..000000000
--- a/internal/lang/vimscript.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: VimScript,
- FileExtensions: []string{".vim", ".vimrc"},
- FunctionNodeTypes: []string{"function_definition"},
- ModuleNodeTypes: []string{"script_file"},
- CallNodeTypes: []string{"call_expression"},
- BranchingNodeTypes: []string{
- "if_statement", "for_statement", "while_statement", "try_statement",
- },
- VariableNodeTypes: []string{"let_statement"},
- })
-}
diff --git a/internal/lang/vue.go b/internal/lang/vue.go
deleted file mode 100644
index 91fb2445a..000000000
--- a/internal/lang/vue.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Vue,
- FileExtensions: []string{".vue"},
- ModuleNodeTypes: []string{"document"},
- })
-}
diff --git a/internal/lang/wolfram.go b/internal/lang/wolfram.go
deleted file mode 100644
index 602ea55e4..000000000
--- a/internal/lang/wolfram.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Wolfram,
- FileExtensions: []string{".wl", ".wls"},
- FunctionNodeTypes: []string{"set_delayed_top", "set_top", "set_delayed", "set"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"apply"},
- ImportNodeTypes: []string{"get_top"},
- })
-}
diff --git a/internal/lang/xml.go b/internal/lang/xml.go
deleted file mode 100644
index 71fcb6b4d..000000000
--- a/internal/lang/xml.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: XML,
- FileExtensions: []string{".xml", ".xsl", ".xsd", ".svg"},
- ModuleNodeTypes: []string{"document"},
- })
-}
diff --git a/internal/lang/yaml_lang.go b/internal/lang/yaml_lang.go
deleted file mode 100644
index 405b73088..000000000
--- a/internal/lang/yaml_lang.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: YAML,
- FileExtensions: []string{".yml", ".yaml"},
- FunctionNodeTypes: []string{},
- ClassNodeTypes: []string{},
- ModuleNodeTypes: []string{"stream"},
- CallNodeTypes: []string{},
- ImportNodeTypes: []string{},
-
- VariableNodeTypes: []string{"block_mapping_pair"},
- })
-}
diff --git a/internal/lang/zig.go b/internal/lang/zig.go
deleted file mode 100644
index df224964b..000000000
--- a/internal/lang/zig.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package lang
-
-func init() {
- Register(&LanguageSpec{
- Language: Zig,
- FileExtensions: []string{".zig"},
- FunctionNodeTypes: []string{
- "function_declaration",
- "test_declaration", // test "description" { ... }
- },
- ClassNodeTypes: []string{"struct_declaration", "enum_declaration", "union_declaration"},
- FieldNodeTypes: []string{"container_field"},
- ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"call_expression", "builtin_function"},
- ImportNodeTypes: []string{"builtin_function"},
-
- BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "switch_expression"},
- VariableNodeTypes: []string{"variable_declaration"},
- AssignmentNodeTypes: []string{"assignment_expression"},
- EnvAccessFunctions: []string{"std.os.getenv"},
- })
-}
diff --git a/internal/pipeline/adaptive.go b/internal/pipeline/adaptive.go
deleted file mode 100644
index 9147687f3..000000000
--- a/internal/pipeline/adaptive.go
+++ /dev/null
@@ -1,296 +0,0 @@
-package pipeline
-
-import (
- "context"
- "log/slog"
- "runtime"
- "sync"
- "sync/atomic"
- "time"
-)
-
-// contentionSignal holds platform-specific contention metrics.
-// Populated by getContentionSignal() in adaptive_csw_{unix,windows}.go.
-type contentionSignal struct {
- Nivcsw int64 // involuntary context switches (0 if unavailable)
- CPUTimeSec float64 // cumulative process CPU time in seconds (0 if unavailable)
-}
-
-// contentionTier describes which contention signal is available.
-type contentionTier int
-
-const (
- tierNone contentionTier = iota // tier 3: grow-only with cap
- tierCPU // tier 2: CPU utilization
- tierCSW // tier 1: involuntary context switches (best)
-)
-
-func (t contentionTier) String() string {
- switch t {
- case tierCSW:
- return "1-nivcsw"
- case tierCPU:
- return "2-cpu"
- default:
- return "3-none"
- }
-}
-
-// adaptivePool manages worker concurrency using bytes/sec throughput for grow
-// decisions and tiered contention signals for shrink decisions.
-//
-// Bytes/sec normalizes for file size variation (50KB vs 500B files produce a
-// 5x ratio, not 1000x like files/sec). Shrink only fires when contention is
-// detected (Nivcsw or CPU utilization), preventing the death spiral caused by
-// large-file batches that reduce files/sec without actual over-provisioning.
-type adaptivePool struct {
- mu sync.Mutex
- cond *sync.Cond
- limit int // current concurrency limit
- active int // currently running workers
- minLimit int // floor (NumCPU)
- maxLimit int // ceiling (NumCPU * 8)
- growStep int // additive increase per adjustment
- numCPU int
-
- completed atomic.Int64
- bytesProcessed atomic.Int64
- peakBPS float64
- peakLimit int
- startTime time.Time
- done chan struct{}
-}
-
-func newAdaptivePool(numCPU int) *adaptivePool {
- if numCPU < 1 {
- numCPU = 1
- }
- step := numCPU / 2
- if step < 2 {
- step = 2
- }
- p := &adaptivePool{
- limit: numCPU,
- minLimit: numCPU,
- maxLimit: numCPU * 8,
- growStep: step,
- numCPU: numCPU,
- startTime: time.Now(),
- done: make(chan struct{}),
- }
- p.cond = sync.NewCond(&p.mu)
- return p
-}
-
-func (p *adaptivePool) acquire() {
- p.mu.Lock()
- for p.active >= p.limit {
- p.cond.Wait()
- }
- p.active++
- p.mu.Unlock()
-}
-
-// releaseBytes records a completed file with its size and unblocks a waiting worker.
-func (p *adaptivePool) releaseBytes(size int64) {
- p.completed.Add(1)
- p.bytesProcessed.Add(size)
- p.mu.Lock()
- p.active--
- p.mu.Unlock()
- p.cond.Signal()
-}
-
-func (p *adaptivePool) setLimit(n int) {
- if n < p.minLimit {
- n = p.minLimit
- }
- if n > p.maxLimit {
- n = p.maxLimit
- }
- p.mu.Lock()
- old := p.limit
- p.limit = n
- p.mu.Unlock()
- if n > old {
- p.cond.Broadcast()
- }
-}
-
-func (p *adaptivePool) currentLimit() int {
- p.mu.Lock()
- defer p.mu.Unlock()
- return p.limit
-}
-
-// monitorTuning groups all tuning constants for the adaptive monitor.
-const (
- monitorWarmupTicks = 3
- monitorCooldownLen = 2
- monitorEMAAlpha = 0.3
- monitorGrowThresh = 1.05 // bytes/sec must exceed baseline by 5% to grow
- monitorShrinkBPS = 0.95 // bytes/sec must drop below baseline by 5% to shrink
- monitorCPUCeil = 0.90 // CPU utilization threshold for tier 2 shrink
-)
-
-// monitorState holds mutable per-tick state for the adaptive monitor.
-type monitorState struct {
- tick int
- tier contentionTier
- cooldown int
- lastBytes int64
- lastNivcsw int64
- lastCPU float64
- emaBPS float64
- emaNivcsw float64
- emaCPUUtil float64
- baseBPS float64
- baseNivcsw float64
- numCPU float64
-}
-
-// monitor runs the adaptive concurrency control loop.
-// Tick interval: 1 second. Warmup: 3 ticks. Cooldown: 2 ticks after each adjustment.
-func (p *adaptivePool) monitor(ctx context.Context) {
- ticker := time.NewTicker(1 * time.Second)
- defer ticker.Stop()
- ms := &monitorState{numCPU: float64(runtime.NumCPU())}
- for {
- select {
- case <-ctx.Done():
- return
- case <-p.done:
- return
- case <-ticker.C:
- p.onTick(ms)
- }
- }
-}
-
-// onTick processes one sampling interval: updates metrics, then grows or shrinks.
-func (p *adaptivePool) onTick(ms *monitorState) {
- ms.tick++
-
- // Sample and smooth metrics.
- bytesNow := p.bytesProcessed.Load()
- bps := float64(bytesNow - ms.lastBytes)
- ms.lastBytes = bytesNow
- sig := getContentionSignal()
- nivcsw := sig.Nivcsw - ms.lastNivcsw
- cpuUtil := (sig.CPUTimeSec - ms.lastCPU) / ms.numCPU
- ms.lastNivcsw = sig.Nivcsw
- ms.lastCPU = sig.CPUTimeSec
- p.updateEMA(ms, bps, float64(nivcsw), cpuUtil)
-
- // Track peaks.
- if ms.emaBPS > p.peakBPS {
- p.peakBPS = ms.emaBPS
- }
- cur := p.currentLimit()
- if cur > p.peakLimit {
- p.peakLimit = cur
- }
-
- // Warmup phase: detect tier, grow-only.
- if ms.tick <= monitorWarmupTicks {
- p.handleWarmupTick(ms, sig, cur)
- return
- }
-
- // Calibrate tier on first post-warmup tick.
- if ms.tick == monitorWarmupTicks+1 {
- slog.Info("adaptive.calibrate", "tier", ms.tier.String(),
- "nivcsw_total", sig.Nivcsw, "cpu_sec", sig.CPUTimeSec)
- ms.baseBPS = ms.emaBPS
- ms.baseNivcsw = ms.emaNivcsw
- }
-
- // Cooldown after adjustment.
- if ms.cooldown > 0 {
- ms.cooldown--
- if ms.cooldown == 0 {
- ms.baseBPS = ms.emaBPS
- ms.baseNivcsw = ms.emaNivcsw
- }
- return
- }
-
- // GROW: bytes/sec improving.
- if ms.emaBPS > ms.baseBPS*monitorGrowThresh && cur < p.maxLimit {
- p.setLimit(cur + p.growStep)
- ms.cooldown = monitorCooldownLen
- slog.Info("adaptive.grow", "from", cur, "to", p.currentLimit(),
- "bps_mb", ms.emaBPS/(1024*1024))
- return
- }
-
- // SHRINK: requires contention + throughput decline.
- if p.hasContention(ms) && ms.emaBPS < ms.baseBPS*monitorShrinkBPS && cur > p.minLimit {
- p.setLimit(cur - p.growStep)
- ms.cooldown = monitorCooldownLen
- slog.Info("adaptive.shrink", "from", cur, "to", p.currentLimit(),
- "bps_mb", ms.emaBPS/(1024*1024),
- "nivcsw_ema", int(ms.emaNivcsw), "cpu_util", ms.emaCPUUtil)
- }
-}
-
-// updateEMA applies exponential moving average smoothing to all three metrics.
-func (p *adaptivePool) updateEMA(ms *monitorState, bps, nivcsw, cpuUtil float64) {
- const alpha = monitorEMAAlpha
- if ms.tick == 1 {
- ms.emaBPS = bps
- ms.emaNivcsw = nivcsw
- ms.emaCPUUtil = cpuUtil
- } else {
- ms.emaBPS = alpha*bps + (1-alpha)*ms.emaBPS
- ms.emaNivcsw = alpha*nivcsw + (1-alpha)*ms.emaNivcsw
- ms.emaCPUUtil = alpha*cpuUtil + (1-alpha)*ms.emaCPUUtil
- }
-}
-
-// handleWarmupTick handles one tick during the warmup phase: detects tier and grows only.
-func (p *adaptivePool) handleWarmupTick(ms *monitorState, sig contentionSignal, cur int) {
- if sig.Nivcsw > 0 {
- ms.tier = tierCSW
- } else if sig.CPUTimeSec > 0 && ms.tier < tierCPU {
- ms.tier = tierCPU
- }
- if ms.tick > 1 && ms.emaBPS > ms.baseBPS*monitorGrowThresh && cur < p.maxLimit {
- p.setLimit(cur + p.growStep)
- slog.Info("adaptive.grow", "from", cur, "to", p.currentLimit(),
- "bps_mb", ms.emaBPS/(1024*1024), "phase", "warmup")
- }
- ms.baseBPS = ms.emaBPS
- ms.baseNivcsw = ms.emaNivcsw
-}
-
-// hasContention returns true if the current tier's contention signal is active.
-func (p *adaptivePool) hasContention(ms *monitorState) bool {
- nivcswFloor := ms.numCPU * 100
- switch ms.tier {
- case tierCSW:
- threshold := ms.baseNivcsw * 2
- if threshold < nivcswFloor {
- threshold = nivcswFloor
- }
- return ms.emaNivcsw > threshold
- case tierCPU:
- return ms.emaCPUUtil > monitorCPUCeil
- default:
- return false // tierNone: grow-only mode
- }
-}
-
-func (p *adaptivePool) stop() {
- close(p.done)
- totalBytes := p.bytesProcessed.Load()
- slog.Info("adaptive.summary",
- "start", p.minLimit,
- "peak", p.peakLimit,
- "final", p.currentLimit(),
- "peak_bps_mb", p.peakBPS/(1024*1024),
- "total_mb", float64(totalBytes)/(1024*1024),
- "completed", p.completed.Load(),
- "elapsed", time.Since(p.startTime),
- )
-}
diff --git a/internal/pipeline/adaptive_csw_unix.go b/internal/pipeline/adaptive_csw_unix.go
deleted file mode 100644
index 5bd962c8b..000000000
--- a/internal/pipeline/adaptive_csw_unix.go
+++ /dev/null
@@ -1,16 +0,0 @@
-//go:build !windows
-
-package pipeline
-
-import "syscall"
-
-// getContentionSignal returns process-level contention metrics via getrusage(2).
-// On Unix (Linux + macOS), a single syscall provides both involuntary context
-// switches (Nivcsw) and cumulative CPU time (Utime + Stime).
-func getContentionSignal() contentionSignal {
- var usage syscall.Rusage
- _ = syscall.Getrusage(syscall.RUSAGE_SELF, &usage)
- cpuSec := float64(usage.Utime.Sec) + float64(usage.Utime.Usec)/1e6 +
- float64(usage.Stime.Sec) + float64(usage.Stime.Usec)/1e6
- return contentionSignal{Nivcsw: usage.Nivcsw, CPUTimeSec: cpuSec}
-}
diff --git a/internal/pipeline/adaptive_csw_windows.go b/internal/pipeline/adaptive_csw_windows.go
deleted file mode 100644
index d54ce3497..000000000
--- a/internal/pipeline/adaptive_csw_windows.go
+++ /dev/null
@@ -1,18 +0,0 @@
-//go:build windows
-
-package pipeline
-
-import "syscall"
-
-// getContentionSignal returns process-level CPU time via GetProcessTimes.
-// Windows does not expose involuntary context switches, so Nivcsw is always 0
-// (tier 2 only — CPU utilization based shrink).
-func getContentionSignal() contentionSignal {
- var creation, exit, kernel, user syscall.Filetime
- h, _ := syscall.GetCurrentProcess()
- if err := syscall.GetProcessTimes(h, &creation, &exit, &kernel, &user); err != nil {
- return contentionSignal{}
- }
- cpuSec := float64(kernel.Nanoseconds()+user.Nanoseconds()) / 1e9
- return contentionSignal{CPUTimeSec: cpuSec}
-}
diff --git a/internal/pipeline/c_lsp_cross.go b/internal/pipeline/c_lsp_cross.go
deleted file mode 100644
index 5a9cd7118..000000000
--- a/internal/pipeline/c_lsp_cross.go
+++ /dev/null
@@ -1,251 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// cLSPDefIndex indexes cross-file definitions by header/source path for C/C++ LSP resolution.
-type cLSPDefIndex struct {
- // byRelPath maps file relative path → []CrossFileDef (for #include "local/path.h")
- byRelPath map[string][]cbm.CrossFileDef
- // byDir maps directory relative path → []CrossFileDef (for collecting all defs in a dir)
- byDir map[string][]cbm.CrossFileDef
- // includeGraph maps file relative path → resolved paths of directly included files
- includeGraph map[string][]string
-}
-
-// isCOrCPP returns true if the language is C, C++, or CUDA.
-func isCOrCPP(l lang.Language) bool {
- return l == lang.C || l == lang.CPP || l == lang.CUDA
-}
-
-// resolveFileIncludes builds the list of resolved include paths for a file's imports.
-func (p *Pipeline) resolveFileIncludes(imports []cbm.Import, currentDir string, incDirs []string) []string {
- var includes []string
- for _, imp := range imports {
- if imp.ModulePath == "" {
- continue
- }
- for _, candidate := range resolveIncludePath(imp.ModulePath, currentDir, incDirs) {
- if _, exists := p.extractionCache[candidate]; exists {
- includes = append(includes, candidate)
- break
- }
- }
- }
- return includes
-}
-
-// indexFileDefs adds a file's definitions to the index by path and directory.
-func (idx *cLSPDefIndex) indexFileDefs(relPath string, defs []cbm.CrossFileDef) {
- idx.byRelPath[relPath] = append(idx.byRelPath[relPath], defs...)
- dir := filepath.Dir(relPath)
- if dir == "." {
- dir = ""
- }
- idx.byDir[dir] = append(idx.byDir[dir], defs...)
-}
-
-// buildCLSPDefIndex builds the cross-file definition index for C/C++ LSP resolution.
-// Scans all C/C++/CUDA files in extractionCache, indexes defs by file path and directory.
-func (p *Pipeline) buildCLSPDefIndex() *cLSPDefIndex {
- idx := &cLSPDefIndex{
- byRelPath: make(map[string][]cbm.CrossFileDef),
- byDir: make(map[string][]cbm.CrossFileDef),
- includeGraph: make(map[string][]string),
- }
-
- allIncDirs := p.getAllRelativeIncludeDirs()
-
- hasCFiles := false
- for relPath, ext := range p.extractionCache {
- if !isCOrCPP(ext.Language) || ext.Result == nil {
- continue
- }
- hasCFiles = true
-
- // Build include graph from imports
- if len(ext.Result.Imports) > 0 {
- incDirs := p.getRelativeIncludeDirs(relPath)
- if incDirs == nil {
- incDirs = allIncDirs
- }
- includes := p.resolveFileIncludes(ext.Result.Imports, filepath.Dir(relPath), incDirs)
- if len(includes) > 0 {
- idx.includeGraph[relPath] = includes
- }
- }
-
- if len(ext.Result.Definitions) == 0 {
- continue
- }
-
- defs := cbm.DefsToLSPDefs(ext.Result.Definitions, fqn.ModuleQN(p.ProjectName, relPath))
- if len(defs) > 0 {
- idx.indexFileDefs(relPath, defs)
- }
- }
-
- if !hasCFiles {
- return nil
- }
-
- totalDefs := 0
- for _, defs := range idx.byRelPath {
- totalDefs += len(defs)
- }
- if totalDefs > 0 {
- slog.Info("c_lsp.cross_file.index",
- "files", len(idx.byRelPath),
- "defs", totalDefs,
- "include_edges", len(idx.includeGraph),
- )
- }
-
- return idx
-}
-
-type bfsEntry struct {
- path string
- depth int
-}
-
-// collectDefsForFile adds defs from a file and its corresponding source file.
-func (idx *cLSPDefIndex) collectDefsForFile(filePath string, seen map[string]bool) []cbm.CrossFileDef {
- var result []cbm.CrossFileDef
- if defs, ok := idx.byRelPath[filePath]; ok {
- result = append(result, defs...)
- }
- for _, srcExt := range correspondingSourceExts(filePath) {
- srcPath := swapExtension(filePath, srcExt)
- if seen[srcPath] {
- continue
- }
- seen[srcPath] = true
- if defs, ok := idx.byRelPath[srcPath]; ok {
- result = append(result, defs...)
- }
- }
- return result
-}
-
-// seedDirectIncludes resolves direct imports and returns the initial BFS queue.
-func (idx *cLSPDefIndex) seedDirectIncludes(imports []cbm.Import, currentDir string,
- extraIncDirs []string, seen map[string]bool) ([]cbm.CrossFileDef, []bfsEntry) {
-
- var result []cbm.CrossFileDef
- var queue []bfsEntry
-
- for _, imp := range imports {
- if imp.ModulePath == "" {
- continue
- }
- for _, candidate := range resolveIncludePath(imp.ModulePath, currentDir, extraIncDirs) {
- if seen[candidate] {
- continue
- }
- seen[candidate] = true
- result = append(result, idx.collectDefsForFile(candidate, seen)...)
- queue = append(queue, bfsEntry{candidate, 1})
- }
- }
- return result, queue
-}
-
-// collectCrossFileDefs returns cross-file definitions for all transitively included files.
-// Uses BFS on the include graph (max depth 8) to follow #include chains.
-// Also includes defs from corresponding source files and same-directory files.
-// extraIncDirs are additional include directories from compile_commands.json.
-func (idx *cLSPDefIndex) collectCrossFileDefs(imports []cbm.Import, currentRelPath string, extraIncDirs []string) []cbm.CrossFileDef {
- if idx == nil || len(imports) == 0 {
- return nil
- }
-
- seen := make(map[string]bool)
- currentDir := filepath.Dir(currentRelPath)
-
- // Seed BFS queue with direct includes
- result, queue := idx.seedDirectIncludes(imports, currentDir, extraIncDirs, seen)
-
- // BFS: follow transitive includes up to depth 8
- const maxDepth = 8
- for i := 0; i < len(queue); i++ {
- entry := queue[i]
- if entry.depth >= maxDepth {
- continue
- }
- for _, child := range idx.includeGraph[entry.path] {
- if seen[child] {
- continue
- }
- seen[child] = true
- result = append(result, idx.collectDefsForFile(child, seen)...)
- queue = append(queue, bfsEntry{child, entry.depth + 1})
- }
- }
-
- // Same-directory defs (common C/C++ pattern)
- if !seen["__dir__"+currentDir] {
- seen["__dir__"+currentDir] = true
- if defs, ok := idx.byDir[currentDir]; ok {
- for i := range defs {
- if !seen["__def__"+defs[i].QualifiedName] {
- seen["__def__"+defs[i].QualifiedName] = true
- result = append(result, defs[i])
- }
- }
- }
- }
-
- return result
-}
-
-// resolveIncludePath returns candidate relative paths for a #include path.
-// For #include "foo/bar.h", tries: relative to current dir, compile_commands include dirs,
-// then as-is from repo root.
-func resolveIncludePath(includePath, currentDir string, extraIncDirs []string) []string {
- includePath = strings.Trim(includePath, "\"<>")
- var candidates []string
-
- // Relative to current file's directory
- if currentDir != "" && currentDir != "." {
- candidates = append(candidates, filepath.Join(currentDir, includePath))
- }
-
- // Compile_commands.json include directories (already relative to repo root)
- for _, dir := range extraIncDirs {
- candidates = append(candidates, filepath.Join(dir, includePath))
- }
-
- // As-is from repo root
- candidates = append(candidates, includePath)
-
- return candidates
-}
-
-// correspondingSourceExts returns source file extensions to check for a header file.
-func correspondingSourceExts(path string) []string {
- ext := filepath.Ext(path)
- switch ext {
- case ".h":
- return []string{".c", ".cpp", ".cc", ".cxx"}
- case ".hpp", ".hxx", ".hh":
- return []string{".cpp", ".cc", ".cxx"}
- case ".cuh": // CUDA header
- return []string{".cu"}
- default:
- return nil
- }
-}
-
-// swapExtension replaces the file extension.
-func swapExtension(path, newExt string) string {
- ext := filepath.Ext(path)
- return path[:len(path)-len(ext)] + newExt
-}
diff --git a/internal/pipeline/cancel_integration_test.go b/internal/pipeline/cancel_integration_test.go
deleted file mode 100644
index 7527608fb..000000000
--- a/internal/pipeline/cancel_integration_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package pipeline
-
-import (
- "context"
- "errors"
- "os"
- "testing"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// TestGracefulShutdownLargeRepo indexes a real repo with a short timeout to
-// verify context cancellation propagates correctly through the pipeline.
-// Skipped if /tmp/bench/erlang does not exist.
-func TestGracefulShutdownLargeRepo(t *testing.T) {
- repoPath := "/tmp/bench/erlang"
- if _, err := os.Stat(repoPath); os.IsNotExist(err) {
- t.Skip("skipping: /tmp/bench/erlang not found")
- }
-
- st, err := store.OpenMemory()
- if err != nil {
- t.Fatalf("store: %v", err)
- }
- defer st.Close()
-
- // 50ms fires during the definitions pass (which takes ~60ms for this repo),
- // ensuring cancellation is tested without depending on repo size.
- ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
- defer cancel()
-
- start := time.Now()
- p := New(ctx, st, repoPath, discover.ModeFull)
- err = p.Run()
- elapsed := time.Since(start)
-
- if err == nil {
- t.Fatalf("expected cancellation error, but index completed in %v", elapsed)
- }
- if !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) {
- t.Fatalf("expected context error, got: %v (after %v)", err, elapsed)
- }
-
- t.Logf("PASS: cancelled after %v with %v", elapsed, err)
-
- // Ensure it stopped reasonably fast (within 2s of the 50ms deadline)
- if elapsed > 2*time.Second {
- t.Errorf("cancellation took too long: %v (expected <2s)", elapsed)
- }
-}
diff --git a/internal/pipeline/cbm_debug_test.go b/internal/pipeline/cbm_debug_test.go
deleted file mode 100644
index eecdc79f1..000000000
--- a/internal/pipeline/cbm_debug_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package pipeline
-
-import (
- "fmt"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-func dumpCBM(t *testing.T, name string, l lang.Language, src string) {
- result, err := cbm.ExtractFile([]byte(src), l, "test", "main.x")
- if err != nil {
- t.Logf(" ExtractFile error: %v", err)
- return
- }
- fmt.Printf("--- %s Definitions ---\n", name)
- for i := range result.Definitions {
- d := &result.Definitions[i]
- fmt.Printf(" name=%q label=%q qn=%q parent=%q decorators=%v param_types=%v\n", d.Name, d.Label, d.QualifiedName, d.ParentClass, d.Decorators, d.ParamTypes)
- }
- if len(result.ImplTraits) > 0 {
- fmt.Printf("--- %s ImplTraits ---\n", name)
- for _, it := range result.ImplTraits {
- fmt.Printf(" trait=%q struct=%q\n", it.TraitName, it.StructName)
- }
- }
-}
-
-func TestCBMVariableDebug(t *testing.T) {
- tests := []struct {
- name string
- lang lang.Language
- src string
- }{
- {"Java", lang.Java, "class OwnerController {\n @GetMapping(\"/owners\")\n public void listOwners() {}\n\n @PostMapping(\"/owners\")\n public void createOwner() {}\n}\n"},
- {"Groovy", lang.Groovy, "class Calculator {\n int add(int a, int b) {\n return a + b\n }\n int multiply(int a, int b) {\n return a * b\n }\n}\n"},
- {"Dart", lang.Dart, "class Counter {\n int _count = 0;\n\n void increment() {\n _count++;\n }\n\n int getCount() {\n return _count;\n }\n}\n"},
- {"ObjC", lang.ObjectiveC, "@interface Greeter : NSObject\n- (void)greet:(NSString *)name;\n@end\n\n@implementation Greeter\n- (void)greet:(NSString *)name {\n NSLog(@\"Hello %@\", name);\n}\n\n- (void)run {\n [self greet:@\"World\"];\n}\n@end\n"},
- {"Swift", lang.Swift, "class Animal {\n var name: String = \"\"\n}\n\nclass Dog: Animal {\n func bark() -> String {\n return \"Woof\"\n }\n}\n"},
- {"Lua", lang.Lua, "local function named_func()\n return 1\nend\n\nlocal run_before_filter = function()\n return 2\nend\n\nlocal run_after_filter = function()\n return 3\nend\n"},
- {"Elixir", lang.Elixir, "defmodule Greeter do\n def greet(name) do\n \"Hello \"\n end\n\n defp internal_work(x) do\n x * 2\n end\nend\n"},
- {"R", lang.R, "mutate <- function(x) {\n x + 1\n}\n\nsquare <- function(n) {\n n * n\n}\n"},
- {"Erlang", lang.Erlang, "-module(mymod).\n-define(TIMEOUT, 5000).\n-record(person, {name, age}).\n"},
- {"SQL_Table", lang.SQL, "CREATE TABLE users (\n id INTEGER PRIMARY KEY,\n name TEXT NOT NULL\n);\nCREATE VIEW active_users AS SELECT * FROM users WHERE active = true;\n"},
- {"SQL_Func", lang.SQL, "CREATE FUNCTION add(a INT, b INT) RETURNS INT AS $$ SELECT a + b; $$ LANGUAGE SQL;\n"},
- {"YAML", lang.YAML, "name: myapp\nversion: \"1.0\"\nservices:\n web:\n image: nginx\n"},
- {"SCSS", lang.SCSS, "$primary-color: #007bff;\n$font-size: 16px;\n\nbody {\n color: $primary-color;\n}\n"},
- {"Rust_Impl", lang.Rust, "trait Handler {\n fn handle(&self) -> String;\n}\nstruct MyHandler;\nimpl Handler for MyHandler {\n fn handle(&self) -> String {\n String::from(\"handled\")\n }\n}\n"},
- {"Java_Params", lang.Java, "class Service {\n\tvoid process(Config cfg) {}\n}\n"},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- dumpCBM(t, tt.name, tt.lang, tt.src)
- })
- }
-}
diff --git a/internal/pipeline/communities.go b/internal/pipeline/communities.go
deleted file mode 100644
index 2d8c42576..000000000
--- a/internal/pipeline/communities.go
+++ /dev/null
@@ -1,405 +0,0 @@
-package pipeline
-
-import (
- "fmt"
- "log/slog"
- "math"
- "sort"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// passCommunities runs hybrid LPA→Leiden community detection on the CALLS graph
-// and creates Community nodes + MEMBER_OF edges.
-func (p *Pipeline) passCommunities() {
- slog.Info("pass.communities")
-
- // Load CALLS edges
- callEdges, err := p.Store.FindEdgesByType(p.ProjectName, "CALLS")
- if err != nil || len(callEdges) == 0 {
- slog.Info("pass.communities.skip", "reason", "no_calls")
- return
- }
-
- // Build adjacency list (undirected for community detection)
- adj := make(map[int64]map[int64]bool)
- allNodes := make(map[int64]bool)
- for _, e := range callEdges {
- allNodes[e.SourceID] = true
- allNodes[e.TargetID] = true
- if adj[e.SourceID] == nil {
- adj[e.SourceID] = make(map[int64]bool)
- }
- if adj[e.TargetID] == nil {
- adj[e.TargetID] = make(map[int64]bool)
- }
- adj[e.SourceID][e.TargetID] = true
- adj[e.TargetID][e.SourceID] = true
- }
-
- slog.Info("pass.communities.graph", "nodes", len(allNodes), "edges", len(callEdges))
-
- // Run hybrid LPA→Leiden community detection
- t := time.Now()
- communities := hybridCommunities(adj, allNodes)
- slog.Info("pass.communities.algo", "elapsed", time.Since(t), "communities", len(communities))
-
- // Create Community nodes + MEMBER_OF edges
- communityCount, memberOfCount := p.storeCommunities(communities)
- slog.Info("pass.communities.done", "communities", communityCount, "member_of", memberOfCount)
-}
-
-// hybridCommunities runs LPA for fast initial partition, then Leiden refinement
-// to guarantee connected communities. Replaces Louvain for better scaling.
-func hybridCommunities(adj map[int64]map[int64]bool, allNodes map[int64]bool) map[int][]int64 {
- partition := lpaInitPartition(adj, allNodes)
- refined := leidenRefine(adj, partition)
- return groupAndFilter(refined)
-}
-
-// lpaInitPartition runs Label Propagation for quick O(m) partitioning.
-// Each node starts with a unique label, then adopts the most frequent neighbor label.
-// Converges when <1% of nodes change labels per iteration.
-func lpaInitPartition(adj map[int64]map[int64]bool, allNodes map[int64]bool) map[int64]int {
- label := make(map[int64]int, len(allNodes))
- id := 0
- for n := range allNodes {
- label[n] = id
- id++
- }
-
- nodeCount := len(allNodes)
- threshold := nodeCount / 100 // <1% changed → converged
- if threshold < 1 {
- threshold = 1
- }
-
- for iter := 0; iter < 10; iter++ {
- changed := 0
- for node, neighbors := range adj {
- if len(neighbors) == 0 {
- continue
- }
- // Count neighbor labels
- freq := make(map[int]int, len(neighbors))
- for nb := range neighbors {
- freq[label[nb]]++
- }
- // Pick most frequent (deterministic tie-break by lower label)
- bestLabel, bestCount := label[node], 0
- for lbl, cnt := range freq {
- if cnt > bestCount || (cnt == bestCount && lbl < bestLabel) {
- bestLabel = lbl
- bestCount = cnt
- }
- }
- if bestLabel != label[node] {
- label[node] = bestLabel
- changed++
- }
- }
- if changed <= threshold {
- break
- }
- }
- return label
-}
-
-// leidenRefine guarantees connected communities by splitting disconnected
-// sub-components, then runs one modularity-optimization pass for edge cases.
-func leidenRefine(adj map[int64]map[int64]bool, partition map[int64]int) map[int64]int {
- // Group nodes by community
- communities := make(map[int][]int64)
- for node, comm := range partition {
- communities[comm] = append(communities[comm], node)
- }
-
- nextID := 0
- refined := make(map[int64]int, len(partition))
-
- for _, members := range communities {
- // BFS to find connected components within this community
- memberSet := make(map[int64]bool, len(members))
- for _, m := range members {
- memberSet[m] = true
- }
- visited := make(map[int64]bool, len(members))
-
- for _, seed := range members {
- if visited[seed] {
- continue
- }
- component := bfsComponent(seed, adj, memberSet, visited)
- for _, n := range component {
- refined[n] = nextID
- }
- nextID++
- }
- }
-
- // One modularity pass: move border nodes to better-connected community
- modularityPass(adj, refined, len(partition))
-
- return refined
-}
-
-// bfsComponent does BFS from seed, staying within memberSet.
-// Marks visited nodes and returns the connected component.
-func bfsComponent(seed int64, adj map[int64]map[int64]bool, memberSet, visited map[int64]bool) []int64 {
- queue := []int64{seed}
- visited[seed] = true
- var component []int64
-
- for len(queue) > 0 {
- node := queue[0]
- queue = queue[1:]
- component = append(component, node)
-
- for nb := range adj[node] {
- if memberSet[nb] && !visited[nb] {
- visited[nb] = true
- queue = append(queue, nb)
- }
- }
- }
- return component
-}
-
-// modularityPass does one greedy pass moving border nodes to the community
-// with which they share the most edges. This fixes edge cases from LPA.
-func modularityPass(adj map[int64]map[int64]bool, partition map[int64]int, _ int) {
- // Pre-compute total edges (for modularity denominator)
- totalEdges := 0
- for _, neighbors := range adj {
- totalEdges += len(neighbors)
- }
- m := float64(totalEdges) / 2.0
- if m == 0 {
- return
- }
-
- // Pre-compute community degree sums
- commDegree := make(map[int]float64)
- for node, neighbors := range adj {
- commDegree[partition[node]] += float64(len(neighbors))
- }
-
- m2 := 2.0 * m * m
- for node, neighbors := range adj {
- currentComm := partition[node]
- ki := float64(len(neighbors))
-
- // Count edges to each neighboring community
- edgesToComm := make(map[int]float64, len(neighbors))
- for nb := range neighbors {
- edgesToComm[partition[nb]]++
- }
-
- // Remove self from current community for fair comparison
- commDegree[currentComm] -= ki
- kiInCurrent := edgesToComm[currentComm]
- removeCost := kiInCurrent/m - ki*commDegree[currentComm]/m2
-
- bestComm := currentComm
- bestGain := 0.0
-
- for comm, kiIn := range edgesToComm {
- if comm == currentComm {
- continue
- }
- gain := kiIn/m - ki*commDegree[comm]/m2 - removeCost
- if gain > bestGain {
- bestGain = gain
- bestComm = comm
- }
- }
-
- if bestComm != currentComm && bestGain > 1e-10 {
- partition[node] = bestComm
- commDegree[bestComm] += ki
- // currentComm already had ki subtracted
- } else {
- commDegree[currentComm] += ki // restore
- }
- }
-}
-
-// groupAndFilter groups nodes by community and filters out singletons.
-func groupAndFilter(nodeCommunity map[int64]int) map[int][]int64 {
- communities := make(map[int][]int64)
- for nodeID, comm := range nodeCommunity {
- communities[comm] = append(communities[comm], nodeID)
- }
-
- filtered := make(map[int][]int64)
- idx := 0
- for _, members := range communities {
- if len(members) >= 2 {
- filtered[idx] = members
- idx++
- }
- }
- return filtered
-}
-
-// storeCommunities creates Community nodes and MEMBER_OF edges in the database.
-// Uses nodeMap (already fetched via FindNodesByIDs) for member lookups instead
-// of per-member FindNodeByQN queries.
-func (p *Pipeline) storeCommunities(communities map[int][]int64) (communityCount, memberOfCount int) {
- if len(communities) == 0 {
- return 0, 0
- }
-
- // Collect all member node IDs for batch lookup
- var allMemberIDs []int64
- for _, members := range communities {
- allMemberIDs = append(allMemberIDs, members...)
- }
- nodeMap, _ := p.Store.FindNodesByIDs(allMemberIDs)
-
- communityNodes := make([]*store.Node, 0, len(communities))
- // pendingEdge now carries SourceID (not SourceQN) to avoid redundant DB lookups
- type memberEdge struct {
- SourceID int64
- TargetQN string
- }
- memberEdges := make([]memberEdge, 0, len(allMemberIDs))
-
- for commIdx, memberIDs := range communities {
- // Find top symbols by name for labeling
- topNames := topMemberNames(memberIDs, nodeMap, 5)
-
- commName := fmt.Sprintf("community_%d", commIdx)
- if len(topNames) > 0 {
- commName = topNames[0] + "_cluster"
- }
-
- commQN := fmt.Sprintf("%s.__community__.%d", p.ProjectName, commIdx)
-
- // Calculate cohesion: ratio of internal edges to possible edges
- cohesion := communityCohesion(memberIDs, nodeMap)
-
- communityNodes = append(communityNodes, &store.Node{
- Project: p.ProjectName,
- Label: "Community",
- Name: commName,
- QualifiedName: commQN,
- Properties: map[string]any{
- "cohesion": math.Round(cohesion*100) / 100,
- "symbol_count": len(memberIDs),
- "top_symbols": topNames,
- },
- })
-
- for _, memberID := range memberIDs {
- if nodeMap[memberID] == nil {
- continue
- }
- memberEdges = append(memberEdges, memberEdge{
- SourceID: memberID,
- TargetQN: commQN,
- })
-
- // Also store community_id on the member node (via properties update)
- memberNode := nodeMap[memberID]
- if memberNode.Properties == nil {
- memberNode.Properties = make(map[string]any)
- }
- memberNode.Properties["community_id"] = commIdx
- }
- }
-
- // Batch insert community nodes
- idMap, err := p.Store.UpsertNodeBatch(communityNodes)
- if err != nil {
- slog.Warn("pass.communities.upsert.err", "err", err)
- return 0, 0
- }
-
- // Resolve and insert MEMBER_OF edges using direct ID lookup (no DB queries)
- var edges []*store.Edge
- for _, me := range memberEdges {
- tgtID, tgtOK := idMap[me.TargetQN]
- if tgtOK {
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: me.SourceID,
- TargetID: tgtID,
- Type: "MEMBER_OF",
- })
- }
- }
-
- if len(edges) > 0 {
- if err := p.Store.InsertEdgeBatch(edges); err != nil {
- slog.Warn("pass.communities.edges.err", "err", err)
- }
- }
-
- return len(communityNodes), len(edges)
-}
-
-func topMemberNames(memberIDs []int64, nodeMap map[int64]*store.Node, limit int) []string {
- type entry struct {
- name string
- label string
- }
- var entries []entry
- for _, id := range memberIDs {
- n := nodeMap[id]
- if n != nil {
- entries = append(entries, entry{n.Name, n.Label})
- }
- }
-
- // Sort: Classes first, then Functions, alphabetical
- sort.Slice(entries, func(i, j int) bool {
- if entries[i].label != entries[j].label {
- // Prefer Class/Interface over Function/Method
- return labelPriority(entries[i].label) < labelPriority(entries[j].label)
- }
- return entries[i].name < entries[j].name
- })
-
- names := make([]string, 0, limit)
- for i, e := range entries {
- if i >= limit {
- break
- }
- names = append(names, e.name)
- }
- return names
-}
-
-func labelPriority(label string) int {
- switch label {
- case "Class":
- return 0
- case "Interface":
- return 1
- case "Type":
- return 2
- case "Function":
- return 3
- case "Method":
- return 4
- default:
- return 5
- }
-}
-
-func communityCohesion(memberIDs []int64, nodeMap map[int64]*store.Node) float64 {
- n := len(memberIDs)
- if n < 2 {
- return 1.0
- }
- // Simplified cohesion: proportion of members with known types
- knownCount := 0
- for _, id := range memberIDs {
- if nodeMap[id] != nil {
- knownCount++
- }
- }
- return float64(knownCount) / float64(n)
-}
diff --git a/internal/pipeline/compile_commands.go b/internal/pipeline/compile_commands.go
deleted file mode 100644
index 8d51cc2aa..000000000
--- a/internal/pipeline/compile_commands.go
+++ /dev/null
@@ -1,256 +0,0 @@
-package pipeline
-
-import (
- "encoding/json"
- "log/slog"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
-)
-
-// CompileFlags holds extracted compilation flags for a single file.
-type CompileFlags struct {
- IncludePaths []string // -I and -isystem paths (resolved to absolute)
- Defines []string // -D defines as "NAME=VALUE" or "NAME"
- Standard string // -std= value (e.g., "c++17", "c11")
-}
-
-// CompileFlagsMap maps relative file paths to their compile flags.
-type CompileFlagsMap map[string]*CompileFlags
-
-// compileCommandEntry is a single entry in compile_commands.json.
-type compileCommandEntry struct {
- Directory string `json:"directory"`
- File string `json:"file"`
- Command string `json:"command"`
- Arguments []string `json:"arguments"`
- Output string `json:"output"`
-}
-
-// loadCompileCommands searches for compile_commands.json in common locations
-// relative to repoPath, parses it, and returns per-file compile flags.
-func loadCompileCommands(repoPath string) CompileFlagsMap {
- candidates := []string{
- filepath.Join(repoPath, "compile_commands.json"),
- filepath.Join(repoPath, "build", "compile_commands.json"),
- filepath.Join(repoPath, "out", "compile_commands.json"),
- }
-
- // Also check cmake-build-* directories
- entries, _ := os.ReadDir(repoPath)
- for _, e := range entries {
- if e.IsDir() && strings.HasPrefix(e.Name(), "cmake-build-") {
- candidates = append(candidates,
- filepath.Join(repoPath, e.Name(), "compile_commands.json"))
- }
- }
-
- for _, path := range candidates {
- data, err := os.ReadFile(path)
- if err != nil {
- continue
- }
- result := parseCompileCommands(data, repoPath)
- if len(result) > 0 {
- slog.Info("compile_commands.loaded", "path", path, "entries", len(result))
- return result
- }
- }
-
- return nil
-}
-
-// parseCompileCommands parses compile_commands.json content and extracts
-// per-file include paths, defines, and standard flags.
-func parseCompileCommands(data []byte, repoPath string) CompileFlagsMap {
- var entries []compileCommandEntry
- if err := json.Unmarshal(data, &entries); err != nil {
- slog.Warn("compile_commands.parse_err", "err", err)
- return nil
- }
-
- result := make(CompileFlagsMap, len(entries))
- for _, e := range entries {
- // Get the arguments list
- args := e.Arguments
- if len(args) == 0 && e.Command != "" {
- args = splitCommand(e.Command)
- }
- if len(args) == 0 {
- continue
- }
-
- flags := extractFlags(args, e.Directory)
-
- // Resolve file path to relative
- filePath := e.File
- if !filepath.IsAbs(filePath) && e.Directory != "" {
- filePath = filepath.Join(e.Directory, filePath)
- }
- relPath, err := filepath.Rel(repoPath, filePath)
- if err != nil || strings.HasPrefix(relPath, "..") {
- continue
- }
- relPath = filepath.ToSlash(relPath)
-
- result[relPath] = flags
- }
-
- return result
-}
-
-// extractFlags extracts -I, -isystem, -D, and -std= flags from compiler arguments.
-func extractFlags(args []string, directory string) *CompileFlags {
- flags := &CompileFlags{}
-
- for i := 0; i < len(args); i++ {
- arg := args[i]
-
- // Include paths: -I<path> or -I <path>
- if strings.HasPrefix(arg, "-I") {
- path := arg[2:]
- if path == "" && i+1 < len(args) {
- i++
- path = args[i]
- }
- if path != "" {
- flags.IncludePaths = append(flags.IncludePaths, resolvePath(path, directory))
- }
- continue
- }
-
- // System include paths: -isystem <path>
- if arg == "-isystem" && i+1 < len(args) {
- i++
- flags.IncludePaths = append(flags.IncludePaths, resolvePath(args[i], directory))
- continue
- }
-
- // Defines: -D<name> or -D<name>=<value> or -D <name>
- if strings.HasPrefix(arg, "-D") {
- define := arg[2:]
- if define == "" && i+1 < len(args) {
- i++
- define = args[i]
- }
- if define != "" {
- flags.Defines = append(flags.Defines, define)
- }
- continue
- }
-
- // Standard: -std=c++17 etc.
- if strings.HasPrefix(arg, "-std=") {
- flags.Standard = arg[5:]
- continue
- }
- }
-
- return flags
-}
-
-// resolvePath resolves a path relative to a directory, returning absolute path.
-func resolvePath(path, directory string) string {
- if filepath.IsAbs(path) {
- return filepath.Clean(path)
- }
- if directory != "" {
- return filepath.Clean(filepath.Join(directory, path))
- }
- return filepath.Clean(path)
-}
-
-// getRelativeIncludeDirs returns include paths relative to repo root for a file.
-// Used by cross-file include resolution (extractionCache uses repo-relative paths).
-func (p *Pipeline) getRelativeIncludeDirs(relPath string) []string {
- if p.compileFlags == nil {
- return nil
- }
- flags, ok := p.compileFlags[relPath]
- if !ok || len(flags.IncludePaths) == 0 {
- return nil
- }
- var relDirs []string
- for _, absPath := range flags.IncludePaths {
- rel, err := filepath.Rel(p.RepoPath, absPath)
- if err != nil || strings.HasPrefix(rel, "..") {
- continue // outside repo — skip
- }
- relDirs = append(relDirs, filepath.ToSlash(rel))
- }
- return relDirs
-}
-
-// getAllRelativeIncludeDirs returns the union of all include dirs across all files.
-// Used when resolving includes for files not in compile_commands.
-func (p *Pipeline) getAllRelativeIncludeDirs() []string {
- if p.compileFlags == nil {
- return nil
- }
- seen := make(map[string]bool)
- var dirs []string
- for _, flags := range p.compileFlags {
- for _, absPath := range flags.IncludePaths {
- rel, err := filepath.Rel(p.RepoPath, absPath)
- if err != nil || strings.HasPrefix(rel, "..") {
- continue
- }
- relSlash := filepath.ToSlash(rel)
- if !seen[relSlash] {
- seen[relSlash] = true
- dirs = append(dirs, relSlash)
- }
- }
- }
- return dirs
-}
-
-// getCompileFlags returns ExtractionFlags for a file, or nil if no compile_commands data.
-func (p *Pipeline) getCompileFlags(relPath string) *cbm.ExtractionFlags {
- if p.compileFlags == nil {
- return nil
- }
- flags, ok := p.compileFlags[relPath]
- if !ok {
- return nil
- }
- return &cbm.ExtractionFlags{
- IncludePaths: flags.IncludePaths,
- Defines: flags.Defines,
- }
-}
-
-// splitCommand does a simple shell-like split of a command string.
-// Handles basic quoting but not escapes.
-func splitCommand(cmd string) []string {
- var args []string
- var current strings.Builder
- inQuote := byte(0)
-
- for i := 0; i < len(cmd); i++ {
- c := cmd[i]
- switch {
- case inQuote != 0:
- if c == inQuote {
- inQuote = 0
- } else {
- current.WriteByte(c)
- }
- case c == '"' || c == '\'':
- inQuote = c
- case c == ' ' || c == '\t':
- if current.Len() > 0 {
- args = append(args, current.String())
- current.Reset()
- }
- default:
- current.WriteByte(c)
- }
- }
- if current.Len() > 0 {
- args = append(args, current.String())
- }
- return args
-}
diff --git a/internal/pipeline/compile_commands_test.go b/internal/pipeline/compile_commands_test.go
deleted file mode 100644
index 80ea5d930..000000000
--- a/internal/pipeline/compile_commands_test.go
+++ /dev/null
@@ -1,121 +0,0 @@
-package pipeline
-
-import (
- "testing"
-)
-
-func TestParseCompileCommands(t *testing.T) {
- data := []byte(`[
- {
- "directory": "/home/user/project/build",
- "command": "gcc -I/home/user/project/include -I/home/user/project/src -DDEBUG=1 -DVERSION=\"1.0\" -std=c11 -o main.o -c /home/user/project/src/main.c",
- "file": "/home/user/project/src/main.c"
- },
- {
- "directory": "/home/user/project/build",
- "arguments": ["g++", "-I/home/user/project/include", "-isystem", "/home/user/project/third_party", "-DUSE_SSL", "-std=c++17", "-c", "/home/user/project/src/server.cpp"],
- "file": "/home/user/project/src/server.cpp"
- },
- {
- "directory": "/home/user/project/build",
- "command": "gcc -c /outside/repo/file.c",
- "file": "/outside/repo/file.c"
- }
- ]`)
-
- repoPath := "/home/user/project"
- result := parseCompileCommands(data, repoPath)
-
- // main.c
- mainFlags := result["src/main.c"]
- if mainFlags == nil {
- t.Fatal("expected flags for src/main.c")
- }
- if len(mainFlags.IncludePaths) != 2 {
- t.Errorf("expected 2 include paths for main.c, got %d: %v", len(mainFlags.IncludePaths), mainFlags.IncludePaths)
- }
- if len(mainFlags.Defines) != 2 {
- t.Errorf("expected 2 defines for main.c, got %d: %v", len(mainFlags.Defines), mainFlags.Defines)
- }
- if mainFlags.Standard != "c11" {
- t.Errorf("expected standard c11, got %q", mainFlags.Standard)
- }
-
- // server.cpp (using arguments array)
- serverFlags := result["src/server.cpp"]
- if serverFlags == nil {
- t.Fatal("expected flags for src/server.cpp")
- }
- if len(serverFlags.IncludePaths) != 2 {
- t.Errorf("expected 2 include paths for server.cpp, got %d: %v", len(serverFlags.IncludePaths), serverFlags.IncludePaths)
- }
- if len(serverFlags.Defines) != 1 {
- t.Errorf("expected 1 define for server.cpp, got %d: %v", len(serverFlags.Defines), serverFlags.Defines)
- }
- if serverFlags.Standard != "c++17" {
- t.Errorf("expected standard c++17, got %q", serverFlags.Standard)
- }
-
- // Outside-repo file should be excluded
- if _, ok := result["../outside/repo/file.c"]; ok {
- t.Error("should not include files outside repo")
- }
-}
-
-func TestParseCompileCommands_Empty(t *testing.T) {
- result := parseCompileCommands([]byte(`[]`), "/repo")
- if len(result) != 0 {
- t.Errorf("expected empty result, got %d entries", len(result))
- }
-}
-
-func TestParseCompileCommands_InvalidJSON(t *testing.T) {
- result := parseCompileCommands([]byte(`not json`), "/repo")
- if result != nil {
- t.Error("expected nil for invalid JSON")
- }
-}
-
-func TestSplitCommand(t *testing.T) {
- tests := []struct {
- cmd string
- want int
- }{
- {"gcc -c main.c", 3},
- {`gcc -DFOO="bar baz" -c main.c`, 4},
- {"g++ -I/usr/include -std=c++17 -o out -c in.cpp", 7},
- }
-
- for _, tt := range tests {
- got := splitCommand(tt.cmd)
- if len(got) != tt.want {
- t.Errorf("splitCommand(%q): got %d args %v, want %d", tt.cmd, len(got), got, tt.want)
- }
- }
-}
-
-func TestExtractFlags(t *testing.T) {
- args := []string{
- "g++",
- "-I", "/abs/include",
- "-I/rel/include",
- "-isystem", "/sys/include",
- "-DFOO",
- "-DBAR=42",
- "-std=c++20",
- "-O2",
- "-Wall",
- "-c", "main.cpp",
- }
-
- flags := extractFlags(args, "/project")
- if len(flags.IncludePaths) != 3 {
- t.Errorf("expected 3 include paths, got %d: %v", len(flags.IncludePaths), flags.IncludePaths)
- }
- if len(flags.Defines) != 2 {
- t.Errorf("expected 2 defines, got %d: %v", len(flags.Defines), flags.Defines)
- }
- if flags.Standard != "c++20" {
- t.Errorf("expected c++20, got %q", flags.Standard)
- }
-}
diff --git a/internal/pipeline/configlink_strategies.go b/internal/pipeline/configlink_strategies.go
deleted file mode 100644
index 6112cc694..000000000
--- a/internal/pipeline/configlink_strategies.go
+++ /dev/null
@@ -1,558 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "os"
- "path/filepath"
- "regexp"
- "runtime"
- "strings"
- "sync"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// configExtensions are file extensions considered "config files".
-var configExtensions = map[string]bool{
- ".env": true, ".toml": true, ".ini": true, ".yaml": true, ".yml": true,
- ".cfg": true, ".properties": true, ".json": true, ".xml": true, ".conf": true,
-}
-
-// manifestFiles are package manifest filenames used for dependency→import linking.
-var manifestFiles = map[string]bool{
- "Cargo.toml": true, "package.json": true, "go.mod": true,
- "requirements.txt": true, "Gemfile": true, "build.gradle": true,
- "pom.xml": true, "composer.json": true,
-}
-
-// depSectionNames are section/key names that indicate dependency lists.
-var depSectionNames = map[string]bool{
- "dependencies": true, "devDependencies": true, "peerDependencies": true,
- "dev-dependencies": true, "build-dependencies": true,
-}
-
-// configFileRefRe matches string literals referencing config files.
-var configFileRefRe = regexp.MustCompile(
- `["']([^"']*\.(toml|yaml|yml|ini|json|xml|conf|cfg|env))["']`)
-
-// passConfigLinker runs 3 post-flush strategies to link config↔code.
-func (p *Pipeline) passConfigLinker() {
- t := time.Now()
- t1 := time.Now()
- keyEdges := p.matchConfigKeySymbols()
- slog.Info("configlinker.strategy", "name", "key_symbol", "edges", len(keyEdges), "elapsed", time.Since(t1))
-
- t2 := time.Now()
- depEdges := p.matchDependencyImports()
- slog.Info("configlinker.strategy", "name", "dep_import", "edges", len(depEdges), "elapsed", time.Since(t2))
-
- t3 := time.Now()
- refEdges := p.matchConfigFileRefs()
- slog.Info("configlinker.strategy", "name", "file_ref", "edges", len(refEdges), "elapsed", time.Since(t3))
-
- all := make([]*store.Edge, 0, len(keyEdges)+len(depEdges)+len(refEdges))
- all = append(all, keyEdges...)
- all = append(all, depEdges...)
- all = append(all, refEdges...)
-
- if len(all) > 0 {
- if err := p.Store.InsertEdgeBatch(all); err != nil {
- slog.Warn("configlinker.write_err", "err", err)
- }
- }
-
- slog.Info("configlinker.done",
- "key_symbol", len(keyEdges),
- "dep_import", len(depEdges),
- "file_ref", len(refEdges),
- "total", len(all),
- "elapsed", time.Since(t))
-}
-
-// --- Strategy 1: Config Key → Code Symbol ---
-
-// normalizeConfigKey splits a config key on camelCase, underscores, dots, hyphens,
-// lowercases all tokens, and joins with underscore.
-func normalizeConfigKey(key string) (normalized string, tokens []string) {
- // Split on non-alphanumeric chars first
- parts := strings.FieldsFunc(key, func(r rune) bool {
- return r == '_' || r == '-' || r == '.'
- })
-
- for _, part := range parts {
- camel := splitCamelCase(part)
- for _, w := range camel {
- tokens = append(tokens, strings.ToLower(w))
- }
- }
-
- normalized = strings.Join(tokens, "_")
- return
-}
-
-// configEntry pairs a config node with its normalized key.
-type configEntry struct {
- node *store.Node
- normalized string
-}
-
-// collectConfigEntries returns config Variable nodes with min 2 tokens, each ≥3 chars.
-func collectConfigEntries(vars []*store.Node) []configEntry {
- var entries []configEntry
- for _, v := range vars {
- if !hasConfigExtension(v.FilePath) {
- continue
- }
- norm, tokens := normalizeConfigKey(v.Name)
- if len(tokens) < 2 {
- continue
- }
- allLong := true
- for _, t := range tokens {
- if len(t) < 3 {
- allLong = false
- break
- }
- }
- if allLong {
- entries = append(entries, configEntry{node: v, normalized: norm})
- }
- }
- return entries
-}
-
-// collectCodeNodes returns Function/Variable/Class nodes not from config files.
-func (p *Pipeline) collectCodeNodes() []*store.Node {
- var codeNodes []*store.Node
- for _, label := range []string{"Function", "Variable", "Class"} {
- nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, n := range nodes {
- if !hasConfigExtension(n.FilePath) {
- codeNodes = append(codeNodes, n)
- }
- }
- }
- return codeNodes
-}
-
-// matchConfigKeySymbols links config Variable nodes to code symbols when
-// the normalized config key is a contiguous substring of the normalized code name.
-// Pre-normalizes all code node names in O(n) to avoid O(n×m) normalizeConfigKey calls.
-func (p *Pipeline) matchConfigKeySymbols() []*store.Edge {
- configVars, err := p.Store.FindNodesByLabel(p.ProjectName, "Variable")
- if err != nil {
- return nil
- }
-
- entries := collectConfigEntries(configVars)
- if len(entries) == 0 {
- return nil
- }
-
- codeNodes := p.collectCodeNodes()
-
- // Pre-normalize: build map[normalizedName] → []*store.Node (single O(n) pass)
- codeByNorm := make(map[string][]*store.Node, len(codeNodes))
- for _, code := range codeNodes {
- norm, _ := normalizeConfigKey(code.Name)
- if norm != "" {
- codeByNorm[norm] = append(codeByNorm[norm], code)
- }
- }
- slog.Info("configlinker.key_symbol.stats",
- "config_entries", len(entries),
- "code_nodes", len(codeNodes),
- "unique_norms", len(codeByNorm))
-
- var edges []*store.Edge
-
- // Exact match: O(1) lookup per config entry.
- for _, ce := range entries {
- if matches, ok := codeByNorm[ce.normalized]; ok {
- for _, code := range matches {
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: code.ID,
- TargetID: ce.node.ID,
- Type: "CONFIGURES",
- Properties: map[string]any{
- "strategy": "key_symbol",
- "confidence": 0.85,
- "config_key": ce.node.Name,
- },
- })
- }
- }
- }
-
- // Substring match via Aho-Corasick: build AC from config keys, scan code names.
- // This replaces O(entries × unique_norms) string comparisons with O(sum(name_lengths)).
- acPatterns := make([]string, len(entries))
- for i, ce := range entries {
- acPatterns[i] = ce.normalized
- }
-
- // Build compact-alphabet AC (config keys only contain [a-z0-9_]).
- var alphaMap [256]byte
- idx := byte(1)
- for c := byte('a'); c <= byte('z'); c++ {
- alphaMap[c] = idx
- idx++
- }
- for c := byte('0'); c <= byte('9'); c++ {
- alphaMap[c] = idx
- idx++
- }
- alphaMap['_'] = idx
- alphaSize := int(idx) + 1
-
- ac := cbm.ACBuildCompact(acPatterns, alphaMap, alphaSize)
- if ac != nil {
- defer ac.Free()
-
- // Collect unique norms as a flat list for batch scanning.
- normList := make([]string, 0, len(codeByNorm))
- for norm := range codeByNorm {
- normList = append(normList, norm)
- }
-
- tAC := time.Now()
- matches := ac.ScanBatch(normList)
- slog.Info("configlinker.ac_scan",
- "names", len(normList),
- "matches", len(matches),
- "states", ac.NumStates(),
- "table_kb", ac.TableBytes()/1024,
- "elapsed", time.Since(tAC))
-
- // Convert AC matches to edges (skip exact matches, already handled above).
- for _, m := range matches {
- norm := normList[m.NameIndex]
- ce := entries[m.PatternID]
- if norm == ce.normalized {
- continue // already added as exact match
- }
- codes := codeByNorm[norm]
- for _, code := range codes {
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: code.ID,
- TargetID: ce.node.ID,
- Type: "CONFIGURES",
- Properties: map[string]any{
- "strategy": "key_symbol",
- "confidence": 0.75,
- "config_key": ce.node.Name,
- },
- })
- }
- }
- }
-
- return edges
-}
-
-// --- Strategy 2: Dependency Name → Import Match ---
-
-// depEntry pairs a manifest dependency node with its name.
-type depEntry struct {
- node *store.Node
- name string
-}
-
-// collectManifestDeps returns dependency Variable nodes from package manifest files.
-func collectManifestDeps(vars []*store.Node) []depEntry {
- var deps []depEntry
- for _, v := range vars {
- basename := filepath.Base(v.FilePath)
- if !manifestFiles[basename] {
- continue
- }
- isDep := false
- qnLower := strings.ToLower(v.QualifiedName)
- for sec := range depSectionNames {
- if strings.Contains(qnLower, strings.ToLower(sec)) {
- isDep = true
- break
- }
- }
- if !isDep && basename == "Cargo.toml" {
- isDep = isDependencyChild(v)
- }
- if isDep {
- deps = append(deps, depEntry{node: v, name: v.Name})
- }
- }
- return deps
-}
-
-// resolveEdgeNodes builds a lookup map for source and target nodes of edges.
-// Uses batched FindNodesByIDs instead of per-ID queries.
-func (p *Pipeline) resolveEdgeNodes(edges []*store.Edge) (source, target map[int64]*store.Node) {
- seen := make(map[int64]struct{}, len(edges)*2)
- var ids []int64
- for _, e := range edges {
- if _, ok := seen[e.SourceID]; !ok {
- ids = append(ids, e.SourceID)
- seen[e.SourceID] = struct{}{}
- }
- if _, ok := seen[e.TargetID]; !ok {
- ids = append(ids, e.TargetID)
- seen[e.TargetID] = struct{}{}
- }
- }
- lookup, _ := p.Store.FindNodesByIDs(ids)
- if lookup == nil {
- lookup = make(map[int64]*store.Node)
- }
- slog.Info("configlinker.resolve_nodes", "unique_ids", len(ids), "resolved", len(lookup))
- return lookup, lookup
-}
-
-// matchDependencyImports links dependency entries in package manifests
-// to code modules that import them.
-func (p *Pipeline) matchDependencyImports() []*store.Edge {
- configVars, err := p.Store.FindNodesByLabel(p.ProjectName, "Variable")
- if err != nil {
- return nil
- }
-
- deps := collectManifestDeps(configVars)
- if len(deps) == 0 {
- return nil
- }
-
- importEdges, err := p.Store.FindEdgesByType(p.ProjectName, "IMPORTS")
- if err != nil {
- return nil
- }
-
- nodeLookup, _ := p.resolveEdgeNodes(importEdges)
-
- var edges []*store.Edge
- for _, dep := range deps {
- depNameLower := strings.ToLower(dep.name)
- for _, impEdge := range importEdges {
- target := nodeLookup[impEdge.TargetID]
- source := nodeLookup[impEdge.SourceID]
- if target == nil || source == nil {
- continue
- }
-
- targetNameLower := strings.ToLower(target.Name)
- targetQNLower := strings.ToLower(target.QualifiedName)
-
- var confidence float64
- switch {
- case targetNameLower == depNameLower:
- confidence = 0.95
- case strings.Contains(targetQNLower, depNameLower):
- confidence = 0.80
- default:
- continue
- }
-
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: source.ID,
- TargetID: dep.node.ID,
- Type: "CONFIGURES",
- Properties: map[string]any{
- "strategy": "dependency_import",
- "confidence": confidence,
- "dep_name": dep.name,
- },
- })
- }
- }
- return edges
-}
-
-// isDependencyChild checks if a Variable node's QN suggests it's under a dependency section.
-func isDependencyChild(v *store.Node) bool {
- parts := strings.Split(v.QualifiedName, ".")
- for _, p := range parts {
- pLower := strings.ToLower(p)
- if depSectionNames[pLower] {
- return true
- }
- }
- return false
-}
-
-// --- Strategy 3: Config File Path → Code String Reference ---
-
-// fileRefResult holds a matched config file reference for concurrent collection.
-type fileRefResult struct {
- sourceQN string
- targetNode *store.Node
- confidence float64
- refPath string
-}
-
-// matchConfigFileRefs scans source code for string literals referencing config files.
-// Parallelizes disk I/O across CPUs for large codebases.
-func (p *Pipeline) matchConfigFileRefs() []*store.Edge { //nolint:gocognit,funlen // parallel file scanning with concurrent result collection
- // Collect config Module nodes
- modules, err := p.Store.FindNodesByLabel(p.ProjectName, "Module")
- if err != nil {
- return nil
- }
-
- configModules := make(map[string]*store.Node) // basename → Module
- configModulesFull := make(map[string]*store.Node) // relPath → Module
- for _, m := range modules {
- if hasConfigExtension(m.FilePath) {
- configModules[filepath.Base(m.FilePath)] = m
- configModulesFull[m.FilePath] = m
- }
- }
- if len(configModules) == 0 {
- return nil
- }
-
- // Collect non-config modules to scan
- var toScan []*store.Node
- for _, m := range modules {
- if !hasConfigExtension(m.FilePath) {
- toScan = append(toScan, m)
- }
- }
-
- slog.Info("configlinker.file_ref.stats",
- "config_modules", len(configModules),
- "files_to_scan", len(toScan),
- "concurrency", runtime.NumCPU())
-
- // Parallel file scanning with bounded concurrency
- sem := make(chan struct{}, runtime.NumCPU())
- var mu sync.Mutex
- var results []fileRefResult
-
- var wg sync.WaitGroup
- for _, m := range toScan {
- wg.Add(1)
- go func(mod *store.Node) {
- defer wg.Done()
- sem <- struct{}{}
- defer func() { <-sem }()
-
- source := p.getSource(mod.FilePath)
- if len(source) == 0 {
- // Disk fallback for incremental mode
- var err error
- source, err = os.ReadFile(filepath.Join(p.RepoPath, mod.FilePath))
- if err != nil {
- return
- }
- }
-
- matches := configFileRefRe.FindAllStringSubmatch(string(source), -1)
- if len(matches) == 0 {
- return
- }
-
- var local []fileRefResult
- for _, match := range matches {
- if len(match) < 2 {
- continue
- }
- refPath := match[1]
-
- var target *store.Node
- var confidence float64
- if t, ok := configModulesFull[refPath]; ok {
- target = t
- confidence = 0.90
- } else {
- refBase := filepath.Base(refPath)
- if t, ok := configModules[refBase]; ok {
- target = t
- confidence = 0.70
- }
- }
- if target == nil {
- continue
- }
-
- moduleQN := moduleQNForFile(p.ProjectName, mod.FilePath)
- local = append(local, fileRefResult{
- sourceQN: moduleQN,
- targetNode: target,
- confidence: confidence,
- refPath: refPath,
- })
- }
-
- if len(local) > 0 {
- mu.Lock()
- results = append(results, local...)
- mu.Unlock()
- }
- }(m)
- }
- wg.Wait()
-
- // Batch-resolve source QNs (deduplicate first)
- qnSet := make(map[string]struct{}, len(results))
- for _, r := range results {
- qnSet[r.sourceQN] = struct{}{}
- }
- qnMap := make(map[string]*store.Node, len(qnSet))
- for qn := range qnSet {
- n, err := p.Store.FindNodeByQN(p.ProjectName, qn)
- if err == nil && n != nil {
- qnMap[qn] = n
- }
- }
-
- var edges []*store.Edge
- for _, r := range results {
- sourceNode := qnMap[r.sourceQN]
- if sourceNode == nil {
- continue
- }
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: sourceNode.ID,
- TargetID: r.targetNode.ID,
- Type: "CONFIGURES",
- Properties: map[string]any{
- "strategy": "file_reference",
- "confidence": r.confidence,
- "ref_path": r.refPath,
- },
- })
- }
- return edges
-}
-
-// --- Helpers ---
-
-// hasConfigExtension checks if a file path has a config file extension.
-func hasConfigExtension(filePath string) bool {
- ext := filepath.Ext(filePath)
- return configExtensions[ext]
-}
-
-// moduleQNForFile computes the Module QN for a given file.
-func moduleQNForFile(project, relPath string) string {
- // Strip extension, replace / with .
- noExt := strings.TrimSuffix(relPath, filepath.Ext(relPath))
- parts := strings.Split(noExt, "/")
-
- // Filter empty and special parts
- var filtered []string
- for _, p := range parts {
- if p != "" && p != "__init__" && p != "index" {
- filtered = append(filtered, p)
- }
- }
-
- return project + "." + strings.Join(filtered, ".")
-}
diff --git a/internal/pipeline/configlink_test.go b/internal/pipeline/configlink_test.go
deleted file mode 100644
index 3375f2af3..000000000
--- a/internal/pipeline/configlink_test.go
+++ /dev/null
@@ -1,259 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// --- Strategy 1: Key → Symbol Matching ---
-
-func TestConfigKeySymbol_ExactMatch(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "config.toml"), `[database]
-max_connections = 100
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func getMaxConnections() int { return 100 }
-`)
-
- edges := runAndGetConfigures(t, dir)
- found := false
- for _, e := range edges {
- if props, ok := e.Properties["strategy"]; ok && props == "key_symbol" {
- found = true
- break
- }
- }
- if !found {
- t.Errorf("expected key_symbol CONFIGURES edge for max_connections, got %d total CONFIGURES", len(edges))
- }
-}
-
-func TestConfigKeySymbol_SubstringMatch(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "config.toml"), `[app]
-request_timeout = 30
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func getRequestTimeoutSeconds() int { return 30 }
-`)
-
- edges := runAndGetConfigures(t, dir)
- found := false
- for _, e := range edges {
- props := e.Properties
- if props["strategy"] == "key_symbol" {
- conf, _ := props["confidence"].(float64)
- if conf == 0.75 {
- found = true
- }
- }
- }
- if !found {
- t.Logf("got %d CONFIGURES edges", len(edges))
- for _, e := range edges {
- t.Logf(" strategy=%v confidence=%v", e.Properties["strategy"], e.Properties["confidence"])
- }
- t.Errorf("expected substring match (confidence=0.75) for request_timeout")
- }
-}
-
-func TestConfigKeySymbol_ShortKeySkipped(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "config.toml"), `port = 8080
-host = "localhost"
-name = "test"
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func getPort() int { return 8080 }
-`)
-
- edges := runAndGetConfigures(t, dir)
- for _, e := range edges {
- if e.Properties["strategy"] == "key_symbol" {
- t.Errorf("expected no key_symbol edges for short keys, got one: config_key=%v", e.Properties["config_key"])
- }
- }
-}
-
-func TestConfigKeySymbol_CamelCaseNormalization(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "config.json"), `{"maxRetryCount": 3}`)
- writeFile(t, filepath.Join(dir, "handler.go"), `package main
-
-func getMaxRetryCount() int { return 3 }
-`)
-
- edges := runAndGetConfigures(t, dir)
- found := false
- for _, e := range edges {
- if e.Properties["strategy"] == "key_symbol" {
- found = true
- break
- }
- }
- if !found {
- t.Errorf("expected key_symbol CONFIGURES edge for maxRetryCount")
- }
-}
-
-func TestConfigKeySymbol_NoFalsePositive(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "config.toml"), `[db]
-url = "postgres://..."
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func parseURL(s string) string { return s }
-`)
-
- edges := runAndGetConfigures(t, dir)
- for _, e := range edges {
- if e.Properties["strategy"] == "key_symbol" && e.Properties["config_key"] == "url" {
- t.Errorf("expected no CONFIGURES edge for 'url' (1 token), but got one")
- }
- }
-}
-
-// --- Strategy 2: Dependency → Import Matching ---
-
-func TestDependencyImport_PackageJson(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "package.json"), `{"dependencies":{"express":"^4.0","lodash":"^4.17"}}`)
- writeFile(t, filepath.Join(dir, "app.js"), `const express = require('express');
-
-function handleRequest() {
- return express();
-}
-`)
-
- edges := runAndGetConfigures(t, dir)
- found := false
- for _, e := range edges {
- if e.Properties["strategy"] == "dependency_import" {
- found = true
- break
- }
- }
- // This test may not produce edges since IMPORTS resolution depends on registry
- // but it should at least not crash
- t.Logf("dependency_import edges found: %v", found)
-}
-
-// --- Strategy 3: File Path Reference ---
-
-func TestConfigFileRef_ExactPath(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "config", "database.toml"), `[database]
-host = "localhost"
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func loadConfig() {
- cfg := readFile("config/database.toml")
- _ = cfg
-}
-`)
-
- edges := runAndGetConfigures(t, dir)
- found := false
- for _, e := range edges {
- if e.Properties["strategy"] == "file_reference" {
- found = true
- break
- }
- }
- if !found {
- t.Logf("got %d CONFIGURES edges total", len(edges))
- t.Errorf("expected file_reference CONFIGURES edge for config/database.toml")
- }
-}
-
-func TestConfigFileRef_BasenameMatch(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "settings.yaml"), `database:
- host: localhost
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func loadSettings() {
- cfg := readFile("settings.yaml")
- _ = cfg
-}
-`)
-
- edges := runAndGetConfigures(t, dir)
- found := false
- for _, e := range edges {
- if e.Properties["strategy"] == "file_reference" {
- conf, _ := e.Properties["confidence"].(float64)
- if conf == 0.70 {
- found = true
- }
- }
- }
- // Basename match may produce 0.70 or 0.90 depending on path resolution
- t.Logf("basename file_reference found: %v", found)
-}
-
-func TestConfigFileRef_NoFalsePositive(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "data.csv"), `a,b,c`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func loadData() {
- f := readFile("data.csv")
- _ = f
-}
-`)
-
- edges := runAndGetConfigures(t, dir)
- for _, e := range edges {
- if e.Properties["strategy"] == "file_reference" {
- t.Errorf("expected no file_reference edge for .csv file")
- }
- }
-}
-
-// --- Helpers ---
-
-func runAndGetConfigures(t *testing.T, dir string) []*store.Edge {
- t.Helper()
-
- // Initialize as a git repo so discover works
- gitInit(t, dir)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- edges, err := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
- if err != nil {
- t.Fatalf("FindEdgesByType: %v", err)
- }
- return edges
-}
-
-func gitInit(t *testing.T, dir string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {
- t.Fatal(err)
- }
- // Create minimal .git structure so discover recognizes it
- writeFile(t, filepath.Join(dir, ".git", "HEAD"), "ref: refs/heads/main\n")
-}
diff --git a/internal/pipeline/configures.go b/internal/pipeline/configures.go
deleted file mode 100644
index b03766d29..000000000
--- a/internal/pipeline/configures.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "path/filepath"
- "runtime"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "golang.org/x/sync/errgroup"
-)
-
-// passConfigures creates CONFIGURES edges using pre-extracted CBM env access data.
-func (p *Pipeline) passConfigures() {
- slog.Info("pass.configures")
-
- // Stage 1: Build env key → module QN index from Module constants
- envIndex := p.buildEnvIndex()
- if len(envIndex) == 0 {
- slog.Info("pass.configures.skip", "reason", "no_env_bindings")
- return
- }
-
- // Stage 2: Parallel per-file env access resolution using CBM data
- type fileEntry struct {
- relPath string
- ext *cachedExtraction
- }
- var files []fileEntry
- for relPath, ext := range p.extractionCache {
- if len(ext.Result.EnvAccesses) > 0 {
- files = append(files, fileEntry{relPath, ext})
- }
- }
-
- if len(files) == 0 {
- return
- }
-
- results := make([][]resolvedEdge, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g := new(errgroup.Group)
- g.SetLimit(numWorkers)
- for i, fe := range files {
- g.Go(func() error {
- results[i] = p.resolveFileConfiguresCBM(fe.relPath, fe.ext, envIndex)
- return nil
- })
- }
- _ = g.Wait()
-
- // Stage 3: Batch write
- p.flushResolvedEdges(results)
-
- total := 0
- for _, r := range results {
- total += len(r)
- }
- slog.Info("pass.configures.done", "edges", total)
-}
-
-// extractModuleConstants scans Module node constants for KEY = VALUE patterns
-// and adds env-var-like keys to the index.
-func extractModuleConstants(modules []*store.Node, index map[string]string) {
- for _, m := range modules {
- constants, ok := m.Properties["constants"]
- if !ok {
- continue
- }
- constList, ok := constants.([]any)
- if !ok {
- continue
- }
- for _, c := range constList {
- constStr, ok := c.(string)
- if !ok {
- continue
- }
- parts := strings.SplitN(constStr, " = ", 2)
- if len(parts) == 2 {
- key := strings.TrimSpace(parts[0])
- if key != "" && isEnvVarName(key) {
- index[key] = m.QualifiedName
- }
- }
- }
- }
-}
-
-// buildEnvIndex creates a mapping from env var key → module QN
-// by scanning Module node constants and config Variable nodes.
-func (p *Pipeline) buildEnvIndex() map[string]string {
- modules, err := p.Store.FindNodesByLabel(p.ProjectName, "Module")
- if err != nil {
- return nil
- }
-
- index := make(map[string]string)
- extractModuleConstants(modules, index)
-
- // Also scan config Variable nodes for env-var-like names.
- // Only add if key not already in index — existing Module constants
- // (which carry URL values for HTTP linking) always take priority.
- variables, err := p.Store.FindNodesByLabel(p.ProjectName, "Variable")
- if err == nil {
- added := 0
- for _, v := range variables {
- ext := filepath.Ext(v.FilePath)
- if !configExtensions[ext] {
- continue
- }
- if isEnvVarName(v.Name) && index[v.Name] == "" {
- moduleQN := fqn.ModuleQN(p.ProjectName, v.FilePath)
- index[v.Name] = moduleQN
- added++
- }
- }
- if added > 0 {
- slog.Info("pass.configures.env_vars_from_config", "added", added)
- }
- }
-
- return index
-}
-
-// isEnvVarName checks if a string looks like an environment variable name
-// (uppercase with underscores).
-func isEnvVarName(s string) bool {
- if len(s) < 2 {
- return false
- }
- hasUpper := false
- for _, c := range s {
- switch {
- case c >= 'A' && c <= 'Z':
- hasUpper = true
- case c == '_', c >= '0' && c <= '9':
- // ok
- default:
- return false
- }
- }
- return hasUpper
-}
diff --git a/internal/pipeline/configures_test.go b/internal/pipeline/configures_test.go
deleted file mode 100644
index acb57ce78..000000000
--- a/internal/pipeline/configures_test.go
+++ /dev/null
@@ -1,257 +0,0 @@
-package pipeline
-
-import (
- "context"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func TestBuildEnvIndex_ConfigVariableAdded(t *testing.T) {
- dir := t.TempDir()
- gitInit(t, dir)
-
- // Create a config file with an env-var-like key
- writeFile(t, filepath.Join(dir, "config.toml"), `DATABASE_URL = "postgresql://localhost/db"
-`)
- // Need a code file so pipeline runs
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-import "os"
-
-func main() {
- url := os.Getenv("DATABASE_URL")
- _ = url
-}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Check that CONFIGURES edges were created
- edges, err := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
- if err != nil {
- t.Fatal(err)
- }
- t.Logf("CONFIGURES edges: %d", len(edges))
- // The env var access in main.go should link to the config file
- // via the extended buildEnvIndex
- if len(edges) == 0 {
- t.Logf("warning: no CONFIGURES edges (may depend on extraction)")
- }
-}
-
-func TestBuildEnvIndex_LowercaseKeySkipped(t *testing.T) {
- dir := t.TempDir()
- gitInit(t, dir)
-
- writeFile(t, filepath.Join(dir, "config.toml"), `database_host = "localhost"
-`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func main() {}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // lowercase keys should NOT be in the env index (isEnvVarName rejects them)
- // so no CONFIGURES edges from env var matching for lowercase keys
- edges, err := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
- if err != nil {
- t.Fatal(err)
- }
- for _, e := range edges {
- // If there's a CONFIGURES edge that came from env var matching
- // to a lowercase key, that's a bug
- if e.Properties != nil && e.Properties["strategy"] == nil {
- // Env-var CONFIGURES edges don't have a "strategy" property
- // (they come from passConfigures, not passConfigLinker)
- t.Logf("env var CONFIGURES edge found: source=%d target=%d", e.SourceID, e.TargetID)
- }
- }
-}
-
-func TestBuildEnvIndex_NonConfigFileSkipped(t *testing.T) {
- dir := t.TempDir()
- gitInit(t, dir)
-
- // Put an env-var-like variable in a Go file (should not be added to env index)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-var API_URL = "https://api.example.com"
-
-func main() {}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // No config file exists, so buildEnvIndex should not find config Variables
- // Only Module constants might produce env index entries
- t.Log("pipeline ran successfully without config files")
-}
-
-func TestIsEnvVarName(t *testing.T) {
- tests := []struct {
- input string
- want bool
- }{
- {"DATABASE_URL", true},
- {"API_KEY", true},
- {"PORT", true},
- {"A", false}, // too short
- {"port", false}, // lowercase
- {"apiKey", false}, // camelCase
- {"DB_2", true}, // with digit
- {"__", false}, // no uppercase
- {"", false}, // empty
- }
-
- for _, tt := range tests {
- got := isEnvVarName(tt.input)
- if got != tt.want {
- t.Errorf("isEnvVarName(%q) = %v, want %v", tt.input, got, tt.want)
- }
- }
-}
-
-func TestNormalizeConfigKey(t *testing.T) {
- tests := []struct {
- input string
- wantNorm string
- wantTokens int
- }{
- {"max_connections", "max_connections", 2},
- {"maxConnections", "max_connections", 2},
- {"DATABASE_HOST", "database_host", 2},
- {"database.host", "database_host", 2},
- {"port", "port", 1},
- {"maxRetryCount", "max_retry_count", 3},
- }
-
- for _, tt := range tests {
- norm, tokens := normalizeConfigKey(tt.input)
- if norm != tt.wantNorm {
- t.Errorf("normalizeConfigKey(%q) norm = %q, want %q", tt.input, norm, tt.wantNorm)
- }
- if len(tokens) != tt.wantTokens {
- t.Errorf("normalizeConfigKey(%q) tokens = %d, want %d", tt.input, len(tokens), tt.wantTokens)
- }
- }
-}
-
-func TestHasConfigExtension(t *testing.T) {
- tests := []struct {
- path string
- want bool
- }{
- {"config.toml", true},
- {"settings.yaml", true},
- {"config.yml", true},
- {".env", true},
- {"config.ini", true},
- {"data.json", true},
- {"pom.xml", true},
- {"main.go", false},
- {"app.py", false},
- {"data.csv", false},
- }
-
- for _, tt := range tests {
- got := hasConfigExtension(tt.path)
- if got != tt.want {
- t.Errorf("hasConfigExtension(%q) = %v, want %v", tt.path, got, tt.want)
- }
- }
-}
-
-// Helper: ensure pipeline doesn't crash with config+code project
-func TestConfigIntegration_FullPipeline(t *testing.T) {
- dir := t.TempDir()
- gitInit(t, dir)
-
- writeFile(t, filepath.Join(dir, "config.toml"), `[database]
-host = "localhost"
-port = 5432
-max_connections = 100
-
-[server]
-bind_address = "0.0.0.0"
-`)
- writeFile(t, filepath.Join(dir, "settings.ini"), `[database]
-host = localhost
-port = 5432
-`)
- writeFile(t, filepath.Join(dir, "config.json"), `{"appName": "test", "maxRetries": 3}`)
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-import "os"
-
-func getMaxConnections() int { return 100 }
-
-func loadConfig() {
- cfg := readFile("config.toml")
- _ = cfg
- dbURL := os.Getenv("DATABASE_URL")
- _ = dbURL
-}
-
-func readFile(path string) string { return "" }
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Verify nodes were created for config files
- nodes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
- vars, _ := s.FindNodesByLabel(p.ProjectName, "Variable")
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
- edges, _ := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
-
- t.Logf("Classes: %d, Variables: %d, Functions: %d, CONFIGURES edges: %d",
- len(nodes), len(vars), len(funcs), len(edges))
-
- // Should have config Class nodes (database, server sections)
- if len(nodes) == 0 {
- t.Error("expected Class nodes from config files")
- }
- // Should have Variable nodes from config files
- if len(vars) == 0 {
- t.Error("expected Variable nodes from config files")
- }
-}
diff --git a/internal/pipeline/decorates.go b/internal/pipeline/decorates.go
deleted file mode 100644
index 6e3d49f13..000000000
--- a/internal/pipeline/decorates.go
+++ /dev/null
@@ -1,193 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "slices"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// passDecorates creates DECORATES edges from decorated functions/classes to
-// the decorator function node (if it exists in the project).
-func (p *Pipeline) passDecorates() {
- slog.Info("pass.decorates")
-
- count := 0
- for _, label := range []string{"Function", "Method", "Class"} {
- nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, n := range nodes {
- count += p.processNodeDecorators(n)
- }
- }
-
- slog.Info("pass.decorates.done", "edges", count)
-}
-
-// processNodeDecorators creates DECORATES edges for a single node's decorators.
-func (p *Pipeline) processNodeDecorators(n *store.Node) int {
- decs, ok := n.Properties["decorators"]
- if !ok {
- return 0
- }
- decList, ok := decs.([]any)
- if !ok {
- return 0
- }
-
- moduleQN := qualifiedNamePrefix(n.QualifiedName)
- importMap := p.importMaps[moduleQN]
- count := 0
-
- for _, d := range decList {
- decStr, ok := d.(string)
- if !ok || decStr == "" {
- continue
- }
-
- funcName := decoratorFunctionName(decStr)
- if funcName == "" {
- continue
- }
-
- targetResult := p.registry.Resolve(funcName, moduleQN, importMap)
- if targetResult.QualifiedName == "" {
- continue
- }
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetResult.QualifiedName)
- if targetNode == nil {
- continue
- }
-
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: n.ID,
- TargetID: targetNode.ID,
- Type: "DECORATES",
- Properties: map[string]any{"decorator": decStr},
- })
- count++
- }
- return count
-}
-
-// decoratorFunctionName extracts the function name from a decorator string.
-// "@app.route('/api')" → "app.route"
-// "@pytest.fixture" → "pytest.fixture"
-// "@Override" → "Override"
-func decoratorFunctionName(dec string) string {
- dec = strings.TrimPrefix(dec, "@")
- if idx := strings.Index(dec, "("); idx > 0 {
- dec = dec[:idx]
- }
- return strings.TrimSpace(dec)
-}
-
-type taggedNode struct {
- qn string
- words []string
-}
-
-// collectDecoratedNodes extracts tokenized decorator words from all decorated nodes.
-func (p *Pipeline) collectDecoratedNodes() (nodes []taggedNode, wordCount map[string]int) {
- wordCount = map[string]int{}
-
- for _, label := range []string{"Function", "Method", "Class"} {
- found, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, n := range found {
- words := extractDecoratorWords(n)
- if len(words) > 0 {
- nodes = append(nodes, taggedNode{qn: n.QualifiedName, words: words})
- for _, w := range words {
- wordCount[w]++
- }
- }
- }
- }
- return nodes, wordCount
-}
-
-// extractDecoratorWords tokenizes all decorators on a node into unique words.
-func extractDecoratorWords(n *store.Node) []string {
- decs, ok := n.Properties["decorators"]
- if !ok {
- return nil
- }
- decList, ok := decs.([]any)
- if !ok {
- return nil
- }
- seen := map[string]bool{}
- var words []string
- for _, d := range decList {
- decStr, ok := d.(string)
- if !ok {
- continue
- }
- for _, w := range tokenizeDecorator(decStr) {
- if !seen[w] {
- seen[w] = true
- words = append(words, w)
- }
- }
- }
- return words
-}
-
-// passDecoratorTags classifies decorators into semantic tags via auto-discovery.
-// Words appearing on 2+ distinct nodes become tag candidates.
-func (p *Pipeline) passDecoratorTags() {
- nodes, wordCount := p.collectDecoratedNodes()
-
- // Tag candidates: words on 2+ distinct nodes
- candidates := map[string]bool{}
- for w, c := range wordCount {
- if c >= 2 {
- candidates[w] = true
- }
- }
-
- if len(candidates) == 0 {
- return
- }
-
- tagged := 0
- for _, tn := range nodes {
- var tags []string
- for _, w := range tn.words {
- if candidates[w] {
- tags = append(tags, w)
- }
- }
-
- node, err := p.Store.FindNodeByQN(p.ProjectName, tn.qn)
- if err != nil || node == nil {
- continue
- }
-
- if len(tags) == 0 {
- // Remove stale tags from previous runs
- if _, hasTags := node.Properties["decorator_tags"]; hasTags {
- delete(node.Properties, "decorator_tags")
- _, _ = p.Store.UpsertNode(node)
- }
- continue
- }
-
- slices.Sort(tags)
- if node.Properties == nil {
- node.Properties = map[string]any{}
- }
- node.Properties["decorator_tags"] = tags
- _, _ = p.Store.UpsertNode(node)
- tagged++
- }
-
- slog.Info("pass.decorator_tags", "candidates", len(candidates), "tagged", tagged)
-}
diff --git a/internal/pipeline/docstrings.go b/internal/pipeline/docstrings.go
deleted file mode 100644
index fb2071c7f..000000000
--- a/internal/pipeline/docstrings.go
+++ /dev/null
@@ -1 +0,0 @@
-package pipeline
diff --git a/internal/pipeline/docstrings_test.go b/internal/pipeline/docstrings_test.go
deleted file mode 100644
index d74f32391..000000000
--- a/internal/pipeline/docstrings_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func writeLangTestFile(t *testing.T, path, content string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-// TestDocstringIntegration verifies the pipeline stores docstring properties on nodes.
-func TestDocstringIntegration(t *testing.T) {
- tests := []struct {
- name string
- language lang.Language
- ext string
- source string
- label string // "Function" or "Class"
- wantName string // node name to find
- want string // docstring substring
- }{
- {
- "Go_function",
- lang.Go, ".go",
- "package main\n\n// Compute does something.\nfunc Compute() {}\n",
- "Function", "Compute", "Compute does something.",
- },
- {
- "Python_function",
- lang.Python, ".py",
- "def compute():\n\t\"\"\"Does something.\"\"\"\n\tpass\n",
- "Function", "compute", "Does something.",
- },
- {
- "Java_method",
- lang.Java, ".java",
- "class A {\n\t/** Computes result. */\n\tvoid compute() {}\n}\n",
- "Method", "compute", "Computes result.",
- },
- {
- "Kotlin_function",
- lang.Kotlin, ".kt",
- "/** Computes result. */\nfun compute() {}\n",
- "Function", "compute", "Computes result.",
- },
- {
- "Go_class",
- lang.Go, ".go",
- "package main\n\n// MyStruct is documented.\ntype MyStruct struct{}\n",
- "Class", "MyStruct", "MyStruct is documented.",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- dir := t.TempDir()
- writeLangTestFile(t, filepath.Join(dir, "main"+tt.ext), tt.source)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatal(err)
- }
-
- nodes, err := s.FindNodesByLabel(p.ProjectName, tt.label)
- if err != nil {
- t.Fatal(err)
- }
-
- var found bool
- for _, n := range nodes {
- if n.Name != tt.wantName {
- continue
- }
- found = true
- doc, ok := n.Properties["docstring"].(string)
- if !ok || doc == "" {
- t.Errorf("node %q has no docstring property", n.QualifiedName)
- continue
- }
- if !strings.Contains(doc, tt.want) {
- t.Errorf("node %q docstring = %q, want substring %q", n.QualifiedName, doc, tt.want)
- }
- }
- if !found {
- t.Errorf("no %s node named %q found", tt.label, tt.wantName)
- }
- })
- }
-}
diff --git a/internal/pipeline/enrichment.go b/internal/pipeline/enrichment.go
deleted file mode 100644
index 854e3da69..000000000
--- a/internal/pipeline/enrichment.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package pipeline
-
-import (
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// buildSymbolSummary creates a compact symbol list for File node enrichment.
-// Format: "kind:name" where kind is func/method/class/interface/type/var/const/macro/field.
-func buildSymbolSummary(nodes []*store.Node, moduleQN string) []string {
- symbols := make([]string, 0, len(nodes))
- for _, n := range nodes {
- if n.QualifiedName == moduleQN {
- continue
- }
- prefix := labelToSymbolPrefix(n.Label)
- if prefix == "" {
- continue
- }
- symbols = append(symbols, prefix+":"+n.Name)
- }
- return symbols
-}
-
-// tokenizeDecorator strips decorator syntax and splits into lowercase words.
-// Example: "@login_required" → ["login", "required"]
-// Example: "@GetMapping(\"/api\")" → ["mapping"] (stopword "get" filtered)
-func tokenizeDecorator(dec string) []string {
- // Strip leading syntax: @, #[
- dec = strings.TrimPrefix(dec, "@")
- dec = strings.TrimPrefix(dec, "#[")
- dec = strings.TrimSuffix(dec, "]")
- // Strip arguments: everything from first ( onwards
- if idx := strings.Index(dec, "("); idx >= 0 {
- dec = dec[:idx]
- }
- // Split on delimiters: dots, underscores, hyphens, colons, slashes
- parts := strings.FieldsFunc(dec, func(r rune) bool {
- return r == '.' || r == '_' || r == '-' || r == ':' || r == '/'
- })
- // Split camelCase and collect lowercase words
- var words []string
- for _, part := range parts {
- for _, w := range splitCamelCase(part) {
- w = strings.ToLower(w)
- if len(w) >= 2 && !decoratorStopwords[w] {
- words = append(words, w)
- }
- }
- }
- return words
-}
-
-// splitCamelCase splits a string on lowercase→uppercase transitions.
-// Example: "GetMapping" → ["Get", "Mapping"]
-func splitCamelCase(s string) []string {
- if s == "" {
- return nil
- }
- var words []string
- start := 0
- for i := 1; i < len(s); i++ {
- if s[i] >= 'A' && s[i] <= 'Z' && s[i-1] >= 'a' && s[i-1] <= 'z' {
- words = append(words, s[start:i])
- start = i
- }
- }
- words = append(words, s[start:])
- return words
-}
-
-// decoratorStopwords are common words filtered from decorator tag candidates.
-var decoratorStopwords = map[string]bool{
- "get": true, "set": true, "new": true, "class": true,
- "method": true, "function": true, "value": true, "type": true,
- "param": true, "return": true, "public": true, "private": true,
- "for": true, "if": true, "the": true, "and": true,
- "or": true, "not": true, "with": true, "from": true,
- "app": true, "router": true,
-}
-
-func labelToSymbolPrefix(label string) string {
- switch label {
- case "Function":
- return "func"
- case "Method":
- return "method"
- case "Class":
- return "class"
- case "Interface":
- return "interface"
- case "Type":
- return "type"
- case "Enum":
- return "enum"
- case "Variable":
- return "var"
- case "Macro":
- return "macro"
- case "Field":
- return "field"
- default:
- return ""
- }
-}
diff --git a/internal/pipeline/enrichment_test.go b/internal/pipeline/enrichment_test.go
deleted file mode 100644
index 613f05c33..000000000
--- a/internal/pipeline/enrichment_test.go
+++ /dev/null
@@ -1,262 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func TestTokenizeDecorator(t *testing.T) {
- tests := []struct {
- input string
- want []string
- }{
- {"@Override", []string{"override"}},
- {"@Deprecated", []string{"deprecated"}},
- {"@Test", []string{"test"}},
- {"@login_required", []string{"login", "required"}},
- {"@cache", []string{"cache"}},
- {"@pytest.fixture", []string{"pytest", "fixture"}},
- {`@GetMapping("/api")`, []string{"mapping"}}, // "get" is stopword
- {`@PostMapping("/api")`, []string{"post", "mapping"}},
- {`@Transactional`, []string{"transactional"}},
- {`@MessageMapping("/chat")`, []string{"message", "mapping"}},
- {`#[test]`, []string{"test"}},
- {`#[derive(Debug)]`, []string{"derive"}},
- {"@app.get(\"/api\")", nil}, // both "app" and "get" are stopwords
- {"@router.post(\"/api\")", []string{"post"}}, // "router" is stopword, "post" passes
- {"@x", nil}, // too short after filtering
- {"", nil}, // empty
- {"@click.command", []string{"click", "command"}},
- {"@celery.task", []string{"celery", "task"}},
- }
- for _, tt := range tests {
- got := tokenizeDecorator(tt.input)
- if !sliceEqual(got, tt.want) {
- t.Errorf("tokenizeDecorator(%q) = %v, want %v", tt.input, got, tt.want)
- }
- }
-}
-
-func TestSplitCamelCase(t *testing.T) {
- tests := []struct {
- input string
- want []string
- }{
- {"GetMapping", []string{"Get", "Mapping"}},
- {"getMessage", []string{"get", "Message"}},
- {"cache", []string{"cache"}},
- {"HTMLParser", []string{"HTMLParser"}}, // no lowercase→uppercase transition
- {"", nil},
- }
- for _, tt := range tests {
- got := splitCamelCase(tt.input)
- if !sliceEqual(got, tt.want) {
- t.Errorf("splitCamelCase(%q) = %v, want %v", tt.input, got, tt.want)
- }
- }
-}
-
-func TestDecoratorTagAutoDiscovery(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-dectag-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Create Python files with repeated decorators
- writeFile(t, filepath.Join(dir, "views.py"), `
-from functools import cache
-
-@login_required
-def list_orders():
- pass
-
-@login_required
-def get_order():
- pass
-
-@cache
-def compute_total():
- pass
-
-@cache
-def compute_tax():
- pass
-
-@unique_helper
-def special():
- pass
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Check decorator_tags on nodes
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
-
- tagMap := map[string][]string{} // funcName → tags
- for _, f := range funcs {
- tags, ok := f.Properties["decorator_tags"]
- if !ok {
- continue
- }
- tagList, ok := tags.([]any)
- if !ok {
- continue
- }
- var ts []string
- for _, tag := range tagList {
- if s, ok := tag.(string); ok {
- ts = append(ts, s)
- }
- }
- tagMap[f.Name] = ts
- }
-
- // "login" and "required" appear on 2 nodes → should be tags
- assertHasTag(t, tagMap, "list_orders", "login")
- assertHasTag(t, tagMap, "list_orders", "required")
- assertHasTag(t, tagMap, "get_order", "login")
- assertHasTag(t, tagMap, "get_order", "required")
-
- // "cache" appears on 2 nodes → should be a tag
- assertHasTag(t, tagMap, "compute_total", "cache")
- assertHasTag(t, tagMap, "compute_tax", "cache")
-
- // "unique" and "helper" appear on only 1 node → should NOT be tags
- if tags, ok := tagMap["special"]; ok {
- for _, tag := range tags {
- if tag == "unique" || tag == "helper" {
- t.Errorf("special should not have tag %q (freq < 2)", tag)
- }
- }
- }
-}
-
-func TestDecoratorTagJavaClassMethods(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-javadec-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "Controller.java"), `
-class OwnerController {
- @GetMapping("/owners")
- public void listOwners() {}
-
- @GetMapping("/owners/{id}")
- public void showOwner() {}
-
- @PostMapping("/owners")
- public void createOwner() {}
-
- @Transactional
- @PostMapping("/owners/{id}")
- public void updateOwner() {}
-}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Verify decorators are extracted on class methods
- methods, _ := s.FindNodesByLabel(p.ProjectName, "Method")
-
- decoMap := map[string][]string{}
- tagMap := map[string][]string{}
- for _, m := range methods {
- if ds := extractStringSliceProp(m.Properties, "decorators"); len(ds) > 0 {
- decoMap[m.Name] = ds
- }
- if ts := extractStringSliceProp(m.Properties, "decorator_tags"); len(ts) > 0 {
- tagMap[m.Name] = ts
- }
- }
-
- // decorators should be extracted
- if len(decoMap["listOwners"]) == 0 {
- t.Error("listOwners should have decorators")
- }
- if len(decoMap["showOwner"]) == 0 {
- t.Error("showOwner should have decorators")
- }
-
- // "mapping" appears on all 4 methods → should be a tag
- assertHasTag(t, tagMap, "listOwners", "mapping")
- assertHasTag(t, tagMap, "showOwner", "mapping")
-
- // "post" appears on 2 methods → should be a tag
- assertHasTag(t, tagMap, "createOwner", "post")
- assertHasTag(t, tagMap, "updateOwner", "post")
-}
-
-func assertHasTag(t *testing.T, tagMap map[string][]string, funcName, tag string) {
- t.Helper()
- tags, ok := tagMap[funcName]
- if !ok {
- t.Errorf("%s has no decorator_tags", funcName)
- return
- }
- for _, tt := range tags {
- if tt == tag {
- return
- }
- }
- t.Errorf("%s missing tag %q, got %v", funcName, tag, tags)
-}
-
-// extractStringSliceProp extracts a []any property as []string.
-func extractStringSliceProp(props map[string]any, key string) []string {
- val, ok := props[key]
- if !ok {
- return nil
- }
- list, ok := val.([]any)
- if !ok {
- return nil
- }
- out := make([]string, 0, len(list))
- for _, item := range list {
- if s, ok := item.(string); ok {
- out = append(out, s)
- }
- }
- return out
-}
-
-func sliceEqual(a, b []string) bool {
- if len(a) == 0 && len(b) == 0 {
- return true
- }
- if len(a) != len(b) {
- return false
- }
- for i := range a {
- if a[i] != b[i] {
- return false
- }
- }
- return true
-}
diff --git a/internal/pipeline/envscan.go b/internal/pipeline/envscan.go
deleted file mode 100644
index 6e3eb7ea6..000000000
--- a/internal/pipeline/envscan.go
+++ /dev/null
@@ -1,307 +0,0 @@
-package pipeline
-
-import (
- "bufio"
- "bytes"
- "os"
- "path/filepath"
- "regexp"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
-)
-
-// EnvBinding represents an extracted environment variable with a URL value.
-type EnvBinding struct {
- Key string
- Value string
- FilePath string // relative path where found
-}
-
-// ScanProjectEnvURLs walks the project root, scanning all non-ignored files for
-// env var assignments where the value looks like a URL.
-func ScanProjectEnvURLs(rootPath string) []EnvBinding {
- var bindings []EnvBinding
-
- _ = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- name := info.Name()
-
- // Skip ignored directories (reuse discover package patterns)
- if info.IsDir() {
- if discover.IGNORE_PATTERNS[name] {
- return filepath.SkipDir
- }
- return nil
- }
-
- // Skip secret files
- if isSecretFile(name) {
- return nil
- }
-
- // Skip ignored suffixes
- for suffix := range discover.IGNORE_SUFFIXES {
- if strings.HasSuffix(name, suffix) {
- return nil
- }
- }
-
- // Skip binary/large files
- if info.Size() > 1<<20 { // 1MB
- return nil
- }
-
- relPath, _ := filepath.Rel(rootPath, path)
- if relPath == "" {
- return nil
- }
-
- fileBindings := scanFileForEnvURLs(path, relPath)
- bindings = append(bindings, fileBindings...)
-
- return nil
- })
-
- return bindings
-}
-
-// scanEnvURLsFromStore iterates sourceStore keys and scans for env URL bindings.
-// Used when sourceStore is populated (RAM path) to avoid filesystem walk.
-func (p *Pipeline) scanEnvURLsFromStore() []EnvBinding {
- var bindings []EnvBinding
- for relPath := range p.sourceStore {
- name := filepath.Base(relPath)
- lowerName := strings.ToLower(name)
- ext := filepath.Ext(name)
-
- // Skip secret files
- if isSecretFile(name) {
- continue
- }
-
- var patterns []*regexp.Regexp
- switch {
- case isDockerfile(lowerName):
- patterns = dockerfilePatterns
- case ext == ".yaml" || ext == ".yml":
- patterns = yamlPatterns
- case ext == ".tf" || ext == ".hcl":
- patterns = terraformPatterns
- case ext == ".sh" || ext == ".bash" || ext == ".zsh":
- patterns = shellPatterns
- case isEnvFile(lowerName):
- patterns = envFilePatterns
- case ext == ".toml":
- patterns = tomlPatterns
- case ext == ".properties" || ext == ".cfg" || ext == ".ini":
- patterns = propertiesPatterns
- default:
- continue
- }
-
- source := p.getSource(relPath)
- if len(source) == 0 || len(source) > 1<<20 {
- continue
- }
- fileBindings := scanWithPatternsFromSource(source, relPath, patterns)
- bindings = append(bindings, fileBindings...)
- }
- return bindings
-}
-
-func scanFileForEnvURLs(absPath, relPath string) []EnvBinding {
- name := filepath.Base(absPath)
- ext := filepath.Ext(name)
- lowerName := strings.ToLower(name)
-
- // Determine which patterns to use based on file type
- var patterns []*regexp.Regexp
-
- switch {
- case isDockerfile(lowerName):
- patterns = dockerfilePatterns
- case ext == ".yaml" || ext == ".yml":
- patterns = yamlPatterns
- case ext == ".tf" || ext == ".hcl":
- patterns = terraformPatterns
- case ext == ".sh" || ext == ".bash" || ext == ".zsh":
- patterns = shellPatterns
- case isEnvFile(lowerName):
- patterns = envFilePatterns
- case ext == ".toml":
- patterns = tomlPatterns
- case ext == ".properties" || ext == ".cfg" || ext == ".ini":
- patterns = propertiesPatterns
- default:
- // Not a config file type we scan
- return nil
- }
-
- return scanWithPatterns(absPath, relPath, patterns)
-}
-
-// Pattern definitions (compiled once as package-level vars).
-var (
- // Dockerfile: ENV KEY=VALUE or ENV KEY VALUE, ARG KEY=VALUE
- dockerfilePatterns = []*regexp.Regexp{
- regexp.MustCompile(`^(?:ENV|ARG)\s+(\w+)[= ](.*)`),
- }
-
- // YAML: key: "https://..." or --set-env-vars KEY=VALUE
- yamlPatterns = []*regexp.Regexp{
- regexp.MustCompile(`(\w+):\s*["']?(https?://[^\s"']+)`),
- regexp.MustCompile(`--set-env-vars\s+(\w+)=(\S+)`),
- }
-
- // Terraform/HCL: default = "https://..." or value = "https://..."
- terraformPatterns = []*regexp.Regexp{
- regexp.MustCompile(`(?:default|value)\s*=\s*"(https?://[^"]+)"`),
- }
-
- // Shell: export KEY="https://..." or KEY="https://..."
- shellPatterns = []*regexp.Regexp{
- regexp.MustCompile(`(?:export\s+)?(\w+)=["']?(https?://[^\s"']+)`),
- }
-
- // .env files: KEY=https://...
- envFilePatterns = []*regexp.Regexp{
- regexp.MustCompile(`^(\w+)=(https?://\S+)`),
- }
-
- // TOML: key = "https://..."
- tomlPatterns = []*regexp.Regexp{
- regexp.MustCompile(`(\w+)\s*=\s*"(https?://[^"]+)"`),
- }
-
- // Properties/cfg/ini: key=https://...
- propertiesPatterns = []*regexp.Regexp{
- regexp.MustCompile(`(\w+)\s*=\s*(https?://\S+)`),
- }
-)
-
-func isDockerfile(name string) bool {
- lower := strings.ToLower(name)
- if lower == "dockerfile" {
- return true
- }
- if strings.HasPrefix(lower, "dockerfile.") || strings.HasSuffix(lower, ".dockerfile") {
- return true
- }
- return false
-}
-
-func isEnvFile(name string) bool {
- lower := strings.ToLower(name)
- if lower == ".env" || strings.HasPrefix(lower, ".env.") || strings.HasSuffix(lower, ".env") {
- return true
- }
- return false
-}
-
-// Secret exclusion patterns.
-var secretKeyPattern = regexp.MustCompile(
- `(?i)(secret|password|passwd|token|api_key|apikey|private_key|` +
- `credential|auth_token|access_key|client_secret|signing_key|` +
- `encryption_key|ssh_key|deploy_key|service_account|bearer|jwt_secret)`)
-
-var secretValuePattern = regexp.MustCompile(
- `(?i)(-----BEGIN|AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{20,}|` +
- `ghp_[a-zA-Z0-9]{36}|glpat-[a-zA-Z0-9\-]{20,}|xox[bps]-[a-zA-Z0-9\-]+)`)
-
-func isSecretFile(name string) bool {
- lower := strings.ToLower(name)
- secretFilePatterns := []string{
- "service_account", "credentials", "key.json", "key.pem",
- "id_rsa", "id_ed25519", ".pem", ".key",
- }
- for _, p := range secretFilePatterns {
- if strings.Contains(lower, p) {
- return true
- }
- }
- return false
-}
-
-func isSecretBinding(key, value string) bool {
- if secretKeyPattern.MatchString(key) {
- return true
- }
- if secretValuePattern.MatchString(value) {
- return true
- }
- return false
-}
-
-// isSecretValue checks only the value pattern, not the key name.
-// Use for compose/infra files where key names like JWT_PRIVATE_KEY_ID
-// are config references, not actual secrets.
-func isSecretValue(value string) bool {
- return secretValuePattern.MatchString(value)
-}
-
-func scanWithPatterns(absPath, relPath string, patterns []*regexp.Regexp) []EnvBinding {
- f, err := os.Open(absPath)
- if err != nil {
- return nil
- }
- defer f.Close()
- return scanWithPatternsReader(bufio.NewScanner(f), relPath, patterns)
-}
-
-func scanWithPatternsFromSource(source []byte, relPath string, patterns []*regexp.Regexp) []EnvBinding {
- return scanWithPatternsReader(bufio.NewScanner(bytes.NewReader(source)), relPath, patterns)
-}
-
-func scanWithPatternsReader(scanner *bufio.Scanner, relPath string, patterns []*regexp.Regexp) []EnvBinding {
- var bindings []EnvBinding
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
-
- // Skip comments
- if strings.HasPrefix(line, "#") || strings.HasPrefix(line, "//") {
- continue
- }
-
- for _, pat := range patterns {
- matches := pat.FindStringSubmatch(line)
- if matches == nil {
- continue
- }
-
- var key, value string
- switch len(matches) {
- case 2:
- // Pattern with only value capture (terraform: default = "URL")
- key = "_tf_default"
- value = matches[1]
- case 3:
- key = matches[1]
- value = strings.Trim(matches[2], `"'`)
- default:
- continue
- }
-
- // Validate: must be a URL
- if !strings.HasPrefix(value, "http://") && !strings.HasPrefix(value, "https://") {
- continue
- }
-
- // Secret exclusion
- if isSecretBinding(key, value) {
- continue
- }
-
- bindings = append(bindings, EnvBinding{
- Key: key,
- Value: value,
- FilePath: relPath,
- })
- }
- }
-
- return bindings
-}
diff --git a/internal/pipeline/envscan_test.go b/internal/pipeline/envscan_test.go
deleted file mode 100644
index e860f713b..000000000
--- a/internal/pipeline/envscan_test.go
+++ /dev/null
@@ -1,377 +0,0 @@
-package pipeline
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-func createTempFile(t *testing.T, dir, name, content string) {
- t.Helper()
- fullPath := filepath.Join(dir, name)
- if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(fullPath, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestScanDockerfileEnvURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "Dockerfile", `FROM python:3.9-slim
-ENV ORDER_URL=https://api.example.com/api/orders
-ENV DB_HOST=localhost
-ARG WEBHOOK_URL=https://hooks.example.com/webhook
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- found := map[string]string{}
- for _, b := range bindings {
- found[b.Key] = b.Value
- }
-
- if v, ok := found["ORDER_URL"]; !ok || v != "https://api.example.com/api/orders" {
- t.Errorf("expected ORDER_URL=https://api.example.com/api/orders, got %q", v)
- }
- if v, ok := found["WEBHOOK_URL"]; !ok || v != "https://hooks.example.com/webhook" {
- t.Errorf("expected WEBHOOK_URL=https://hooks.example.com/webhook, got %q", v)
- }
- if _, ok := found["DB_HOST"]; ok {
- t.Error("DB_HOST=localhost should not be extracted (not a URL)")
- }
-}
-
-func TestScanYAMLEnvURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "config.yaml", `
-service:
- service_url: "https://api.internal.com/api/process"
- timeout: 30
- callback_url: "https://hooks.internal.com/callback"
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- found := map[string]string{}
- for _, b := range bindings {
- found[b.Key] = b.Value
- }
-
- if v, ok := found["service_url"]; !ok || v != "https://api.internal.com/api/process" {
- t.Errorf("expected service_url, got %q (ok=%v)", v, ok)
- }
- if v, ok := found["callback_url"]; !ok || v != "https://hooks.internal.com/callback" {
- t.Errorf("expected callback_url, got %q (ok=%v)", v, ok)
- }
-}
-
-func TestScanShellEnvURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "setup.sh", `#!/bin/bash
-export DB_URL="https://db.example.com/api/sync"
-APP_NAME="my-service"
-CALLBACK_URL=https://hooks.example.com/notify
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- found := map[string]string{}
- for _, b := range bindings {
- found[b.Key] = b.Value
- }
-
- if v, ok := found["DB_URL"]; !ok || v != "https://db.example.com/api/sync" {
- t.Errorf("expected DB_URL=https://db.example.com/api/sync, got %q", v)
- }
- if v, ok := found["CALLBACK_URL"]; !ok || v != "https://hooks.example.com/notify" {
- t.Errorf("expected CALLBACK_URL=https://hooks.example.com/notify, got %q", v)
- }
- if _, ok := found["APP_NAME"]; ok {
- t.Error("APP_NAME=my-service should not be extracted (not a URL)")
- }
-}
-
-func TestScanEnvFileURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, ".env", `
-API_URL=https://api.example.com/v1
-DEBUG=true
-SERVICE_URL=https://service.example.com/api
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- found := map[string]string{}
- for _, b := range bindings {
- found[b.Key] = b.Value
- }
-
- if v, ok := found["API_URL"]; !ok || v != "https://api.example.com/v1" {
- t.Errorf("expected API_URL=https://api.example.com/v1, got %q", v)
- }
- if v, ok := found["SERVICE_URL"]; !ok || v != "https://service.example.com/api" {
- t.Errorf("expected SERVICE_URL=https://service.example.com/api, got %q", v)
- }
- if _, ok := found["DEBUG"]; ok {
- t.Error("DEBUG=true should not be extracted (not a URL)")
- }
-}
-
-func TestScanTerraformURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "variables.tf", `
-variable "webhook_url" {
- description = "Webhook endpoint"
- default = "https://api.example.com/webhook"
-}
-
-variable "region" {
- default = "us-east-1"
-}
-
-resource "aws_lambda_function" "handler" {
- environment {
- variables = {
- API_ENDPOINT = "https://api.example.com/v2"
- }
- }
-}
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- if len(bindings) == 0 {
- t.Fatal("expected at least 1 binding from terraform file")
- }
-
- foundURL := false
- for _, b := range bindings {
- if b.Value == "https://api.example.com/webhook" {
- foundURL = true
- }
- }
- if !foundURL {
- t.Error("expected to find https://api.example.com/webhook in terraform bindings")
- }
-}
-
-func TestScanTomlURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "config.toml", `
-[service]
-base_url = "https://api.example.com"
-name = "my-service"
-callback_url = "https://hooks.example.com/notify"
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- found := map[string]string{}
- for _, b := range bindings {
- found[b.Key] = b.Value
- }
-
- if v, ok := found["base_url"]; !ok || v != "https://api.example.com" {
- t.Errorf("expected base_url=https://api.example.com, got %q", v)
- }
- if v, ok := found["callback_url"]; !ok || v != "https://hooks.example.com/notify" {
- t.Errorf("expected callback_url=https://hooks.example.com/notify, got %q", v)
- }
- if _, ok := found["name"]; ok {
- t.Error("name=my-service should not be extracted (not a URL)")
- }
-}
-
-func TestScanPropertiesURLs(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "app.properties", `
-api.url=https://api.example.com/health
-app.name=myapp
-service.endpoint=https://service.example.com/api
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- found := map[string]string{}
- for _, b := range bindings {
- // Properties patterns use dot-separated keys; the regex captures the last key segment
- found[b.Key] = b.Value
- }
-
- foundHealthURL := false
- foundServiceURL := false
- for _, b := range bindings {
- if b.Value == "https://api.example.com/health" {
- foundHealthURL = true
- }
- if b.Value == "https://service.example.com/api" {
- foundServiceURL = true
- }
- }
-
- if !foundHealthURL {
- t.Error("expected to find https://api.example.com/health")
- }
- if !foundServiceURL {
- t.Error("expected to find https://service.example.com/api")
- }
-}
-
-func TestSecretKeyExclusion(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "Dockerfile", `FROM node:18
-ENV SECRET_TOKEN=https://api.example.com/api
-ENV API_KEY=https://api.example.com/v1
-ENV PASSWORD=https://auth.example.com/login
-ENV NORMAL_URL=https://api.example.com/orders
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- for _, b := range bindings {
- if b.Key == "SECRET_TOKEN" || b.Key == "API_KEY" || b.Key == "PASSWORD" {
- t.Errorf("secret key %q should have been excluded", b.Key)
- }
- }
-
- found := false
- for _, b := range bindings {
- if b.Key == "NORMAL_URL" {
- found = true
- }
- }
- if !found {
- t.Error("NORMAL_URL should not be excluded")
- }
-}
-
-func TestSecretValueExclusion(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "deploy.sh", `#!/bin/bash
-export GH_URL="https://[email protected]/repo"
-export NORMAL_ENDPOINT="https://api.example.com/orders"
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- for _, b := range bindings {
- if b.Key == "GH_URL" {
- t.Error("value containing ghp_ token should have been excluded")
- }
- }
-
- found := false
- for _, b := range bindings {
- if b.Key == "NORMAL_ENDPOINT" {
- found = true
- }
- }
- if !found {
- t.Error("NORMAL_ENDPOINT should not be excluded")
- }
-}
-
-func TestSecretFileExclusion(t *testing.T) {
- dir := t.TempDir()
-
- // Create a file that matches secret file patterns
- createTempFile(t, dir, "credentials.sh", `#!/bin/bash
-export API_URL="https://api.example.com/v1"
-`)
-
- // Also create a normal file for comparison
- createTempFile(t, dir, "setup.sh", `#!/bin/bash
-export API_URL="https://api.example.com/v1"
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- for _, b := range bindings {
- if b.FilePath == "credentials.sh" {
- t.Error("files matching secret patterns (credentials.sh) should be skipped")
- }
- }
-
- found := false
- for _, b := range bindings {
- if b.FilePath == "setup.sh" {
- found = true
- }
- }
- if !found {
- t.Error("setup.sh should be scanned normally")
- }
-}
-
-func TestSkipsIgnoredDirs(t *testing.T) {
- dir := t.TempDir()
-
- // File inside .git directory should be skipped
- createTempFile(t, dir, ".git/config.sh", `#!/bin/bash
-export API_URL="https://api.example.com/v1"
-`)
-
- // File inside node_modules should be skipped
- createTempFile(t, dir, "node_modules/pkg/config.sh", `#!/bin/bash
-export API_URL="https://api.example.com/v1"
-`)
-
- // File at root level should be scanned
- createTempFile(t, dir, "deploy.sh", `#!/bin/bash
-export API_URL="https://api.example.com/v1"
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- for _, b := range bindings {
- if filepath.Dir(b.FilePath) == ".git" || filepath.Dir(b.FilePath) == "node_modules/pkg" {
- t.Errorf("file in ignored directory should be skipped: %s", b.FilePath)
- }
- }
-
- found := false
- for _, b := range bindings {
- if b.FilePath == "deploy.sh" {
- found = true
- }
- }
- if !found {
- t.Error("deploy.sh at root level should be scanned")
- }
-}
-
-func TestNonURLValuesSkipped(t *testing.T) {
- dir := t.TempDir()
-
- createTempFile(t, dir, "Dockerfile", `FROM python:3.9
-ENV APP_NAME=my-service
-ENV PORT=8080
-ENV DEBUG=true
-ENV LOG_LEVEL=info
-`)
-
- createTempFile(t, dir, "config.sh", `#!/bin/bash
-export REGION="us-east-1"
-export COUNT=42
-`)
-
- bindings := ScanProjectEnvURLs(dir)
-
- if len(bindings) != 0 {
- t.Errorf("expected 0 bindings for non-URL values, got %d", len(bindings))
- for _, b := range bindings {
- t.Logf(" unexpected: %s=%s (%s)", b.Key, b.Value, b.FilePath)
- }
- }
-}
diff --git a/internal/pipeline/gitdiff.go b/internal/pipeline/gitdiff.go
deleted file mode 100644
index d54644e70..000000000
--- a/internal/pipeline/gitdiff.go
+++ /dev/null
@@ -1,225 +0,0 @@
-package pipeline
-
-import (
- "bufio"
- "context"
- "fmt"
- "log/slog"
- "os/exec"
- "strconv"
- "strings"
- "time"
-)
-
-// DiffScope controls which changes to include.
-type DiffScope string
-
-const (
- DiffUnstaged DiffScope = "unstaged"
- DiffStaged DiffScope = "staged"
- DiffAll DiffScope = "all"
- DiffBranch DiffScope = "branch"
-)
-
-// ChangedFile represents a file with a status from git diff --name-status.
-type ChangedFile struct {
- Status string // M, A, D, R (modified, added, deleted, renamed)
- Path string
- OldPath string // non-empty only for renames
-}
-
-// ChangedHunk represents a changed region within a file.
-type ChangedHunk struct {
- Path string
- StartLine int
- EndLine int
-}
-
-// ParseGitDiffFiles runs git diff --name-status and returns changed files.
-func ParseGitDiffFiles(repoPath string, scope DiffScope, baseBranch string) ([]ChangedFile, error) {
- args := buildDiffArgs(scope, baseBranch)
- args = append(args, "--name-status")
- return parseDiffNameStatus(repoPath, args)
-}
-
-// ParseGitDiffHunks runs git diff --unified=0 and extracts changed line ranges.
-func ParseGitDiffHunks(repoPath string, scope DiffScope, baseBranch string) ([]ChangedHunk, error) {
- args := buildDiffArgs(scope, baseBranch)
- args = append(args, "--unified=0")
- return parseDiffHunks(repoPath, args)
-}
-
-func buildDiffArgs(scope DiffScope, baseBranch string) []string {
- base := []string{"diff"}
- switch scope {
- case DiffStaged:
- return append(base, "--cached")
- case DiffAll:
- return append(base, "HEAD")
- case DiffBranch:
- if baseBranch == "" {
- baseBranch = "main"
- }
- return append(base, baseBranch+"...HEAD")
- default: // unstaged
- return base
- }
-}
-
-func parseDiffNameStatus(repoPath string, args []string) ([]ChangedFile, error) {
- output, err := runGit(repoPath, args)
- if err != nil {
- return nil, err
- }
- return ParseNameStatusOutput(output), nil
-}
-
-// ParseNameStatusOutput parses the raw output of git diff --name-status.
-func ParseNameStatusOutput(output string) []ChangedFile {
- var files []ChangedFile
- scanner := bufio.NewScanner(strings.NewReader(output))
- for scanner.Scan() {
- line := scanner.Text()
- if line == "" {
- continue
- }
- parts := strings.Split(line, "\t")
- if len(parts) < 2 {
- continue
- }
- status := parts[0]
- path := parts[1]
-
- cf := ChangedFile{Path: path}
-
- // Handle renames: R100\told\tnew
- if strings.HasPrefix(status, "R") {
- cf.Status = "R"
- cf.OldPath = path
- if len(parts) >= 3 {
- cf.Path = parts[2]
- }
- } else {
- cf.Status = status[:1] // first char: M, A, D, etc.
- }
-
- if !isTrackableFile(cf.Path) {
- continue
- }
- files = append(files, cf)
- }
- return files
-}
-
-func parseDiffHunks(repoPath string, args []string) ([]ChangedHunk, error) {
- output, err := runGit(repoPath, args)
- if err != nil {
- return nil, err
- }
- return ParseHunksOutput(output), nil
-}
-
-// ParseHunksOutput parses the raw output of git diff --unified=0.
-func ParseHunksOutput(output string) []ChangedHunk {
- var hunks []ChangedHunk
- var currentFile string
-
- scanner := bufio.NewScanner(strings.NewReader(output))
- for scanner.Scan() {
- line := scanner.Text()
-
- // Track current file from +++ header
- if strings.HasPrefix(line, "+++ b/") {
- currentFile = strings.TrimPrefix(line, "+++ b/")
- continue
- }
-
- // Skip binary files
- if strings.HasPrefix(line, "Binary files") {
- continue
- }
-
- // Parse @@ hunk headers: @@ -old,count +new,count @@
- if strings.HasPrefix(line, "@@") && currentFile != "" {
- hunk := parseHunkHeader(line, currentFile)
- if hunk != nil && isTrackableFile(currentFile) {
- hunks = append(hunks, *hunk)
- }
- }
- }
- return hunks
-}
-
-// parseHunkHeader extracts the new-file line range from a @@ header.
-// Format: @@ -old_start[,old_count] +new_start[,new_count] @@
-func parseHunkHeader(line, file string) *ChangedHunk {
- // Find the +start,count part
- plusIdx := strings.Index(line, "+")
- if plusIdx < 0 {
- return nil
- }
- // Find the end @@
- endIdx := strings.Index(line[plusIdx:], " @@")
- if endIdx < 0 {
- endIdx = len(line) - plusIdx
- }
- rangeStr := line[plusIdx+1 : plusIdx+endIdx]
-
- start, count := parseRange(rangeStr)
- if start == 0 {
- return nil
- }
- end := start + count - 1
- if end < start {
- end = start
- }
-
- return &ChangedHunk{
- Path: file,
- StartLine: start,
- EndLine: end,
- }
-}
-
-// parseRange parses "start,count" or "start" into (start, count).
-func parseRange(s string) (start, count int) {
- parts := strings.SplitN(s, ",", 2)
- start, err := strconv.Atoi(parts[0])
- if err != nil {
- return 0, 0
- }
- count = 1
- if len(parts) == 2 {
- count, err = strconv.Atoi(parts[1])
- if err != nil {
- count = 1
- }
- }
- return start, count
-}
-
-// runGit executes a git command and returns stdout. Returns a clear error if git is not found.
-func runGit(repoPath string, args []string) (string, error) {
- gitPath, err := exec.LookPath("git")
- if err != nil {
- return "", fmt.Errorf("git not found in PATH: install git to use detect_changes")
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- cmd := exec.CommandContext(ctx, gitPath, args...)
- cmd.Dir = repoPath
-
- output, err := cmd.Output()
- if err != nil {
- // git diff returns exit code 1 when there are differences in some modes
- // but we still want the output
- if exitErr, ok := err.(*exec.ExitError); ok {
- slog.Debug("git.exit", "code", exitErr.ExitCode(), "args", args)
- return string(output), nil
- }
- return "", fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
- }
- return string(output), nil
-}
diff --git a/internal/pipeline/gitdiff_test.go b/internal/pipeline/gitdiff_test.go
deleted file mode 100644
index 0aee95d8f..000000000
--- a/internal/pipeline/gitdiff_test.go
+++ /dev/null
@@ -1,182 +0,0 @@
-package pipeline
-
-import (
- "strings"
- "testing"
-)
-
-func TestParseNameStatusOutput(t *testing.T) {
- input := "M\tinternal/store/nodes.go\nA\tnew_file.go\nD\told_file.go\nR100\tsrc/old.go\tsrc/new.go\n"
-
- files := ParseNameStatusOutput(input)
-
- if len(files) != 4 {
- t.Fatalf("expected 4 files, got %d", len(files))
- }
-
- tests := []struct {
- idx int
- status string
- path string
- oldPath string
- }{
- {0, "M", "internal/store/nodes.go", ""},
- {1, "A", "new_file.go", ""},
- {2, "D", "old_file.go", ""},
- {3, "R", "src/new.go", "src/old.go"},
- }
-
- for _, tt := range tests {
- f := files[tt.idx]
- if f.Status != tt.status {
- t.Errorf("[%d] status = %q, want %q", tt.idx, f.Status, tt.status)
- }
- if f.Path != tt.path {
- t.Errorf("[%d] path = %q, want %q", tt.idx, f.Path, tt.path)
- }
- if f.OldPath != tt.oldPath {
- t.Errorf("[%d] oldPath = %q, want %q", tt.idx, f.OldPath, tt.oldPath)
- }
- }
-}
-
-func TestParseNameStatusOutput_FiltersUntrackable(t *testing.T) {
- input := "M\tpackage-lock.json\nM\tsrc/main.go\nM\tvendor/lib.go\n"
- files := ParseNameStatusOutput(input)
-
- if len(files) != 1 {
- t.Fatalf("expected 1 trackable file, got %d", len(files))
- }
- if files[0].Path != "src/main.go" {
- t.Errorf("expected src/main.go, got %s", files[0].Path)
- }
-}
-
-func TestParseHunksOutput(t *testing.T) {
- input := `diff --git a/main.go b/main.go
-index abc1234..def5678 100644
---- a/main.go
-+++ b/main.go
-@@ -10,3 +10,5 @@ func main() {
-+ newLine1()
-+ newLine2()
-@@ -50,0 +52,2 @@ func helper() {
-+ another()
-+ line()
-diff --git a/binary.png b/binary.png
-Binary files a/binary.png and b/binary.png differ
-diff --git a/utils.go b/utils.go
---- a/utils.go
-+++ b/utils.go
-@@ -1 +1 @@ package utils
--old
-+new
-`
-
- hunks := ParseHunksOutput(input)
-
- if len(hunks) != 3 {
- t.Fatalf("expected 3 hunks, got %d", len(hunks))
- }
-
- // First hunk: main.go @@ -10,3 +10,5 @@
- if hunks[0].Path != "main.go" {
- t.Errorf("hunk 0 path = %q", hunks[0].Path)
- }
- if hunks[0].StartLine != 10 || hunks[0].EndLine != 14 {
- t.Errorf("hunk 0 range = %d-%d, want 10-14", hunks[0].StartLine, hunks[0].EndLine)
- }
-
- // Second hunk: main.go @@ -50,0 +52,2 @@
- if hunks[1].Path != "main.go" {
- t.Errorf("hunk 1 path = %q", hunks[1].Path)
- }
- if hunks[1].StartLine != 52 || hunks[1].EndLine != 53 {
- t.Errorf("hunk 1 range = %d-%d, want 52-53", hunks[1].StartLine, hunks[1].EndLine)
- }
-
- // Third hunk: utils.go @@ -1 +1 @@
- if hunks[2].Path != "utils.go" {
- t.Errorf("hunk 2 path = %q", hunks[2].Path)
- }
- if hunks[2].StartLine != 1 || hunks[2].EndLine != 1 {
- t.Errorf("hunk 2 range = %d-%d, want 1-1", hunks[2].StartLine, hunks[2].EndLine)
- }
-}
-
-func TestParseHunksOutput_NoNewlineMarker(t *testing.T) {
- input := `diff --git a/file.go b/file.go
---- a/file.go
-+++ b/file.go
-@@ -5,2 +5,3 @@ func foo() {
-+ bar()
-\ No newline at end of file
-`
- hunks := ParseHunksOutput(input)
- if len(hunks) != 1 {
- t.Fatalf("expected 1 hunk, got %d", len(hunks))
- }
- if hunks[0].StartLine != 5 || hunks[0].EndLine != 7 {
- t.Errorf("range = %d-%d, want 5-7", hunks[0].StartLine, hunks[0].EndLine)
- }
-}
-
-func TestParseRange(t *testing.T) {
- tests := []struct {
- input string
- wantStart int
- wantCount int
- }{
- {"10,5", 10, 5},
- {"10", 10, 1},
- {"52,2", 52, 2},
- {"1,0", 1, 0},
- }
- for _, tt := range tests {
- start, count := parseRange(tt.input)
- if start != tt.wantStart || count != tt.wantCount {
- t.Errorf("parseRange(%q) = (%d, %d), want (%d, %d)", tt.input, start, count, tt.wantStart, tt.wantCount)
- }
- }
-}
-
-func TestParseHunksOutput_ModeChange(t *testing.T) {
- input := `diff --git a/script.sh b/script.sh
-old mode 100644
-new mode 100755
-`
- hunks := ParseHunksOutput(input)
- if len(hunks) != 0 {
- t.Fatalf("expected 0 hunks for mode-only change, got %d", len(hunks))
- }
-}
-
-func TestGitNotFound(t *testing.T) {
- // Override PATH to ensure git can't be found
- t.Setenv("PATH", t.TempDir())
-
- _, err := runGit(t.TempDir(), []string{"status"})
- if err == nil {
- t.Fatal("expected error when git is not found")
- }
- if !strings.Contains(err.Error(), "git not found in PATH") {
- t.Errorf("expected 'git not found in PATH' error, got: %v", err)
- }
-}
-
-func TestParseHunksOutput_Deletion(t *testing.T) {
- // Deletion hunks have +start,0 — should still produce a valid hunk at start line
- input := `diff --git a/file.go b/file.go
---- a/file.go
-+++ b/file.go
-@@ -10,3 +10,0 @@ func foo() {
-`
- hunks := ParseHunksOutput(input)
- if len(hunks) != 1 {
- t.Fatalf("expected 1 hunk, got %d", len(hunks))
- }
- // count=0, so endLine = start + 0 - 1 = 9, but we clamp to start
- if hunks[0].StartLine != 10 {
- t.Errorf("start = %d, want 10", hunks[0].StartLine)
- }
-}
diff --git a/internal/pipeline/githistory.go b/internal/pipeline/githistory.go
deleted file mode 100644
index af33ec790..000000000
--- a/internal/pipeline/githistory.go
+++ /dev/null
@@ -1,220 +0,0 @@
-package pipeline
-
-import (
- "bufio"
- "context"
- "fmt"
- "log/slog"
- "os/exec"
- "sort"
- "strings"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// CommitFiles holds the files changed in a single commit.
-type CommitFiles struct {
- Hash string
- Files []string
-}
-
-// ChangeCoupling represents a pair of files that change together.
-type ChangeCoupling struct {
- FileA string
- FileB string
- CoChangeCount int
- TotalChangesA int
- TotalChangesB int
- CouplingScore float64
-}
-
-// passGitHistory analyzes git log to find change coupling and creates FILE_CHANGES_WITH edges.
-func (p *Pipeline) passGitHistory() {
- slog.Info("pass6.githistory")
-
- commits, err := parseGitLog(p.RepoPath)
- if err != nil {
- slog.Warn("pass6.githistory.err", "err", err)
- return
- }
-
- if len(commits) == 0 {
- slog.Info("pass6.githistory.skip", "reason", "no_commits")
- return
- }
-
- couplings := computeChangeCoupling(commits)
- edgeCount := p.createCouplingEdges(couplings)
-
- slog.Info("pass6.githistory.done", "commits", len(commits), "couplings", len(couplings), "edges", edgeCount)
-}
-
-// parseGitLog runs git log and extracts commit → files mapping.
-func parseGitLog(repoPath string) ([]CommitFiles, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- cmd := exec.CommandContext(ctx, "git", "log", "--name-only", "--pretty=format:COMMIT:%H", "--since=6 months ago")
- cmd.Dir = repoPath
-
- output, err := cmd.Output()
- if err != nil {
- return nil, fmt.Errorf("git log: %w", err)
- }
-
- var commits []CommitFiles
- var current *CommitFiles
-
- scanner := bufio.NewScanner(strings.NewReader(string(output)))
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" {
- continue
- }
- if strings.HasPrefix(line, "COMMIT:") {
- if current != nil && len(current.Files) > 0 {
- commits = append(commits, *current)
- }
- current = &CommitFiles{Hash: strings.TrimPrefix(line, "COMMIT:")}
- continue
- }
- if current != nil && isTrackableFile(line) {
- current.Files = append(current.Files, line)
- }
- }
- if current != nil && len(current.Files) > 0 {
- commits = append(commits, *current)
- }
-
- return commits, nil
-}
-
-// isTrackableFile returns true if the file is a source file worth tracking.
-func isTrackableFile(path string) bool {
- skipPrefixes := []string{".git/", "node_modules/", "vendor/", "__pycache__/", ".cache/"}
- for _, prefix := range skipPrefixes {
- if strings.HasPrefix(path, prefix) {
- return false
- }
- }
- // Exact lock file names
- skipNames := []string{"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "Cargo.lock", "poetry.lock", "composer.lock", "Gemfile.lock", "Pipfile.lock"}
- base := path[strings.LastIndex(path, "/")+1:]
- for _, name := range skipNames {
- if base == name {
- return false
- }
- }
- skipSuffixes := []string{".lock", ".sum", ".min.js", ".min.css", ".map", ".wasm", ".png", ".jpg", ".gif", ".ico", ".svg"}
- for _, suffix := range skipSuffixes {
- if strings.HasSuffix(path, suffix) {
- return false
- }
- }
- return true
-}
-
-// computeChangeCoupling computes which file pairs change together frequently.
-func computeChangeCoupling(commits []CommitFiles) []ChangeCoupling {
- fileChangeCount := make(map[string]int)
- pairCount := make(map[[2]string]int)
-
- for _, commit := range commits {
- files := commit.Files
- if len(files) > 20 {
- continue // skip large merge/refactor commits
- }
-
- for _, f := range files {
- fileChangeCount[f]++
- }
-
- for i := 0; i < len(files); i++ {
- for j := i + 1; j < len(files); j++ {
- a, b := files[i], files[j]
- if a > b {
- a, b = b, a
- }
- pairCount[[2]string{a, b}]++
- }
- }
- }
-
- couplings := make([]ChangeCoupling, 0, len(pairCount)/2)
- for pair, count := range pairCount {
- if count < 3 {
- continue
- }
-
- totalA := fileChangeCount[pair[0]]
- totalB := fileChangeCount[pair[1]]
- minTotal := totalA
- if totalB < minTotal {
- minTotal = totalB
- }
- if minTotal == 0 {
- continue
- }
-
- score := float64(count) / float64(minTotal)
- if score < 0.3 {
- continue
- }
-
- couplings = append(couplings, ChangeCoupling{
- FileA: pair[0],
- FileB: pair[1],
- CoChangeCount: count,
- TotalChangesA: totalA,
- TotalChangesB: totalB,
- CouplingScore: score,
- })
- }
-
- sort.Slice(couplings, func(i, j int) bool {
- return couplings[i].CouplingScore > couplings[j].CouplingScore
- })
-
- if len(couplings) > 100 {
- couplings = couplings[:100]
- }
-
- return couplings
-}
-
-// createCouplingEdges creates FILE_CHANGES_WITH edges for detected change couplings.
-func (p *Pipeline) createCouplingEdges(couplings []ChangeCoupling) int {
- count := 0
- for _, c := range couplings {
- nodeA := p.findFileNode(c.FileA)
- nodeB := p.findFileNode(c.FileB)
- if nodeA == nil || nodeB == nil {
- continue
- }
-
- _, err := p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: nodeA.ID,
- TargetID: nodeB.ID,
- Type: "FILE_CHANGES_WITH",
- Properties: map[string]any{
- "co_change_count": c.CoChangeCount,
- "total_changes_a": c.TotalChangesA,
- "total_changes_b": c.TotalChangesB,
- "coupling_score": c.CouplingScore,
- },
- })
- if err == nil {
- count++
- }
- }
- return count
-}
-
-// findFileNode looks up the File node for a given relative path.
-func (p *Pipeline) findFileNode(relPath string) *store.Node {
- fileQN := fqn.Compute(p.ProjectName, relPath, "") + ".__file__"
- n, _ := p.Store.FindNodeByQN(p.ProjectName, fileQN)
- return n
-}
diff --git a/internal/pipeline/githistory_test.go b/internal/pipeline/githistory_test.go
deleted file mode 100644
index 679329307..000000000
--- a/internal/pipeline/githistory_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package pipeline
-
-import (
- "fmt"
- "testing"
-)
-
-func TestIsTrackableFile(t *testing.T) {
- tests := []struct {
- path string
- want bool
- }{
- {"main.go", true},
- {"src/app.py", true},
- {"node_modules/foo/bar.js", false},
- {"vendor/lib/dep.go", false},
- {"package-lock.json", false},
- {"go.sum", false},
- {"image.png", false},
- {".git/config", false},
- {"__pycache__/mod.pyc", false},
- {"src/style.min.css", false},
- {"README.md", true},
- }
- for _, tt := range tests {
- if got := isTrackableFile(tt.path); got != tt.want {
- t.Errorf("isTrackableFile(%q) = %v, want %v", tt.path, got, tt.want)
- }
- }
-}
-
-func TestComputeChangeCoupling(t *testing.T) {
- commits := []CommitFiles{
- {Hash: "aaa", Files: []string{"a.go", "b.go", "c.go"}},
- {Hash: "bbb", Files: []string{"a.go", "b.go"}},
- {Hash: "ccc", Files: []string{"a.go", "b.go"}},
- {Hash: "ddd", Files: []string{"a.go", "c.go"}},
- {Hash: "eee", Files: []string{"d.go", "e.go"}},
- }
-
- couplings := computeChangeCoupling(commits)
-
- found := false
- for _, c := range couplings {
- if (c.FileA == "a.go" && c.FileB == "b.go") || (c.FileA == "b.go" && c.FileB == "a.go") {
- found = true
- if c.CoChangeCount != 3 {
- t.Errorf("expected 3 co-changes for a.go/b.go, got %d", c.CoChangeCount)
- }
- if c.CouplingScore < 0.9 {
- t.Errorf("expected high coupling score, got %f", c.CouplingScore)
- }
- }
- }
- if !found {
- t.Error("expected coupling between a.go and b.go")
- }
-
- for _, c := range couplings {
- if c.FileA == "d.go" || c.FileB == "d.go" {
- t.Error("d.go should not appear (below threshold)")
- }
- }
-}
-
-func TestComputeChangeCouplingSkipsLargeCommits(t *testing.T) {
- files := make([]string, 25)
- for i := range files {
- files[i] = fmt.Sprintf("file%d.go", i)
- }
- commits := []CommitFiles{{Hash: "large", Files: files}}
-
- couplings := computeChangeCoupling(commits)
- if len(couplings) != 0 {
- t.Errorf("expected 0 couplings from large commit, got %d", len(couplings))
- }
-}
-
-func TestComputeChangeCouplingLimitsTo100(t *testing.T) {
- // Create many commits with overlapping files to generate >100 couplings
- var commits []CommitFiles
- for i := 0; i < 50; i++ {
- for j := i + 1; j < 50; j++ {
- // Create 3 commits per pair to exceed threshold
- for k := 0; k < 3; k++ {
- commits = append(commits, CommitFiles{
- Hash: fmt.Sprintf("c%d_%d_%d", i, j, k),
- Files: []string{fmt.Sprintf("f%d.go", i), fmt.Sprintf("f%d.go", j)},
- })
- }
- }
- }
-
- couplings := computeChangeCoupling(commits)
- if len(couplings) > 100 {
- t.Errorf("expected max 100 couplings, got %d", len(couplings))
- }
-}
diff --git a/internal/pipeline/go_dep_registry.go b/internal/pipeline/go_dep_registry.go
deleted file mode 100644
index ec06fa044..000000000
--- a/internal/pipeline/go_dep_registry.go
+++ /dev/null
@@ -1,356 +0,0 @@
-package pipeline
-
-import (
- "go/ast"
- "go/parser"
- "go/token"
- "log/slog"
- "os"
- "path/filepath"
- "strings"
- "sync"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
-)
-
-// goDepCache caches parsed third-party module definitions.
-// Keyed by module@version (immutable in Go module cache).
-var (
- goDepCacheMu sync.RWMutex
- goDepCache = make(map[string]map[string][]cbm.CrossFileDef) // module@version -> importPath -> defs
-)
-
-// goDepVersions maps Go import path prefix → module@version directory path.
-// Built from go.mod + go.sum.
-type goDepVersions struct {
- // modDirByPath maps module import path → absolute directory in module cache
- modDirByPath map[string]string
-}
-
-// buildGoDepVersions reads go.mod and locates each dependency in the module cache.
-func buildGoDepVersions(repoPath string) *goDepVersions {
- data, err := os.ReadFile(filepath.Join(repoPath, "go.mod"))
- if err != nil {
- return nil
- }
-
- goPath := os.Getenv("GOPATH")
- if goPath == "" {
- home, _ := os.UserHomeDir()
- goPath = filepath.Join(home, "go")
- }
- modCacheBase := filepath.Join(goPath, "pkg", "mod")
-
- dv := &goDepVersions{
- modDirByPath: make(map[string]string),
- }
-
- // Parse go.mod for require directives
- inRequire := false
- for _, line := range strings.Split(string(data), "\n") {
- line = strings.TrimSpace(line)
- if line == "require (" {
- inRequire = true
- continue
- }
- if line == ")" {
- inRequire = false
- continue
- }
- if strings.HasPrefix(line, "require ") {
- // Single-line require
- line = strings.TrimPrefix(line, "require ")
- } else if !inRequire {
- continue
- }
-
- // Parse "module/path v1.2.3 // indirect"
- parts := strings.Fields(line)
- if len(parts) < 2 {
- continue
- }
- modPath := parts[0]
- version := parts[1]
-
- // Module cache uses escaped paths (uppercase letters → !lowercase)
- escaped := escapeModPath(modPath)
- modDir := filepath.Join(modCacheBase, escaped+"@"+version)
-
- if info, err := os.Stat(modDir); err == nil && info.IsDir() { //nolint:gosec // path from trusted go.mod + GOPATH
- dv.modDirByPath[modPath] = modDir
- }
- }
-
- return dv
-}
-
-// escapeModPath applies Go module cache path escaping.
-// Uppercase letters are replaced with !lowercase.
-func escapeModPath(path string) string {
- var b strings.Builder
- for _, c := range path {
- if c >= 'A' && c <= 'Z' {
- b.WriteByte('!')
- b.WriteRune(c + 32)
- } else {
- b.WriteRune(c)
- }
- }
- return b.String()
-}
-
-// resolveModDir returns the module cache directory for a Go import path.
-// Handles subpackage paths by finding the longest matching module prefix.
-func (dv *goDepVersions) resolveModDir(importPath string) (modPath, modDir, subPkg string) {
- if dv == nil {
- return "", "", ""
- }
- // Try exact match first, then progressively shorter prefixes
- path := importPath
- for path != "" {
- if dir, ok := dv.modDirByPath[path]; ok {
- sub := strings.TrimPrefix(importPath, path)
- sub = strings.TrimPrefix(sub, "/")
- return path, dir, sub
- }
- idx := strings.LastIndex(path, "/")
- if idx < 0 {
- break
- }
- path = path[:idx]
- }
- return "", "", ""
-}
-
-// parseThirdPartyPackage parses a third-party Go package directory and extracts definitions.
-func parseThirdPartyPackage(modPath, modDir, subPkg string) []cbm.CrossFileDef {
- pkgDir := modDir
- if subPkg != "" {
- pkgDir = filepath.Join(modDir, subPkg)
- }
-
- // The import path for this specific package
- importPath := modPath
- if subPkg != "" {
- importPath = modPath + "/" + subPkg
- }
-
- // Check cache
- cacheKey := modDir // module@version dir is unique and immutable
- goDepCacheMu.RLock()
- if cached, ok := goDepCache[cacheKey]; ok {
- if defs, ok := cached[importPath]; ok {
- goDepCacheMu.RUnlock()
- return defs
- }
- }
- goDepCacheMu.RUnlock()
-
- // Parse Go files in the package directory
- fset := token.NewFileSet()
- pkgs, err := parser.ParseDir(fset, pkgDir, func(fi os.FileInfo) bool { //nolint:staticcheck // SA1019: go/packages is heavyweight; ParseDir suffices for extracting exported names from module cache
- name := fi.Name()
- // Skip test files and non-Go files
- return strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, "_test.go")
- }, 0) // no comments needed
- if err != nil {
- return nil
- }
-
- var defs []cbm.CrossFileDef
- for _, pkg := range pkgs {
- for _, file := range pkg.Files {
- defs = append(defs, extractDefsFromAST(file, importPath)...)
- }
- }
-
- // Cache the result
- goDepCacheMu.Lock()
- if goDepCache[cacheKey] == nil {
- goDepCache[cacheKey] = make(map[string][]cbm.CrossFileDef)
- }
- goDepCache[cacheKey][importPath] = defs
- goDepCacheMu.Unlock()
-
- return defs
-}
-
-// extractDefsFromAST extracts exported function/method/type definitions from an AST file.
-func extractDefsFromAST(file *ast.File, importPath string) []cbm.CrossFileDef {
- var defs []cbm.CrossFileDef
-
- for _, decl := range file.Decls {
- switch d := decl.(type) {
- case *ast.FuncDecl:
- if cd, ok := extractFuncDef(d, importPath); ok {
- defs = append(defs, cd)
- }
- case *ast.GenDecl:
- defs = append(defs, extractTypeDefs(d, importPath)...)
- }
- }
-
- return defs
-}
-
-// extractFuncDef extracts a single exported function/method definition from a FuncDecl.
-func extractFuncDef(d *ast.FuncDecl, importPath string) (cbm.CrossFileDef, bool) {
- if !d.Name.IsExported() {
- return cbm.CrossFileDef{}, false
- }
-
- cd := cbm.CrossFileDef{
- ShortName: d.Name.Name,
- DefModuleQN: importPath,
- }
-
- // Return types
- if d.Type.Results != nil && len(d.Type.Results.List) > 0 {
- retTypes := make([]string, 0, len(d.Type.Results.List))
- for _, field := range d.Type.Results.List {
- retTypes = append(retTypes, typeExprToString(field.Type))
- }
- cd.ReturnTypes = strings.Join(retTypes, "|")
- }
-
- if d.Recv != nil && len(d.Recv.List) > 0 {
- cd.Label = "Method"
- recvType := typeExprToString(d.Recv.List[0].Type)
- recvType = strings.TrimPrefix(recvType, "*")
- cd.ReceiverType = importPath + "." + recvType
- cd.QualifiedName = importPath + "." + recvType + "." + d.Name.Name
- } else {
- cd.Label = "Function"
- cd.QualifiedName = importPath + "." + d.Name.Name
- }
-
- return cd, true
-}
-
-// extractTypeDefs extracts exported type definitions from a GenDecl.
-func extractTypeDefs(d *ast.GenDecl, importPath string) []cbm.CrossFileDef {
- if d.Tok != token.TYPE {
- return nil
- }
- var defs []cbm.CrossFileDef
- for _, spec := range d.Specs {
- ts, ok := spec.(*ast.TypeSpec)
- if !ok || !ts.Name.IsExported() {
- continue
- }
-
- cd := cbm.CrossFileDef{
- QualifiedName: importPath + "." + ts.Name.Name,
- ShortName: ts.Name.Name,
- DefModuleQN: importPath,
- }
-
- switch t := ts.Type.(type) {
- case *ast.InterfaceType:
- cd.Label = "Interface"
- cd.IsInterface = true
- case *ast.StructType:
- cd.Label = "Type"
- cd.EmbeddedTypes = extractStructEmbeds(t, importPath)
- default:
- cd.Label = "Type"
- }
-
- defs = append(defs, cd)
- }
- return defs
-}
-
-// extractStructEmbeds extracts embedded type names from a struct type.
-func extractStructEmbeds(st *ast.StructType, importPath string) string {
- if st.Fields == nil {
- return ""
- }
- var embeds []string
- for _, field := range st.Fields.List {
- if len(field.Names) == 0 {
- embed := typeExprToString(field.Type)
- embed = strings.TrimPrefix(embed, "*")
- embeds = append(embeds, importPath+"."+embed)
- }
- }
- if len(embeds) > 0 {
- return strings.Join(embeds, "|")
- }
- return ""
-}
-
-// typeExprToString converts an ast.Expr representing a type to its string form.
-func typeExprToString(expr ast.Expr) string {
- switch t := expr.(type) {
- case *ast.Ident:
- return t.Name
- case *ast.StarExpr:
- return "*" + typeExprToString(t.X)
- case *ast.ArrayType:
- if t.Len == nil {
- return "[]" + typeExprToString(t.Elt)
- }
- return "[...]" + typeExprToString(t.Elt)
- case *ast.SelectorExpr:
- return typeExprToString(t.X) + "." + t.Sel.Name
- case *ast.MapType:
- return "map[" + typeExprToString(t.Key) + "]" + typeExprToString(t.Value)
- case *ast.ChanType:
- return "chan " + typeExprToString(t.Value)
- case *ast.InterfaceType:
- return "interface{}"
- case *ast.FuncType:
- return "func()"
- case *ast.Ellipsis:
- return "..." + typeExprToString(t.Elt)
- default:
- return "any"
- }
-}
-
-// integrateThirdPartyDeps extends buildGoLSPDefIndex to also parse third-party deps.
-// Called during pipeline setup, populates the index with dep definitions.
-func (idx *goLSPDefIndex) integrateThirdPartyDeps(repoPath string, importMaps map[string]map[string]string) {
- if idx == nil {
- return
- }
-
- dv := buildGoDepVersions(repoPath)
- if dv == nil || len(dv.modDirByPath) == 0 {
- return
- }
-
- // Collect all unique third-party import paths from all files
- needed := make(map[string]bool)
- for _, importMap := range importMaps {
- for _, goImportPath := range importMap {
- if _, exists := idx.byImportPath[goImportPath]; !exists {
- needed[goImportPath] = true
- }
- }
- }
-
- parsedCount := 0
- defCount := 0
- for importPath := range needed {
- modPath, modDir, subPkg := dv.resolveModDir(importPath)
- if modDir == "" {
- continue
- }
-
- defs := parseThirdPartyPackage(modPath, modDir, subPkg)
- if len(defs) > 0 {
- idx.byImportPath[importPath] = defs
- defCount += len(defs)
- parsedCount++
- }
- }
-
- if parsedCount > 0 {
- slog.Info("go_lsp.third_party.index",
- "packages", parsedCount,
- "defs", defCount,
- )
- }
-}
diff --git a/internal/pipeline/go_lsp_cross.go b/internal/pipeline/go_lsp_cross.go
deleted file mode 100644
index 710cd72f8..000000000
--- a/internal/pipeline/go_lsp_cross.go
+++ /dev/null
@@ -1,348 +0,0 @@
-package pipeline
-
-import (
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "log/slog"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// goLSPDefIndex indexes cross-file definitions by Go import path for LSP resolution.
-type goLSPDefIndex struct {
- // byImportPath maps Go import path → []CrossFileDef
- byImportPath map[string][]cbm.CrossFileDef
- // goModulePath is the Go module path from go.mod (e.g., "github.com/DeusData/...")
- goModulePath string
-}
-
-// buildGoLSPDefIndex builds the cross-file definition index for Go LSP resolution.
-// Called once before pass3 (passCalls). Scans all Go files in extractionCache.
-func (p *Pipeline) buildGoLSPDefIndex() *goLSPDefIndex {
- goModPath := readGoModulePath(p.RepoPath)
- if goModPath == "" {
- return nil
- }
-
- idx := &goLSPDefIndex{
- byImportPath: make(map[string][]cbm.CrossFileDef),
- goModulePath: goModPath,
- }
-
- for relPath, ext := range p.extractionCache {
- if ext.Language != lang.Go {
- continue
- }
- if ext.Result == nil || len(ext.Result.Definitions) == 0 {
- continue
- }
-
- // Compute Go import path for this file's package
- dir := filepath.Dir(relPath)
- var importPath string
- if dir == "." || dir == "" {
- importPath = goModPath
- } else {
- importPath = goModPath + "/" + filepath.ToSlash(dir)
- }
-
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- defs := cbm.DefsToLSPDefs(ext.Result.Definitions, moduleQN)
-
- // Enrich struct types with field definitions and interfaces with method names from Go source
- if len(defs) > 0 {
- enrichStructFieldDefs(p, relPath, defs)
- enrichInterfaceMethodNames(p, relPath, defs)
- idx.byImportPath[importPath] = append(idx.byImportPath[importPath], defs...)
- }
- }
-
- totalDefs := 0
- for _, defs := range idx.byImportPath {
- totalDefs += len(defs)
- }
- if totalDefs > 0 {
- slog.Info("go_lsp.cross_file.index",
- "packages", len(idx.byImportPath),
- "defs", totalDefs,
- )
- }
-
- return idx
-}
-
-// collectCrossFileDefs returns cross-file definitions for all imported packages.
-func (idx *goLSPDefIndex) collectCrossFileDefs(importMap map[string]string) []cbm.CrossFileDef {
- if idx == nil || len(importMap) == 0 {
- return nil
- }
-
- var result []cbm.CrossFileDef
- seen := make(map[string]bool)
-
- for _, goImportPath := range importMap {
- if seen[goImportPath] {
- continue
- }
- seen[goImportPath] = true
-
- // Check if this import path matches a project package
- if defs, ok := idx.byImportPath[goImportPath]; ok {
- // Rewrite QNs: the C resolver will look up "importPath.TypeName",
- // so cross-file defs need their QN prefixed with the Go import path.
- for i := range defs {
- cd := defs[i]
- cd.QualifiedName = requalifyForImport(defs[i].QualifiedName, defs[i].DefModuleQN, goImportPath)
- cd.DefModuleQN = goImportPath
- if cd.ReceiverType != "" {
- cd.ReceiverType = requalifyForImport(defs[i].ReceiverType, defs[i].DefModuleQN, goImportPath)
- }
- // Requalify embedded types
- if cd.EmbeddedTypes != "" {
- parts := strings.Split(cd.EmbeddedTypes, "|")
- for j, part := range parts {
- parts[j] = requalifyForImport(part, defs[i].DefModuleQN, goImportPath)
- }
- cd.EmbeddedTypes = strings.Join(parts, "|")
- }
- result = append(result, cd)
- }
- }
- }
-
- return result
-}
-
-// requalifyForImport replaces the module QN prefix in a qualified name with
-// the Go import path prefix so the C resolver can match it via import map lookup.
-// E.g., "proj.internal-store-store.go.Store" → "github.com/.../internal/store.Store"
-func requalifyForImport(qn, moduleQN, goImportPath string) string {
- if moduleQN == "" || !strings.HasPrefix(qn, moduleQN) {
- return qn
- }
- suffix := qn[len(moduleQN):]
- return goImportPath + suffix
-}
-
-// enrichStructFieldDefs parses Go source to extract struct field name:type pairs.
-// Populates FieldDefs on Type/Class CrossFileDef entries.
-func enrichStructFieldDefs(p *Pipeline, relPath string, defs []cbm.CrossFileDef) {
- // Collect struct type names that need field info
- structNames := make(map[string]int) // shortName -> index in defs
- for i := range defs {
- d := &defs[i]
- if (d.Label == "Type" || d.Label == "Class") && !d.IsInterface {
- structNames[d.ShortName] = i
- }
- }
- if len(structNames) == 0 {
- return
- }
-
- src := readFileSource(p, relPath)
- if len(src) == 0 {
- return
- }
-
- fset := token.NewFileSet()
- f, err := parser.ParseFile(fset, relPath, src, 0)
- if err != nil {
- return
- }
-
- for _, decl := range f.Decls {
- gd, ok := decl.(*ast.GenDecl)
- if !ok || gd.Tok != token.TYPE {
- continue
- }
- enrichStructFieldsFromGenDecl(gd, structNames, defs)
- }
-}
-
-// enrichStructFieldsFromGenDecl processes a single GenDecl to extract struct field definitions.
-func enrichStructFieldsFromGenDecl(gd *ast.GenDecl, structNames map[string]int, defs []cbm.CrossFileDef) {
- for _, spec := range gd.Specs {
- ts, ok := spec.(*ast.TypeSpec)
- if !ok {
- continue
- }
- idx, found := structNames[ts.Name.Name]
- if !found {
- continue
- }
- st, ok := ts.Type.(*ast.StructType)
- if !ok {
- continue
- }
- if fields := extractExportedStructFields(st); len(fields) > 0 {
- defs[idx].FieldDefs = strings.Join(fields, "|")
- }
- }
-}
-
-// extractExportedStructFields returns exported field name:type pairs from a struct.
-func extractExportedStructFields(st *ast.StructType) []string {
- var fields []string
- for _, field := range st.Fields.List {
- if len(field.Names) == 0 {
- continue // embedded field, skip
- }
- typeText := goTypeToString(field.Type)
- if typeText == "" {
- continue
- }
- for _, name := range field.Names {
- if !name.IsExported() {
- continue
- }
- fields = append(fields, name.Name+":"+typeText)
- }
- }
- return fields
-}
-
-// goTypeToString converts a Go AST type expression to a string representation
-// suitable for the LSP type resolver (e.g., "*Echo", "Binder", "[]string").
-func goTypeToString(expr ast.Expr) string {
- switch t := expr.(type) {
- case *ast.Ident:
- return t.Name
- case *ast.StarExpr:
- inner := goTypeToString(t.X)
- if inner == "" {
- return ""
- }
- return "*" + inner
- case *ast.ArrayType:
- elem := goTypeToString(t.Elt)
- if elem == "" {
- return ""
- }
- return "[]" + elem
- case *ast.SelectorExpr:
- pkg := goTypeToString(t.X)
- if pkg == "" {
- return ""
- }
- return pkg + "." + t.Sel.Name
- case *ast.MapType:
- k := goTypeToString(t.Key)
- v := goTypeToString(t.Value)
- if k == "" || v == "" {
- return ""
- }
- return fmt.Sprintf("map[%s]%s", k, v)
- case *ast.InterfaceType:
- return "interface{}"
- case *ast.FuncType:
- return "func"
- default:
- return ""
- }
-}
-
-// enrichInterfaceMethodNames parses Go source to extract interface method names.
-// Populates MethodNames on Interface CrossFileDef entries as "|"-separated strings.
-func enrichInterfaceMethodNames(p *Pipeline, relPath string, defs []cbm.CrossFileDef) {
- ifaceNames := make(map[string]int) // shortName -> index in defs
- for i := range defs {
- d := &defs[i]
- if d.IsInterface || d.Label == "Interface" {
- ifaceNames[d.ShortName] = i
- }
- }
- if len(ifaceNames) == 0 {
- return
- }
-
- src := readFileSource(p, relPath)
- if len(src) == 0 {
- return
- }
-
- fset := token.NewFileSet()
- f, err := parser.ParseFile(fset, relPath, src, 0)
- if err != nil {
- return
- }
-
- for _, decl := range f.Decls {
- gd, ok := decl.(*ast.GenDecl)
- if !ok || gd.Tok != token.TYPE {
- continue
- }
- enrichIfaceMethodsFromGenDecl(gd, ifaceNames, defs)
- }
-}
-
-// enrichIfaceMethodsFromGenDecl processes a single GenDecl to extract interface method names.
-func enrichIfaceMethodsFromGenDecl(gd *ast.GenDecl, ifaceNames map[string]int, defs []cbm.CrossFileDef) {
- for _, spec := range gd.Specs {
- ts, ok := spec.(*ast.TypeSpec)
- if !ok {
- continue
- }
- idx, found := ifaceNames[ts.Name.Name]
- if !found {
- continue
- }
- iface, ok := ts.Type.(*ast.InterfaceType)
- if !ok {
- continue
- }
- if methods := extractExportedIfaceMethods(iface); len(methods) > 0 {
- defs[idx].MethodNames = strings.Join(methods, "|")
- }
- }
-}
-
-// extractExportedIfaceMethods returns exported method names from an interface type.
-func extractExportedIfaceMethods(iface *ast.InterfaceType) []string {
- if iface.Methods == nil {
- return nil
- }
- var methods []string
- for _, m := range iface.Methods.List {
- for _, name := range m.Names {
- if name.IsExported() {
- methods = append(methods, name.Name)
- }
- }
- }
- return methods
-}
-
-// readGoModulePath reads the module path from go.mod in the given directory.
-func readGoModulePath(repoPath string) string {
- data, err := os.ReadFile(filepath.Join(repoPath, "go.mod"))
- if err != nil {
- return ""
- }
- for _, line := range strings.Split(string(data), "\n") {
- line = strings.TrimSpace(line)
- if strings.HasPrefix(line, "module ") {
- return strings.TrimSpace(strings.TrimPrefix(line, "module "))
- }
- }
- return ""
-}
-
-// readFileSource reads source from the in-memory sourceStore, falling back to disk.
-func readFileSource(p *Pipeline, relPath string) []byte {
- if src := p.getSource(relPath); len(src) > 0 {
- return src
- }
- // Fallback for files not in sourceStore (e.g., go.mod)
- data, err := os.ReadFile(filepath.Join(p.RepoPath, relPath))
- if err != nil {
- return nil
- }
- return data
-}
diff --git a/internal/pipeline/graph_buffer.go b/internal/pipeline/graph_buffer.go
deleted file mode 100644
index 1d941b172..000000000
--- a/internal/pipeline/graph_buffer.go
+++ /dev/null
@@ -1,589 +0,0 @@
-package pipeline
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "runtime"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// Compile-time assertion: *GraphBuffer implements store.StoreBackend.
-var _ store.StoreBackend = (*GraphBuffer)(nil)
-
-// GraphBuffer holds all nodes and edges in memory during the buffered indexing phase.
-// Implements store.StoreBackend so pipeline passes can run against it directly,
-// eliminating the need for an in-memory SQLite during full indexing.
-//
-// Assigns temporary IDs (sequential counter) that are remapped to real SQLite-assigned
-// IDs during FlushTo/DumpToSQLite.
-type GraphBuffer struct {
- project string
- rootPath string
- nextID int64
-
- // Primary indexes
- nodeByQN map[string]*store.Node
- nodeByID map[int64]*store.Node
-
- // Secondary node indexes
- nodesByLabel map[string][]*store.Node
- nodesByName map[string][]*store.Node
-
- // Edge storage
- edges []*store.Edge
- edgeByKey map[edgeKey]*store.Edge
-
- // Edge indexes
- edgesBySourceType map[int64]map[string][]*store.Edge // sourceID → type → edges
- edgesByTargetType map[int64]map[string][]*store.Edge // targetID → type → edges
- edgesByType map[string][]*store.Edge // edge type → edges
-}
-
-type edgeKey struct {
- SourceID int64
- TargetID int64
- Type string
-}
-
-func newGraphBuffer(project, rootPath string) *GraphBuffer {
- return &GraphBuffer{
- project: project,
- rootPath: rootPath,
- nextID: 1,
- nodeByQN: make(map[string]*store.Node),
- nodeByID: make(map[int64]*store.Node),
- nodesByLabel: make(map[string][]*store.Node),
- nodesByName: make(map[string][]*store.Node),
- edgeByKey: make(map[edgeKey]*store.Edge),
- edgesBySourceType: make(map[int64]map[string][]*store.Edge),
- edgesByTargetType: make(map[int64]map[string][]*store.Edge),
- edgesByType: make(map[string][]*store.Edge),
- }
-}
-
-// --- StoreBackend: Node methods ---
-
-// UpsertNode inserts or updates a node. Returns the temp ID.
-// Properties are JSON-round-tripped to normalize types (e.g., []string → []any),
-// matching the behavior of SQLite serialization/deserialization.
-func (b *GraphBuffer) UpsertNode(n *store.Node) (int64, error) {
- if existing, ok := b.nodeByQN[n.QualifiedName]; ok {
- // Update in-place (pointer is shared by secondary indexes).
- if existing.Label != n.Label {
- b.removeFromLabelIndex(existing.Label, existing.ID)
- b.nodesByLabel[n.Label] = append(b.nodesByLabel[n.Label], existing)
- }
- if existing.Name != n.Name {
- b.removeFromNameIndex(existing.Name, existing.ID)
- b.nodesByName[n.Name] = append(b.nodesByName[n.Name], existing)
- }
- existing.Label = n.Label
- existing.Name = n.Name
- existing.FilePath = n.FilePath
- existing.StartLine = n.StartLine
- existing.EndLine = n.EndLine
- if n.Properties != nil {
- existing.Properties = roundTripProps(n.Properties)
- }
- return existing.ID, nil
- }
-
- // New node: assign temp ID.
- id := b.nextID
- b.nextID++
- n.ID = id
- n.Project = b.project
- n.Properties = roundTripProps(n.Properties)
- b.nodeByQN[n.QualifiedName] = n
- b.nodeByID[id] = n
- b.nodesByLabel[n.Label] = append(b.nodesByLabel[n.Label], n)
- b.nodesByName[n.Name] = append(b.nodesByName[n.Name], n)
- return id, nil
-}
-
-// roundTripProps normalizes property types via JSON marshal/unmarshal.
-func roundTripProps(props map[string]any) map[string]any {
- if len(props) == 0 {
- return props
- }
- data, err := json.Marshal(props)
- if err != nil {
- return props
- }
- var result map[string]any
- if err := json.Unmarshal(data, &result); err != nil {
- return props
- }
- return result
-}
-
-// removeFromLabelIndex removes a node from the label secondary index by ID.
-func (b *GraphBuffer) removeFromLabelIndex(label string, id int64) {
- nodes := b.nodesByLabel[label]
- for i, n := range nodes {
- if n.ID == id {
- nodes[i] = nodes[len(nodes)-1]
- b.nodesByLabel[label] = nodes[:len(nodes)-1]
- return
- }
- }
-}
-
-// removeFromNameIndex removes a node from the name secondary index by ID.
-func (b *GraphBuffer) removeFromNameIndex(name string, id int64) {
- nodes := b.nodesByName[name]
- for i, n := range nodes {
- if n.ID == id {
- nodes[i] = nodes[len(nodes)-1]
- b.nodesByName[name] = nodes[:len(nodes)-1]
- return
- }
- }
-}
-
-// UpsertNodeBatch upserts multiple nodes and returns a QN → tempID map.
-func (b *GraphBuffer) UpsertNodeBatch(nodes []*store.Node) (map[string]int64, error) {
- result := make(map[string]int64, len(nodes))
- for _, n := range nodes {
- id, _ := b.UpsertNode(n)
- result[n.QualifiedName] = id
- }
- return result, nil
-}
-
-// FindNodeByID returns the node with the given temp ID.
-func (b *GraphBuffer) FindNodeByID(id int64) (*store.Node, error) {
- return b.nodeByID[id], nil
-}
-
-// FindNodeByQN returns the node with the given qualified name.
-// project param is ignored (buffer is single-project).
-func (b *GraphBuffer) FindNodeByQN(_, qn string) (*store.Node, error) {
- return b.nodeByQN[qn], nil
-}
-
-// FindNodesByLabel returns all nodes with the given label.
-// project param is ignored (buffer is single-project).
-func (b *GraphBuffer) FindNodesByLabel(_, label string) ([]*store.Node, error) {
- return b.nodesByLabel[label], nil
-}
-
-// FindNodesByName returns all nodes with the given name.
-// project param is ignored (buffer is single-project).
-func (b *GraphBuffer) FindNodesByName(_, name string) ([]*store.Node, error) {
- return b.nodesByName[name], nil
-}
-
-// FindNodesByIDs returns a map of nodeID → *Node for the given IDs.
-func (b *GraphBuffer) FindNodesByIDs(ids []int64) (map[int64]*store.Node, error) {
- result := make(map[int64]*store.Node, len(ids))
- for _, id := range ids {
- if n, ok := b.nodeByID[id]; ok {
- result[id] = n
- }
- }
- return result, nil
-}
-
-// FindNodeIDsByQNs returns a map of QN → tempID for the given qualified names.
-// project param is ignored (buffer is single-project).
-func (b *GraphBuffer) FindNodeIDsByQNs(_ string, qns []string) (map[string]int64, error) {
- result := make(map[string]int64, len(qns))
- for _, qn := range qns {
- if n, ok := b.nodeByQN[qn]; ok {
- result[qn] = n.ID
- }
- }
- return result, nil
-}
-
-// DeleteNodesByLabel deletes all nodes with the given label and cascade-deletes
-// any edges referencing the deleted node IDs.
-func (b *GraphBuffer) DeleteNodesByLabel(_, label string) error {
- nodes := b.nodesByLabel[label]
- if len(nodes) == 0 {
- return nil
- }
-
- // Build set of deleted node IDs
- deleted := make(map[int64]struct{}, len(nodes))
- for _, n := range nodes {
- deleted[n.ID] = struct{}{}
- delete(b.nodeByQN, n.QualifiedName)
- delete(b.nodeByID, n.ID)
- b.removeFromNameIndex(n.Name, n.ID)
- }
- delete(b.nodesByLabel, label)
-
- // Cascade-delete edges referencing deleted nodes
- b.cascadeDeleteEdges(deleted)
- return nil
-}
-
-// cascadeDeleteEdges removes all edges where SourceID or TargetID is in the deleted set.
-func (b *GraphBuffer) cascadeDeleteEdges(deletedNodes map[int64]struct{}) {
- // Sweep edges, remove any referencing deleted nodes
- kept := make([]*store.Edge, 0, len(b.edges))
- for _, e := range b.edges {
- _, srcDeleted := deletedNodes[e.SourceID]
- _, tgtDeleted := deletedNodes[e.TargetID]
- if srcDeleted || tgtDeleted {
- // Remove from all edge indexes
- key := edgeKey{e.SourceID, e.TargetID, e.Type}
- delete(b.edgeByKey, key)
- b.removeFromEdgeSourceType(e)
- b.removeFromEdgeTargetType(e)
- b.removeFromEdgeType(e)
- } else {
- kept = append(kept, e)
- }
- }
- b.edges = kept
-}
-
-func (b *GraphBuffer) removeFromEdgeSourceType(e *store.Edge) {
- if byType, ok := b.edgesBySourceType[e.SourceID]; ok {
- edges := byType[e.Type]
- for i, ee := range edges {
- if ee.ID == e.ID {
- edges[i] = edges[len(edges)-1]
- byType[e.Type] = edges[:len(edges)-1]
- return
- }
- }
- }
-}
-
-func (b *GraphBuffer) removeFromEdgeTargetType(e *store.Edge) {
- if byType, ok := b.edgesByTargetType[e.TargetID]; ok {
- edges := byType[e.Type]
- for i, ee := range edges {
- if ee.ID == e.ID {
- edges[i] = edges[len(edges)-1]
- byType[e.Type] = edges[:len(edges)-1]
- return
- }
- }
- }
-}
-
-func (b *GraphBuffer) removeFromEdgeType(e *store.Edge) {
- edges := b.edgesByType[e.Type]
- for i, ee := range edges {
- if ee.ID == e.ID {
- edges[i] = edges[len(edges)-1]
- b.edgesByType[e.Type] = edges[:len(edges)-1]
- return
- }
- }
-}
-
-// CountNodes returns the number of nodes in the buffer.
-func (b *GraphBuffer) CountNodes(_ string) (int, error) {
- return len(b.nodeByQN), nil
-}
-
-// --- StoreBackend: Edge methods ---
-
-// InsertEdge inserts an edge with dedup by (sourceID, targetID, type).
-// On conflict, merges properties. Returns the edge ID.
-func (b *GraphBuffer) InsertEdge(e *store.Edge) (int64, error) {
- key := edgeKey{e.SourceID, e.TargetID, e.Type}
- if existing, ok := b.edgeByKey[key]; ok {
- // Merge properties (emulates json_patch).
- if e.Properties != nil {
- if existing.Properties == nil {
- existing.Properties = make(map[string]any)
- }
- for k, v := range e.Properties {
- existing.Properties[k] = v
- }
- }
- return existing.ID, nil
- }
-
- // New edge: assign temp ID.
- id := b.nextID
- b.nextID++
- e.ID = id
- e.Project = b.project
- b.edges = append(b.edges, e)
- b.edgeByKey[key] = e
-
- // Update source type index
- if byType, ok := b.edgesBySourceType[e.SourceID]; ok {
- byType[e.Type] = append(byType[e.Type], e)
- } else {
- b.edgesBySourceType[e.SourceID] = map[string][]*store.Edge{e.Type: {e}}
- }
-
- // Update target type index
- if byType, ok := b.edgesByTargetType[e.TargetID]; ok {
- byType[e.Type] = append(byType[e.Type], e)
- } else {
- b.edgesByTargetType[e.TargetID] = map[string][]*store.Edge{e.Type: {e}}
- }
-
- // Update type index
- b.edgesByType[e.Type] = append(b.edgesByType[e.Type], e)
-
- return id, nil
-}
-
-// InsertEdgeBatch inserts multiple edges.
-func (b *GraphBuffer) InsertEdgeBatch(edges []*store.Edge) error {
- for _, e := range edges {
- if _, err := b.InsertEdge(e); err != nil {
- return err
- }
- }
- return nil
-}
-
-// FindEdgesBySourceAndType returns edges from sourceID with the given type.
-func (b *GraphBuffer) FindEdgesBySourceAndType(sourceID int64, edgeType string) ([]*store.Edge, error) {
- byType, ok := b.edgesBySourceType[sourceID]
- if !ok {
- return nil, nil
- }
- return byType[edgeType], nil
-}
-
-// FindEdgesByTargetAndType returns edges to targetID with the given type.
-func (b *GraphBuffer) FindEdgesByTargetAndType(targetID int64, edgeType string) ([]*store.Edge, error) {
- byType, ok := b.edgesByTargetType[targetID]
- if !ok {
- return nil, nil
- }
- return byType[edgeType], nil
-}
-
-// FindEdgesByType returns all edges of the given type.
-// project param is ignored (buffer is single-project).
-func (b *GraphBuffer) FindEdgesByType(_, edgeType string) ([]*store.Edge, error) {
- return b.edgesByType[edgeType], nil
-}
-
-// DeleteEdgesByType removes all edges of the given type from all indexes.
-func (b *GraphBuffer) DeleteEdgesByType(_, edgeType string) error {
- edges := b.edgesByType[edgeType]
- if len(edges) == 0 {
- return nil
- }
-
- // Remove from all indexes
- for _, e := range edges {
- key := edgeKey{e.SourceID, e.TargetID, e.Type}
- delete(b.edgeByKey, key)
- b.removeFromEdgeSourceType(e)
- b.removeFromEdgeTargetType(e)
- }
- delete(b.edgesByType, edgeType)
-
- // Rebuild edges slice without the deleted type
- kept := make([]*store.Edge, 0, len(b.edges)-len(edges))
- for _, e := range b.edges {
- if e.Type != edgeType {
- kept = append(kept, e)
- }
- }
- b.edges = kept
- return nil
-}
-
-// CountEdgesByType returns the number of edges of a given type.
-func (b *GraphBuffer) CountEdgesByType(_, edgeType string) (int, error) {
- return len(b.edgesByType[edgeType]), nil
-}
-
-// CountEdges returns the total number of edges in the buffer.
-func (b *GraphBuffer) CountEdges(_ string) (int, error) {
- return len(b.edges), nil
-}
-
-// --- StoreBackend: Project methods ---
-
-// GetProject returns a synthetic Project for the buffer.
-func (b *GraphBuffer) GetProject(_ string) (*store.Project, error) {
- return &store.Project{
- Name: b.project,
- IndexedAt: store.Now(),
- RootPath: b.rootPath,
- }, nil
-}
-
-// --- FlushTo (existing, used by incremental path and DumpToSQLite) ---
-
-// FlushTo writes all buffered nodes and edges to the SQLite store.
-// Drops indexes before bulk insert and recreates them after for O(N) index builds.
-// On a fresh DB (no existing data), skips the expensive DROP INDEX + DELETE steps.
-func (b *GraphBuffer) FlushTo(ctx context.Context, s *store.Store) error {
- t := time.Now()
-
- // 1. Drop user indexes so bulk INSERT doesn't maintain them.
- if err := s.DropUserIndexes(ctx); err != nil {
- return fmt.Errorf("drop indexes: %w", err)
- }
-
- // 2. Delete existing project data (skip on fresh DB — nothing to delete).
- existingCount, _ := s.CountNodes(b.project)
- if existingCount > 0 {
- if err := s.DeleteEdgesByProject(b.project); err != nil {
- return fmt.Errorf("delete edges: %w", err)
- }
- if err := s.DeleteNodesByProject(b.project); err != nil {
- return fmt.Errorf("delete nodes: %w", err)
- }
- }
-
- // 3. Bulk insert nodes (plain INSERT, no ON CONFLICT — table is empty for this project).
- nodes := b.allNodes()
- if err := s.BulkInsertNodes(ctx, nodes); err != nil {
- return fmt.Errorf("bulk insert nodes: %w", err)
- }
-
- // 4. Build QN → real SQLite ID map.
- qnToRealID, err := s.LoadNodeIDMap(ctx, b.project)
- if err != nil {
- return fmt.Errorf("load node id map: %w", err)
- }
-
- // 5. Build tempID → QN for edge remapping.
- tempToQN := make(map[int64]string, len(b.nodeByQN))
- for qn, n := range b.nodeByQN {
- tempToQN[n.ID] = qn
- }
-
- // 6. Remap edges from temp IDs to real SQLite IDs.
- remapped := make([]*store.Edge, 0, len(b.edges))
- skipped := 0
- for _, e := range b.edges {
- srcQN := tempToQN[e.SourceID]
- tgtQN := tempToQN[e.TargetID]
- realSrc := qnToRealID[srcQN]
- realTgt := qnToRealID[tgtQN]
- if realSrc == 0 || realTgt == 0 {
- skipped++
- continue
- }
- remapped = append(remapped, &store.Edge{
- Project: b.project,
- SourceID: realSrc,
- TargetID: realTgt,
- Type: e.Type,
- Properties: e.Properties,
- })
- }
-
- if err := s.BulkInsertEdges(ctx, remapped); err != nil {
- return fmt.Errorf("bulk insert edges: %w", err)
- }
-
- // 7. Recreate indexes (single sorted pass, O(N)).
- if err := s.CreateUserIndexes(ctx); err != nil {
- return fmt.Errorf("create indexes: %w", err)
- }
-
- slog.Info("graph_buffer.flush",
- "nodes", len(nodes),
- "edges", len(remapped),
- "skipped_edges", skipped,
- "elapsed", time.Since(t),
- )
- return nil
-}
-
-// DumpToSQLite writes the buffer contents directly as a SQLite .db file
-// using the C direct page writer. No SQL parser, no INSERTs, no B-tree
-// rebalancing. Constructs valid B-tree pages from pre-sorted data.
-// releaseIndexes frees secondary indexes that are only needed during passes.
-// Called before DumpToSQLite to reduce peak memory during the dump phase.
-func (b *GraphBuffer) releaseIndexes() {
- b.nodeByID = nil
- b.nodesByLabel = nil
- b.nodesByName = nil
- b.edges = nil
- b.edgesBySourceType = nil
- b.edgesByTargetType = nil
- b.edgesByType = nil
-}
-
-func (b *GraphBuffer) DumpToSQLite(path string) error {
- indexedAt := store.Now()
-
- // Assign sequential IDs and build lookup for edge remapping.
- tempToFinal := make(map[int64]int64, len(b.nodeByQN))
- dumpNodes := make([]cbm.DumpNode, 0, len(b.nodeByQN))
- finalID := int64(1)
- for _, n := range b.nodeByQN {
- tempToFinal[n.ID] = finalID
- dumpNodes = append(dumpNodes, cbm.DumpNode{
- ID: finalID,
- Project: b.project,
- Label: n.Label,
- Name: n.Name,
- QualifiedName: n.QualifiedName,
- FilePath: n.FilePath,
- StartLine: n.StartLine,
- EndLine: n.EndLine,
- Properties: marshalPropsString(n.Properties),
- })
- finalID++
- }
-
- // Remap edge IDs and collect.
- dumpEdges := make([]cbm.DumpEdge, 0, len(b.edgeByKey))
- edgeID := int64(1)
- for _, e := range b.edgeByKey {
- srcID, okS := tempToFinal[e.SourceID]
- tgtID, okT := tempToFinal[e.TargetID]
- if !okS || !okT {
- continue
- }
- urlPath, _ := e.Properties["url_path"].(string)
- dumpEdges = append(dumpEdges, cbm.DumpEdge{
- ID: edgeID,
- Project: b.project,
- SourceID: srcID,
- TargetID: tgtID,
- Type: e.Type,
- Properties: marshalPropsString(e.Properties),
- URLPath: urlPath,
- })
- edgeID++
- }
-
- // Release GraphBuffer maps — data is now in dumpNodes/dumpEdges.
- // This frees ~3GB for a Linux kernel-scale index.
- b.nodeByQN = nil
- b.edgeByKey = nil
- runtime.GC()
-
- return cbm.WriteDB(path, b.project, b.rootPath, indexedAt, dumpNodes, dumpEdges)
-}
-
-// marshalPropsString serializes properties to a JSON string.
-func marshalPropsString(props map[string]any) string {
- if len(props) == 0 {
- return "{}"
- }
- b, err := json.Marshal(props)
- if err != nil {
- return "{}"
- }
- return string(b)
-}
-
-// allNodes returns all nodes in the buffer as a slice.
-func (b *GraphBuffer) allNodes() []*store.Node {
- nodes := make([]*store.Node, 0, len(b.nodeByQN))
- for _, n := range b.nodeByQN {
- nodes = append(nodes, n)
- }
- return nodes
-}
diff --git a/internal/pipeline/implements.go b/internal/pipeline/implements.go
deleted file mode 100644
index 12f4e586c..000000000
--- a/internal/pipeline/implements.go
+++ /dev/null
@@ -1,417 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// ifaceMethodInfo holds a method name and its qualified name for OVERRIDE edge creation.
-type ifaceMethodInfo struct {
- name string
- qualifiedName string
-}
-
-// ifaceInfo holds an interface node and its required methods.
-type ifaceInfo struct {
- node *store.Node
- methods []ifaceMethodInfo
-}
-
-// passImplements detects interface satisfaction and creates IMPLEMENTS edges.
-// Supports Go (implicit, method-set matching) and explicit implements for
-// TypeScript, Java, C#, Kotlin, Scala, and Rust.
-func (p *Pipeline) passImplements() {
- slog.Info("pass5.implements")
-
- var linkCount, overrideCount int
-
- // Go: implicit interface satisfaction (existing)
- l, o := p.implementsGo()
- linkCount += l
- overrideCount += o
-
- // Explicit implements/extends via CBM base_classes data
- l, o = p.implementsExplicitCBM()
- linkCount += l
- overrideCount += o
-
- // Rust: impl Trait for Struct
- l, o = p.implementsRust()
- linkCount += l
- overrideCount += o
-
- slog.Info("pass5.implements.done", "links", linkCount, "overrides", overrideCount)
-}
-
-// implementsGo handles Go's implicit interface satisfaction via method sets.
-func (p *Pipeline) implementsGo() (linkCount, overrideCount int) {
- ifaces := p.collectGoInterfaces()
- if len(ifaces) == 0 {
- return 0, 0
- }
-
- structMethods, structQNPrefix := p.collectStructMethods()
- return p.matchImplements(ifaces, structMethods, structQNPrefix)
-}
-
-// collectGoInterfaces returns Go interfaces with their method names.
-func (p *Pipeline) collectGoInterfaces() []ifaceInfo {
- interfaces, findErr := p.Store.FindNodesByLabel(p.ProjectName, "Interface")
- if findErr != nil || len(interfaces) == 0 {
- return nil
- }
-
- var ifaces []ifaceInfo
- for _, iface := range interfaces {
- if !strings.HasSuffix(iface.FilePath, ".go") {
- continue
- }
-
- edges, edgeErr := p.Store.FindEdgesBySourceAndType(iface.ID, "DEFINES_METHOD")
- if edgeErr != nil || len(edges) == 0 {
- continue
- }
-
- var methods []ifaceMethodInfo
- for _, e := range edges {
- methodNode, _ := p.Store.FindNodeByID(e.TargetID)
- if methodNode != nil {
- methods = append(methods, ifaceMethodInfo{
- name: methodNode.Name,
- qualifiedName: methodNode.QualifiedName,
- })
- }
- }
-
- if len(methods) > 0 {
- ifaces = append(ifaces, ifaceInfo{node: iface, methods: methods})
- }
- }
- return ifaces
-}
-
-// collectStructMethods builds maps of receiver type -> method names and QN prefixes
-// from Go methods with receiver properties.
-func (p *Pipeline) collectStructMethods() (structMethods map[string]map[string]bool, structQNPrefix map[string]string) {
- methodNodes, findErr := p.Store.FindNodesByLabel(p.ProjectName, "Method")
- if findErr != nil {
- return nil, nil
- }
-
- structMethods = make(map[string]map[string]bool)
- structQNPrefix = make(map[string]string)
-
- for _, m := range methodNodes {
- if !strings.HasSuffix(m.FilePath, ".go") {
- continue
- }
- recv, ok := m.Properties["receiver"]
- if !ok {
- continue
- }
- recvStr, ok := recv.(string)
- if !ok || recvStr == "" {
- continue
- }
-
- typeName := extractReceiverType(recvStr)
- if typeName == "" {
- continue
- }
-
- if structMethods[typeName] == nil {
- structMethods[typeName] = make(map[string]bool)
- }
- structMethods[typeName][m.Name] = true
-
- if _, exists := structQNPrefix[typeName]; !exists {
- if idx := strings.LastIndex(m.QualifiedName, "."); idx > 0 {
- structQNPrefix[typeName] = m.QualifiedName[:idx]
- }
- }
- }
- return
-}
-
-// matchImplements checks each struct against each interface and creates IMPLEMENTS + OVERRIDE edges.
-func (p *Pipeline) matchImplements(
- ifaces []ifaceInfo,
- structMethods map[string]map[string]bool,
- structQNPrefix map[string]string,
-) (linkCount, overrideCount int) {
- for _, iface := range ifaces {
- for typeName, methodSet := range structMethods {
- if !satisfies(iface.methods, methodSet) {
- continue
- }
-
- structNode := p.findStructNode(typeName, structQNPrefix)
- if structNode == nil {
- continue
- }
-
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: structNode.ID,
- TargetID: iface.node.ID,
- Type: "IMPLEMENTS",
- })
- linkCount++
-
- overrideCount += p.createOverrideEdges(iface.methods, typeName, structQNPrefix)
- }
- }
- return linkCount, overrideCount
-}
-
-// createOverrideEdges creates OVERRIDE edges from struct methods to interface methods.
-func (p *Pipeline) createOverrideEdges(
- ifaceMethods []ifaceMethodInfo,
- typeName string,
- structQNPrefix map[string]string,
-) int {
- prefix, ok := structQNPrefix[typeName]
- if !ok {
- return 0
- }
-
- count := 0
- for _, im := range ifaceMethods {
- structMethodQN := prefix + "." + im.name
- structMethodNode, _ := p.Store.FindNodeByQN(p.ProjectName, structMethodQN)
- if structMethodNode == nil {
- continue
- }
-
- ifaceMethodNode, _ := p.Store.FindNodeByQN(p.ProjectName, im.qualifiedName)
- if ifaceMethodNode == nil {
- continue
- }
-
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: structMethodNode.ID,
- TargetID: ifaceMethodNode.ID,
- Type: "OVERRIDE",
- })
- count++
- }
- return count
-}
-
-// findStructNode looks up the struct/class node for a given receiver type name.
-func (p *Pipeline) findStructNode(typeName string, structQNPrefix map[string]string) *store.Node {
- if prefix, ok := structQNPrefix[typeName]; ok {
- structQN := prefix + "." + typeName
- if n, _ := p.Store.FindNodeByQN(p.ProjectName, structQN); n != nil {
- return n
- }
- }
-
- classes, _ := p.Store.FindNodesByLabel(p.ProjectName, "Class")
- for _, c := range classes {
- if c.Name == typeName && strings.HasSuffix(c.FilePath, ".go") {
- return c
- }
- }
- return nil
-}
-
-// extractReceiverType extracts the type name from a Go receiver string.
-// "(h *Handlers)" -> "Handlers", "(s Store)" -> "Store"
-func extractReceiverType(recv string) string {
- recv = strings.TrimSpace(recv)
- recv = strings.Trim(recv, "()")
- parts := strings.Fields(recv)
- if len(parts) == 0 {
- return ""
- }
- // Last field is the type, possibly with * prefix
- typeName := parts[len(parts)-1]
- typeName = strings.TrimPrefix(typeName, "*")
- return typeName
-}
-
-// satisfies checks if a set of method names includes all interface methods.
-func satisfies(ifaceMethods []ifaceMethodInfo, structMethodSet map[string]bool) bool {
- for _, m := range ifaceMethods {
- if !structMethodSet[m.name] {
- return false
- }
- }
- return true
-}
-
-// --- Explicit implements via CBM base_classes data ---
-
-// explicitImplementsExts maps languages to the extensions to check.
-var explicitImplementsExts = map[lang.Language]string{
- lang.TypeScript: ".ts",
- lang.TSX: ".tsx",
- lang.Java: ".java",
- lang.CSharp: ".cs",
- lang.Kotlin: ".kt",
- lang.Scala: ".scala",
- lang.PHP: ".php",
-}
-
-// implementsExplicitCBM detects explicit implements/extends relationships
-// using CBM-extracted base_classes data from Class/Interface nodes.
-func (p *Pipeline) implementsExplicitCBM() (linkCount, overrideCount int) {
- for _, label := range []string{"Class", "Interface"} {
- nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, classNode := range nodes {
- lc, oc := p.processExplicitBases(classNode)
- linkCount += lc
- overrideCount += oc
- }
- }
- return
-}
-
-// processExplicitBases links one class/interface node to all its base types.
-func (p *Pipeline) processExplicitBases(classNode *store.Node) (linkCount, overrideCount int) {
- ext := strings.ToLower(filepath.Ext(classNode.FilePath))
- fileLang, hasLang := lang.LanguageForExtension(ext)
- if !hasLang {
- return
- }
- if _, isExplicit := explicitImplementsExts[fileLang]; !isExplicit {
- return
- }
-
- baseClasses, ok := classNode.Properties["base_classes"]
- if !ok {
- return
- }
- baseList, ok := baseClasses.([]any)
- if !ok {
- return
- }
-
- moduleQN := fqn.ModuleQN(p.ProjectName, classNode.FilePath)
- importMap := p.importMaps[moduleQN]
-
- for _, bc := range baseList {
- baseName, ok := bc.(string)
- if !ok || baseName == "" {
- continue
- }
- ifaceQN := resolveAsClass(baseName, p.registry, moduleQN, importMap)
- if ifaceQN == "" {
- continue
- }
- ifaceNode, _ := p.Store.FindNodeByQN(p.ProjectName, ifaceQN)
- if ifaceNode == nil {
- continue
- }
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: classNode.ID,
- TargetID: ifaceNode.ID,
- Type: "IMPLEMENTS",
- })
- linkCount++
- overrideCount += p.createOverrideEdgesExplicit(classNode, ifaceNode)
- }
- return
-}
-
-// createOverrideEdgesExplicit creates OVERRIDE edges by matching method names
-// between a class and an interface.
-func (p *Pipeline) createOverrideEdgesExplicit(classNode, ifaceNode *store.Node) int {
- // Get interface methods
- ifaceEdges, err := p.Store.FindEdgesBySourceAndType(ifaceNode.ID, "DEFINES_METHOD")
- if err != nil || len(ifaceEdges) == 0 {
- return 0
- }
-
- // Get class methods
- classEdges, err := p.Store.FindEdgesBySourceAndType(classNode.ID, "DEFINES_METHOD")
- if err != nil || len(classEdges) == 0 {
- return 0
- }
-
- // Build class method name -> node ID map
- classMethodByName := make(map[string]int64)
- for _, e := range classEdges {
- methodNode, _ := p.Store.FindNodeByID(e.TargetID)
- if methodNode != nil {
- classMethodByName[methodNode.Name] = methodNode.ID
- }
- }
-
- count := 0
- for _, e := range ifaceEdges {
- ifaceMethodNode, _ := p.Store.FindNodeByID(e.TargetID)
- if ifaceMethodNode == nil {
- continue
- }
- classMethodID, ok := classMethodByName[ifaceMethodNode.Name]
- if !ok {
- continue
- }
-
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: classMethodID,
- TargetID: ifaceMethodNode.ID,
- Type: "OVERRIDE",
- })
- count++
- }
- return count
-}
-
-// --- Rust: impl Trait for Struct ---
-
-// implementsRust detects `impl Trait for Struct` from CBM extraction data.
-func (p *Pipeline) implementsRust() (linkCount, overrideCount int) {
- for relPath, ext := range p.extractionCache {
- if ext.Language != lang.Rust || ext.Result == nil {
- continue
- }
- if len(ext.Result.ImplTraits) == 0 {
- continue
- }
-
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- importMap := p.importMaps[moduleQN]
-
- for _, it := range ext.Result.ImplTraits {
- traitQN := resolveAsClass(it.TraitName, p.registry, moduleQN, importMap)
- if traitQN == "" {
- continue
- }
- structQN := resolveAsClass(it.StructName, p.registry, moduleQN, importMap)
- if structQN == "" {
- continue
- }
-
- traitDBNode, _ := p.Store.FindNodeByQN(p.ProjectName, traitQN)
- structDBNode, _ := p.Store.FindNodeByQN(p.ProjectName, structQN)
- if traitDBNode == nil || structDBNode == nil {
- continue
- }
-
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: structDBNode.ID,
- TargetID: traitDBNode.ID,
- Type: "IMPLEMENTS",
- })
- linkCount++
-
- overrideCount += p.createOverrideEdgesExplicit(structDBNode, traitDBNode)
- }
- }
- return
-}
diff --git a/internal/pipeline/implements_test.go b/internal/pipeline/implements_test.go
deleted file mode 100644
index 83f1ff6b1..000000000
--- a/internal/pipeline/implements_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package pipeline
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func TestPassImplementsCreatesOverrideEdges(t *testing.T) {
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- project := "test-proj"
- _ = s.UpsertProject(project, "/tmp/test")
-
- // Create interface node
- ifaceID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Interface", Name: "Reader",
- QualifiedName: "pkg.Reader", FilePath: "pkg/reader.go",
- })
-
- // Create interface method nodes
- readMethodID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Read",
- QualifiedName: "pkg.Reader.Read", FilePath: "pkg/reader.go",
- })
- closeMethodID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Close",
- QualifiedName: "pkg.Reader.Close", FilePath: "pkg/reader.go",
- })
-
- // DEFINES_METHOD edges (interface → method)
- _, _ = s.InsertEdge(&store.Edge{
- Project: project, SourceID: ifaceID, TargetID: readMethodID, Type: "DEFINES_METHOD",
- })
- _, _ = s.InsertEdge(&store.Edge{
- Project: project, SourceID: ifaceID, TargetID: closeMethodID, Type: "DEFINES_METHOD",
- })
-
- // Create struct (Class) node
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Class", Name: "FileReader",
- QualifiedName: "pkg.FileReader", FilePath: "pkg/filereader.go",
- })
-
- // Create struct method nodes with receiver property
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Read",
- QualifiedName: "pkg.FileReader.Read", FilePath: "pkg/filereader.go",
- Properties: map[string]any{"receiver": "(f *FileReader)"},
- })
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Close",
- QualifiedName: "pkg.FileReader.Close", FilePath: "pkg/filereader.go",
- Properties: map[string]any{"receiver": "(f *FileReader)"},
- })
-
- // Run passImplements
- p := &Pipeline{
- Store: s,
- ProjectName: project,
- }
- p.passImplements()
-
- // Verify IMPLEMENTS edge exists (struct → interface)
- structNode, _ := s.FindNodeByQN(project, "pkg.FileReader")
- if structNode == nil {
- t.Fatal("struct node not found")
- }
- implEdges, _ := s.FindEdgesBySourceAndType(structNode.ID, "IMPLEMENTS")
- if len(implEdges) != 1 {
- t.Fatalf("expected 1 IMPLEMENTS edge, got %d", len(implEdges))
- }
- if implEdges[0].TargetID != ifaceID {
- t.Errorf("IMPLEMENTS target should be interface, got %d", implEdges[0].TargetID)
- }
-
- // Verify OVERRIDE edges (struct_method → interface_method)
- structReadNode, _ := s.FindNodeByQN(project, "pkg.FileReader.Read")
- if structReadNode == nil {
- t.Fatal("struct Read method not found")
- }
- readOverrides, _ := s.FindEdgesBySourceAndType(structReadNode.ID, "OVERRIDE")
- if len(readOverrides) != 1 {
- t.Fatalf("expected 1 OVERRIDE edge for Read, got %d", len(readOverrides))
- }
- if readOverrides[0].TargetID != readMethodID {
- t.Errorf("OVERRIDE target should be interface Read method")
- }
-
- structCloseNode, _ := s.FindNodeByQN(project, "pkg.FileReader.Close")
- if structCloseNode == nil {
- t.Fatal("struct Close method not found")
- }
- closeOverrides, _ := s.FindEdgesBySourceAndType(structCloseNode.ID, "OVERRIDE")
- if len(closeOverrides) != 1 {
- t.Fatalf("expected 1 OVERRIDE edge for Close, got %d", len(closeOverrides))
- }
- if closeOverrides[0].TargetID != closeMethodID {
- t.Errorf("OVERRIDE target should be interface Close method")
- }
-}
-
-func TestPassImplementsNoOverrideWithoutMatch(t *testing.T) {
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- project := "test-proj"
- _ = s.UpsertProject(project, "/tmp/test")
-
- // Interface with 2 methods
- ifaceID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Interface", Name: "ReadWriter",
- QualifiedName: "pkg.ReadWriter", FilePath: "pkg/rw.go",
- })
- readID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Read",
- QualifiedName: "pkg.ReadWriter.Read", FilePath: "pkg/rw.go",
- })
- writeID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Write",
- QualifiedName: "pkg.ReadWriter.Write", FilePath: "pkg/rw.go",
- })
- _, _ = s.InsertEdge(&store.Edge{
- Project: project, SourceID: ifaceID, TargetID: readID, Type: "DEFINES_METHOD",
- })
- _, _ = s.InsertEdge(&store.Edge{
- Project: project, SourceID: ifaceID, TargetID: writeID, Type: "DEFINES_METHOD",
- })
-
- // Struct with only Read (missing Write) — should NOT implement
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Class", Name: "OnlyReader",
- QualifiedName: "pkg.OnlyReader", FilePath: "pkg/onlyreader.go",
- })
- _, _ = s.UpsertNode(&store.Node{
- Project: project, Label: "Method", Name: "Read",
- QualifiedName: "pkg.OnlyReader.Read", FilePath: "pkg/onlyreader.go",
- Properties: map[string]any{"receiver": "(o *OnlyReader)"},
- })
-
- p := &Pipeline{Store: s, ProjectName: project}
- p.passImplements()
-
- // No IMPLEMENTS or OVERRIDE edges should exist
- structNode, _ := s.FindNodeByQN(project, "pkg.OnlyReader")
- if structNode == nil {
- t.Fatal("struct not found")
- }
- implEdges, _ := s.FindEdgesBySourceAndType(structNode.ID, "IMPLEMENTS")
- if len(implEdges) != 0 {
- t.Errorf("expected 0 IMPLEMENTS edges, got %d", len(implEdges))
- }
-
- methodNode, _ := s.FindNodeByQN(project, "pkg.OnlyReader.Read")
- if methodNode == nil {
- t.Fatal("method not found")
- }
- overrideEdges, _ := s.FindEdgesBySourceAndType(methodNode.ID, "OVERRIDE")
- if len(overrideEdges) != 0 {
- t.Errorf("expected 0 OVERRIDE edges, got %d", len(overrideEdges))
- }
-}
diff --git a/internal/pipeline/imports.go b/internal/pipeline/imports.go
deleted file mode 100644
index 8445868e1..000000000
--- a/internal/pipeline/imports.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package pipeline
-
-import "log/slog"
-
-// logImportDrop logs when an import edge cannot be created because the target node wasn't found.
-func logImportDrop(moduleQN, localName, targetQN string) {
- slog.Debug("import.drop", "module", moduleQN, "local", localName, "target", targetQN)
-}
diff --git a/internal/pipeline/infrascan.go b/internal/pipeline/infrascan.go
deleted file mode 100644
index 5098019c5..000000000
--- a/internal/pipeline/infrascan.go
+++ /dev/null
@@ -1,563 +0,0 @@
-package pipeline
-
-import (
- "bufio"
- "bytes"
- "log/slog"
- "os"
- "path/filepath"
- "regexp"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// infraFile holds parsed metadata from an infrastructure file.
-type infraFile struct {
- relPath string
- infraType string
- properties map[string]any
-}
-
-// passInfraFiles detects infrastructure files, parses them,
-// and creates File + InfraFile nodes for each.
-// Uses sourceStore when available (RAM path), falls back to filepath.Walk.
-func (p *Pipeline) passInfraFiles() {
- var infras []infraFile
-
- if p.sourceStore != nil {
- infras = p.scanInfraFromRAM()
- } else {
- infras = p.scanInfraFromDisk()
- }
-
- if len(infras) == 0 {
- return
- }
-
- for _, inf := range infras {
- p.upsertInfraNodes(inf)
- }
- slog.Info("pass4.infra", "nodes", len(infras))
-}
-
-// scanInfraFromRAM iterates sourceStore keys and parses infra files from RAM.
-func (p *Pipeline) scanInfraFromRAM() []infraFile {
- var infras []infraFile
- for relPath := range p.sourceStore {
- name := filepath.Base(relPath)
- source := p.getSource(relPath)
- if len(source) == 0 || len(source) > 1<<20 {
- continue
- }
- infras = append(infras, parseInfraFileFromSource(source, relPath, name)...)
- }
- return infras
-}
-
-// scanInfraFromDisk walks the filesystem and parses infra files from disk.
-func (p *Pipeline) scanInfraFromDisk() []infraFile {
- var infras []infraFile
- _ = filepath.Walk(p.RepoPath, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- if info.IsDir() {
- if discover.IGNORE_PATTERNS[info.Name()] {
- return filepath.SkipDir
- }
- return nil
- }
- for suffix := range discover.IGNORE_SUFFIXES {
- if strings.HasSuffix(info.Name(), suffix) {
- return nil
- }
- }
- if info.Size() > 1<<20 {
- return nil
- }
-
- relPath, _ := filepath.Rel(p.RepoPath, path)
- if relPath == "" {
- return nil
- }
- relPath = filepath.ToSlash(relPath)
-
- infras = append(infras, parseInfraFile(path, relPath, info.Name())...)
- return nil
- })
- return infras
-}
-
-// parseInfraFileFromSource routes a file from RAM to the appropriate parser.
-func parseInfraFileFromSource(source []byte, relPath, name string) []infraFile {
- lower := strings.ToLower(name)
- ext := strings.ToLower(filepath.Ext(name))
-
- switch {
- case isDockerfile(lower):
- return parseDockerfileFromSource(source, relPath)
- case isComposeFile(lower):
- return parseComposeFileFromSource(source, relPath)
- case isCloudbuildFile(lower):
- return parseCloudbuildFileFromSource(source, relPath)
- case isEnvFile(lower):
- return parseDotenvFileFromSource(source, relPath)
- case ext == ".tf":
- return parseTerraformFileFromSource(source, relPath)
- case isShellScript(lower, ext):
- return parseShellScriptFromSource(source, relPath)
- default:
- return nil
- }
-}
-
-// parseInfraFile routes a file to the appropriate parser based on its name.
-func parseInfraFile(absPath, relPath, name string) []infraFile {
- lower := strings.ToLower(name)
-
- ext := strings.ToLower(filepath.Ext(name))
-
- switch {
- case isDockerfile(lower):
- return parseDockerfile(absPath, relPath)
- case isComposeFile(lower):
- return parseComposeFile(absPath, relPath)
- case isCloudbuildFile(lower):
- return parseCloudbuildFile(absPath, relPath)
- case isEnvFile(lower):
- return parseDotenvFile(absPath, relPath)
- case ext == ".tf":
- return parseTerraformFile(absPath, relPath)
- case isShellScript(lower, ext):
- return parseShellScript(absPath, relPath)
- default:
- return nil
- }
-}
-
-// isComposeFile returns true for docker-compose/compose YAML files.
-func isComposeFile(name string) bool {
- lower := strings.ToLower(name)
- if strings.HasPrefix(lower, "docker-compose") || lower == "compose.yml" || lower == "compose.yaml" {
- ext := filepath.Ext(lower)
- return ext == ".yml" || ext == ".yaml"
- }
- return false
-}
-
-// isCloudbuildFile returns true for cloudbuild YAML files.
-func isCloudbuildFile(name string) bool {
- lower := strings.ToLower(name)
- if strings.HasPrefix(lower, "cloudbuild") {
- ext := filepath.Ext(lower)
- return ext == ".yml" || ext == ".yaml"
- }
- return false
-}
-
-// upsertInfraNodes creates a File node (for search_code) and an InfraFile node
-// (for structured graph queries) for each infrastructure file.
-func (p *Pipeline) upsertInfraNodes(inf infraFile) {
- // File node — enables search_code (which queries label="File")
- fileQN := fqn.Compute(p.ProjectName, inf.relPath, "") + ".__file__"
- _, _ = p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
- Label: "File",
- Name: filepath.Base(inf.relPath),
- QualifiedName: fileQN,
- FilePath: inf.relPath,
- Properties: map[string]any{"extension": filepath.Ext(inf.relPath)},
- })
-
- // InfraFile node — structured metadata queryable via query_graph
- infraQN := p.infraQN(inf.relPath, inf.properties)
- _, _ = p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
- Label: "InfraFile",
- Name: filepath.Base(inf.relPath),
- QualifiedName: infraQN,
- FilePath: inf.relPath,
- Properties: inf.properties,
- })
-}
-
-// infraQN builds the qualified name for an InfraFile node.
-// For compose services: project.path.docker-compose::service-name
-// For others: project.path.__infra__
-func (p *Pipeline) infraQN(relPath string, props map[string]any) string {
- base := fqn.Compute(p.ProjectName, relPath, "")
-
- // Compose services get a per-service QN suffix
- if sn, ok := props["service_name"].(string); ok && props["infra_type"] == "compose-service" {
- return base + "::" + sn
- }
- return base + ".__infra__"
-}
-
-// --- Dockerfile parser (regex) ---
-
-var (
- reFrom = regexp.MustCompile(`(?i)^FROM\s+(\S+)(?:\s+AS\s+(\w+))?`)
- reExpose = regexp.MustCompile(`(?i)^EXPOSE\s+(.+)`)
- reEnv = regexp.MustCompile(`(?i)^ENV\s+(\w+)[= ](.+)`)
- reArg = regexp.MustCompile(`(?i)^ARG\s+(\w+)(?:=(.+))?`)
- reWorkdir = regexp.MustCompile(`(?i)^WORKDIR\s+(.+)`)
- reCmd = regexp.MustCompile(`(?i)^CMD\s+(.+)`)
- reEntrypoint = regexp.MustCompile(`(?i)^ENTRYPOINT\s+(.+)`)
- reUser = regexp.MustCompile(`(?i)^USER\s+(\w+)`)
- reHealthcheck = regexp.MustCompile(`(?i)^HEALTHCHECK\s+.*CMD\s+(.+)`)
-)
-
-func parseDockerfile(absPath, relPath string) []infraFile {
- f, err := os.Open(absPath)
- if err != nil {
- return nil
- }
- defer f.Close()
- return parseDockerfileScanner(bufio.NewScanner(f), relPath)
-}
-
-func parseDockerfileFromSource(source []byte, relPath string) []infraFile {
- return parseDockerfileScanner(bufio.NewScanner(bytes.NewReader(source)), relPath)
-}
-
-func parseDockerfileScanner(scanner *bufio.Scanner, relPath string) []infraFile {
- var d dockerfileState
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
- d.parseLine(line)
- }
-
- props := d.toProperties()
- if len(props) == 0 {
- return nil
- }
- return []infraFile{{relPath: relPath, infraType: "dockerfile", properties: props}}
-}
-
-// dockerfileState accumulates parsed Dockerfile directives.
-type dockerfileState struct {
- stages []map[string]string
- ports []string
- envVars map[string]string
- args []string
- workdir string
- cmd string
- entry string
- health string
- user string
-}
-
-func (d *dockerfileState) parseLine(line string) {
- d.parseFrom(line)
- d.parseExpose(line)
- d.parseEnvArg(line)
- d.parseDirectives(line)
-}
-
-func (d *dockerfileState) parseFrom(line string) {
- if m := reFrom.FindStringSubmatch(line); m != nil {
- stage := map[string]string{"image": m[1]}
- if m[2] != "" {
- stage["name"] = m[2]
- }
- d.stages = append(d.stages, stage)
- }
-}
-
-func (d *dockerfileState) parseExpose(line string) {
- if m := reExpose.FindStringSubmatch(line); m != nil {
- ports := strings.Fields(m[1])
- for _, port := range ports {
- // Strip protocol suffix (e.g. 8080/tcp)
- port = strings.Split(port, "/")[0]
- d.ports = append(d.ports, port)
- }
- }
-}
-
-func (d *dockerfileState) parseEnvArg(line string) {
- if m := reEnv.FindStringSubmatch(line); m != nil {
- key, val := m[1], strings.TrimSpace(m[2])
- if !isSecretBinding(key, val) {
- if d.envVars == nil {
- d.envVars = make(map[string]string)
- }
- d.envVars[key] = val
- }
- }
- if m := reArg.FindStringSubmatch(line); m != nil {
- d.args = append(d.args, m[1])
- }
-}
-
-func (d *dockerfileState) parseDirectives(line string) {
- if m := reWorkdir.FindStringSubmatch(line); m != nil {
- d.workdir = strings.TrimSpace(m[1])
- }
- if m := reCmd.FindStringSubmatch(line); m != nil {
- d.cmd = cleanJSONBrackets(strings.TrimSpace(m[1]))
- }
- if m := reEntrypoint.FindStringSubmatch(line); m != nil {
- d.entry = cleanJSONBrackets(strings.TrimSpace(m[1]))
- }
- if m := reUser.FindStringSubmatch(line); m != nil {
- d.user = m[1]
- }
- if m := reHealthcheck.FindStringSubmatch(line); m != nil {
- d.health = strings.TrimSpace(m[1])
- }
-}
-
-func (d *dockerfileState) toProperties() map[string]any {
- if len(d.stages) == 0 {
- return nil
- }
-
- props := map[string]any{
- "infra_type": "dockerfile",
- }
-
- // base_image = last stage's image (final runtime image)
- lastImage := d.stages[len(d.stages)-1]["image"]
- props["base_image"] = lastImage
-
- // base_images = all unique images
- images := make([]string, 0, len(d.stages))
- for _, s := range d.stages {
- images = append(images, s["image"])
- }
- props["base_images"] = images
-
- // stages with name/image
- props["stages"] = d.stages
-
- setNonEmpty(props, "exposed_ports", d.ports)
- setNonEmptyMap(props, "env_vars", d.envVars)
- setNonEmpty(props, "build_args", d.args)
- setNonEmptyStr(props, "workdir", d.workdir)
- setNonEmptyStr(props, "cmd", d.cmd)
- setNonEmptyStr(props, "entrypoint", d.entry)
- setNonEmptyStr(props, "healthcheck", d.health)
- setNonEmptyStr(props, "user", d.user)
-
- return props
-}
-
-// --- .env file parser ---
-
-var reDotenvLine = regexp.MustCompile(`^([A-Za-z_]\w*)=(.*)$`)
-
-func parseDotenvFile(absPath, relPath string) []infraFile {
- f, err := os.Open(absPath)
- if err != nil {
- return nil
- }
- defer f.Close()
- return parseDotenvScanner(bufio.NewScanner(f), relPath)
-}
-
-func parseDotenvFileFromSource(source []byte, relPath string) []infraFile {
- return parseDotenvScanner(bufio.NewScanner(bytes.NewReader(source)), relPath)
-}
-
-func parseDotenvScanner(scanner *bufio.Scanner, relPath string) []infraFile {
- envVars := make(map[string]string)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
- if m := reDotenvLine.FindStringSubmatch(line); m != nil {
- key, val := m[1], strings.Trim(m[2], `"'`)
- if !isSecretBinding(key, val) {
- envVars[key] = val
- }
- }
- }
-
- if len(envVars) == 0 {
- return nil
- }
-
- props := map[string]any{
- "infra_type": "env",
- "env_vars": envVars,
- }
- return []infraFile{{relPath: relPath, infraType: "env", properties: props}}
-}
-
-// --- Shell script parser ---
-
-// isShellScript returns true for shell script files.
-func isShellScript(name, ext string) bool {
- _ = name // reserved for future name-based detection
- return ext == ".sh" || ext == ".bash" || ext == ".zsh"
-}
-
-var (
- reShebang = regexp.MustCompile(`^#!\s*(.+)`)
- reExportVar = regexp.MustCompile(`^export\s+(\w+)=(.*)`)
- reShellVar = regexp.MustCompile(`^(\w+)=["']?([^"'\n]*)["']?`)
- reSourceFile = regexp.MustCompile(`^(?:source|\.) ["']?(\S+)["']?`)
- reDockerCmd = regexp.MustCompile(`^(docker(?:-compose)?)\s+(\w+)`)
-)
-
-func parseShellScript(absPath, relPath string) []infraFile {
- f, err := os.Open(absPath)
- if err != nil {
- return nil
- }
- defer f.Close()
- return parseShellScanner(bufio.NewScanner(f), relPath)
-}
-
-func parseShellScriptFromSource(source []byte, relPath string) []infraFile {
- return parseShellScanner(bufio.NewScanner(bytes.NewReader(source)), relPath)
-}
-
-func parseShellScanner(scanner *bufio.Scanner, relPath string) []infraFile {
- var st shellState
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- st.parseLine(line)
- }
-
- props := st.toProperties()
- if len(props) <= 1 {
- return nil
- }
- return []infraFile{{relPath: relPath, infraType: "shell", properties: props}}
-}
-
-// shellState accumulates parsed shell script metadata.
-type shellState struct {
- shebang string
- envVars map[string]string
- sources []string
- dockerCmds []string
-}
-
-func (s *shellState) parseLine(line string) {
- if line == "" {
- return
- }
-
- // Shebang (first non-empty line starting with #!)
- if s.shebang == "" {
- if m := reShebang.FindStringSubmatch(line); m != nil {
- s.shebang = strings.TrimSpace(m[1])
- return
- }
- }
-
- // Skip comments
- if strings.HasPrefix(line, "#") {
- return
- }
-
- s.parseVarsAndCmds(line)
-}
-
-func (s *shellState) parseVarsAndCmds(line string) {
- // Exported env vars
- if m := reExportVar.FindStringSubmatch(line); m != nil {
- s.addEnvVar(m[1], strings.Trim(m[2], `"'`))
- return
- }
-
- // Plain var assignments (only at line start, not inside commands)
- if m := reShellVar.FindStringSubmatch(line); m != nil && !strings.Contains(line, " ") {
- s.addEnvVar(m[1], m[2])
- return
- }
-
- // Source/dot includes
- if m := reSourceFile.FindStringSubmatch(line); m != nil {
- s.sources = append(s.sources, m[1])
- return
- }
-
- // Docker commands
- if m := reDockerCmd.FindStringSubmatch(line); m != nil {
- s.dockerCmds = append(s.dockerCmds, m[1]+" "+m[2])
- }
-}
-
-func (s *shellState) addEnvVar(key, val string) {
- if isSecretBinding(key, val) {
- return
- }
- if s.envVars == nil {
- s.envVars = make(map[string]string)
- }
- s.envVars[key] = val
-}
-
-func (s *shellState) toProperties() map[string]any {
- props := map[string]any{
- "infra_type": "shell",
- }
- setNonEmptyStr(props, "shebang", s.shebang)
- setNonEmptyMap(props, "env_vars", s.envVars)
- setNonEmpty(props, "sources", s.sources)
- setNonEmpty(props, "docker_commands", s.dockerCmds)
- return props
-}
-
-// --- Property helpers ---
-
-func setNonEmpty(m map[string]any, key string, val []string) {
- if len(val) > 0 {
- m[key] = val
- }
-}
-
-func setNonEmptyMap(m map[string]any, key string, val map[string]string) {
- if len(val) > 0 {
- m[key] = val
- }
-}
-
-func setNonEmptyStr(m map[string]any, key, val string) {
- if val != "" {
- m[key] = val
- }
-}
-
-// cleanJSONBrackets strips JSON array brackets from CMD/ENTRYPOINT values.
-// e.g. ["./app", "--flag"] → ./app --flag
-func cleanJSONBrackets(s string) string {
- if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
- inner := s[1 : len(s)-1]
- inner = strings.ReplaceAll(inner, `"`, "")
- inner = strings.ReplaceAll(inner, ",", " ")
- return collapseSpaces(strings.TrimSpace(inner))
- }
- return s
-}
-
-// collapseSpaces replaces runs of whitespace with a single space.
-func collapseSpaces(s string) string {
- var b strings.Builder
- b.Grow(len(s))
- inSpace := false
- for _, r := range s {
- if r == ' ' || r == '\t' {
- if !inSpace {
- b.WriteByte(' ')
- inSpace = true
- }
- } else {
- b.WriteRune(r)
- inSpace = false
- }
- }
- return b.String()
-}
diff --git a/internal/pipeline/infrascan_test.go b/internal/pipeline/infrascan_test.go
deleted file mode 100644
index ec1146233..000000000
--- a/internal/pipeline/infrascan_test.go
+++ /dev/null
@@ -1,1032 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// --- Dockerfile parser tests ---
-
-func TestParseDockerfile(t *testing.T) {
- tests := []struct {
- name string
- content string
- check func(t *testing.T, props map[string]any)
- }{
- {
- name: "multi-stage with all directives",
- content: `FROM golang:1.23-alpine AS builder
-WORKDIR /app
-ARG SSH_PRIVATE_KEY
-RUN go build -o server .
-
-FROM alpine:3.19
-WORKDIR /usr/app
-ENV PORT=8080
-ENV PYTHONUNBUFFERED=1
-EXPOSE 8080 443
-USER appuser
-CMD ["./server"]
-HEALTHCHECK CMD wget http://localhost:8080/health
-`,
- check: func(t *testing.T, props map[string]any) {
- t.Helper()
- assertEqual(t, props["infra_type"], "dockerfile")
- assertEqual(t, props["base_image"], "alpine:3.19")
- assertSliceContains(t, props["base_images"], "golang:1.23-alpine")
- assertSliceContains(t, props["base_images"], "alpine:3.19")
- assertSliceContains(t, props["exposed_ports"], "8080")
- assertSliceContains(t, props["exposed_ports"], "443")
- assertEqual(t, props["workdir"], "/usr/app")
- assertEqual(t, props["user"], "appuser")
- assertEqual(t, props["cmd"], "./server")
- assertEqual(t, props["healthcheck"], "wget http://localhost:8080/health")
-
- envVars := requireMapStringString(t, props["env_vars"])
- assertEqual(t, envVars["PORT"], "8080")
- assertEqual(t, envVars["PYTHONUNBUFFERED"], "1")
-
- assertSliceContains(t, props["build_args"], "SSH_PRIVATE_KEY")
- },
- },
- {
- name: "single stage with entrypoint",
- content: `FROM python:3.9-slim
-ENTRYPOINT ["python", "main.py"]
-`,
- check: func(t *testing.T, props map[string]any) {
- t.Helper()
- assertEqual(t, props["base_image"], "python:3.9-slim")
- assertEqual(t, props["entrypoint"], "python main.py")
-
- stages, ok := props["stages"].([]map[string]string)
- if !ok {
- t.Fatal("stages is not []map[string]string")
- }
- if len(stages) != 1 {
- t.Fatalf("stages len: got %d, want 1", len(stages))
- }
- },
- },
- {
- name: "secret env vars filtered",
- content: `FROM node:20
-ENV API_KEY=sk-1234567890abcdef12345
-ENV DATABASE_URL=https://db.example.com
-ENV JWT_SECRET=supersecret
-`,
- check: func(t *testing.T, props map[string]any) {
- t.Helper()
- envVars := requireMapStringString(t, props["env_vars"])
- if _, ok := envVars["API_KEY"]; ok {
- t.Error("API_KEY should be filtered as secret value")
- }
- if _, ok := envVars["JWT_SECRET"]; ok {
- t.Error("JWT_SECRET should be filtered as secret key")
- }
- assertEqual(t, envVars["DATABASE_URL"], "https://db.example.com")
- },
- },
- {
- name: "expose with protocol suffix",
- content: `FROM nginx:latest
-EXPOSE 80/tcp 443/tcp
-`,
- check: func(t *testing.T, props map[string]any) {
- t.Helper()
- assertSliceContains(t, props["exposed_ports"], "80")
- assertSliceContains(t, props["exposed_ports"], "443")
- },
- },
- {
- name: "ENV space-separated format",
- content: `FROM python:3.9
-ENV PYTHONPATH /usr/app
-`,
- check: func(t *testing.T, props map[string]any) {
- t.Helper()
- envVars := requireMapStringString(t, props["env_vars"])
- assertEqual(t, envVars["PYTHONPATH"], "/usr/app")
- },
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- path := writeTempFile(t, "Dockerfile", tt.content)
- result := parseDockerfile(path, "Dockerfile")
- if len(result) == 0 {
- t.Fatal("expected at least one result")
- }
- tt.check(t, result[0].properties)
- })
- }
-}
-
-func TestParseDockerfileEmpty(t *testing.T) {
- path := writeTempFile(t, "Dockerfile", "# just a comment\n")
- result := parseDockerfile(path, "Dockerfile")
- if len(result) != 0 {
- t.Errorf("expected empty result for comment-only Dockerfile, got %d", len(result))
- }
-}
-
-// --- docker-compose parser tests ---
-
-func TestParseComposeFile(t *testing.T) {
- content := `
-services:
- auth-service:
- build:
- context: ./auth-service
- ports:
- - "8080:8080"
- environment:
- PORT: "8080"
- JWT_SECRET: "sk-1234567890abcdefghijkl"
- depends_on:
- - db
- networks:
- - backend
- container_name: my-auth
- volumes:
- - ./data:/app/data
-
- db:
- image: postgres:15-alpine
- expose:
- - "5432"
- environment:
- - POSTGRES_DB=mydb
- - POSTGRES_PASSWORD=secret-should-filter
-`
-
- path := writeTempFile(t, "docker-compose.yml", content)
- results := parseComposeFile(path, "docker-compose.yml")
- if len(results) != 2 {
- t.Fatalf("expected 2 services, got %d", len(results))
- }
-
- // Find auth-service
- var auth, db *infraFile
- for i := range results {
- sn, ok := results[i].properties["service_name"].(string)
- if !ok {
- t.Fatal("service_name is not a string")
- }
- switch sn {
- case "auth-service":
- auth = &results[i]
- case "db":
- db = &results[i]
- }
- }
-
- if auth == nil || db == nil {
- t.Fatal("missing expected services")
- }
-
- // auth-service checks
- assertEqual(t, auth.properties["infra_type"], "compose-service")
- assertEqual(t, auth.properties["build_context"], "./auth-service")
- assertSliceContains(t, auth.properties["ports"], "8080:8080")
- assertEqual(t, auth.properties["container_name"], "my-auth")
-
- authEnv := requireMapStringString(t, auth.properties["environment"])
- assertEqual(t, authEnv["PORT"], "8080")
- if _, ok := authEnv["JWT_SECRET"]; ok {
- t.Error("JWT_SECRET should be filtered")
- }
-
- assertSliceContains(t, auth.properties["depends_on"], "db")
- assertSliceContains(t, auth.properties["networks"], "backend")
-
- // db checks
- assertEqual(t, db.properties["image"], "postgres:15-alpine")
- assertSliceContains(t, db.properties["expose"], "5432")
-}
-
-func TestParseComposeMapDependsOn(t *testing.T) {
- content := `
-services:
- web:
- image: nginx:latest
- depends_on:
- api:
- condition: service_healthy
- cache:
- condition: service_started
-`
- path := writeTempFile(t, "docker-compose.yml", content)
- results := parseComposeFile(path, "docker-compose.yml")
- if len(results) != 1 {
- t.Fatalf("expected 1 service, got %d", len(results))
- }
- deps, ok := results[0].properties["depends_on"].([]string)
- if !ok {
- t.Fatal("depends_on is not []string")
- }
- if len(deps) != 2 {
- t.Fatalf("expected 2 deps, got %d", len(deps))
- }
-}
-
-func TestParseComposeStringBuild(t *testing.T) {
- content := `
-services:
- app:
- build: ./myapp
-`
- path := writeTempFile(t, "docker-compose.yml", content)
- results := parseComposeFile(path, "docker-compose.yml")
- if len(results) != 1 {
- t.Fatalf("expected 1 service, got %d", len(results))
- }
- assertEqual(t, results[0].properties["build_context"], "./myapp")
-}
-
-// --- cloudbuild parser tests ---
-
-func TestParseCloudbuildFile(t *testing.T) {
- content := `
-substitutions:
- _SERVICE_NAME: order-processor
- _REGION: europe-west3
-
-steps:
- - name: gcr.io/cloud-builders/docker
- args: ['build', '-t', 'eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME', '.']
-
- - name: gcr.io/google.com/cloudsdktool/cloud-sdk
- args:
- - gcloud
- - run
- - deploy
- - $_SERVICE_NAME
- - --image=eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME
- - --region=$_REGION
- - --cpu=2
- - --memory=4Gi
- - --concurrency=1
- - --max-instances=1
- - --timeout=3600s
- - --ingress=internal
- - --set-env-vars=SOURCE_ENTITY=$_SERVICE_NAME,LOG_LEVEL=INFO
-
-images:
- - eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME
-`
-
- path := writeTempFile(t, "cloudbuild.yaml", content)
- results := parseCloudbuildFile(path, "cloudbuild.yaml")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
-
- props := results[0].properties
- assertEqual(t, props["infra_type"], "cloudbuild")
- assertEqual(t, props["service_name"], "order-processor")
- assertEqual(t, props["deploy_region"], "$_REGION")
- assertEqual(t, props["deploy_cpu"], "2")
- assertEqual(t, props["deploy_memory"], "4Gi")
- assertEqual(t, props["deploy_concurrency"], "1")
- assertEqual(t, props["deploy_max_instances"], "1")
- assertEqual(t, props["deploy_timeout"], "3600s")
- assertEqual(t, props["deploy_ingress"], "internal")
- assertEqual(t, props["image_registry"], "eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME")
-
- envVars := requireMapStringString(t, props["deploy_env_vars"])
- assertEqual(t, envVars["SOURCE_ENTITY"], "$_SERVICE_NAME")
- assertEqual(t, envVars["LOG_LEVEL"], "INFO")
-}
-
-func TestParseCloudbuildSeparateFlags(t *testing.T) {
- content := `
-steps:
- - name: gcr.io/google.com/cloudsdktool/cloud-sdk
- args:
- - gcloud
- - run
- - deploy
- - my-service
- - --region
- - us-central1
- - --memory
- - 1Gi
-`
- path := writeTempFile(t, "cloudbuild.yaml", content)
- results := parseCloudbuildFile(path, "cloudbuild.yaml")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
- props := results[0].properties
- assertEqual(t, props["deploy_region"], "us-central1")
- assertEqual(t, props["deploy_memory"], "1Gi")
-}
-
-// --- .env file parser tests ---
-
-func TestParseDotenvFile(t *testing.T) {
- content := `# Database config
-DATABASE_HOST=localhost
-DATABASE_PORT=5432
-DATABASE_NAME=mydb
-API_SECRET=should-not-appear
-PLAIN_VALUE=hello world
-`
- path := writeTempFile(t, ".env", content)
- results := parseDotenvFile(path, ".env")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
-
- envVars := requireMapStringString(t, results[0].properties["env_vars"])
- assertEqual(t, envVars["DATABASE_HOST"], "localhost")
- assertEqual(t, envVars["DATABASE_PORT"], "5432")
- assertEqual(t, envVars["PLAIN_VALUE"], "hello world")
-
- if _, ok := envVars["API_SECRET"]; ok {
- t.Error("API_SECRET should be filtered")
- }
-}
-
-func TestParseDotenvQuotedValues(t *testing.T) {
- content := `KEY1="quoted value"
-KEY2='single quoted'
-`
- path := writeTempFile(t, ".env", content)
- results := parseDotenvFile(path, ".env")
- if len(results) != 1 {
- t.Fatal("expected 1 result")
- }
- envVars := requireMapStringString(t, results[0].properties["env_vars"])
- assertEqual(t, envVars["KEY1"], "quoted value")
- assertEqual(t, envVars["KEY2"], "single quoted")
-}
-
-// --- File identification tests ---
-
-func TestIsComposeFile(t *testing.T) {
- tests := []struct {
- name string
- expect bool
- }{
- {"docker-compose.yml", true},
- {"docker-compose.yaml", true},
- {"docker-compose.prod.yml", true},
- {"compose.yml", true},
- {"compose.yaml", true},
- {"mycompose.yml", false},
- {"docker-compose.txt", false},
- {"Dockerfile", false},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := isComposeFile(tt.name); got != tt.expect {
- t.Errorf("isComposeFile(%q) = %v, want %v", tt.name, got, tt.expect)
- }
- })
- }
-}
-
-func TestIsCloudbuildFile(t *testing.T) {
- tests := []struct {
- name string
- expect bool
- }{
- {"cloudbuild.yaml", true},
- {"cloudbuild.yml", true},
- {"cloudbuild-prod.yaml", true},
- {"Cloudbuild.yml", true},
- {"build.yaml", false},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := isCloudbuildFile(tt.name); got != tt.expect {
- t.Errorf("isCloudbuildFile(%q) = %v, want %v", tt.name, got, tt.expect)
- }
- })
- }
-}
-
-// --- Terraform parser tests ---
-
-func TestParseTerraformFile(t *testing.T) {
- content := `
-terraform {
- required_providers {
- google = {
- source = "hashicorp/google"
- version = "~> 6.35.0"
- }
- }
- backend "gcs" {
- bucket = "hoepke-tf"
- prefix = "state"
- }
-}
-
-variable "project_id" {
- description = "The GCP project ID"
- type = string
- default = "hoepke-cloud"
-}
-
-variable "region" {
- description = "The region"
- type = string
-}
-
-resource "google_cloud_run_service" "main" {
- name = "my-service"
- location = var.region
-}
-
-resource "google_compute_address" "nat_ip" {
- name = "nat-ip"
- region = var.region
-}
-
-output "service_url" {
- value = google_cloud_run_service.main.status[0].url
-}
-
-data "google_project" "project" {
-}
-
-module "vpc" {
- source = "./modules/vpc"
-}
-
-locals {
- env = "prod"
-}
-`
- path := writeTempFile(t, "main.tf", content)
- results := parseTerraformFile(path, "opentofu/main.tf")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
-
- props := results[0].properties
- assertEqual(t, props["infra_type"], "terraform")
- assertEqual(t, props["backend"], "gcs")
-
- t.Run("resources", func(t *testing.T) { verifyTFResources(t, props) })
- t.Run("variables", func(t *testing.T) { verifyTFVariables(t, props) })
- t.Run("other_blocks", func(t *testing.T) { verifyTFOtherBlocks(t, props) })
-}
-
-func verifyTFResources(t *testing.T, props map[string]any) {
- t.Helper()
- resources, ok := props["resources"].([]map[string]string)
- if !ok {
- t.Fatal("resources is not []map[string]string")
- }
- if len(resources) != 2 {
- t.Fatalf("expected 2 resources, got %d", len(resources))
- }
- foundCloudRun := false
- for _, r := range resources {
- if r["type"] == "google_cloud_run_service" && r["name"] == "main" {
- foundCloudRun = true
- }
- }
- if !foundCloudRun {
- t.Error("missing google_cloud_run_service.main resource")
- }
-}
-
-func verifyTFVariables(t *testing.T, props map[string]any) {
- t.Helper()
- variables, ok := props["variables"].([]map[string]string)
- if !ok {
- t.Fatal("variables is not []map[string]string")
- }
- if len(variables) != 2 {
- t.Fatalf("expected 2 variables, got %d", len(variables))
- }
- for _, v := range variables {
- if v["name"] == "project_id" {
- assertEqual(t, v["default"], "hoepke-cloud")
- assertEqual(t, v["type"], "string")
- assertEqual(t, v["description"], "The GCP project ID")
- return
- }
- }
- t.Error("missing project_id variable")
-}
-
-func verifyTFOtherBlocks(t *testing.T, props map[string]any) {
- t.Helper()
- assertSliceContains(t, props["outputs"], "service_url")
-
- dataSources, ok := props["data_sources"].([]map[string]string)
- if !ok {
- t.Fatal("data_sources is not []map[string]string")
- }
- if len(dataSources) != 1 {
- t.Fatalf("expected 1 data source, got %d", len(dataSources))
- }
-
- modules, ok := props["modules"].([]map[string]string)
- if !ok {
- t.Fatal("modules is not []map[string]string")
- }
- if len(modules) != 1 {
- t.Fatalf("expected 1 module, got %d", len(modules))
- }
- assertEqual(t, modules[0]["name"], "vpc")
- assertEqual(t, modules[0]["source"], "./modules/vpc")
-
- if props["has_locals"] != true {
- t.Error("expected has_locals=true")
- }
-}
-
-func TestParseTerraformVariablesOnly(t *testing.T) {
- content := `
-variable "project_id" {
- description = "The GCP project ID"
- type = string
- default = "hoepke-cloud"
-}
-
-variable "secret_key" {
- description = "A secret"
- type = string
- default = "sk-1234567890abcdef12345"
-}
-`
- path := writeTempFile(t, "variables.tf", content)
- results := parseTerraformFile(path, "opentofu/variables.tf")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
-
- variables, ok := results[0].properties["variables"].([]map[string]string)
- if !ok {
- t.Fatal("variables is not []map[string]string")
- }
-
- // Secret default should be filtered
- for _, v := range variables {
- if v["name"] == "secret_key" {
- if _, hasDefault := v["default"]; hasDefault {
- t.Error("secret_key default should be filtered")
- }
- }
- }
-}
-
-func TestParseTerraformEmpty(t *testing.T) {
- path := writeTempFile(t, "empty.tf", "# just comments\n")
- results := parseTerraformFile(path, "empty.tf")
- if len(results) != 0 {
- t.Errorf("expected empty result for comment-only .tf, got %d", len(results))
- }
-}
-
-// --- Shell script parser tests ---
-
-func TestParseShellScript(t *testing.T) {
- content := `#!/bin/bash
-set -e
-
-# Configuration
-YOUR_CONTAINER_NAME="order-email-extractor-endpoint"
-DOCKERFILE_PATH="/path/to/dockerfile"
-
-export ENVIRONMENT="development"
-export USE_STACKDRIVER="false"
-
-# Shut down existing containers
-./shut-down-docker-container.sh
-
-docker build -t "$YOUR_CONTAINER_NAME" "$DOCKERFILE_PATH"
-docker run -d --name "$YOUR_CONTAINER_NAME" "$YOUR_CONTAINER_NAME"
-docker-compose up -d
-`
- path := writeTempFile(t, "run.sh", content)
- results := parseShellScript(path, "scripts/run.sh")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
-
- props := results[0].properties
- assertEqual(t, props["infra_type"], "shell")
- assertEqual(t, props["shebang"], "/bin/bash")
-
- envVars := requireMapStringString(t, props["env_vars"])
- assertEqual(t, envVars["ENVIRONMENT"], "development")
- assertEqual(t, envVars["YOUR_CONTAINER_NAME"], "order-email-extractor-endpoint")
-
- assertSliceContains(t, props["docker_commands"], "docker build")
- assertSliceContains(t, props["docker_commands"], "docker run")
- assertSliceContains(t, props["docker_commands"], "docker-compose up")
-}
-
-func TestParseShellScriptWithSource(t *testing.T) {
- content := `#!/usr/bin/env bash
-source ./config.sh
-. /etc/profile.d/env.sh
-`
- path := writeTempFile(t, "init.sh", content)
- results := parseShellScript(path, "init.sh")
- if len(results) != 1 {
- t.Fatal("expected 1 result")
- }
-
- props := results[0].properties
- assertEqual(t, props["shebang"], "/usr/bin/env bash")
- assertSliceContains(t, props["sources"], "./config.sh")
- assertSliceContains(t, props["sources"], "/etc/profile.d/env.sh")
-}
-
-func TestParseShellScriptSecretFiltered(t *testing.T) {
- content := `#!/bin/bash
-export API_SECRET="should-not-appear"
-export DATABASE_URL="https://db.example.com"
-`
- path := writeTempFile(t, "env.sh", content)
- results := parseShellScript(path, "env.sh")
- if len(results) != 1 {
- t.Fatal("expected 1 result")
- }
-
- envVars := requireMapStringString(t, results[0].properties["env_vars"])
- if _, ok := envVars["API_SECRET"]; ok {
- t.Error("API_SECRET should be filtered")
- }
- assertEqual(t, envVars["DATABASE_URL"], "https://db.example.com")
-}
-
-func TestParseShellScriptShebanOnly(t *testing.T) {
- // A script with only shebang still produces a result (shebang is useful metadata)
- path := writeTempFile(t, "empty.sh", "#!/bin/bash\n# just comments\n")
- results := parseShellScript(path, "empty.sh")
- if len(results) != 1 {
- t.Fatalf("expected 1 result for shebang-only .sh, got %d", len(results))
- }
- assertEqual(t, results[0].properties["shebang"], "/bin/bash")
-}
-
-func TestParseShellScriptTrulyEmpty(t *testing.T) {
- path := writeTempFile(t, "empty.sh", "# no shebang, just comments\n")
- results := parseShellScript(path, "empty.sh")
- if len(results) != 0 {
- t.Errorf("expected empty result for no-shebang .sh, got %d", len(results))
- }
-}
-
-func TestIsShellScript(t *testing.T) {
- tests := []struct {
- name string
- ext string
- expect bool
- }{
- {"run.sh", ".sh", true},
- {"deploy.bash", ".bash", true},
- {"init.zsh", ".zsh", true},
- {"main.py", ".py", false},
- {"Dockerfile", "", false},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := isShellScript(tt.name, tt.ext); got != tt.expect {
- t.Errorf("isShellScript(%q, %q) = %v, want %v", tt.name, tt.ext, got, tt.expect)
- }
- })
- }
-}
-
-// --- Integration test: passInfraFiles creates nodes ---
-
-func TestPassInfraFilesIntegration(t *testing.T) {
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- // Create a temp repo with infra files
- tmpDir := t.TempDir()
- writeFile(t, filepath.Join(tmpDir, "Dockerfile"), `FROM alpine:3.19
-EXPOSE 8080
-`)
- writeFile(t, filepath.Join(tmpDir, ".env"), `APP_PORT=8080
-`)
- writeFile(t, filepath.Join(tmpDir, "docker-compose.yml"), `
-services:
- web:
- image: nginx:latest
- ports:
- - "80:80"
-`)
-
- p := New(context.Background(), s, tmpDir, discover.ModeFull)
- err = s.WithTransaction(context.Background(), func(txStore *store.Store) error {
- p.Store = txStore
- _ = txStore.UpsertProject(p.ProjectName, tmpDir)
- p.passInfraFiles()
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Verify InfraFile nodes were created
- infraNodes, err := s.FindNodesByLabel(p.ProjectName, "InfraFile")
- if err != nil {
- t.Fatal(err)
- }
- if len(infraNodes) < 3 {
- t.Errorf("expected at least 3 InfraFile nodes, got %d", len(infraNodes))
- }
-
- // Verify File nodes were also created (for search_code)
- fileNodes, err := s.FindNodesByLabel(p.ProjectName, "File")
- if err != nil {
- t.Fatal(err)
- }
- if len(fileNodes) < 3 {
- t.Errorf("expected at least 3 File nodes, got %d", len(fileNodes))
- }
-
- // Verify no Module nodes were created (InfraFile, not Module)
- moduleNodes, err := s.FindNodesByLabel(p.ProjectName, "Module")
- if err != nil {
- t.Fatal(err)
- }
- if len(moduleNodes) != 0 {
- t.Errorf("expected 0 Module nodes from infra scan, got %d", len(moduleNodes))
- }
-
- // Check InfraFile properties
- for _, n := range infraNodes {
- infraType, ok := n.Properties["infra_type"].(string)
- if !ok {
- t.Errorf("node %s missing infra_type", n.QualifiedName)
- continue
- }
- switch infraType {
- case "dockerfile":
- assertEqual(t, n.Properties["base_image"], "alpine:3.19")
- case "env":
- envVars, eOk := n.Properties["env_vars"].(map[string]any)
- if !eOk {
- t.Fatal("env_vars is not map[string]any")
- }
- assertEqual(t, envVars["APP_PORT"], "8080")
- case "compose-service":
- assertEqual(t, n.Properties["service_name"], "web")
- }
- }
-}
-
-// TestPassInfraFilesIdempotent verifies that re-running passInfraFiles
-// does not create duplicate nodes (upsert behavior).
-func TestPassInfraFilesIdempotent(t *testing.T) {
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- tmpDir := t.TempDir()
- writeFile(t, filepath.Join(tmpDir, "Dockerfile"), `FROM alpine:3.19
-EXPOSE 8080
-`)
-
- p := New(context.Background(), s, tmpDir, discover.ModeFull)
- err = s.WithTransaction(context.Background(), func(txStore *store.Store) error {
- p.Store = txStore
- _ = txStore.UpsertProject(p.ProjectName, tmpDir)
- p.passInfraFiles()
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
-
- countBefore, _ := s.CountNodes(p.ProjectName)
-
- // Run again — should delete and recreate (same count)
- err = s.WithTransaction(context.Background(), func(txStore *store.Store) error {
- p.Store = txStore
- _ = txStore.DeleteNodesByLabel(p.ProjectName, "InfraFile")
- p.passInfraFiles()
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
-
- countAfter, _ := s.CountNodes(p.ProjectName)
- if countBefore != countAfter {
- t.Errorf("node count changed: before=%d, after=%d", countBefore, countAfter)
- }
-}
-
-// --- cleanJSONBrackets tests ---
-
-func TestCleanJSONBrackets(t *testing.T) {
- tests := []struct {
- input string
- want string
- }{
- {`["./server"]`, `./server`},
- {`["python", "main.py"]`, `python main.py`},
- {`./server`, `./server`},
- {`["./app", "--flag", "value"]`, `./app --flag value`},
- }
- for _, tt := range tests {
- t.Run(tt.input, func(t *testing.T) {
- got := cleanJSONBrackets(tt.input)
- if got != tt.want {
- t.Errorf("cleanJSONBrackets(%q) = %q, want %q", tt.input, got, tt.want)
- }
- })
- }
-}
-
-// --- infraQN tests ---
-
-func TestInfraQN(t *testing.T) {
- p := &Pipeline{ProjectName: "myproject"}
-
- // Regular infra file
- qn := p.infraQN("docker-images/service/Dockerfile", map[string]any{"infra_type": "dockerfile"})
- if !strings.Contains(qn, ".__infra__") {
- t.Errorf("expected __infra__ suffix, got %s", qn)
- }
-
- // Compose service gets per-service suffix
- qn = p.infraQN("docker-compose.yml", map[string]any{
- "infra_type": "compose-service",
- "service_name": "web",
- })
- if !strings.Contains(qn, "::web") {
- t.Errorf("expected ::web suffix, got %s", qn)
- }
-}
-
-// --- Bug fix regression tests ---
-
-func TestParseComposeNonStringEnvValues(t *testing.T) {
- content := `
-services:
- auth-service:
- image: auth:latest
- environment:
- PORT: 8090
- DEBUG: true
- RATE_LIMIT: 1.5
- NAME: "string-value"
-`
- path := writeTempFile(t, "docker-compose.yml", content)
- results := parseComposeFile(path, "docker-compose.yml")
- if len(results) != 1 {
- t.Fatalf("expected 1 service, got %d", len(results))
- }
-
- envVars := requireMapStringString(t, results[0].properties["environment"])
- assertEqual(t, envVars["PORT"], "8090")
- assertEqual(t, envVars["DEBUG"], "true")
- assertEqual(t, envVars["RATE_LIMIT"], "1.5")
- assertEqual(t, envVars["NAME"], "string-value")
-}
-
-func TestParseComposeSecretKeyNotFiltered(t *testing.T) {
- // Key names like JWT_PRIVATE_KEY_ID are config references, not secrets.
- // Only actual secret VALUES should be filtered.
- content := `
-services:
- auth-service:
- image: auth:latest
- environment:
- JWT_PRIVATE_KEY_ID: jwt-private-key
- GOOGLE_CLIENT_SECRET_ID: google-oauth-secret
- ACCESS_TOKEN_TTL: 15m
- ACTUAL_SECRET: "sk-1234567890abcdef12345"
-`
- path := writeTempFile(t, "docker-compose.yml", content)
- results := parseComposeFile(path, "docker-compose.yml")
- if len(results) != 1 {
- t.Fatalf("expected 1 service, got %d", len(results))
- }
-
- envVars := requireMapStringString(t, results[0].properties["environment"])
- // These should NOT be filtered — key name matches pattern but value is a reference
- assertEqual(t, envVars["JWT_PRIVATE_KEY_ID"], "jwt-private-key")
- assertEqual(t, envVars["GOOGLE_CLIENT_SECRET_ID"], "google-oauth-secret")
- assertEqual(t, envVars["ACCESS_TOKEN_TTL"], "15m")
-
- // This SHOULD be filtered — value matches secret pattern (sk-...)
- if _, ok := envVars["ACTUAL_SECRET"]; ok {
- t.Error("ACTUAL_SECRET should be filtered (value matches secret pattern)")
- }
-}
-
-func TestParseCloudbuildBashScript(t *testing.T) {
- content := `
-substitutions:
- _SERVICE_NAME: my-service
-
-steps:
- - name: gcr.io/cloud-builders/docker
- args: ['build', '-t', 'eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME', '.']
-
- - name: gcr.io/google.com/cloudsdktool/cloud-sdk
- entrypoint: bash
- args:
- - "-c"
- - |
- gcloud run deploy $_SERVICE_NAME \
- --region=europe-west3 \
- --memory=2Gi \
- --cpu=2 \
- --concurrency=80 \
- --max-instances=10 \
- --ingress=internal-and-cloud-load-balancing \
- --set-env-vars=LOG_LEVEL=INFO,SOURCE_ENTITY=$_SERVICE_NAME
-
-images:
- - eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME
-`
- path := writeTempFile(t, "cloudbuild.yaml", content)
- results := parseCloudbuildFile(path, "cloudbuild.yaml")
- if len(results) != 1 {
- t.Fatalf("expected 1 result, got %d", len(results))
- }
-
- props := results[0].properties
- assertEqual(t, props["service_name"], "my-service")
- assertEqual(t, props["deploy_region"], "europe-west3")
- assertEqual(t, props["deploy_memory"], "2Gi")
- assertEqual(t, props["deploy_cpu"], "2")
- assertEqual(t, props["deploy_concurrency"], "80")
- assertEqual(t, props["deploy_max_instances"], "10")
- assertEqual(t, props["deploy_ingress"], "internal-and-cloud-load-balancing")
-
- envVars := requireMapStringString(t, props["deploy_env_vars"])
- assertEqual(t, envVars["LOG_LEVEL"], "INFO")
- assertEqual(t, envVars["SOURCE_ENTITY"], "$_SERVICE_NAME")
-}
-
-// --- helpers ---
-
-func writeTempFile(t *testing.T, name, content string) string {
- t.Helper()
- dir := t.TempDir()
- path := filepath.Join(dir, name)
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
- return path
-}
-
-// requireMapStringString asserts the value is map[string]string (from parsed props)
-// and returns it. Fails the test if not.
-func requireMapStringString(t *testing.T, v any) map[string]string {
- t.Helper()
- m, ok := v.(map[string]string)
- if !ok {
- t.Fatalf("expected map[string]string, got %T", v)
- }
- return m
-}
-
-func assertEqual(t *testing.T, got, want any) {
- t.Helper()
- gotStr, _ := got.(string)
- wantStr, _ := want.(string)
- if gotStr != wantStr {
- t.Errorf("got %v, want %v", got, want)
- }
-}
-
-func assertSliceContains(t *testing.T, sliceAny any, want string) {
- t.Helper()
- switch s := sliceAny.(type) {
- case []string:
- for _, v := range s {
- if v == want {
- return
- }
- }
- case []any:
- for _, v := range s {
- if v == want {
- return
- }
- }
- }
- t.Errorf("slice %v does not contain %q", sliceAny, want)
-}
diff --git a/internal/pipeline/infrascan_tf.go b/internal/pipeline/infrascan_tf.go
deleted file mode 100644
index bd755b259..000000000
--- a/internal/pipeline/infrascan_tf.go
+++ /dev/null
@@ -1,216 +0,0 @@
-package pipeline
-
-import (
- "bufio"
- "bytes"
- "os"
- "regexp"
- "strings"
-)
-
-// --- Terraform parser (regex, line-oriented with brace tracking) ---
-
-var (
- reResource = regexp.MustCompile(`^resource\s+"(\S+)"\s+"(\S+)"`)
- reVariable = regexp.MustCompile(`^variable\s+"(\S+)"`)
- reOutput = regexp.MustCompile(`^output\s+"(\S+)"`)
- reProvider = regexp.MustCompile(`^provider\s+"(\S+)"`)
- reTFModule = regexp.MustCompile(`^module\s+"(\S+)"`)
- reDataSrc = regexp.MustCompile(`^data\s+"(\S+)"\s+"(\S+)"`)
- reBackend = regexp.MustCompile(`^\s*backend\s+"(\S+)"`)
- reTFDefault = regexp.MustCompile(`^\s*default\s*=\s*"?([^"\n]*)"?`)
- reTFType = regexp.MustCompile(`^\s*type\s*=\s*(\S+)`)
- reTFSource = regexp.MustCompile(`^\s*source\s*=\s*"([^"]*)"`)
- reTFDesc = regexp.MustCompile(`^\s*description\s*=\s*"([^"]*)"`)
- reTFLocals = regexp.MustCompile(`^locals\s*\{`)
-)
-
-// blockKind identifies what type of HCL block we're inside.
-type blockKind int
-
-const (
- blockNone blockKind = iota
- blockVariable
- blockModule
- blockTerraform
-)
-
-// tfState accumulates parsed Terraform file metadata.
-type tfState struct {
- resources []map[string]string // [{type, name}]
- variables []map[string]string // [{name, type, default, description}]
- outputs []string
- providers []string
- modules []map[string]string // [{name, source}]
- dataSources []map[string]string // [{type, name}]
- backend string
- hasLocals bool
-}
-
-func parseTerraformFile(absPath, relPath string) []infraFile {
- f, err := os.Open(absPath)
- if err != nil {
- return nil
- }
- defer f.Close()
- return parseTerraformScanner(bufio.NewScanner(f), relPath)
-}
-
-func parseTerraformFileFromSource(source []byte, relPath string) []infraFile {
- return parseTerraformScanner(bufio.NewScanner(bytes.NewReader(source)), relPath)
-}
-
-func parseTerraformScanner(scanner *bufio.Scanner, relPath string) []infraFile {
- var st tfState
- var curBlock blockKind
- var curBlockData map[string]string
- braceDepth := 0
-
- for scanner.Scan() {
- line := scanner.Text()
- trimmed := strings.TrimSpace(line)
-
- if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, "//") {
- continue
- }
-
- // Track brace depth
- braceDepth += strings.Count(trimmed, "{") - strings.Count(trimmed, "}")
-
- // At top level (depth 0 or entering depth 1), detect block headers
- if braceDepth <= 1 {
- if newBlock, data := st.matchBlockHeader(trimmed); newBlock != blockNone {
- curBlock = newBlock
- curBlockData = data
- continue
- }
- }
-
- // Inside a block, extract attributes.
- // Depth 1 for variable/module attrs, depth 1-2 for terraform (backend is nested).
- if curBlock != blockNone && braceDepth >= 1 && braceDepth <= 2 {
- st.extractBlockAttr(trimmed, curBlock, curBlockData)
- }
-
- // Block closed — finalize
- if braceDepth == 0 && curBlock != blockNone {
- st.finalizeBlock(curBlock, curBlockData)
- curBlock = blockNone
- curBlockData = nil
- }
- }
-
- props := st.toProperties()
- if len(props) <= 1 { // only infra_type, nothing useful
- return nil
- }
- return []infraFile{{relPath: relPath, infraType: "terraform", properties: props}}
-}
-
-// matchBlockHeader checks if the line starts a recognized HCL block.
-// Returns the block kind and a data map to accumulate attributes into.
-func (st *tfState) matchBlockHeader(line string) (kind blockKind, data map[string]string) {
- if m := reResource.FindStringSubmatch(line); m != nil {
- st.resources = append(st.resources, map[string]string{"type": m[1], "name": m[2]})
- return blockNone, nil // no attribute extraction needed
- }
- if m := reVariable.FindStringSubmatch(line); m != nil {
- return blockVariable, map[string]string{"name": m[1]}
- }
- if m := reOutput.FindStringSubmatch(line); m != nil {
- st.outputs = append(st.outputs, m[1])
- return blockNone, nil
- }
- if m := reProvider.FindStringSubmatch(line); m != nil {
- st.providers = append(st.providers, m[1])
- return blockNone, nil
- }
- if m := reTFModule.FindStringSubmatch(line); m != nil {
- return blockModule, map[string]string{"name": m[1]}
- }
- if m := reDataSrc.FindStringSubmatch(line); m != nil {
- st.dataSources = append(st.dataSources, map[string]string{"type": m[1], "name": m[2]})
- return blockNone, nil
- }
- if strings.HasPrefix(line, "terraform") && strings.Contains(line, "{") {
- return blockTerraform, nil
- }
- if reTFLocals.MatchString(line) {
- st.hasLocals = true
- }
- return blockNone, nil
-}
-
-// extractBlockAttr extracts key attributes from inside a block.
-func (st *tfState) extractBlockAttr(line string, kind blockKind, data map[string]string) {
- switch kind {
- case blockVariable:
- st.extractVariableAttr(line, data)
- case blockModule:
- if m := reTFSource.FindStringSubmatch(line); m != nil {
- data["source"] = m[1]
- }
- case blockTerraform:
- if m := reBackend.FindStringSubmatch(line); m != nil {
- st.backend = m[1]
- }
- }
-}
-
-func (st *tfState) extractVariableAttr(line string, data map[string]string) {
- if m := reTFDefault.FindStringSubmatch(line); m != nil {
- val := strings.TrimSpace(m[1])
- if !isSecretBinding(data["name"], val) {
- data["default"] = val
- }
- }
- if m := reTFType.FindStringSubmatch(line); m != nil {
- data["type"] = m[1]
- }
- if m := reTFDesc.FindStringSubmatch(line); m != nil {
- data["description"] = m[1]
- }
-}
-
-// finalizeBlock saves the accumulated block data to the state.
-func (st *tfState) finalizeBlock(kind blockKind, data map[string]string) {
- switch kind {
- case blockVariable:
- if data != nil {
- st.variables = append(st.variables, data)
- }
- case blockModule:
- if data != nil {
- st.modules = append(st.modules, data)
- }
- case blockTerraform:
- // backend already extracted inline
- }
-}
-
-func (st *tfState) toProperties() map[string]any {
- props := map[string]any{
- "infra_type": "terraform",
- }
-
- setNonEmptyMaps(props, "resources", st.resources)
- setNonEmptyMaps(props, "variables", st.variables)
- setNonEmpty(props, "outputs", st.outputs)
- setNonEmpty(props, "providers", st.providers)
- setNonEmptyMaps(props, "modules", st.modules)
- setNonEmptyMaps(props, "data_sources", st.dataSources)
- setNonEmptyStr(props, "backend", st.backend)
-
- if st.hasLocals {
- props["has_locals"] = true
- }
-
- return props
-}
-
-// setNonEmptyMaps sets a property if the slice of maps is non-empty.
-func setNonEmptyMaps(m map[string]any, key string, val []map[string]string) {
- if len(val) > 0 {
- m[key] = val
- }
-}
diff --git a/internal/pipeline/infrascan_yaml.go b/internal/pipeline/infrascan_yaml.go
deleted file mode 100644
index 145053900..000000000
--- a/internal/pipeline/infrascan_yaml.go
+++ /dev/null
@@ -1,411 +0,0 @@
-package pipeline
-
-import (
- "os"
- "regexp"
- "strconv"
- "strings"
-
- "gopkg.in/yaml.v3"
-)
-
-// --- docker-compose parser ---
-
-// composeFile represents the top-level structure of a docker-compose file.
-type composeFile struct {
- Services map[string]composeService `yaml:"services"`
-}
-
-// composeService represents a single service in docker-compose.
-type composeService struct {
- Build any `yaml:"build"`
- Image string `yaml:"image"`
- Ports []string `yaml:"ports"`
- Expose []string `yaml:"expose"`
- Environment any `yaml:"environment"`
- DependsOn any `yaml:"depends_on"`
- Networks any `yaml:"networks"`
- ContainerName string `yaml:"container_name"`
- Volumes []string `yaml:"volumes"`
- Command any `yaml:"command"`
- Labels map[string]string `yaml:"labels"`
-}
-
-func parseComposeFile(absPath, relPath string) []infraFile {
- data, err := os.ReadFile(absPath)
- if err != nil {
- return nil
- }
- return parseComposeData(data, relPath)
-}
-
-func parseComposeFileFromSource(source []byte, relPath string) []infraFile {
- return parseComposeData(source, relPath)
-}
-
-func parseComposeData(data []byte, relPath string) []infraFile {
- var cf composeFile
- if err := yaml.Unmarshal(data, &cf); err != nil {
- return nil
- }
-
- if len(cf.Services) == 0 {
- return nil
- }
-
- result := make([]infraFile, 0, len(cf.Services))
- for name := range cf.Services {
- svc := cf.Services[name]
- props := buildComposeServiceProps(name, &svc)
- result = append(result, infraFile{
- relPath: relPath,
- infraType: "compose-service",
- properties: props,
- })
- }
- return result
-}
-
-func buildComposeServiceProps(name string, svc *composeService) map[string]any {
- props := map[string]any{
- "infra_type": "compose-service",
- "service_name": name,
- }
-
- setNonEmptyStr(props, "image", svc.Image)
- setNonEmptyStr(props, "container_name", svc.ContainerName)
- setBuildContext(props, svc.Build)
- setNonEmpty(props, "ports", svc.Ports)
- setNonEmpty(props, "expose", svc.Expose)
- setNonEmpty(props, "volumes", svc.Volumes)
-
- envMap := parseComposeEnvironment(svc.Environment)
- setNonEmptyMap(props, "environment", envMap)
-
- deps := parseDependsOn(svc.DependsOn)
- setNonEmpty(props, "depends_on", deps)
-
- nets := parseNetworks(svc.Networks)
- setNonEmpty(props, "networks", nets)
-
- return props
-}
-
-// setBuildContext extracts the build context from various docker-compose formats.
-// build can be a string or a map with "context" key.
-func setBuildContext(props map[string]any, build any) {
- switch v := build.(type) {
- case string:
- setNonEmptyStr(props, "build_context", v)
- case map[string]any:
- if ctx, ok := v["context"].(string); ok {
- setNonEmptyStr(props, "build_context", ctx)
- }
- }
-}
-
-// parseComposeEnvironment handles both map and list formats for environment.
-func parseComposeEnvironment(env any) map[string]string {
- if env == nil {
- return nil
- }
- result := make(map[string]string)
-
- switch v := env.(type) {
- case map[string]any:
- for k, val := range v {
- var s string
- switch tv := val.(type) {
- case string:
- s = tv
- case int:
- s = strconv.Itoa(tv)
- case float64:
- s = strconv.FormatFloat(tv, 'f', -1, 64)
- case bool:
- s = strconv.FormatBool(tv)
- default:
- continue
- }
- if !isSecretValue(s) {
- result[k] = s
- }
- }
- case []any:
- for _, item := range v {
- s, ok := item.(string)
- if !ok {
- continue
- }
- parts := strings.SplitN(s, "=", 2)
- if len(parts) == 2 && !isSecretValue(parts[1]) {
- result[parts[0]] = parts[1]
- }
- }
- }
-
- if len(result) == 0 {
- return nil
- }
- return result
-}
-
-// parseDependsOn handles both list and map formats for depends_on.
-func parseDependsOn(dep any) []string {
- if dep == nil {
- return nil
- }
- switch v := dep.(type) {
- case []any:
- var result []string
- for _, item := range v {
- if s, ok := item.(string); ok {
- result = append(result, s)
- }
- }
- return result
- case map[string]any:
- var result []string
- for name := range v {
- result = append(result, name)
- }
- return result
- }
- return nil
-}
-
-// parseNetworks handles both list and map formats for networks.
-func parseNetworks(nets any) []string {
- if nets == nil {
- return nil
- }
- switch v := nets.(type) {
- case []any:
- var result []string
- for _, item := range v {
- if s, ok := item.(string); ok {
- result = append(result, s)
- }
- }
- return result
- case map[string]any:
- var result []string
- for name := range v {
- result = append(result, name)
- }
- return result
- }
- return nil
-}
-
-// --- cloudbuild parser ---
-
-// cloudbuildFile represents the top-level structure of a Cloud Build YAML.
-type cloudbuildFile struct {
- Steps []cloudbuildStep `yaml:"steps"`
- Substitutions map[string]string `yaml:"substitutions"`
- Images []string `yaml:"images"`
- Options map[string]any `yaml:"options"`
-}
-
-type cloudbuildStep struct {
- Name string `yaml:"name"`
- Entrypoint string `yaml:"entrypoint"`
- Args []string `yaml:"args"`
- Env []string `yaml:"env"`
-}
-
-func parseCloudbuildFile(absPath, relPath string) []infraFile {
- data, err := os.ReadFile(absPath)
- if err != nil {
- return nil
- }
- return parseCloudbuildData(data, relPath)
-}
-
-func parseCloudbuildFileFromSource(source []byte, relPath string) []infraFile {
- return parseCloudbuildData(source, relPath)
-}
-
-func parseCloudbuildData(data []byte, relPath string) []infraFile {
- var cb cloudbuildFile
- if err := yaml.Unmarshal(data, &cb); err != nil {
- return nil
- }
-
- props := buildCloudbuildProps(cb)
- props["infra_type"] = "cloudbuild"
-
- return []infraFile{{relPath: relPath, infraType: "cloudbuild", properties: props}}
-}
-
-func buildCloudbuildProps(cb cloudbuildFile) map[string]any {
- props := make(map[string]any)
-
- if len(cb.Substitutions) > 0 {
- filtered := filterSecretMap(cb.Substitutions)
- setNonEmptyMap(props, "substitutions", filtered)
- if sn, ok := cb.Substitutions["_SERVICE_NAME"]; ok {
- props["service_name"] = sn
- }
- }
-
- if len(cb.Images) > 0 {
- props["image_registry"] = cb.Images[0]
- }
-
- // Walk steps looking for gcloud run deploy
- extractDeployFlags(cb.Steps, props)
-
- return props
-}
-
-// extractDeployFlags scans cloudbuild steps for gcloud run deploy commands
-// and extracts deployment flags.
-func extractDeployFlags(steps []cloudbuildStep, props map[string]any) {
- for _, step := range steps {
- // Direct args format: ["gcloud", "run", "deploy", "--flag=val", ...]
- if isDeployStep(step.Args) {
- parseDeployArgs(step.Args, props)
- parseDeployEnvVars(step.Args, props)
- return
- }
- // Bash script format: entrypoint=bash, args=["-c", "gcloud run deploy ..."]
- if isBashDeployStep(&step) {
- parseBashDeployScript(step.Args[1], props)
- return
- }
- }
-}
-
-// isBashDeployStep checks if a step is a bash entrypoint with a gcloud run deploy script.
-func isBashDeployStep(step *cloudbuildStep) bool {
- isBash := step.Entrypoint == "bash" || step.Entrypoint == "/bin/bash" || step.Entrypoint == "/bin/sh"
- if !isBash && len(step.Args) >= 2 {
- isBash = step.Args[0] == "-c"
- }
- if !isBash || len(step.Args) < 2 {
- return false
- }
- script := step.Args[len(step.Args)-1]
- return strings.Contains(script, "gcloud") &&
- strings.Contains(script, "run") &&
- strings.Contains(script, "deploy")
-}
-
-// parseBashDeployScript extracts deploy flags from a bash script string.
-func parseBashDeployScript(script string, props map[string]any) {
- // Normalize line continuations
- normalized := strings.ReplaceAll(script, "\\\n", " ")
-
- // Extract flags using the same flag map as parseDeployArgs
- for flag, propName := range deployFlagMap {
- re := regexp.MustCompile(regexp.QuoteMeta(flag) + `[= ]+([^\s\\]+)`)
- if m := re.FindStringSubmatch(normalized); len(m) == 2 {
- props[propName] = m[1]
- }
- }
-
- // Extract env vars from --set-env-vars or --update-env-vars
- envRe := regexp.MustCompile(`--(?:set|update)-env-vars[= ]+([^\s\\]+(?:,[^\s\\]+)*)`)
- if m := envRe.FindStringSubmatch(normalized); len(m) == 2 {
- envMap := make(map[string]string)
- for _, pair := range strings.Split(m[1], ",") {
- parts := strings.SplitN(pair, "=", 2)
- if len(parts) == 2 && !isSecretBinding(parts[0], parts[1]) {
- envMap[parts[0]] = parts[1]
- }
- }
- setNonEmptyMap(props, "deploy_env_vars", envMap)
- }
-}
-
-// isDeployStep returns true if the args list contains "gcloud run deploy" sequence.
-func isDeployStep(args []string) bool {
- if len(args) < 3 {
- return false
- }
- // Match "run" + "deploy" anywhere in args (gcloud run deploy ...)
- for i := 0; i < len(args)-1; i++ {
- if args[i] == "run" && args[i+1] == "deploy" {
- return true
- }
- }
- return false
-}
-
-// deployFlagMap maps gcloud run deploy flags to property names.
-var deployFlagMap = map[string]string{
- "--region": "deploy_region",
- "--cpu": "deploy_cpu",
- "--memory": "deploy_memory",
- "--concurrency": "deploy_concurrency",
- "--max-instances": "deploy_max_instances",
- "--timeout": "deploy_timeout",
- "--ingress": "deploy_ingress",
- "--image": "image_registry",
- "--service-account": "deploy_service_account",
-}
-
-func parseDeployArgs(args []string, props map[string]any) {
- for i, arg := range args {
- // --flag=value format
- if idx := strings.Index(arg, "="); idx > 0 {
- flag := arg[:idx]
- val := arg[idx+1:]
- if propName, ok := deployFlagMap[flag]; ok {
- props[propName] = val
- }
- continue
- }
- // --flag value format (next arg is value)
- if propName, ok := deployFlagMap[arg]; ok && i+1 < len(args) {
- props[propName] = args[i+1]
- }
- }
-}
-
-// parseDeployEnvVars extracts --set-env-vars or --update-env-vars from deploy args.
-func parseDeployEnvVars(args []string, props map[string]any) {
- for i, arg := range args {
- envStr := extractEnvVarsFlag(arg, args, i)
- if envStr == "" {
- continue
- }
-
- envMap := make(map[string]string)
- for _, pair := range strings.Split(envStr, ",") {
- parts := strings.SplitN(pair, "=", 2)
- if len(parts) == 2 && !isSecretBinding(parts[0], parts[1]) {
- envMap[parts[0]] = parts[1]
- }
- }
- setNonEmptyMap(props, "deploy_env_vars", envMap)
- return
- }
-}
-
-// extractEnvVarsFlag extracts the env vars string from --set-env-vars or --update-env-vars flags.
-func extractEnvVarsFlag(arg string, args []string, i int) string {
- switch {
- case strings.HasPrefix(arg, "--set-env-vars="):
- return arg[len("--set-env-vars="):]
- case strings.HasPrefix(arg, "--update-env-vars="):
- return arg[len("--update-env-vars="):]
- case (arg == "--set-env-vars" || arg == "--update-env-vars") && i+1 < len(args):
- return args[i+1]
- default:
- return ""
- }
-}
-
-// filterSecretMap returns a copy of the map with secret key/values removed.
-func filterSecretMap(m map[string]string) map[string]string {
- filtered := make(map[string]string, len(m))
- for k, v := range m {
- if !isSecretBinding(k, v) {
- filtered[k] = v
- }
- }
- return filtered
-}
diff --git a/internal/pipeline/inherits.go b/internal/pipeline/inherits.go
deleted file mode 100644
index 396eb782d..000000000
--- a/internal/pipeline/inherits.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// passInherits creates INHERITS edges from Class nodes to their base classes.
-// Reads base_classes property (set during extractClassDef) and resolves via registry.
-func (p *Pipeline) passInherits() {
- slog.Info("pass.inherits")
-
- count := 0
- for _, label := range []string{"Class", "Type", "Interface", "Enum"} {
- nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, n := range nodes {
- bases, ok := n.Properties["base_classes"]
- if !ok {
- continue
- }
- baseList, ok := bases.([]any)
- if !ok {
- continue
- }
-
- moduleQN := qualifiedNamePrefix(n.QualifiedName)
- importMap := p.importMaps[moduleQN]
-
- for _, b := range baseList {
- baseName, ok := b.(string)
- if !ok || baseName == "" {
- continue
- }
-
- // Resolve base class to a registered Class/Type/Interface
- targetQN := resolveAsClass(baseName, p.registry, moduleQN, importMap)
- if targetQN == "" {
- continue
- }
-
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
- if targetNode == nil {
- continue
- }
-
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: n.ID,
- TargetID: targetNode.ID,
- Type: "INHERITS",
- })
- count++
- }
- }
- }
-
- slog.Info("pass.inherits.done", "edges", count)
-}
-
-// qualifiedNamePrefix returns the module QN portion of a fully qualified name.
-// e.g., "project.path.module.ClassName" → "project.path.module"
-func qualifiedNamePrefix(qn string) string {
- for i := len(qn) - 1; i >= 0; i-- {
- if qn[i] == '.' {
- return qn[:i]
- }
- }
- return qn
-}
diff --git a/internal/pipeline/main_test.go b/internal/pipeline/main_test.go
deleted file mode 100644
index 01546c980..000000000
--- a/internal/pipeline/main_test.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package pipeline
-
-import (
- "testing"
-
- "go.uber.org/goleak"
-)
-
-func TestMain(m *testing.M) {
- goleak.VerifyTestMain(m,
- // HTTP transport dial goroutines from version checker
- goleak.IgnoreTopFunction("net/http.(*Transport).dialConnFor"),
- goleak.IgnoreTopFunction("internal/poll.runtime_pollWait"),
- // SQLite connection opener from store.OpenPath in full-index tests
- goleak.IgnoreTopFunction("database/sql.(*DB).connectionOpener"),
- )
-}
diff --git a/internal/pipeline/memleak_test.go b/internal/pipeline/memleak_test.go
deleted file mode 100644
index 68b7d034c..000000000
--- a/internal/pipeline/memleak_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "path/filepath"
- "runtime"
- "runtime/debug"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// TestMemoryStability indexes a small fixture repo N times and asserts
-// that heap usage does not grow unboundedly between iterations.
-// Uses HeapInuse as the primary metric (cross-platform). RSS via
-// syscall.Getrusage would also capture C-side allocations but is
-// Unix-only; HeapInuse catches Go-side leaks which are the main concern.
-func TestMemoryStability(t *testing.T) {
- // Create a minimal fixture repo with enough files to exercise the pipeline.
- fixtureDir := t.TempDir()
- writeFixtureFiles(t, fixtureDir)
-
- dbDir := t.TempDir()
- const projectName = "memleak-test"
- const iterations = 5
-
- heapSamples := make([]uint64, iterations)
-
- for i := 0; i < iterations; i++ {
- st, err := store.OpenInDir(dbDir, projectName)
- if err != nil {
- t.Fatalf("iter %d: open store: %v", i, err)
- }
-
- p := New(context.Background(), st, fixtureDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- st.Close()
- t.Fatalf("iter %d: pipeline.Run: %v", i, err)
- }
- st.Close()
-
- // Force GC + return memory to OS
- runtime.GC()
- debug.FreeOSMemory()
-
- var m runtime.MemStats
- runtime.ReadMemStats(&m)
- heapSamples[i] = m.HeapInuse
-
- t.Logf("iter %d: heap_inuse=%d MB, heap_alloc=%d MB, sys=%d MB",
- i, m.HeapInuse/(1<<20), m.HeapAlloc/(1<<20), m.Sys/(1<<20))
- }
-
- // Compare first iteration (after warm-up) to last.
- // Allow 30% growth to account for CI runner variance and GC timing.
- baseline := heapSamples[0]
- final := heapSamples[iterations-1]
-
- if baseline == 0 {
- t.Log("baseline heap is 0, skipping growth check")
- return
- }
-
- growthPct := float64(final-baseline) / float64(baseline) * 100
- t.Logf("heap growth: baseline=%d MB, final=%d MB, growth=%.1f%%",
- baseline/(1<<20), final/(1<<20), growthPct)
-
- if final > baseline && growthPct > 30.0 {
- t.Errorf("heap grew %.1f%% over %d iterations (baseline=%d, final=%d) — possible memory leak",
- growthPct, iterations, baseline, final)
- }
-}
-
-// writeFixtureFiles creates a small multi-language fixture repo.
-func writeFixtureFiles(t *testing.T, dir string) {
- t.Helper()
-
- files := map[string]string{
- "main.go": `package main
-
-import "fmt"
-
-func main() {
- fmt.Println(greet("world"))
-}
-
-func greet(name string) string {
- return "hello " + name
-}
-`,
- "util.go": `package main
-
-func add(a, b int) int {
- return a + b
-}
-
-func multiply(a, b int) int {
- return a * b
-}
-`,
- "handler.go": `package main
-
-import "net/http"
-
-func handleHealth(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- w.Write([]byte("ok"))
-}
-
-func handleReady(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
-}
-`,
- "lib/calc.py": `
-def calculate(x, y):
- return x + y
-
-def divide(x, y):
- if y == 0:
- raise ValueError("division by zero")
- return x / y
-
-class Calculator:
- def __init__(self):
- self.history = []
-
- def add(self, a, b):
- result = calculate(a, b)
- self.history.append(result)
- return result
-`,
- "src/app.js": `
-function fetchData(url) {
- return fetch(url).then(res => res.json());
-}
-
-function processData(data) {
- return data.map(item => item.value);
-}
-
-class DataService {
- constructor(baseUrl) {
- this.baseUrl = baseUrl;
- }
-
- async getAll() {
- return fetchData(this.baseUrl + '/items');
- }
-}
-`,
- }
-
- for relPath, content := range files {
- absPath := filepath.Join(dir, relPath)
- if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(absPath, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
- }
-
- // Create a .git directory marker so discover treats it as a repo root.
- if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/internal/pipeline/mmap_madvise_linux.go b/internal/pipeline/mmap_madvise_linux.go
deleted file mode 100644
index 00c7649ec..000000000
--- a/internal/pipeline/mmap_madvise_linux.go
+++ /dev/null
@@ -1,9 +0,0 @@
-//go:build linux
-
-package pipeline
-
-import "syscall"
-
-func madviseSequential(b []byte) {
- _ = syscall.Madvise(b, syscall.MADV_SEQUENTIAL)
-}
diff --git a/internal/pipeline/mmap_madvise_other.go b/internal/pipeline/mmap_madvise_other.go
deleted file mode 100644
index b9d876968..000000000
--- a/internal/pipeline/mmap_madvise_other.go
+++ /dev/null
@@ -1,7 +0,0 @@
-//go:build !linux && !windows
-
-package pipeline
-
-// madviseSequential is a no-op on platforms without syscall.Madvise (e.g. macOS).
-// The prefetcher and kernel default readahead provide sufficient coverage.
-func madviseSequential(_ []byte) {}
diff --git a/internal/pipeline/mmap_unix.go b/internal/pipeline/mmap_unix.go
deleted file mode 100644
index b4a8c4a1c..000000000
--- a/internal/pipeline/mmap_unix.go
+++ /dev/null
@@ -1,53 +0,0 @@
-//go:build !windows
-
-package pipeline
-
-import (
- "os"
- "syscall"
-)
-
-// mmapMinSize is the minimum file size worth mmap'ing.
-// Below this, mmap syscall overhead exceeds the copy savings.
-const mmapMinSize = 4096
-
-// mmapFile memory-maps a file for reading. Returns the mapped data and a
-// cleanup function that must be called when done (typically via defer).
-// For small files (<4KB) or on mmap failure, falls back to os.ReadFile.
-func mmapFile(path string) (data []byte, cleanup func(), err error) {
- f, err := os.Open(path)
- if err != nil {
- return nil, nil, err
- }
-
- fi, err := f.Stat()
- if err != nil {
- f.Close()
- return nil, nil, err
- }
-
- size := fi.Size()
-
- // Small files: mmap overhead not worth it
- if size < mmapMinSize || size == 0 {
- f.Close()
- d, err := os.ReadFile(path)
- return d, nil, err
- }
-
- mapped, err := syscall.Mmap(int(f.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_PRIVATE)
- if err != nil {
- // mmap failed (NFS, FUSE, etc.) — fall back
- f.Close()
- d, readErr := os.ReadFile(path)
- return d, nil, readErr
- }
-
- // Hint sequential access for readahead (best-effort, not on all platforms)
- madviseSequential(mapped)
-
- // Close fd — mmap keeps a kernel reference; fd is no longer needed
- f.Close()
-
- return mapped, func() { _ = syscall.Munmap(mapped) }, nil
-}
diff --git a/internal/pipeline/mmap_windows.go b/internal/pipeline/mmap_windows.go
deleted file mode 100644
index aaf31cf6c..000000000
--- a/internal/pipeline/mmap_windows.go
+++ /dev/null
@@ -1,13 +0,0 @@
-//go:build windows
-
-package pipeline
-
-import "os"
-
-// mmapFile on Windows falls back to os.ReadFile.
-// Windows mmap (CreateFileMapping) requires different syscalls;
-// for now the primary target is Linux/macOS.
-func mmapFile(path string) (data []byte, cleanup func(), err error) {
- d, err := os.ReadFile(path)
- return d, nil, err
-}
diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go
deleted file mode 100644
index d43a00cf9..000000000
--- a/internal/pipeline/pipeline.go
+++ /dev/null
@@ -1,1517 +0,0 @@
-package pipeline
-
-import (
- "context"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "regexp"
- "runtime"
- "runtime/debug"
- "strings"
- "sync"
- "time"
-
- "github.com/zeebo/xxh3"
- "golang.org/x/sync/errgroup"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/httplink"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// Pipeline orchestrates the 3-pass indexing of a repository.
-type Pipeline struct {
- ctx context.Context
- Store store.StoreBackend // graph ops (buffer or SQLite)
- diskStore *store.Store // SQLite-specific: project mgmt, file hashes, backup
- RepoPath string
- ProjectName string
- Mode discover.IndexMode
- // buf holds typed reference to GraphBuffer for FlushTo during dump.
- // During full index, p.Store points to the same object.
- buf *GraphBuffer
- // extractionCache maps file rel_path -> CBM extraction result for all post-definition passes
- extractionCache map[string]*cachedExtraction
- // registry indexes all Function/Method/Class nodes for call resolution
- registry *FunctionRegistry
- // importMaps stores per-module import maps: moduleQN -> localName -> resolvedQN
- importMaps map[string]map[string]string
- // returnTypes maps function QN -> return type QN for return-type-based type inference
- returnTypes ReturnTypeMap
- // goLSPIdx indexes Go cross-file definitions for LSP resolution in pass3
- goLSPIdx *goLSPDefIndex
- // cLSPIdx indexes C/C++/CUDA cross-file definitions for LSP resolution in pass3
- cLSPIdx *cLSPDefIndex
- // compileFlags holds per-file compile flags from compile_commands.json (C/C++ only)
- compileFlags CompileFlagsMap
- // sourceStore holds LZ4-compressed file bytes loaded during bulk load.
- // All post-parse passes decompress from here instead of re-reading from disk.
- // Nil'd after all passes complete.
- sourceStore map[string]*compressedSource
-}
-
-// compressedSource holds an LZ4 HC compressed file with pre-computed hash.
-type compressedSource struct {
- data []byte // LZ4 HC compressed
- originalLen int // for decompressor
- hash string // xxh3 hex, pre-computed during bulk load
- mtimeNs int64 // file mtime from stat during bulk load
- size int64 // file size from stat during bulk load
-}
-
-// New creates a new Pipeline.
-func New(ctx context.Context, s *store.Store, repoPath string, mode discover.IndexMode) *Pipeline {
- if mode == "" {
- mode = discover.ModeFull
- }
- projectName := ProjectNameFromPath(repoPath)
- return &Pipeline{
- ctx: ctx,
- Store: s, // StoreBackend interface — initially the disk store
- diskStore: s, // always the disk store
- RepoPath: repoPath,
- ProjectName: projectName,
- Mode: mode,
- extractionCache: make(map[string]*cachedExtraction),
- registry: NewFunctionRegistry(),
- importMaps: make(map[string]map[string]string),
- }
-}
-
-// ProjectNameFromPath derives a unique project name from an absolute path
-// by replacing path separators with dashes and trimming the leading dash.
-func ProjectNameFromPath(absPath string) string {
- // Clean and normalize separators (backslash is not a separator on non-Windows)
- cleaned := filepath.ToSlash(filepath.Clean(absPath))
- cleaned = strings.ReplaceAll(cleaned, "\\", "/")
- // Normalize Windows drive letter casing: "D:/foo" → "d:/foo"
- // Prevents duplicate DBs for same path with different drive letter case.
- if len(cleaned) >= 2 && cleaned[1] == ':' {
- cleaned = strings.ToLower(cleaned[:1]) + cleaned[1:]
- }
- // Replace slashes and colons with dashes
- name := strings.ReplaceAll(cleaned, "/", "-")
- name = strings.ReplaceAll(name, ":", "-")
- // Collapse consecutive dashes (e.g. C:/ → C--)
- for strings.Contains(name, "--") {
- name = strings.ReplaceAll(name, "--", "-")
- }
- // Trim leading dash (from leading /)
- name = strings.TrimLeft(name, "-")
- if name == "" {
- return "root"
- }
- return name
-}
-
-// checkCancel returns ctx.Err() if the pipeline's context has been cancelled.
-func (p *Pipeline) checkCancel() error {
- return p.ctx.Err()
-}
-
-// Run executes the full 3-pass pipeline within a single transaction.
-// If file hashes from a previous run exist, only changed files are re-processed.
-func (p *Pipeline) Run() error {
- runStart := time.Now()
- slog.Info("pipeline.start", "project", p.ProjectName, "path", p.RepoPath, "mode", string(p.Mode))
-
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // Load compile_commands.json for C/C++ include paths and defines
- p.compileFlags = loadCompileCommands(p.RepoPath)
-
- // Discover source files (filesystem, no DB — runs outside transaction)
- discoverOpts := &discover.Options{Mode: p.Mode}
- if p.Mode == discover.ModeFast {
- discoverOpts.MaxFileSize = 512 * 1024 // 512KB cutoff in fast mode
- }
- files, err := discover.Discover(p.ctx, p.RepoPath, discoverOpts)
- if err != nil {
- return fmt.Errorf("discover: %w", err)
- }
- slog.Info("pipeline.discovered", "files", len(files))
- logHeapStats("pre_index")
-
- // Classify files (read-only) to decide full vs incremental path
- changed, unchanged := p.classifyFiles(files)
- isFullIndex := len(unchanged) == 0
-
- if isFullIndex {
- // Full index: use in-memory SQLite for zero disk I/O during passes.
- // All data is built in RAM and restored to the disk store at the end.
- if err := p.runFullIndex(files, runStart); err != nil {
- return err
- }
- } else {
- // Incremental: use existing disk-backed store with transaction
- if err := p.runIncrementalIndex(files, changed, unchanged, runStart); err != nil {
- return err
- }
- }
-
- nc, _ := p.Store.CountNodes(p.ProjectName)
- ec, _ := p.Store.CountEdges(p.ProjectName)
- logHeapStats("post_index")
- slog.Info("pipeline.done", "nodes", nc, "edges", ec, "total_elapsed", time.Since(runStart))
-
- // Final cleanup: release remaining heavy fields and return memory to OS.
- // Pipeline is a local var in callers, but explicit nil + FreeOSMemory
- // ensures RSS drops immediately rather than waiting for next GC cycle.
- p.compileFlags = nil
- p.buf = nil
- p.sourceStore = nil
- debug.FreeOSMemory()
-
- return nil
-}
-
-// runSemanticEdgePasses runs the semantic edge passes (USES_TYPE, THROWS, READS/WRITES, CONFIGURES).
-func (p *Pipeline) runSemanticEdgePasses() {
- t := time.Now()
- p.passUsesType()
- slog.Info("pass.timing", "pass", "usestype", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passThrows()
- slog.Info("pass.timing", "pass", "throws", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passReadsWrites()
- slog.Info("pass.timing", "pass", "readwrite", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passConfigures()
- slog.Info("pass.timing", "pass", "configures", "elapsed", time.Since(t))
-}
-
-// logEdgeCounts logs the count of each edge type for observability.
-func (p *Pipeline) logEdgeCounts() {
- edgeTypes := []string{
- "CALLS", "USAGE", "IMPORTS", "DEFINES", "DEFINES_METHOD",
- "TESTS", "TESTS_FILE", "INHERITS", "DECORATES", "USES_TYPE",
- "THROWS", "RAISES", "READS", "WRITES", "CONFIGURES", "MEMBER_OF",
- "HTTP_CALLS", "HANDLES", "ASYNC_CALLS", "IMPLEMENTS", "OVERRIDE",
- "FILE_CHANGES_WITH", "CONTAINS_FILE", "CONTAINS_FOLDER", "CONTAINS_PACKAGE",
- }
- for _, edgeType := range edgeTypes {
- count, err := p.Store.CountEdgesByType(p.ProjectName, edgeType)
- if err == nil && count > 0 {
- slog.Info("pipeline.edges", "type", edgeType, "count", count)
- }
- }
-}
-
-// fieldGroup identifies which FileResult fields to release after a pass.
-type fieldGroup int
-
-const (
- fieldsPostCalls fieldGroup = iota // Definitions, Calls, ResolvedCalls, TypeAssigns, Imports
- fieldsPostUsages // Usages
- fieldsPostSemantic // TypeRefs, Throws, ReadWrites, EnvAccesses
-)
-
-// releaseExtractionFields nils out consumed FileResult slices to reduce peak memory.
-// Each FileResult field is used by specific passes; once a pass completes, its fields
-// can be released. For a 100K-file repo, Definitions+Calls alone hold ~10 GB.
-func (p *Pipeline) releaseExtractionFields(group fieldGroup) {
- for _, ext := range p.extractionCache {
- if ext.Result == nil {
- continue
- }
- switch group {
- case fieldsPostCalls:
- ext.Result.Definitions = nil
- ext.Result.Calls = nil
- ext.Result.ResolvedCalls = nil
- ext.Result.TypeAssigns = nil
- ext.Result.Imports = nil
- case fieldsPostUsages:
- ext.Result.Usages = nil
- case fieldsPostSemantic:
- ext.Result.TypeRefs = nil
- ext.Result.Throws = nil
- ext.Result.ReadWrites = nil
- ext.Result.EnvAccesses = nil
- }
- }
-}
-
-func (p *Pipeline) cleanupASTCache() {
- // Free C-allocated TSTree handles before dropping Go references.
- // Without this, the Go GC reclaims FileResult structs but the C trees
- // (allocated via ts_parser_parse_string, held as unsafe.Pointer) leak.
- for _, ext := range p.extractionCache {
- if ext.Result != nil {
- ext.Result.FreeTree()
- }
- }
- p.extractionCache = nil
- // Prompt the Go runtime to return freed pages to the OS.
- // Especially useful under GOMEMLIMIT to keep RSS closer to actual usage.
- debug.FreeOSMemory()
-}
-
-// getSource returns the raw source bytes for a file from the in-memory sourceStore.
-// Decompresses LZ4 on-the-fly (~3μs per 17KB file at 5.7 GB/s).
-// Returns nil if the file is not in the store (e.g., infra files not parsed by CBM).
-func (p *Pipeline) getSource(relPath string) []byte {
- if p.sourceStore == nil {
- return nil
- }
- cs := p.sourceStore[relPath]
- if cs == nil {
- return nil
- }
- return cbm.LZ4Decompress(cs.data, cs.originalLen)
-}
-
-// getHash returns the pre-computed xxh3 hash for a file. O(1), no disk I/O.
-func (p *Pipeline) getHash(relPath string) (hash string, mtimeNs, size int64, ok bool) {
- if p.sourceStore == nil {
- return "", 0, 0, false
- }
- cs := p.sourceStore[relPath]
- if cs == nil {
- return "", 0, 0, false
- }
- return cs.hash, cs.mtimeNs, cs.size, true
-}
-
-// bulkLoadSources reads all files, computes xxh3 hashes, and LZ4 HC compresses
-// them into the sourceStore. This is the ONLY bulk disk read for full indexing.
-func (p *Pipeline) bulkLoadSources(files []discover.FileInfo) {
- t := time.Now()
- p.sourceStore = make(map[string]*compressedSource, len(files))
-
- type loadResult struct {
- relPath string
- cs *compressedSource
- err error
- }
-
- results := make([]loadResult, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g := new(errgroup.Group)
- g.SetLimit(numWorkers)
- for i, f := range files {
- g.Go(func() error {
- if err := p.ctx.Err(); err != nil {
- return err //nolint:wrapcheck // context cancellation
- }
- source, cleanup, err := mmapFile(f.Path)
- if err != nil {
- results[i] = loadResult{relPath: f.RelPath, err: err}
- if cleanup != nil {
- cleanup()
- }
- return nil
- }
-
- // Compute xxh3 hash from raw source
- h := xxh3.New()
- _, _ = h.Write(source)
- hashHex := hex.EncodeToString(h.Sum(nil))
-
- // Get stat info
- var mtimeNs, size int64
- if fi, statErr := os.Stat(f.Path); statErr == nil {
- mtimeNs = fi.ModTime().UnixNano()
- size = fi.Size()
- }
-
- // LZ4 HC compress
- compressed := cbm.LZ4CompressHC(source)
- originalLen := len(source)
-
- // Unmap before storing (we have the compressed copy)
- if cleanup != nil {
- cleanup()
- }
-
- results[i] = loadResult{
- relPath: f.RelPath,
- cs: &compressedSource{
- data: compressed,
- originalLen: originalLen,
- hash: hashHex,
- mtimeNs: mtimeNs,
- size: size,
- },
- }
- return nil
- })
- }
- _ = g.Wait()
-
- // Collect results (sequential, no lock needed)
- var totalRaw, totalCompressed int64
- var loaded int
- for _, r := range results {
- if r.cs == nil {
- continue
- }
- p.sourceStore[r.relPath] = r.cs
- totalRaw += int64(r.cs.originalLen)
- totalCompressed += int64(len(r.cs.data))
- loaded++
- }
-
- ratio := float64(0)
- if totalCompressed > 0 {
- ratio = float64(totalRaw) / float64(totalCompressed)
- }
- slog.Info("bulk_load.done",
- "files", loaded,
- "raw_mb", totalRaw/(1<<20),
- "compressed_mb", totalCompressed/(1<<20),
- "ratio", fmt.Sprintf("%.1fx", ratio),
- "elapsed", time.Since(t),
- )
-}
-
-// getSourceLines returns a line range from the in-memory sourceStore.
-// Equivalent to readSourceLines but without disk I/O.
-func (p *Pipeline) getSourceLines(relPath string, startLine, endLine int) string {
- src := p.getSource(relPath)
- if len(src) == 0 {
- return ""
- }
- return extractLines(src, startLine, endLine)
-}
-
-// extractLines extracts lines [startLine, endLine] (1-based) from source bytes.
-func extractLines(src []byte, startLine, endLine int) string {
- var lines []string
- lineNum := 0
- start := 0
- for i := 0; i <= len(src); i++ {
- if i == len(src) || src[i] == '\n' {
- lineNum++
- if lineNum >= startLine && lineNum <= endLine {
- end := i
- if end > start && end > 0 && src[end-1] == '\r' {
- end--
- }
- lines = append(lines, string(src[start:end]))
- }
- if lineNum > endLine {
- break
- }
- start = i + 1
- }
- }
- return strings.Join(lines, "\n")
-}
-
-// logHeapStats logs current Go heap metrics for memory diagnostics.
-func logHeapStats(stage string) {
- var m runtime.MemStats
- runtime.ReadMemStats(&m)
- slog.Info("mem.stats",
- "stage", stage,
- "heap_inuse_mb", m.HeapInuse/(1<<20),
- "heap_alloc_mb", m.HeapAlloc/(1<<20),
- "sys_mb", m.Sys/(1<<20),
- )
-}
-
-// passStructure creates Project, Folder, Package, File nodes and containment edges.
-// Collects all nodes/edges in memory first, then batch-writes to DB.
-func (p *Pipeline) passStructure(files []discover.FileInfo) error {
- slog.Info("pass1.structure")
-
- dirSet, dirIsPackage := p.classifyDirectories(files)
-
- nodes := make([]*store.Node, 0, len(files)*2)
- edges := make([]pendingEdge, 0, len(files)*2)
-
- projectQN := p.ProjectName
- nodes = append(nodes, &store.Node{
- Project: p.ProjectName,
- Label: "Project",
- Name: p.ProjectName,
- QualifiedName: projectQN,
- })
-
- dirNodes, dirEdges := p.buildDirNodesEdges(dirSet, dirIsPackage, projectQN)
- nodes = append(nodes, dirNodes...)
- edges = append(edges, dirEdges...)
-
- fileNodes, fileEdges := p.buildFileNodesEdges(files)
- nodes = append(nodes, fileNodes...)
- edges = append(edges, fileEdges...)
-
- return p.batchWriteStructure(nodes, edges)
-}
-
-// classifyDirectories collects all directories and determines which are packages.
-func (p *Pipeline) classifyDirectories(files []discover.FileInfo) (allDirs, packageDirs map[string]bool) {
- packageIndicators := make(map[string]bool)
- for _, l := range lang.AllLanguages() {
- spec := lang.ForLanguage(l)
- if spec != nil {
- for _, pi := range spec.PackageIndicators {
- packageIndicators[pi] = true
- }
- }
- }
-
- allDirs = make(map[string]bool)
- for _, f := range files {
- dir := filepath.Dir(f.RelPath)
- for dir != "." && dir != "" && !allDirs[dir] {
- allDirs[dir] = true
- dir = filepath.Dir(dir)
- }
- }
-
- packageDirs = make(map[string]bool, len(allDirs))
- for dir := range allDirs {
- absDir := filepath.Join(p.RepoPath, dir)
- for indicator := range packageIndicators {
- if _, err := os.Stat(filepath.Join(absDir, indicator)); err == nil {
- packageDirs[dir] = true
- break
- }
- }
- }
- return
-}
-
-func (p *Pipeline) buildDirNodesEdges(dirSet, dirIsPackage map[string]bool, projectQN string) ([]*store.Node, []pendingEdge) {
- nodes := make([]*store.Node, 0, len(dirSet))
- edges := make([]pendingEdge, 0, len(dirSet))
-
- for dir := range dirSet {
- label := "Folder"
- edgeType := "CONTAINS_FOLDER"
- if dirIsPackage[dir] {
- label = "Package"
- edgeType = "CONTAINS_PACKAGE"
- }
- qn := fqn.FolderQN(p.ProjectName, dir)
- nodes = append(nodes, &store.Node{
- Project: p.ProjectName,
- Label: label,
- Name: filepath.Base(dir),
- QualifiedName: qn,
- FilePath: dir,
- })
-
- parent := filepath.Dir(dir)
- parentQN := projectQN
- if parent != "." && parent != "" {
- parentQN = fqn.FolderQN(p.ProjectName, parent)
- }
- edges = append(edges, pendingEdge{SourceQN: parentQN, TargetQN: qn, Type: edgeType})
- }
- return nodes, edges
-}
-
-func (p *Pipeline) buildFileNodesEdges(files []discover.FileInfo) ([]*store.Node, []pendingEdge) {
- nodes := make([]*store.Node, 0, len(files))
- edges := make([]pendingEdge, 0, len(files))
-
- for _, f := range files {
- fileQN := fqn.Compute(p.ProjectName, f.RelPath, "") + ".__file__"
- fileProps := map[string]any{
- "extension": filepath.Ext(f.RelPath),
- "is_test": isTestFile(f.RelPath, f.Language),
- }
- if f.Language != "" {
- fileProps["language"] = string(f.Language)
- }
- nodes = append(nodes, &store.Node{
- Project: p.ProjectName,
- Label: "File",
- Name: filepath.Base(f.RelPath),
- QualifiedName: fileQN,
- FilePath: f.RelPath,
- Properties: fileProps,
- })
-
- parentQN := p.dirQN(filepath.Dir(f.RelPath))
- edges = append(edges, pendingEdge{SourceQN: parentQN, TargetQN: fileQN, Type: "CONTAINS_FILE"})
- }
- return nodes, edges
-}
-
-func (p *Pipeline) batchWriteStructure(nodes []*store.Node, edges []pendingEdge) error {
- idMap, err := p.Store.UpsertNodeBatch(nodes)
- if err != nil {
- return fmt.Errorf("pass1 batch upsert: %w", err)
- }
-
- realEdges := make([]*store.Edge, 0, len(edges))
- for _, pe := range edges {
- srcID, srcOK := idMap[pe.SourceQN]
- tgtID, tgtOK := idMap[pe.TargetQN]
- if srcOK && tgtOK {
- realEdges = append(realEdges, &store.Edge{
- Project: p.ProjectName,
- SourceID: srcID,
- TargetID: tgtID,
- Type: pe.Type,
- Properties: pe.Properties,
- })
- }
- }
-
- if err := p.Store.InsertEdgeBatch(realEdges); err != nil {
- return fmt.Errorf("pass1 batch edges: %w", err)
- }
- return nil
-}
-
-func (p *Pipeline) dirQN(relDir string) string {
- if relDir == "." || relDir == "" {
- return p.ProjectName
- }
- return fqn.FolderQN(p.ProjectName, relDir)
-}
-
-// pendingEdge represents an edge to be created after batch node insertion,
-// using qualified names that will be resolved to IDs.
-type pendingEdge struct {
- SourceQN string
- TargetQN string
- Type string
- Properties map[string]any
-}
-
-// parseResult holds the output of a pure file parse (no DB access).
-type parseResult struct {
- File discover.FileInfo
- Nodes []*store.Node
- PendingEdges []pendingEdge
- ImportMap map[string]string
- CBMResult *cbm.FileResult // CBM extraction result (nil when using legacy AST path)
- Source []byte // raw file bytes, kept for post-parse passes (sourceStore)
- Err error
-}
-
-// passDefinitions extracts definitions from each file via CBM (C extraction library).
-// Uses parallel extraction (Stage 1) followed by sequential batch DB writes (Stage 2).
-func (p *Pipeline) passDefinitions(files []discover.FileInfo) { //nolint:gocognit,cyclop,funlen // two-stage parallel extraction + sequential DB write
- slog.Info("pass2.definitions")
-
- // Enrich JSON files with URL constants (for HTTP linking), then include
- // them in normal CBM extraction so they also get Variable/Class nodes.
- parseableFiles := make([]discover.FileInfo, 0, len(files))
- for _, f := range files {
- if f.Language == lang.JSON {
- if p.ctx.Err() != nil {
- return
- }
- if err := p.processJSONFile(f); err != nil {
- slog.Warn("pass2.json.err", "path", f.RelPath, "err", err)
- }
- }
- parseableFiles = append(parseableFiles, f)
- }
-
- if len(parseableFiles) == 0 {
- return
- }
-
- // Stage 1: Parallel CBM extraction (CPU-only when sourceStore is populated)
- t1 := time.Now()
- results := make([]*parseResult, len(parseableFiles))
- hasBulkLoaded := p.sourceStore != nil
-
- if hasBulkLoaded {
- // RAM path: decompress from sourceStore, no disk I/O
- pool := newAdaptivePool(runtime.NumCPU())
- go pool.monitor(p.ctx)
- var wg sync.WaitGroup
- for i, f := range parseableFiles {
- pool.acquire()
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer pool.releaseBytes(f.Size)
- if p.ctx.Err() != nil {
- return
- }
- source := p.getSource(f.RelPath)
- var readErr error
- if source == nil {
- readErr = fmt.Errorf("not in sourceStore: %s", f.RelPath)
- }
- results[i] = cbmParseFileFromSource(p.ProjectName, f, source, readErr, p.getCompileFlags(f.RelPath))
- }()
- }
- wg.Wait()
- pool.stop()
- } else {
- // Disk path (incremental): mmap from disk as before
- pf := newPrefetcher(parseableFiles, 100)
- go pf.run(p.ctx)
- defer pf.stop()
-
- pool := newAdaptivePool(runtime.NumCPU())
- go pool.monitor(p.ctx)
- var wg sync.WaitGroup
- for i, f := range parseableFiles {
- pool.acquire()
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer pool.releaseBytes(f.Size)
- if p.ctx.Err() != nil {
- return
- }
- results[i] = cbmParseFile(p.ProjectName, f, p.getCompileFlags(f.RelPath))
- pf.advance(i + 1)
- }()
- }
- wg.Wait()
- pool.stop()
- }
- slog.Info("pass2.stage1.extract", "files", len(parseableFiles), "from_ram", hasBulkLoaded, "elapsed", time.Since(t1))
-
- // Log C-side parse vs extraction breakdown
- profile := cbm.GetProfile()
- if profile.Files > 0 {
- slog.Info("pass2.stage1.profile",
- "files", profile.Files,
- "parse_total", time.Duration(profile.ParseNs),
- "extract_total", time.Duration(profile.ExtractNs),
- "parse_avg_us", profile.ParseNs/profile.Files/1000,
- "extract_avg_us", profile.ExtractNs/profile.Files/1000,
- "preprocess_total", time.Duration(profile.PreprocessNs),
- "files_preprocessed", profile.FilesPreprocessed,
- )
- }
-
- // Stage 2: Sequential cache population + batch DB writes + inline registry build
- t2 := time.Now()
- var allNodes []*store.Node
- var allPendingEdges []pendingEdge
-
- // Initialize sourceStore for incremental path (bulk load already did this for full)
- if p.sourceStore == nil {
- p.sourceStore = make(map[string]*compressedSource, len(results))
- }
-
- for _, r := range results {
- if r == nil {
- continue
- }
- if r.Err != nil {
- slog.Warn("pass2.file.err", "path", r.File.RelPath, "err", r.Err)
- continue
- }
- // Populate extraction cache for use by later passes
- if r.CBMResult != nil {
- p.extractionCache[r.File.RelPath] = &cachedExtraction{
- Result: r.CBMResult,
- Language: r.File.Language,
- }
- }
- // Store raw source bytes for incremental path (full path already has them in sourceStore)
- if !hasBulkLoaded && len(r.Source) > 0 {
- compressed := cbm.LZ4CompressHC(r.Source)
- p.sourceStore[r.File.RelPath] = &compressedSource{
- data: compressed,
- originalLen: len(r.Source),
- }
- r.Source = nil
- }
- // Store import map
- moduleQN := fqn.ModuleQN(p.ProjectName, r.File.RelPath)
- if len(r.ImportMap) > 0 {
- p.importMaps[moduleQN] = r.ImportMap
- }
- // Inline registry build: register each callable node as it's collected,
- // eliminating the separate buildRegistry() scan over the entire store.
- for _, n := range r.Nodes {
- if isRegistrableLabel(n.Label) {
- p.registry.Register(n.Name, n.QualifiedName, n.Label)
- }
- }
- allNodes = append(allNodes, r.Nodes...)
- allPendingEdges = append(allPendingEdges, r.PendingEdges...)
- }
-
- slog.Info("pass2.stage2.collect", "nodes", len(allNodes), "edges", len(allPendingEdges), "elapsed", time.Since(t2))
-
- // Batch insert all nodes
- t3 := time.Now()
- idMap, err := p.Store.UpsertNodeBatch(allNodes)
- if err != nil {
- slog.Warn("pass2.batch_upsert.err", "err", err)
- return
- }
- slog.Info("pass2.stage3.upsert_nodes", "nodes", len(allNodes), "elapsed", time.Since(t3))
-
- // Resolve pending edges to real edges using the ID map
- t4 := time.Now()
- edges := make([]*store.Edge, 0, len(allPendingEdges))
- for _, pe := range allPendingEdges {
- srcID, srcOK := idMap[pe.SourceQN]
- tgtID, tgtOK := idMap[pe.TargetQN]
- if srcOK && tgtOK {
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: srcID,
- TargetID: tgtID,
- Type: pe.Type,
- Properties: pe.Properties,
- })
- }
- }
-
- if err := p.Store.InsertEdgeBatch(edges); err != nil {
- slog.Warn("pass2.batch_edges.err", "err", err)
- }
- slog.Info("pass2.stage4.insert_edges", "edges", len(edges), "elapsed", time.Since(t4))
-}
-
-// isRegistrableLabel returns true if nodes with this label should be registered
-// in the FunctionRegistry for call resolution.
-func isRegistrableLabel(label string) bool {
- switch label {
- case "Function", "Method", "Class", "Type", "Interface", "Enum", "Macro", "Variable":
- return true
- }
- return false
-}
-
-// buildRegistry populates the FunctionRegistry from all Function, Method,
-// and Class nodes in the store. Used by the incremental path where inline
-// registration during passDefinitions isn't available for existing nodes.
-func (p *Pipeline) buildRegistry() {
- for _, label := range []string{"Function", "Method", "Class", "Type", "Interface", "Enum", "Macro", "Variable"} {
- nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, n := range nodes {
- p.registry.Register(n.Name, n.QualifiedName, n.Label)
- }
- }
- slog.Info("registry.built", "entries", p.registry.Size())
-}
-
-// buildReturnTypeMap builds a map from function QN to its return type QN.
-// Uses the "return_types" property stored on Function/Method nodes during pass2.
-func (p *Pipeline) buildReturnTypeMap() {
- p.returnTypes = make(ReturnTypeMap)
- for _, label := range []string{"Function", "Method"} {
- nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
- if err != nil {
- continue
- }
- for _, n := range nodes {
- retTypes, ok := n.Properties["return_types"]
- if !ok {
- continue
- }
- // return_types is stored as []any (JSON round-trip) containing type name strings
- typeList, ok := retTypes.([]any)
- if !ok || len(typeList) == 0 {
- continue
- }
- // Use the first return type — most functions return a single type
- firstType, ok := typeList[0].(string)
- if !ok || firstType == "" {
- continue
- }
- // Resolve the type name to a class QN
- classQN := resolveAsClass(firstType, p.registry, "", nil)
- if classQN != "" {
- p.returnTypes[n.QualifiedName] = classQN
- }
- }
- }
- if len(p.returnTypes) > 0 {
- slog.Info("return_types.built", "entries", len(p.returnTypes))
- }
-}
-
-// resolvedEdge represents an edge resolved during parallel call/usage resolution,
-// stored as QN pairs to be converted to ID-based edges in the batch write stage.
-type resolvedEdge struct {
- CallerQN string
- TargetQN string
- Type string // "CALLS" or "USAGE"
- Properties map[string]any
-}
-
-// passCalls resolves call targets and creates CALLS edges.
-// Phase 1: Batch cross-file LSP (Go + C/C++) — one CGo call per language family.
-// Phase 2: Parallel per-file registry + fuzzy resolution (pure Go, no CGo).
-// Phase 3: Batch QN→ID resolution + edge insert.
-func (p *Pipeline) passCalls() {
- slog.Info("pass3.calls")
-
- // Collect files to process from extraction cache
- var files []fileEntry
- for relPath, ext := range p.extractionCache {
- if lang.ForLanguage(ext.Language) != nil {
- files = append(files, fileEntry{relPath, ext})
- }
- }
-
- if len(files) == 0 {
- return
- }
-
- // Phase 1: Batch cross-file LSP — partitioned for parallel CGo calls
- p.batchGoLSPCrossFileResolution(files)
- p.batchCLSPCrossFileResolution(files)
-
- // Free cached trees — no longer needed after cross-file LSP
- for _, fe := range files {
- if fe.ext.Result != nil {
- fe.ext.Result.FreeTree()
- }
- }
-
- // Release Definitions + Imports — only needed for cross-file LSP
- for _, fe := range files {
- if fe.ext.Result != nil {
- fe.ext.Result.Definitions = nil
- fe.ext.Result.Imports = nil
- }
- }
-
- // Phase 2: Parallel per-file call resolution (registry + fuzzy, no CGo)
- results := make([][]resolvedEdge, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g, gctx := errgroup.WithContext(p.ctx)
- g.SetLimit(numWorkers)
- for i, fe := range files {
- g.Go(func() error {
- if gctx.Err() != nil {
- return gctx.Err()
- }
- results[i] = p.resolveFileCallsCBM(fe.relPath, fe.ext)
- return nil
- })
- }
- _ = g.Wait()
-
- // Stage 2: Batch QN→ID resolution + batch edge insert
- p.flushResolvedEdges(results)
-}
-
-// flushResolvedEdges converts QN-based resolved edges to ID-based edges and batch-inserts them.
-func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {
- qnSet, totalEdges := collectEdgeQNs(results)
- if totalEdges == 0 {
- return
- }
-
- // Batch resolve all QNs to IDs
- qns := make([]string, 0, len(qnSet))
- for qn := range qnSet {
- qns = append(qns, qn)
- }
- qnToID, err := p.Store.FindNodeIDsByQNs(p.ProjectName, qns)
- if err != nil {
- slog.Warn("pass3.resolve_ids.err", "err", err)
- return
- }
-
- // Create stub nodes for LSP-resolved targets that don't exist in the graph.
- p.createLSPStubNodes(results, qnToID)
-
- // Build and insert edges
- edges := buildEdgesFromResults(results, qnToID, p.ProjectName, totalEdges)
- if err := p.Store.InsertEdgeBatch(edges); err != nil {
- slog.Warn("pass3.batch_edges.err", "err", err)
- }
-}
-
-// collectEdgeQNs collects all unique qualified names and counts total edges from results.
-func collectEdgeQNs(results [][]resolvedEdge) (qnSet map[string]struct{}, totalEdges int) {
- qnSet = make(map[string]struct{})
- for _, fileEdges := range results {
- for _, re := range fileEdges {
- qnSet[re.CallerQN] = struct{}{}
- qnSet[re.TargetQN] = struct{}{}
- totalEdges++
- }
- }
- return qnSet, totalEdges
-}
-
-// createLSPStubNodes creates stub nodes for LSP-resolved targets that don't exist in the graph.
-// This happens for stdlib/external methods (e.g., context.Context.Done) that
-// the LSP resolver correctly identifies but aren't indexed as nodes.
-func (p *Pipeline) createLSPStubNodes(results [][]resolvedEdge, qnToID map[string]int64) {
- var stubs []*store.Node
- stubQNs := make(map[string]bool)
- for _, fileEdges := range results {
- for _, re := range fileEdges {
- if _, ok := qnToID[re.TargetQN]; ok {
- continue
- }
- if stubQNs[re.TargetQN] {
- continue
- }
- strategy, _ := re.Properties["resolution_strategy"].(string)
- if !strings.HasPrefix(strategy, "lsp_") {
- continue
- }
- stubQNs[re.TargetQN] = true
- name := re.TargetQN
- if idx := strings.LastIndex(name, "."); idx >= 0 {
- name = name[idx+1:]
- }
- label := "Function"
- if strings.Count(re.TargetQN, ".") >= 2 {
- label = "Method"
- }
- stubs = append(stubs, &store.Node{
- Project: p.ProjectName,
- Label: label,
- Name: name,
- QualifiedName: re.TargetQN,
- Properties: map[string]any{"stub": true, "source": "lsp_resolution"},
- })
- }
- }
- if len(stubs) > 0 {
- stubIDs, err := p.Store.UpsertNodeBatch(stubs)
- if err != nil {
- slog.Warn("pass3.stub_nodes.err", "err", err)
- } else {
- for qn, id := range stubIDs {
- qnToID[qn] = id
- }
- slog.Info("pass3.stub_nodes", "count", len(stubs))
- }
- }
-}
-
-// buildEdgesFromResults converts QN-based resolved edges to store.Edge using the QN-to-ID map.
-func buildEdgesFromResults(results [][]resolvedEdge, qnToID map[string]int64, project string, totalEdges int) []*store.Edge {
- edges := make([]*store.Edge, 0, totalEdges)
- for _, fileEdges := range results {
- for _, re := range fileEdges {
- srcID, srcOK := qnToID[re.CallerQN]
- tgtID, tgtOK := qnToID[re.TargetQN]
- if srcOK && tgtOK {
- edges = append(edges, &store.Edge{
- Project: project,
- SourceID: srcID,
- TargetID: tgtID,
- Type: re.Type,
- Properties: re.Properties,
- })
- }
- }
- }
- return edges
-}
-
-// resolveCallWithTypes resolves a callee name using the registry, import maps,
-// and type inference for method dispatch.
-func (p *Pipeline) resolveCallWithTypes(
- calleeName, moduleQN string,
- importMap map[string]string,
- typeMap TypeMap,
-) ResolutionResult {
- // First, try type-based method dispatch for qualified calls like obj.method()
- if strings.Contains(calleeName, ".") {
- parts := strings.SplitN(calleeName, ".", 2)
- objName := parts[0]
- methodName := parts[1]
-
- // Check if the object has a known type from type inference
- if classQN, ok := typeMap[objName]; ok {
- candidate := classQN + "." + methodName
- if p.registry.Exists(candidate) {
- return ResolutionResult{QualifiedName: candidate, Strategy: "type_dispatch", Confidence: 0.90, CandidateCount: 1}
- }
- }
- }
-
- // Delegate to the registry's resolution strategy
- return p.registry.Resolve(calleeName, moduleQN, importMap)
-}
-
-// frameworkDecoratorPrefixes are decorator prefixes that indicate a function
-// is registered as an entry point by a framework (not dead code).
-var frameworkDecoratorPrefixes = []string{
- // Python web frameworks (route handlers)
- "@app.get", "@app.post", "@app.put", "@app.delete", "@app.patch",
- "@app.route", "@app.websocket",
- "@router.get", "@router.post", "@router.put", "@router.delete", "@router.patch",
- "@router.route", "@router.websocket",
- "@blueprint.", "@api.", "@ns.",
- // Python middleware and exception handlers (framework-registered)
- "@app.middleware", "@app.exception_handler", "@app.on_event",
- // Testing frameworks
- "@pytest.fixture", "@pytest.mark",
- // CLI frameworks
- "@click.command", "@click.group",
- // Task/worker frameworks
- "@celery.task", "@shared_task", "@task",
- // Signal handlers
- "@receiver",
- // Rust Actix/Axum/Rocket route macros (#[get("/path")] → extracted as get("/path"))
- "get(", "post(", "put(", "delete(", "patch(", "head(", "options(",
- "route(", "connect(", "trace(",
-}
-
-// hasFrameworkDecorator returns true if any decorator matches a framework pattern.
-func hasFrameworkDecorator(decorators []string) bool {
- for _, dec := range decorators {
- for _, prefix := range frameworkDecoratorPrefixes {
- if strings.HasPrefix(dec, prefix) {
- return true
- }
- }
- }
- return false
-}
-
-// passImports creates IMPORTS edges from the import maps built during pass 2.
-func (p *Pipeline) passImports() {
- slog.Info("pass2b.imports")
- count := 0
- for moduleQN, importMap := range p.importMaps {
- moduleNode, _ := p.Store.FindNodeByQN(p.ProjectName, moduleQN)
- if moduleNode == nil {
- continue
- }
- for localName, targetQN := range importMap {
- // Try to find the target as a Module node first
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
- if targetNode == nil {
- // Try treating import path as a relative file path (e.g. "utils.mag", "lib/helpers.h")
- resolvedQN := fqn.ModuleQN(p.ProjectName, targetQN)
- if resolvedQN != targetQN {
- targetNode, _ = p.Store.FindNodeByQN(p.ProjectName, resolvedQN)
- }
- }
- if targetNode == nil {
- logImportDrop(moduleQN, localName, targetQN)
- continue
- }
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: moduleNode.ID,
- TargetID: targetNode.ID,
- Type: "IMPORTS",
- Properties: map[string]any{
- "alias": localName,
- },
- })
- count++
- }
- }
- slog.Info("pass2b.imports.done", "edges", count)
-}
-
-// passHTTPLinks runs the HTTP linker to discover cross-service HTTP calls.
-func (p *Pipeline) passHTTPLinks() error {
- // Clean up stale Route/InfraFile nodes and HTTP_CALLS/HANDLES/ASYNC_CALLS edges before re-running
- _ = p.Store.DeleteNodesByLabel(p.ProjectName, "Route")
- _ = p.Store.DeleteNodesByLabel(p.ProjectName, "InfraFile")
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "HTTP_CALLS")
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "HANDLES")
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "ASYNC_CALLS")
-
- // Index infrastructure files (Dockerfiles, compose, cloudbuild, .env)
- p.passInfraFiles()
-
- // Scan config files for env var URLs and create synthetic Module nodes
- var envBindings []EnvBinding
- if p.sourceStore != nil {
- envBindings = p.scanEnvURLsFromStore()
- } else {
- envBindings = ScanProjectEnvURLs(p.RepoPath)
- }
- if len(envBindings) > 0 {
- p.injectEnvBindings(envBindings)
- }
-
- linker := httplink.New(p.Store, p.ProjectName)
-
- // Set RAM source readers when sourceStore is available (full index)
- if p.sourceStore != nil {
- linker.SetSourceReader(
- func(relPath string) []byte { return p.getSource(relPath) },
- func(relPath string, start, end int) string { return p.getSourceLines(relPath, start, end) },
- )
-
- // AC pre-screen: single CGo call scans all files for HTTP/async + route keywords.
- acCallFiles, acRouteFiles := p.acScreenHTTPFiles()
- if acCallFiles != nil {
- linker.SetHTTPKeywordFiles(acCallFiles)
- }
- if acRouteFiles != nil {
- linker.SetRouteKeywordFiles(acRouteFiles)
- }
- }
-
- // Feed InfraFile environment URLs into the HTTP linker
- infraSites := p.extractInfraCallSites()
- if len(infraSites) > 0 {
- linker.AddCallSites(infraSites)
- slog.Info("pass4.infra_callsites", "count", len(infraSites))
- }
-
- links, err := linker.Run()
- if err != nil {
- return err
- }
- slog.Info("pass4.httplinks", "links", len(links))
- return nil
-}
-
-// acScreenHTTPFiles uses a single Aho-Corasick automaton to pre-screen all
-// sourceStore files for HTTP client, async dispatch, AND route registration
-// keywords. One CGo call scans all files — zero per-file overhead.
-// Returns two maps: callFiles (HTTP/async keywords) and routeFiles (route keywords).
-func (p *Pipeline) acScreenHTTPFiles() (callFiles, routeFiles map[string]uint64) {
- httpKW := httplink.HTTPClientKeywords()
- asyncKW := httplink.AsyncDispatchKeywords()
- routeKW := httplink.RouteKeywords()
-
- // Layout: [httpClient...][asyncDispatch...][route...]
- // Deduplicate to fit in 64-bit bitmask.
- all := make([]string, 0, len(httpKW)+len(asyncKW)+len(routeKW))
- all = append(all, httpKW...)
- all = append(all, asyncKW...)
- all = append(all, routeKW...)
- seen := make(map[string]bool, len(all))
- patterns := all[:0]
- for _, p := range all {
- if !seen[p] {
- seen[p] = true
- patterns = append(patterns, p)
- }
- }
-
- ac := cbm.ACBuild(patterns)
- if ac == nil {
- return nil, nil
- }
- defer ac.Free()
-
- // Bitmask boundaries — computed from deduplicated positions.
- // Re-map: find which bits correspond to each category.
- var callBits, asyncBits, routeBits uint64
- pidOf := make(map[string]int, len(patterns))
- for i, p := range patterns {
- pidOf[p] = i
- }
- for _, kw := range httpKW {
- if pid, ok := pidOf[kw]; ok && pid < 64 {
- callBits |= 1 << pid
- }
- }
- for _, kw := range asyncKW {
- if pid, ok := pidOf[kw]; ok && pid < 64 {
- asyncBits |= 1 << pid
- }
- }
- for _, kw := range routeKW {
- if pid, ok := pidOf[kw]; ok && pid < 64 {
- routeBits |= 1 << pid
- }
- }
- callAndAsyncBits := callBits | asyncBits
-
- // Build LZ4 entry array + path index for single CGo call.
- t := time.Now()
- entries := make([]cbm.LZ4Entry, 0, len(p.sourceStore))
- paths := make([]string, 0, len(p.sourceStore))
- for relPath, cs := range p.sourceStore {
- entries = append(entries, cbm.LZ4Entry{Data: cs.data, OriginalLen: cs.originalLen})
- paths = append(paths, relPath)
- }
-
- matches := ac.ScanLZ4Batch(entries)
-
- callFiles = make(map[string]uint64)
- routeFiles = make(map[string]uint64)
- for _, m := range matches {
- relPath := paths[m.FileIndex]
- if m.Bitmask&callAndAsyncBits != 0 {
- callFiles[relPath] = m.Bitmask & callAndAsyncBits
- }
- if m.Bitmask&routeBits != 0 {
- routeFiles[relPath] = m.Bitmask & routeBits
- }
- }
-
- slog.Info("httplink.ac_screen",
- "files_total", len(entries),
- "call_files", len(callFiles),
- "route_files", len(routeFiles),
- "patterns", len(patterns),
- "states", ac.NumStates(),
- "table_kb", ac.TableBytes()/1024,
- "elapsed", time.Since(t))
-
- return callFiles, routeFiles
-}
-
-// extractInfraCallSites extracts URL values from InfraFile environment properties
-// and converts them to HTTPCallSite entries for the HTTP linker.
-func (p *Pipeline) extractInfraCallSites() []httplink.HTTPCallSite {
- infraNodes, err := p.Store.FindNodesByLabel(p.ProjectName, "InfraFile")
- if err != nil {
- return nil
- }
-
- var sites []httplink.HTTPCallSite
- for _, node := range infraNodes {
- // InfraFile nodes use different property keys depending on source:
- // compose files: "environment", Dockerfiles/shell/.env: "env_vars",
- // cloudbuild: "deploy_env_vars"
- for _, envKey := range []string{"environment", "env_vars", "deploy_env_vars"} {
- sites = append(sites, extractEnvURLSites(node, envKey)...)
- }
- }
- return sites
-}
-
-// extractEnvURLSites extracts HTTP call sites from a single env property of an InfraFile node.
-func extractEnvURLSites(node *store.Node, propKey string) []httplink.HTTPCallSite {
- env, ok := node.Properties[propKey]
- if !ok {
- return nil
- }
-
- // env_vars are stored as map[string]string (from Go), but after JSON round-trip
- // through SQLite they come back as map[string]any.
- var sites []httplink.HTTPCallSite
- switch envMap := env.(type) {
- case map[string]any:
- for _, val := range envMap {
- valStr, ok := val.(string)
- if !ok {
- continue
- }
- sites = append(sites, urlSitesFromValue(node, valStr)...)
- }
- case map[string]string:
- for _, valStr := range envMap {
- sites = append(sites, urlSitesFromValue(node, valStr)...)
- }
- }
- return sites
-}
-
-// urlSitesFromValue extracts URL paths from a string value and creates HTTPCallSite entries.
-func urlSitesFromValue(node *store.Node, val string) []httplink.HTTPCallSite {
- if !strings.Contains(val, "http://") && !strings.Contains(val, "https://") && !strings.HasPrefix(val, "/") {
- return nil
- }
-
- paths := httplink.ExtractURLPaths(val)
- sites := make([]httplink.HTTPCallSite, 0, len(paths))
- for _, path := range paths {
- sites = append(sites, httplink.HTTPCallSite{
- Path: path,
- SourceName: node.Name,
- SourceQualifiedName: node.QualifiedName,
- SourceLabel: "InfraFile",
- })
- }
- return sites
-}
-
-// injectEnvBindings creates or updates Module nodes for config files that contain
-// environment variable URL bindings. These synthetic constants feed into the
-// HTTP linker's call site discovery.
-func (p *Pipeline) injectEnvBindings(bindings []EnvBinding) {
- byFile := make(map[string][]EnvBinding)
- for _, b := range bindings {
- byFile[b.FilePath] = append(byFile[b.FilePath], b)
- }
-
- count := 0
- for filePath, fileBindings := range byFile {
- moduleQN := fqn.ModuleQN(p.ProjectName, filePath)
- constants := buildConstantsList(fileBindings)
-
- if p.mergeWithExistingModule(moduleQN, constants) {
- count += len(fileBindings)
- continue
- }
-
- _, _ = p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
- Label: "Module",
- Name: filepath.Base(filePath),
- QualifiedName: moduleQN,
- FilePath: filePath,
- Properties: map[string]any{"constants": constants},
- })
- count += len(fileBindings)
- }
-
- if count > 0 {
- slog.Info("envscan.injected", "bindings", count, "files", len(byFile))
- }
-}
-
-// buildConstantsList converts env bindings to "KEY = VALUE" constant strings, capped at 50.
-func buildConstantsList(bindings []EnvBinding) []string {
- constants := make([]string, 0, len(bindings))
- for _, b := range bindings {
- constants = append(constants, b.Key+" = "+b.Value)
- }
- if len(constants) > 50 {
- constants = constants[:50]
- }
- return constants
-}
-
-// mergeWithExistingModule merges new constants into an existing Module node's constant list.
-// Returns true if the module existed and was updated.
-func (p *Pipeline) mergeWithExistingModule(moduleQN string, constants []string) bool {
- existing, _ := p.Store.FindNodeByQN(p.ProjectName, moduleQN)
- if existing == nil {
- return false
- }
- existConsts, ok := existing.Properties["constants"].([]any)
- if !ok {
- return false
- }
- seen := make(map[string]bool, len(existConsts))
- for _, c := range existConsts {
- if s, ok := c.(string); ok {
- seen[s] = true
- }
- }
- for _, c := range constants {
- if !seen[c] {
- existConsts = append(existConsts, c)
- }
- }
- if existing.Properties == nil {
- existing.Properties = map[string]any{}
- }
- existing.Properties["constants"] = existConsts
- _, _ = p.Store.UpsertNode(existing)
- return true
-}
-
-// jsonURLKeyPattern matches JSON keys that likely contain URL/endpoint values.
-var jsonURLKeyPattern = regexp.MustCompile(`(?i)(url|endpoint|base_url|host|api_url|service_url|target_url|callback_url|webhook|href|uri|address|server|origin|proxy|redirect|forward|destination)`)
-
-// processJSONFile extracts URL-related string values from JSON config files.
-// Uses a key-pattern allowlist to avoid flooding constants with noise.
-func (p *Pipeline) processJSONFile(f discover.FileInfo) error {
- // Use sourceStore if available (RAM path), fall back to disk
- data := p.getSource(f.RelPath)
- if data == nil {
- var err error
- data, err = os.ReadFile(f.Path)
- if err != nil {
- return err
- }
- }
-
- var parsed any
- if err := json.Unmarshal(data, &parsed); err != nil {
- return fmt.Errorf("json parse: %w", err)
- }
-
- var constants []string
- extractJSONURLValues(parsed, "", &constants, 0)
-
- if len(constants) == 0 {
- return nil
- }
-
- // Cap at 20 constants per JSON file
- if len(constants) > 20 {
- constants = constants[:20]
- }
-
- moduleQN := fqn.ModuleQN(p.ProjectName, f.RelPath)
- _, err := p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
- Label: "Module",
- Name: filepath.Base(f.RelPath),
- QualifiedName: moduleQN,
- FilePath: f.RelPath,
- Properties: map[string]any{"constants": constants},
- })
- return err
-}
-
-// extractJSONURLValues recursively extracts key=value pairs from JSON where
-// the key matches the URL key pattern or the value looks like a URL/path.
-func extractJSONURLValues(v any, key string, out *[]string, depth int) {
- if depth > 20 {
- return
- }
-
- switch val := v.(type) {
- case map[string]any:
- for k, child := range val {
- extractJSONURLValues(child, k, out, depth+1)
- }
- case []any:
- for _, child := range val {
- extractJSONURLValues(child, key, out, depth+1)
- }
- case string:
- if key == "" || val == "" {
- return
- }
- // Include if key matches URL pattern
- if jsonURLKeyPattern.MatchString(key) {
- *out = append(*out, key+" = "+val)
- return
- }
- // Include if value looks like a URL or API path
- if looksLikeURL(val) {
- *out = append(*out, key+" = "+val)
- }
- }
-}
-
-// looksLikeURL returns true if s appears to be a URL or API path.
-func looksLikeURL(s string) bool {
- if strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") {
- return true
- }
- // Path starting with /api/ or containing at least 2 segments
- if strings.HasPrefix(s, "/") && strings.Count(s, "/") >= 2 {
- // Skip version-like paths: /1.0.0, /v2, /en
- seg := strings.TrimPrefix(s, "/")
- return len(seg) > 3
- }
- return false
-}
-
-// safeRowToLine converts a tree-sitter row (uint) to a 1-based line number (int).
-// Returns math.MaxInt if the value would overflow.
-// stripBOM removes a UTF-8 BOM (0xEF 0xBB 0xBF) from the start of source.
-// Common in C# and Windows-generated files; tree-sitter may choke on BOM bytes.
-func stripBOM(source []byte) []byte {
- if len(source) >= 3 && source[0] == 0xEF && source[1] == 0xBB && source[2] == 0xBF {
- return source[3:]
- }
- return source
-}
diff --git a/internal/pipeline/pipeline_bench_test.go b/internal/pipeline/pipeline_bench_test.go
deleted file mode 100644
index db6f330c4..000000000
--- a/internal/pipeline/pipeline_bench_test.go
+++ /dev/null
@@ -1,334 +0,0 @@
-package pipeline
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// setupBenchRepo creates a temp directory with 10 Go files across 2 packages.
-// Package "model" defines structs and methods; package "handler" calls into model.
-func setupBenchRepo(b *testing.B) (dir string, cleanup func()) {
- b.Helper()
- dir, err := os.MkdirTemp("", "cgm-bench-*")
- if err != nil {
- b.Fatal(err)
- }
- cleanup = func() { os.RemoveAll(dir) }
-
- writeBenchModelFiles(b, dir)
- writeBenchHandlerFiles(b, dir)
-
- return dir, cleanup
-}
-
-func writeBenchModelFiles(b *testing.B, dir string) {
- b.Helper()
-
- writeBenchFile(b, filepath.Join(dir, "model", "order.go"), `package model
-
-type Order struct {
- ID string
- Customer string
- Total float64
- Items []Item
-}
-
-func NewOrder(id, customer string) *Order {
- return &Order{ID: id, Customer: customer}
-}
-
-func (o *Order) AddItem(item Item) {
- o.Items = append(o.Items, item)
- o.Total += item.Price
-}
-
-func (o *Order) Validate() error {
- if o.ID == "" {
- return nil
- }
- return nil
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "model", "item.go"), `package model
-
-type Item struct {
- SKU string
- Name string
- Price float64
- Qty int
-}
-
-func NewItem(sku, name string, price float64, qty int) Item {
- return Item{SKU: sku, Name: name, Price: price, Qty: qty}
-}
-
-func (i Item) Subtotal() float64 {
- return i.Price * float64(i.Qty)
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "model", "customer.go"), `package model
-
-type Customer struct {
- ID string
- Name string
- Email string
-}
-
-func NewCustomer(id, name, email string) *Customer {
- return &Customer{ID: id, Name: name, Email: email}
-}
-
-func (c *Customer) DisplayName() string {
- if c.Name != "" {
- return c.Name
- }
- return c.Email
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "model", "inventory.go"), `package model
-
-type Inventory struct {
- Stock map[string]int
-}
-
-func NewInventory() *Inventory {
- return &Inventory{Stock: make(map[string]int)}
-}
-
-func (inv *Inventory) Reserve(sku string, qty int) bool {
- if inv.Stock[sku] >= qty {
- inv.Stock[sku] -= qty
- return true
- }
- return false
-}
-
-func (inv *Inventory) Restock(sku string, qty int) {
- inv.Stock[sku] += qty
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "model", "pricing.go"), `package model
-
-const (
- TaxRate = 0.19
- DiscountCap = 0.25
-)
-
-func ApplyTax(amount float64) float64 {
- return amount * (1 + TaxRate)
-}
-
-func ApplyDiscount(amount, discount float64) float64 {
- if discount > DiscountCap {
- discount = DiscountCap
- }
- return amount * (1 - discount)
-}
-
-func FinalPrice(amount, discount float64) float64 {
- return ApplyTax(ApplyDiscount(amount, discount))
-}
-`)
-}
-
-func writeBenchHandlerFiles(b *testing.B, dir string) {
- b.Helper()
-
- writeBenchFile(b, filepath.Join(dir, "handler", "order_handler.go"), `package handler
-
-import "example.com/bench/model"
-
-func CreateOrder(customerID string, items []model.Item) (*model.Order, error) {
- c := model.NewCustomer(customerID, "", "")
- order := model.NewOrder("ord-1", c.DisplayName())
- for _, item := range items {
- order.AddItem(item)
- }
- if err := order.Validate(); err != nil {
- return nil, err
- }
- return order, nil
-}
-
-func GetOrderTotal(order *model.Order) float64 {
- return model.ApplyTax(order.Total)
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "handler", "inventory_handler.go"), `package handler
-
-import "example.com/bench/model"
-
-func CheckAndReserve(inv *model.Inventory, sku string, qty int) bool {
- return inv.Reserve(sku, qty)
-}
-
-func RestockItem(inv *model.Inventory, sku string, qty int) {
- inv.Restock(sku, qty)
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "handler", "pricing_handler.go"), `package handler
-
-import "example.com/bench/model"
-
-func CalculatePrice(amount, discount float64) float64 {
- return model.FinalPrice(amount, discount)
-}
-
-func QuotePrice(items []model.Item, discount float64) float64 {
- var total float64
- for _, item := range items {
- total += item.Subtotal()
- }
- return model.ApplyDiscount(total, discount)
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "handler", "customer_handler.go"), `package handler
-
-import "example.com/bench/model"
-
-func RegisterCustomer(id, name, email string) *model.Customer {
- return model.NewCustomer(id, name, email)
-}
-
-func CustomerLabel(c *model.Customer) string {
- return c.DisplayName()
-}
-`)
-
- writeBenchFile(b, filepath.Join(dir, "handler", "admin_handler.go"), `package handler
-
-import "example.com/bench/model"
-
-func AdminRestock(inv *model.Inventory, sku string, qty int) {
- inv.Restock(sku, qty)
-}
-
-func AdminCreateOrder(custName string) *model.Order {
- order := model.NewOrder("admin-1", custName)
- item := model.NewItem("ADMIN-SKU", "Admin Item", 99.99, 1)
- order.AddItem(item)
- return order
-}
-`)
-}
-
-func writeBenchFile(b *testing.B, path, content string) {
- b.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- b.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- b.Fatal(err)
- }
-}
-
-func BenchmarkPipelineRun(b *testing.B) {
- repoDir, cleanup := setupBenchRepo(b)
- defer cleanup()
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- s, err := store.OpenMemory()
- if err != nil {
- b.Fatal(err)
- }
- p := New(context.Background(), s, repoDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- b.Fatalf("Pipeline.Run: %v", err)
- }
- s.Close()
- }
-}
-
-func BenchmarkPipelineReindex(b *testing.B) {
- repoDir, cleanup := setupBenchRepo(b)
- defer cleanup()
-
- s, err := store.OpenMemory()
- if err != nil {
- b.Fatal(err)
- }
- defer s.Close()
-
- // Initial index
- p := New(context.Background(), s, repoDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- b.Fatalf("initial index: %v", err)
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- p := New(context.Background(), s, repoDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- b.Fatalf("reindex %d: %v", i, err)
- }
- }
-}
-
-func BenchmarkPipelineRunScaled(b *testing.B) {
- for _, fileCount := range []int{5, 20, 50} {
- b.Run(fmt.Sprintf("files=%d", fileCount), func(b *testing.B) {
- dir, err := os.MkdirTemp("", "cgm-bench-scale-*")
- if err != nil {
- b.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- for i := 0; i < fileCount; i++ {
- pkg := fmt.Sprintf("pkg%d", i%5)
- name := fmt.Sprintf("file%d.go", i)
- content := fmt.Sprintf(`package %s
-
-func Func%d() int {
- return %d
-}
-
-func Caller%d() int {
- return Func%d()
-}
-
-type Struct%d struct {
- Field int
-}
-
-func (s *Struct%d) Method%d() int {
- return s.Field + Func%d()
-}
-`, pkg, i, i, i, i, i, i, i, i)
- writeBenchFile(b, filepath.Join(dir, pkg, name), content)
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- s, err := store.OpenMemory()
- if err != nil {
- b.Fatal(err)
- }
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- b.Fatalf("Pipeline.Run: %v", err)
- }
- s.Close()
- }
- })
- }
-}
diff --git a/internal/pipeline/pipeline_cbm.go b/internal/pipeline/pipeline_cbm.go
deleted file mode 100644
index 61f9aad5b..000000000
--- a/internal/pipeline/pipeline_cbm.go
+++ /dev/null
@@ -1,725 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// cachedExtraction holds the CBM extraction result for a file.
-// Replaces cachedAST for all post-definition passes.
-type cachedExtraction struct {
- Result *cbm.FileResult
- Language lang.Language
-}
-
-// fileEntry pairs a file's relative path with its cached extraction.
-// Used by passCalls and batch LSP resolution.
-type fileEntry struct {
- relPath string
- ext *cachedExtraction
-}
-
-// cbmParseFile reads a file, calls cbm.ExtractFile(), and converts the
-// result to the same parseResult format used by the batch write infrastructure.
-// Keeps a copy of the source bytes on parseResult.Source for the sourceStore.
-func cbmParseFile(projectName string, f discover.FileInfo, flags *cbm.ExtractionFlags) *parseResult {
- source, cleanup, err := mmapFile(f.Path)
- if cleanup != nil {
- defer cleanup()
- }
- r := cbmParseFileFromSource(projectName, f, source, err, flags)
- // Keep a heap copy of the source bytes for the sourceStore.
- // The mmap will be unmapped after this function returns.
- if r.Err == nil && len(source) > 0 {
- kept := make([]byte, len(source))
- copy(kept, source)
- r.Source = kept
- }
- return r
-}
-
-// cbmParseFileFromSource is like cbmParseFile but takes pre-read source data.
-// Used by the producer-consumer pipeline where I/O and CPU are separated.
-func cbmParseFileFromSource(projectName string, f discover.FileInfo, source []byte, readErr error, flags *cbm.ExtractionFlags) *parseResult {
- result := &parseResult{File: f}
-
- if readErr != nil {
- result.Err = readErr
- return result
- }
-
- // Strip UTF-8 BOM if present (common in C#/Windows-generated files)
- source = stripBOM(source)
-
- cbmResult, err := cbm.ExtractFileWithFlags(source, f.Language, projectName, f.RelPath, flags)
- if err != nil {
- slog.Warn("cbm.extract.err", "path", f.RelPath, "lang", f.Language, "err", err)
- result.Err = err
- return result
- }
-
- result.CBMResult = cbmResult
-
- moduleQN := fqn.ModuleQN(projectName, f.RelPath)
-
- // Module node
- moduleNode := &store.Node{
- Project: projectName,
- Label: "Module",
- Name: filepath.Base(f.RelPath),
- QualifiedName: moduleQN,
- FilePath: f.RelPath,
- Properties: make(map[string]any),
- }
- result.Nodes = append(result.Nodes, moduleNode)
-
- // Convert CBM definitions to store.Node objects
- for i := range cbmResult.Definitions {
- node, edge := cbmDefToNode(&cbmResult.Definitions[i], projectName, moduleQN)
- result.Nodes = append(result.Nodes, node)
- result.PendingEdges = append(result.PendingEdges, edge)
- }
-
- // Enrich module node with properties from CBM result
- enrichModuleNodeCBM(moduleNode, cbmResult, result)
-
- // Build import map from CBM imports
- if len(cbmResult.Imports) > 0 {
- importMap := make(map[string]string, len(cbmResult.Imports))
- for _, imp := range cbmResult.Imports {
- if imp.LocalName != "" && imp.ModulePath != "" {
- importMap[imp.LocalName] = imp.ModulePath
- }
- }
- result.ImportMap = importMap
- }
-
- moduleNode.Properties["imports_count"] = cbmResult.ImportCount
- moduleNode.Properties["is_test"] = cbmResult.IsTestFile
-
- // exports: collect exported symbol names
- var exports []string
- for _, n := range result.Nodes {
- if n.QualifiedName == moduleQN {
- continue
- }
- if exp, ok := n.Properties["is_exported"].(bool); ok && exp {
- exports = append(exports, n.Name)
- }
- }
- if len(exports) > 0 {
- moduleNode.Properties["exports"] = exports
- }
-
- if symbols := buildSymbolSummary(result.Nodes, moduleQN); len(symbols) > 0 {
- moduleNode.Properties["symbols"] = symbols
- }
-
- return result
-}
-
-// cbmDefToNode converts a CBM Definition to a store.Node and its DEFINES/DEFINES_METHOD edge.
-func cbmDefToNode(def *cbm.Definition, projectName, moduleQN string) (*store.Node, pendingEdge) {
- props := map[string]any{}
-
- if def.Signature != "" {
- props["signature"] = def.Signature
- }
- if def.ReturnType != "" {
- props["return_type"] = def.ReturnType
- }
- if def.Receiver != "" {
- props["receiver"] = def.Receiver
- }
- if def.Docstring != "" {
- props["docstring"] = def.Docstring
- }
- if len(def.Decorators) > 0 {
- props["decorators"] = def.Decorators
- if hasFrameworkDecorator(def.Decorators) {
- props["is_entry_point"] = true
- }
- }
- if len(def.BaseClasses) > 0 {
- props["base_classes"] = def.BaseClasses
- }
- if len(def.ParamNames) > 0 {
- props["param_names"] = def.ParamNames
- }
- if len(def.ParamTypes) > 0 {
- props["param_types"] = def.ParamTypes
- }
- if len(def.ReturnTypes) > 0 {
- props["return_types"] = def.ReturnTypes
- }
- if def.Complexity > 0 {
- props["complexity"] = def.Complexity
- }
- if def.Lines > 0 {
- props["lines"] = def.Lines
- }
-
- props["is_exported"] = def.IsExported
-
- if def.IsAbstract {
- props["is_abstract"] = true
- }
- if def.IsTest {
- props["is_test"] = true
- }
- if def.IsEntryPoint {
- props["is_entry_point"] = true
- }
-
- node := &store.Node{
- Project: projectName,
- Label: def.Label,
- Name: def.Name,
- QualifiedName: def.QualifiedName,
- FilePath: def.FilePath,
- StartLine: def.StartLine,
- EndLine: def.EndLine,
- Properties: props,
- }
-
- // Determine edge type and source QN
- edgeType := "DEFINES"
- sourceQN := moduleQN
- if def.Label == "Method" || def.Label == "Field" {
- edgeType = "DEFINES_METHOD"
- if def.Label == "Field" {
- edgeType = "DEFINES_FIELD"
- }
- if def.ParentClass != "" {
- sourceQN = def.ParentClass
- }
- }
-
- edge := pendingEdge{
- SourceQN: sourceQN,
- TargetQN: def.QualifiedName,
- Type: edgeType,
- }
-
- return node, edge
-}
-
-// enrichModuleNodeCBM populates module node properties from CBM extraction results.
-func enrichModuleNodeCBM(moduleNode *store.Node, cbmResult *cbm.FileResult, _ *parseResult) {
- // Additional module-level properties can be added here if CBM exposes them
- // (e.g., macros, constants, global_vars from CBMFileResult)
-}
-
-// inferTypesCBM builds a TypeMap from CBM TypeAssign data + registry resolution.
-// Replaces the 14 language-specific infer*Types() functions.
-func inferTypesCBM(
- typeAssigns []cbm.TypeAssign,
- registry *FunctionRegistry,
- moduleQN string,
- importMap map[string]string,
-) TypeMap {
- types := make(TypeMap, len(typeAssigns))
-
- for _, ta := range typeAssigns {
- if ta.VarName == "" || ta.TypeName == "" {
- continue
- }
- classQN := resolveAsClass(ta.TypeName, registry, moduleQN, importMap)
- if classQN != "" {
- types[ta.VarName] = classQN
- }
- }
-
- // Return type propagation is handled by CBM TypeAssigns which already
- // detect constructor patterns. Additional return-type-based inference
- // from the returnTypes map is still useful for non-constructor calls.
- // This would require the call data which we have in CBM Calls.
- // For now, constructor-based inference covers the primary use case.
-
- return types
-}
-
-// resolveFileCallsCBM resolves all call targets using pre-extracted CBM data.
-// Cross-file LSP results are pre-populated by batch phase in passCalls().
-// This function handles registry + fuzzy resolution only (no CGo).
-func (p *Pipeline) resolveFileCallsCBM(relPath string, ext *cachedExtraction) []resolvedEdge {
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- importMap := p.importMaps[moduleQN]
-
- // Build type map from CBM type assignments
- typeMap := inferTypesCBM(ext.Result.TypeAssigns, p.registry, moduleQN, importMap)
-
- // LSP-resolved calls take priority (high confidence, type-aware).
- edges, lspCallerMethods := collectLSPResolvedEdges(ext.Result.ResolvedCalls)
-
- // Resolve remaining calls via registry + fuzzy matching
- for _, call := range ext.Result.Calls {
- if edge, ok := p.resolveCallEdge(call, moduleQN, importMap, typeMap, lspCallerMethods); ok {
- edges = append(edges, edge)
- }
- }
-
- return edges
-}
-
-// batchGoLSPCrossFileResolution collects all Go files needing cross-file LSP,
-// prepares their data, and resolves them in ONE CGo call via BatchGoLSPCrossFile.
-func (p *Pipeline) batchGoLSPCrossFileResolution(files []fileEntry) {
- if p.goLSPIdx == nil {
- return
- }
-
- type goLSPFile struct {
- fileIdx int
- input cbm.BatchLSPInput
- }
-
- var batch []goLSPFile
- for i, fe := range files {
- if fe.ext.Language != lang.Go || fe.ext.Result == nil {
- continue
- }
- moduleQN := fqn.ModuleQN(p.ProjectName, fe.relPath)
- importMap := p.importMaps[moduleQN]
- crossDefs := p.goLSPIdx.collectCrossFileDefs(importMap)
- if len(crossDefs) == 0 {
- continue
- }
- source := readFileSource(p, fe.relPath)
- if len(source) == 0 {
- continue
- }
- fileDefs := cbm.DefsToLSPDefs(fe.ext.Result.Definitions, moduleQN)
- batch = append(batch, goLSPFile{
- fileIdx: i,
- input: cbm.BatchLSPInput{
- Source: source,
- ModuleQN: moduleQN,
- FileDefs: fileDefs,
- CrossDefs: crossDefs,
- Imports: fe.ext.Result.Imports,
- CachedTree: fe.ext.Result.TreeHandle,
- },
- })
- }
-
- if len(batch) == 0 {
- return
- }
-
- // Build flat input slice for ONE CGo call
- inputs := make([]cbm.BatchLSPInput, len(batch))
- for i := range batch {
- inputs[i] = batch[i].input
- }
-
- slog.Info("go_lsp.batch", "files", len(inputs))
- results := cbm.BatchGoLSPCrossFile(inputs)
-
- // Distribute results back to extraction cache
- for i, result := range results {
- if len(result) > 0 {
- files[batch[i].fileIdx].ext.Result.ResolvedCalls = result
- }
- }
-}
-
-// batchCLSPCrossFileResolution collects all C/C++/CUDA files needing cross-file LSP,
-// prepares their data, and resolves them in ONE CGo call via BatchCLSPCrossFile.
-func (p *Pipeline) batchCLSPCrossFileResolution(files []fileEntry) {
- if p.cLSPIdx == nil {
- return
- }
-
- type cLSPFile struct {
- fileIdx int
- input cbm.BatchCLSPInput
- }
-
- var batch []cLSPFile
- for i, fe := range files {
- if !isCOrCPP(fe.ext.Language) || fe.ext.Result == nil {
- continue
- }
- moduleQN := fqn.ModuleQN(p.ProjectName, fe.relPath)
- incDirs := p.getRelativeIncludeDirs(fe.relPath)
- if incDirs == nil {
- incDirs = p.getAllRelativeIncludeDirs()
- }
- crossDefs := p.cLSPIdx.collectCrossFileDefs(fe.ext.Result.Imports, fe.relPath, incDirs)
- if len(crossDefs) == 0 {
- continue
- }
- source := readFileSource(p, fe.relPath)
- if len(source) == 0 {
- continue
- }
- cppMode := fe.ext.Language == lang.CPP || fe.ext.Language == lang.CUDA
- fileDefs := cbm.DefsToLSPDefs(fe.ext.Result.Definitions, moduleQN)
- batch = append(batch, cLSPFile{
- fileIdx: i,
- input: cbm.BatchCLSPInput{
- Source: source,
- ModuleQN: moduleQN,
- CppMode: cppMode,
- FileDefs: fileDefs,
- CrossDefs: crossDefs,
- Includes: fe.ext.Result.Imports,
- CachedTree: fe.ext.Result.TreeHandle,
- },
- })
- }
-
- if len(batch) == 0 {
- return
- }
-
- inputs := make([]cbm.BatchCLSPInput, len(batch))
- for i := range batch {
- inputs[i] = batch[i].input
- }
-
- slog.Info("c_lsp.batch", "files", len(inputs))
- results := cbm.BatchCLSPCrossFile(inputs)
-
- for i, result := range results {
- if len(result) > 0 {
- files[batch[i].fileIdx].ext.Result.ResolvedCalls = result
- }
- }
-}
-
-// collectLSPResolvedEdges converts LSP-resolved calls to edges and builds a caller+method dedup set.
-func collectLSPResolvedEdges(resolvedCalls []cbm.ResolvedCall) (edges []resolvedEdge, lspCallerMethods map[string]bool) {
- lspResolved := make(map[string]bool)
- lspCallerMethods = make(map[string]bool)
-
- for _, rc := range resolvedCalls {
- if rc.CallerQN == "" || rc.CalleeQN == "" || rc.Confidence == 0 {
- continue
- }
- key := rc.CallerQN + "\x00" + rc.CalleeQN
- if lspResolved[key] {
- continue
- }
- lspResolved[key] = true
- edges = append(edges, resolvedEdge{
- CallerQN: rc.CallerQN,
- TargetQN: rc.CalleeQN,
- Type: "CALLS",
- Properties: map[string]any{
- "confidence": float64(rc.Confidence),
- "confidence_band": confidenceBand(float64(rc.Confidence)),
- "resolution_strategy": rc.Strategy,
- },
- })
-
- shortName := rc.CalleeQN
- if idx := strings.LastIndex(shortName, "."); idx >= 0 {
- shortName = shortName[idx+1:]
- }
- lspCallerMethods[rc.CallerQN+"\x00"+shortName] = true
- }
-
- return edges, lspCallerMethods
-}
-
-// resolveCallEdge resolves a single call to an edge using the registry and type system.
-func (p *Pipeline) resolveCallEdge(
- call cbm.Call, moduleQN string, importMap map[string]string,
- typeMap TypeMap, lspCallerMethods map[string]bool,
-) (resolvedEdge, bool) {
- calleeName := call.CalleeName
- callerQN := call.EnclosingFuncQN
- if calleeName == "" {
- return resolvedEdge{}, false
- }
- if callerQN == "" {
- callerQN = moduleQN
- }
-
- // Skip if LSP already resolved this caller+method
- fuzzyShort := calleeName
- if idx := strings.LastIndex(fuzzyShort, "."); idx >= 0 {
- fuzzyShort = fuzzyShort[idx+1:]
- }
- if lspCallerMethods[callerQN+"\x00"+fuzzyShort] {
- return resolvedEdge{}, false
- }
-
- // Python self.method() resolution
- if strings.HasPrefix(calleeName, "self.") {
- classQN := extractClassFromMethodQN(callerQN)
- if classQN != "" {
- candidate := classQN + "." + calleeName[5:]
- if p.registry.Exists(candidate) {
- return resolvedEdge{CallerQN: callerQN, TargetQN: candidate, Type: "CALLS"}, true
- }
- }
- }
-
- // Type-based method dispatch for qualified calls like obj.method()
- result := p.resolveCallWithTypes(calleeName, moduleQN, importMap, typeMap)
- if result.QualifiedName == "" {
- if fuzzyResult, ok := p.registry.FuzzyResolve(calleeName, moduleQN, importMap); ok && fuzzyResult.Confidence >= 0.10 {
- return resolvedEdge{
- CallerQN: callerQN,
- TargetQN: fuzzyResult.QualifiedName,
- Type: "CALLS",
- Properties: map[string]any{
- "confidence": fuzzyResult.Confidence,
- "confidence_band": confidenceBand(fuzzyResult.Confidence),
- "resolution_strategy": fuzzyResult.Strategy,
- },
- }, true
- }
- return resolvedEdge{}, false
- }
-
- if result.Confidence < 0.10 {
- return resolvedEdge{}, false
- }
- return resolvedEdge{
- CallerQN: callerQN,
- TargetQN: result.QualifiedName,
- Type: "CALLS",
- Properties: map[string]any{
- "confidence": result.Confidence,
- "confidence_band": confidenceBand(result.Confidence),
- "resolution_strategy": result.Strategy,
- },
- }, true
-}
-
-// resolveFileUsagesCBM resolves usage references using pre-extracted CBM data.
-// Replaces resolveFileUsages() — no AST walking needed.
-func (p *Pipeline) resolveFileUsagesCBM(relPath string, ext *cachedExtraction) []resolvedEdge {
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- importMap := p.importMaps[moduleQN]
-
- var edges []resolvedEdge
- seen := make(map[[2]string]bool)
-
- for _, usage := range ext.Result.Usages {
- refName := usage.RefName
- callerQN := usage.EnclosingFuncQN
- if refName == "" {
- continue
- }
- if callerQN == "" {
- callerQN = moduleQN
- }
-
- result := p.registry.Resolve(refName, moduleQN, importMap)
- if result.QualifiedName == "" {
- continue
- }
-
- key := [2]string{callerQN, result.QualifiedName}
- if seen[key] {
- continue
- }
- seen[key] = true
-
- edges = append(edges, resolvedEdge{
- CallerQN: callerQN,
- TargetQN: result.QualifiedName,
- Type: "USAGE",
- })
- }
-
- return edges
-}
-
-// resolveFileThrowsCBM resolves throw/raise targets using pre-extracted CBM data.
-// Replaces resolveFileThrows() — no AST walking needed.
-func (p *Pipeline) resolveFileThrowsCBM(relPath string, ext *cachedExtraction) []resolvedEdge {
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- importMap := p.importMaps[moduleQN]
-
- var edges []resolvedEdge
- seen := make(map[[2]string]bool)
-
- for _, thr := range ext.Result.Throws {
- excName := thr.ExceptionName
- funcQN := thr.EnclosingFuncQN
- if excName == "" || funcQN == "" {
- continue
- }
-
- key := [2]string{funcQN, excName}
- if seen[key] {
- continue
- }
- seen[key] = true
-
- // Determine edge type: THROWS for checked exceptions, RAISES for runtime/unchecked
- edgeType := "RAISES"
- if isCheckedException(excName) {
- edgeType = "THROWS"
- }
-
- // Try to resolve exception class
- result := p.registry.Resolve(excName, moduleQN, importMap)
- targetQN := excName
- if result.QualifiedName != "" {
- targetQN = result.QualifiedName
- }
-
- edges = append(edges, resolvedEdge{
- CallerQN: funcQN,
- TargetQN: targetQN,
- Type: edgeType,
- })
- }
-
- return edges
-}
-
-// resolveFileReadsWritesCBM resolves reads/writes using pre-extracted CBM data.
-// Replaces resolveFileReadsWrites() — no AST walking needed.
-func (p *Pipeline) resolveFileReadsWritesCBM(relPath string, ext *cachedExtraction) []resolvedEdge {
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- importMap := p.importMaps[moduleQN]
-
- var edges []resolvedEdge
- seen := make(map[[3]string]bool)
-
- for _, rw := range ext.Result.ReadWrites {
- varName := rw.VarName
- funcQN := rw.EnclosingFuncQN
- if varName == "" || funcQN == "" {
- continue
- }
-
- edgeType := "READS"
- if rw.IsWrite {
- edgeType = "WRITES"
- }
-
- key := [3]string{funcQN, varName, edgeType}
- if seen[key] {
- continue
- }
- seen[key] = true
-
- // Try to resolve variable to a known node
- result := p.registry.Resolve(varName, moduleQN, importMap)
- if result.QualifiedName == "" {
- continue
- }
-
- edges = append(edges, resolvedEdge{
- CallerQN: funcQN,
- TargetQN: result.QualifiedName,
- Type: edgeType,
- })
- }
-
- return edges
-}
-
-// resolveFileTypeRefsCBM resolves type references using pre-extracted CBM data.
-// Replaces resolveFileTypeRefs() — no AST walking needed.
-func (p *Pipeline) resolveFileTypeRefsCBM(relPath string, ext *cachedExtraction) []resolvedEdge {
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
- importMap := p.importMaps[moduleQN]
-
- var edges []resolvedEdge
- seen := make(map[[2]string]bool)
-
- for _, tr := range ext.Result.TypeRefs {
- typeName := tr.TypeName
- funcQN := tr.EnclosingFuncQN
- if typeName == "" || funcQN == "" {
- continue
- }
-
- key := [2]string{funcQN, typeName}
- if seen[key] {
- continue
- }
- seen[key] = true
-
- // Resolve type name to a node QN
- result := p.registry.Resolve(typeName, moduleQN, importMap)
- if result.QualifiedName == "" {
- continue
- }
-
- edges = append(edges, resolvedEdge{
- CallerQN: funcQN,
- TargetQN: result.QualifiedName,
- Type: "USES_TYPE",
- })
- }
-
- return edges
-}
-
-// resolveFileConfiguresCBM resolves env access calls using pre-extracted CBM data.
-// Replaces resolveFileConfigures() — no AST walking needed.
-func (p *Pipeline) resolveFileConfiguresCBM(relPath string, ext *cachedExtraction, envIndex map[string]string) []resolvedEdge {
- moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
-
- var edges []resolvedEdge
- seen := make(map[[2]string]bool)
-
- for _, ea := range ext.Result.EnvAccesses {
- envKey := ea.EnvKey
- funcQN := ea.EnclosingFuncQN
- if envKey == "" || funcQN == "" {
- continue
- }
-
- targetModuleQN, ok := envIndex[envKey]
- if !ok {
- continue
- }
-
- key := [2]string{funcQN, targetModuleQN}
- if seen[key] {
- continue
- }
- seen[key] = true
-
- _ = moduleQN
- edges = append(edges, resolvedEdge{
- CallerQN: funcQN,
- TargetQN: targetModuleQN,
- Type: "CONFIGURES",
- Properties: map[string]any{
- "env_key": envKey,
- },
- })
- }
-
- return edges
-}
-
-// extractClassFromMethodQN extracts the class QN from a method QN.
-// E.g., "project.path.ClassName.methodName" -> "project.path.ClassName"
-func extractClassFromMethodQN(methodQN string) string {
- idx := strings.LastIndex(methodQN, ".")
- if idx <= 0 {
- return ""
- }
- return methodQN[:idx]
-}
-
-// isCheckedException returns true if the exception name looks like a checked exception
-// (Java convention: checked exceptions don't extend RuntimeException).
-func isCheckedException(excName string) bool {
- // Heuristic: exceptions ending in "Exception" without "Runtime" prefix are checked
- if strings.HasSuffix(excName, "Exception") && !strings.HasPrefix(excName, "Runtime") {
- return true
- }
- return false
-}
diff --git a/internal/pipeline/pipeline_full.go b/internal/pipeline/pipeline_full.go
deleted file mode 100644
index 4657736c0..000000000
--- a/internal/pipeline/pipeline_full.go
+++ /dev/null
@@ -1,231 +0,0 @@
-package pipeline
-
-import (
- "fmt"
- "log/slog"
- "os"
- "runtime"
- "runtime/debug"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// runFullIndex builds the entire graph in RAM via GraphBuffer, then writes
-// directly to a SQLite .db file via the C page writer. Zero SQL during
-// passes — all node/edge ops go through the StoreBackend interface backed
-// by GraphBuffer.
-func (p *Pipeline) runFullIndex(files []discover.FileInfo, _ time.Time) error {
- // Cap Go heap to leave room for C allocations during final dump.
- // Without this, Go grabs ~30GB virtual memory during passes and
- // the C page writer OOMs on machines with ≤36GB RAM.
- prevLimit := debug.SetMemoryLimit(-1) // query current
- if prevLimit <= 0 || prevLimit > 24<<30 {
- debug.SetMemoryLimit(24 << 30) // 24GB
- defer debug.SetMemoryLimit(prevLimit)
- }
-
- // Create GraphBuffer and route all Store calls through it.
- p.buf = newGraphBuffer(p.ProjectName, p.RepoPath)
- p.Store = p.buf // ALL passes now use GraphBuffer — zero SQLite
-
- if err := p.runFullPasses(files); err != nil {
- return err
- }
-
- // Final dump: write GraphBuffer contents to SQLite.
- t := time.Now()
- dbPath := p.diskStore.DBPath()
-
- if err := p.dumpDB(dbPath); err != nil {
- return err
- }
- slog.Info("db.dump", "elapsed", time.Since(t))
-
- // Release GraphBuffer — all data already written to SQLite.
- p.buf = nil
-
- // File hashes + observability go to disk store.
- p.Store = p.diskStore
- p.updateFileHashes(files)
-
- // Release source store — all passes done.
- p.sourceStore = nil
-
- // Observability: per-edge-type counts.
- p.logEdgeCounts()
-
- return nil
-}
-
-// runFullPasses runs the complete pass pipeline. ALL passes run on GraphBuffer —
-// no mid-pipeline flush, no post-flush distinction.
-func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {
- // Pass group 1: Structure + extraction
- t := time.Now()
- if err := p.passStructure(files); err != nil {
- return fmt.Errorf("pass1 structure: %w", err)
- }
- slog.Info("pass.timing", "pass", "structure", "elapsed", time.Since(t))
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // Bulk load: read all files, xxh3 hash, LZ4 HC compress → RAM.
- t = time.Now()
- p.bulkLoadSources(files)
- slog.Info("pass.timing", "pass", "bulk_load", "elapsed", time.Since(t))
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- p.passDefinitions(files)
- slog.Info("pass.timing", "pass", "definitions", "elapsed", time.Since(t))
- logHeapStats("post_definitions")
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- p.passDecoratorTags()
- slog.Info("pass.timing", "pass", "decorator_tags", "elapsed", time.Since(t))
-
- // Registry already built inline during passDefinitions (fused).
- slog.Info("registry.built", "entries", p.registry.Size())
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // Pass group 2-3: Cross-references + resolution
- if err := p.runCrossRefPasses(); err != nil {
- return err
- }
-
- // Pass group 4: post-resolution passes
- return p.runPostPasses()
-}
-
-// runCrossRefPasses runs cross-reference and call resolution passes.
-func (p *Pipeline) runCrossRefPasses() error {
- t := time.Now()
- p.passInherits()
- slog.Info("pass.timing", "pass", "inherits", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passDecorates()
- slog.Info("pass.timing", "pass", "decorates", "elapsed", time.Since(t))
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- p.passImports()
- slog.Info("pass.timing", "pass", "imports", "elapsed", time.Since(t))
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- p.buildReturnTypeMap()
- p.goLSPIdx = p.buildGoLSPDefIndex()
- if p.goLSPIdx != nil {
- p.goLSPIdx.integrateThirdPartyDeps(p.RepoPath, p.importMaps)
- }
- p.cLSPIdx = p.buildCLSPDefIndex()
- p.passCalls()
- slog.Info("pass.timing", "pass", "calls", "elapsed", time.Since(t))
- p.releaseExtractionFields(fieldsPostCalls)
- p.goLSPIdx = nil
- p.cLSPIdx = nil
- logHeapStats("post_calls")
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- p.passUsages()
- slog.Info("pass.timing", "pass", "usages", "elapsed", time.Since(t))
- p.releaseExtractionFields(fieldsPostUsages)
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- p.runSemanticEdgePasses()
- p.releaseExtractionFields(fieldsPostSemantic)
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- p.passImplements()
- slog.Info("pass.timing", "pass", "implements", "elapsed", time.Since(t))
-
- p.cleanupASTCache()
- p.registry = nil
- p.importMaps = nil
- p.returnTypes = nil
- logHeapStats("post_cleanup")
- return nil
-}
-
-// runPostPasses runs post-resolution passes (tests, communities, httplinks, etc.).
-func (p *Pipeline) runPostPasses() error {
- t := time.Now()
- p.passTests()
- slog.Info("pass.timing", "pass", "tests", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passCommunities()
- slog.Info("pass.timing", "pass", "communities", "elapsed", time.Since(t))
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- t = time.Now()
- if err := p.passHTTPLinks(); err != nil {
- slog.Warn("pass.httplink.err", "err", err)
- }
- slog.Info("pass.timing", "pass", "httplinks", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passConfigLinker()
- slog.Info("pass.timing", "pass", "configlinker", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passGitHistory()
- slog.Info("pass.timing", "pass", "githistory", "elapsed", time.Since(t))
-
- return nil
-}
-
-// dumpDB writes GraphBuffer contents to SQLite — in-memory or disk.
-func (p *Pipeline) dumpDB(dbPath string) error {
- if dbPath == ":memory:" {
- if err := p.diskStore.UpsertProject(p.ProjectName, p.RepoPath); err != nil {
- return fmt.Errorf("upsert project: %w", err)
- }
- return p.buf.FlushTo(p.ctx, p.diskStore)
- }
- p.buf.releaseIndexes()
- runtime.GC()
- debug.FreeOSMemory()
- logHeapStats("pre_dump")
- tmpPath := dbPath + ".tmp"
- if err := p.buf.DumpToSQLite(tmpPath); err != nil {
- return fmt.Errorf("dump: %w", err)
- }
- p.diskStore.Close()
- _ = os.Remove(dbPath + "-wal")
- _ = os.Remove(dbPath + "-shm")
- if err := os.Rename(tmpPath, dbPath); err != nil {
- return fmt.Errorf("rename db: %w", err)
- }
- var err error
- p.diskStore, err = store.OpenPath(dbPath)
- if err != nil {
- return fmt.Errorf("reopen db: %w", err)
- }
- return nil
-}
diff --git a/internal/pipeline/pipeline_incremental.go b/internal/pipeline/pipeline_incremental.go
deleted file mode 100644
index 29d81469b..000000000
--- a/internal/pipeline/pipeline_incremental.go
+++ /dev/null
@@ -1,480 +0,0 @@
-package pipeline
-
-import (
- "encoding/hex"
- "fmt"
- "io"
- "log/slog"
- "os"
- "path/filepath"
- "runtime"
- "time"
-
- "github.com/zeebo/xxh3"
- "golang.org/x/sync/errgroup"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cbm"
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/fqn"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// runIncrementalIndex runs the incremental pipeline on the disk-backed store.
-// All SQLite-specific operations (transactions, WAL, file hashes) go through
-// p.diskStore — never through the StoreBackend interface.
-func (p *Pipeline) runIncrementalIndex(files, changed, unchanged []discover.FileInfo, _ time.Time) error {
- slog.Info("incremental.classify", "changed", len(changed), "unchanged", len(unchanged), "total", len(files))
-
- // Fast path: nothing changed → skip all heavy passes
- if len(changed) == 0 {
- slog.Info("incremental.noop", "reason", "no_changes")
- return nil
- }
-
- // Use MEMORY journal mode during incremental writes
- p.diskStore.BeginBulkWrite(p.ctx)
-
- if err := p.diskStore.WithTransaction(p.ctx, func(txStore *store.Store) error {
- origStore := p.Store
- p.Store = txStore
- defer func() { p.Store = origStore }()
-
- if err := txStore.UpsertProject(p.ProjectName, p.RepoPath); err != nil {
- return fmt.Errorf("upsert project: %w", err)
- }
- return p.runIncrementalPasses(files, changed, unchanged)
- }); err != nil {
- p.diskStore.EndBulkWrite(p.ctx)
- return err
- }
-
- p.diskStore.EndBulkWrite(p.ctx)
-
- walBefore := p.diskStore.WALSize()
- p.diskStore.Checkpoint(p.ctx)
- walAfter := p.diskStore.WALSize()
- slog.Info("wal.checkpoint", "before_mb", walBefore/(1<<20), "after_mb", walAfter/(1<<20))
- return nil
-}
-
-// runIncrementalPasses re-indexes only changed files + their dependents.
-// Runs inside a SQLite transaction — p.Store is the txStore.
-func (p *Pipeline) runIncrementalPasses(
- allFiles []discover.FileInfo,
- changed, unchanged []discover.FileInfo,
-) error {
- // Pass 1: Structure always runs on all files (fast, idempotent upserts)
- if err := p.passStructure(allFiles); err != nil {
- return fmt.Errorf("pass1 structure: %w", err)
- }
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // Remove stale nodes/edges for deleted files
- p.removeDeletedFiles(allFiles)
-
- // Delete nodes for changed files (will be re-created in pass 2)
- for _, f := range changed {
- _ = p.diskStore.DeleteNodesByFile(p.ProjectName, f.RelPath)
- }
-
- // Pass 2: Parse changed files only
- p.passDefinitions(changed)
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // Re-compute decorator tags globally (threshold is across all nodes)
- p.passDecoratorTags()
-
- // Build full registry: includes nodes from unchanged files (already in DB)
- // plus newly parsed nodes from changed files
- p.buildRegistry()
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- p.passImports()
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // Determine which files need call re-resolution:
- // changed files + files that import any changed module
- dependents := p.findDependentFiles(changed, unchanged)
- filesToResolve := mergeFiles(changed, dependents)
- slog.Info("incremental.resolve", "changed", len(changed), "dependents", len(dependents))
-
- // Delete edges for files being re-resolved (all AST-derived edge types)
- for _, f := range filesToResolve {
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "CALLS")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "USAGE")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "USES_TYPE")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "THROWS")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "RAISES")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "READS")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "WRITES")
- _ = p.diskStore.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "CONFIGURES")
- }
-
- // Re-resolve calls + usages for changed + dependent files
- p.buildReturnTypeMap()
- p.goLSPIdx = p.buildGoLSPDefIndex()
- if p.goLSPIdx != nil {
- p.goLSPIdx.integrateThirdPartyDeps(p.RepoPath, p.importMaps)
- }
- p.cLSPIdx = p.buildCLSPDefIndex()
- p.passCallsForFiles(filesToResolve)
- p.releaseExtractionFields(fieldsPostCalls)
- p.goLSPIdx = nil
- p.cLSPIdx = nil
- p.passUsagesForFiles(filesToResolve)
- p.releaseExtractionFields(fieldsPostUsages)
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // AST-dependent passes (run on cached files before cleanup)
- p.passUsesType()
- p.passThrows()
- p.passReadsWrites()
- p.passConfigures()
- p.releaseExtractionFields(fieldsPostSemantic)
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- p.cleanupASTCache()
- p.registry = nil
- p.importMaps = nil
- p.returnTypes = nil
-
- // DB-derived edge types: delete all and re-run (cheap)
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "TESTS")
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "TESTS_FILE")
- p.passTests()
-
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "INHERITS")
- p.passInherits()
-
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "DECORATES")
- p.passDecorates()
-
- // Community detection: delete old communities and MEMBER_OF, re-run
- _ = p.Store.DeleteEdgesByType(p.ProjectName, "MEMBER_OF")
- _ = p.Store.DeleteNodesByLabel(p.ProjectName, "Community")
- p.passCommunities()
- if err := p.checkCancel(); err != nil {
- return err
- }
-
- // HTTP linking, config linking, and implements always run fully (they clean up first)
- if err := p.passHTTPLinks(); err != nil {
- slog.Warn("pass.httplink.err", "err", err)
- }
- p.passConfigLinker()
- p.passImplements()
- p.passGitHistory()
-
- p.updateFileHashes(allFiles)
-
- // Observability
- p.logEdgeCounts()
-
- return nil
-}
-
-// classifyFiles splits files into changed and unchanged based on stored hashes.
-// Uses stat (mtime+size) as a fast pre-filter: files whose mtime and size match
-// the stored values are assumed unchanged without reading/hashing. Only files
-// with changed stat (or missing from the store) are hashed.
-func (p *Pipeline) classifyFiles(files []discover.FileInfo) (changed, unchanged []discover.FileInfo) {
- storedHashes, err := p.diskStore.GetFileHashes(p.ProjectName)
- if err != nil || len(storedHashes) == 0 {
- return files, nil // no hashes → full index
- }
-
- // Stage 1: stat pre-filter — separate files into "stat-unchanged" and "needs-hash"
- var needsHash []discover.FileInfo
- for _, f := range files {
- stored, ok := storedHashes[f.RelPath]
- if !ok {
- needsHash = append(needsHash, f) // new file
- continue
- }
- fi, statErr := os.Stat(f.Path)
- if statErr != nil {
- needsHash = append(needsHash, f) // stat failed → hash it
- continue
- }
- if fi.ModTime().UnixNano() == stored.MtimeNs && fi.Size() == stored.Size && stored.MtimeNs != 0 {
- // Stat matches — trust the stored hash
- unchanged = append(unchanged, f)
- } else {
- needsHash = append(needsHash, f)
- }
- }
-
- if len(needsHash) == 0 {
- return changed, unchanged // nothing to hash
- }
-
- // Stage 2: hash only files that need it
- type hashResult struct {
- Hash string
- Err error
- }
-
- results := make([]hashResult, len(needsHash))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(needsHash) {
- numWorkers = len(needsHash)
- }
-
- g := new(errgroup.Group)
- g.SetLimit(numWorkers)
- for i, f := range needsHash {
- g.Go(func() error {
- hash, hashErr := fileHash(f.Path)
- results[i] = hashResult{Hash: hash, Err: hashErr}
- return nil
- })
- }
- _ = g.Wait()
-
- for i, f := range needsHash {
- r := results[i]
- if r.Err != nil {
- changed = append(changed, f)
- continue
- }
- if stored, ok := storedHashes[f.RelPath]; ok && stored.SHA256 == r.Hash {
- unchanged = append(unchanged, f)
- } else {
- changed = append(changed, f)
- }
- }
- return changed, unchanged
-}
-
-// updateFileHashes persists file hashes to the disk store.
-// Uses pre-computed hashes from sourceStore (full index) or hashes from disk (incremental).
-func (p *Pipeline) updateFileHashes(files []discover.FileInfo) {
- // Fast path: use pre-computed hashes from sourceStore (bulk load)
- if p.sourceStore != nil {
- batch := make([]store.FileHash, 0, len(files))
- for _, f := range files {
- if hash, mtimeNs, size, ok := p.getHash(f.RelPath); ok {
- batch = append(batch, store.FileHash{
- Project: p.ProjectName,
- RelPath: f.RelPath,
- SHA256: hash,
- MtimeNs: mtimeNs,
- Size: size,
- })
- }
- }
- _ = p.diskStore.UpsertFileHashBatch(batch)
- return
- }
-
- // Slow path: read from disk (incremental mode)
- type hashResult struct {
- Hash string
- MtimeNs int64
- Size int64
- Err error
- }
-
- results := make([]hashResult, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g := new(errgroup.Group)
- g.SetLimit(numWorkers)
- for i, f := range files {
- g.Go(func() error {
- hash, hashErr := fileHash(f.Path)
- r := hashResult{Hash: hash, Err: hashErr}
- if hashErr == nil {
- if fi, statErr := os.Stat(f.Path); statErr == nil {
- r.MtimeNs = fi.ModTime().UnixNano()
- r.Size = fi.Size()
- }
- }
- results[i] = r
- return nil
- })
- }
- _ = g.Wait()
-
- // Collect successful hashes for batch upsert
- batch := make([]store.FileHash, 0, len(files))
- for i, f := range files {
- if results[i].Err == nil {
- batch = append(batch, store.FileHash{
- Project: p.ProjectName,
- RelPath: f.RelPath,
- SHA256: results[i].Hash,
- MtimeNs: results[i].MtimeNs,
- Size: results[i].Size,
- })
- }
- }
- _ = p.diskStore.UpsertFileHashBatch(batch)
-}
-
-// removeDeletedFiles removes nodes/edges for files that no longer exist on disk.
-func (p *Pipeline) removeDeletedFiles(currentFiles []discover.FileInfo) {
- currentSet := make(map[string]bool, len(currentFiles))
- for _, f := range currentFiles {
- currentSet[f.RelPath] = true
- }
- indexed, err := p.diskStore.ListFilesForProject(p.ProjectName)
- if err != nil {
- return
- }
- for _, filePath := range indexed {
- if !currentSet[filePath] {
- _ = p.diskStore.DeleteNodesByFile(p.ProjectName, filePath)
- _ = p.diskStore.DeleteFileHash(p.ProjectName, filePath)
- slog.Info("incremental.removed", "file", filePath)
- }
- }
-}
-
-// findDependentFiles finds unchanged files that import any changed file's module.
-func (p *Pipeline) findDependentFiles(changed, unchanged []discover.FileInfo) []discover.FileInfo {
- // Build set of module QNs for changed files
- changedModules := make(map[string]bool, len(changed))
- for _, f := range changed {
- mqn := fqn.ModuleQN(p.ProjectName, f.RelPath)
- changedModules[mqn] = true
- // Also add folder QN (for Go package-level imports)
- dir := filepath.Dir(f.RelPath)
- if dir != "." {
- changedModules[fqn.FolderQN(p.ProjectName, dir)] = true
- }
- }
-
- var dependents []discover.FileInfo
- for _, f := range unchanged {
- mqn := fqn.ModuleQN(p.ProjectName, f.RelPath)
- importMap := p.importMaps[mqn]
- // If no cached import map, check the store for IMPORTS edges
- if len(importMap) == 0 {
- importMap = p.loadImportMapFromDB(mqn)
- }
- for _, targetQN := range importMap {
- if changedModules[targetQN] {
- dependents = append(dependents, f)
- break
- }
- }
- }
- return dependents
-}
-
-// loadImportMapFromDB reconstructs an import map from stored IMPORTS edges.
-func (p *Pipeline) loadImportMapFromDB(moduleQN string) map[string]string {
- moduleNode, err := p.Store.FindNodeByQN(p.ProjectName, moduleQN)
- if err != nil || moduleNode == nil {
- return nil
- }
- edges, err := p.Store.FindEdgesBySourceAndType(moduleNode.ID, "IMPORTS")
- if err != nil {
- return nil
- }
- result := make(map[string]string, len(edges))
- for _, e := range edges {
- target, tErr := p.Store.FindNodeByID(e.TargetID)
- if tErr != nil || target == nil {
- continue
- }
- alias := ""
- if a, ok := e.Properties["alias"].(string); ok {
- alias = a
- }
- if alias != "" {
- result[alias] = target.QualifiedName
- }
- }
- return result
-}
-
-// passCallsForFiles resolves calls only for the specified files (incremental).
-func (p *Pipeline) passCallsForFiles(files []discover.FileInfo) {
- slog.Info("pass3.calls.incremental", "files", len(files))
- for _, f := range files {
- if p.ctx.Err() != nil {
- return
- }
- ext, ok := p.extractionCache[f.RelPath]
- if !ok {
- // File not in extraction cache — need to extract it
- source, err := os.ReadFile(f.Path)
- if err != nil {
- continue
- }
- source = stripBOM(source)
- cbmResult, err := cbm.ExtractFile(source, f.Language, p.ProjectName, f.RelPath)
- if err != nil {
- continue
- }
- ext = &cachedExtraction{Result: cbmResult, Language: f.Language}
- p.extractionCache[f.RelPath] = ext
- }
- edges := p.resolveFileCallsCBM(f.RelPath, ext)
- // Release Definitions/Imports per-file after call resolution
- if ext.Result != nil {
- ext.Result.Definitions = nil
- ext.Result.Imports = nil
- }
- for _, re := range edges {
- callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.CallerQN)
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.TargetQN)
- if callerNode != nil && targetNode != nil {
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: callerNode.ID,
- TargetID: targetNode.ID,
- Type: re.Type,
- Properties: re.Properties,
- })
- }
- }
- }
-}
-
-// mergeFiles returns the union of two file slices (deduped by RelPath).
-func mergeFiles(a, b []discover.FileInfo) []discover.FileInfo {
- seen := make(map[string]bool, len(a))
- result := make([]discover.FileInfo, 0, len(a)+len(b))
- for _, f := range a {
- seen[f.RelPath] = true
- result = append(result, f)
- }
- for _, f := range b {
- if !seen[f.RelPath] {
- result = append(result, f)
- }
- }
- return result
-}
-
-// fileHash computes an xxh3 hash of a file.
-func fileHash(path string) (string, error) {
- f, err := os.Open(path)
- if err != nil {
- return "", err
- }
- defer f.Close()
- h := xxh3.New()
- if _, err := io.Copy(h, f); err != nil {
- return "", err
- }
- return hex.EncodeToString(h.Sum(nil)), nil
-}
diff --git a/internal/pipeline/pipeline_linux_bench_test.go b/internal/pipeline/pipeline_linux_bench_test.go
deleted file mode 100644
index ded1fc10b..000000000
--- a/internal/pipeline/pipeline_linux_bench_test.go
+++ /dev/null
@@ -1,346 +0,0 @@
-package pipeline
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// TestLinuxKernelFullIndex indexes the Linux kernel source tree and reports
-// per-phase timings, node/edge counts, and memory usage.
-//
-// Set LINUX_SRC to the kernel source path (e.g. ~/linux).
-// The test is skipped if LINUX_SRC is unset or the directory doesn't exist.
-//
-// Usage:
-//
-// LINUX_SRC=~/linux go test ./internal/pipeline/ -run TestLinuxKernelFullIndex -v -timeout 60m -count=1
-func TestLinuxKernelFullIndex(t *testing.T) {
- srcDir := os.Getenv("LINUX_SRC")
- if srcDir == "" {
- t.Skip("LINUX_SRC not set — skipping Linux kernel benchmark")
- }
- srcDir, _ = filepath.Abs(srcDir)
- if _, err := os.Stat(srcDir); err != nil { //nolint:gosec // G703: srcDir from env, not user input
- t.Skipf("LINUX_SRC=%s not found: %v", srcDir, err)
- }
-
- mode := discover.ModeFull
- if os.Getenv("LINUX_MODE") == "fast" {
- mode = discover.ModeFast
- }
-
- // Capture structured log output for timing extraction.
- var logBuf bytes.Buffer
- handler := slog.NewJSONHandler(&logBuf, &slog.HandlerOptions{Level: slog.LevelInfo})
- slog.SetDefault(slog.New(handler))
- defer slog.SetDefault(slog.Default())
-
- // Use a temp directory for the SQLite db (disk-backed = exercises direct page writer).
- tmpDir := t.TempDir()
- dbPath := filepath.Join(tmpDir, "linux.db")
-
- s, err := store.OpenPath(dbPath)
- if err != nil {
- t.Fatalf("open db: %v", err)
- }
- defer s.Close()
-
- t.Logf("src=%s mode=%s db=%s GOMAXPROCS=%d", srcDir, mode, dbPath, runtime.GOMAXPROCS(0))
-
- start := time.Now()
- p := New(context.Background(), s, srcDir, mode)
- if err := p.Run(); err != nil {
- t.Fatalf("pipeline.Run: %v", err)
- }
- totalElapsed := time.Since(start)
-
- // Reopen store to verify integrity.
- s.Close()
- s2, err := store.OpenPath(dbPath)
- if err != nil {
- t.Fatalf("reopen db: %v", err)
- }
- defer s2.Close()
-
- projectName := ProjectNameFromPath(srcDir)
- nc, _ := s2.CountNodes(projectName)
- ec, _ := s2.CountEdges(projectName)
-
- dbInfo, _ := os.Stat(dbPath) //nolint:gosec // G703: dbPath from tmpdir, not user input
- dbSizeMB := float64(0)
- if dbInfo != nil {
- dbSizeMB = float64(dbInfo.Size()) / (1 << 20)
- }
-
- var m runtime.MemStats
- runtime.ReadMemStats(&m)
-
- // Parse slog JSON lines for phase timings.
- timings := parsePassTimings(logBuf.String())
- memSnapshots := parseMemStats(logBuf.String())
- edgeCounts := parseEdgeCounts(logBuf.String())
- discovered := parseDiscovered(logBuf.String())
-
- // Report.
- t.Logf("")
- t.Logf("═══════════════════════════════════════════════════")
- t.Logf(" LINUX KERNEL INDEX REPORT")
- t.Logf("═══════════════════════════════════════════════════")
- t.Logf(" Source: %s", srcDir)
- t.Logf(" Mode: %s", mode)
- t.Logf(" Files: %d", discovered)
- t.Logf(" GOMAXPROCS: %d", runtime.GOMAXPROCS(0))
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" PHASE TIMINGS")
- t.Logf("───────────────────────────────────────────────────")
- for _, pt := range timings {
- pct := float64(pt.Elapsed) / float64(totalElapsed) * 100
- t.Logf(" %-20s %10s (%4.1f%%)", pt.Pass, pt.Elapsed.Round(time.Millisecond), pct)
- }
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" %-20s %10s", "TOTAL", totalElapsed.Round(time.Millisecond))
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" RESULTS")
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" Nodes: %d", nc)
- t.Logf(" Edges: %d", ec)
- t.Logf(" DB size: %.1f MB", dbSizeMB)
- if len(edgeCounts) > 0 {
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" EDGE BREAKDOWN")
- t.Logf("───────────────────────────────────────────────────")
- for _, ec := range edgeCounts {
- t.Logf(" %-20s %10d", ec.Type, ec.Count)
- }
- }
- if len(memSnapshots) > 0 {
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" MEMORY SNAPSHOTS")
- t.Logf("───────────────────────────────────────────────────")
- for _, ms := range memSnapshots {
- t.Logf(" %-20s heap_inuse=%4dMB heap_alloc=%4dMB sys=%4dMB",
- ms.Stage, ms.HeapInuse, ms.HeapAlloc, ms.Sys)
- }
- }
- t.Logf("───────────────────────────────────────────────────")
- t.Logf(" Final heap: %d MB (inuse), %d MB (sys)", m.HeapInuse/(1<<20), m.Sys/(1<<20))
- t.Logf("═══════════════════════════════════════════════════")
-}
-
-// --- slog JSON parsing helpers ---
-
-type passTiming struct {
- Pass string //nolint:gosec // G117 false positive: struct field name, not a secret
- Elapsed time.Duration
-}
-
-type memSnapshot struct {
- Stage string
- HeapInuse int64
- HeapAlloc int64
- Sys int64
-}
-
-type edgeCount struct {
- Type string
- Count int64
-}
-
-func parsePassTimings(logOutput string) []passTiming {
- var timings []passTiming
- for _, line := range strings.Split(logOutput, "\n") {
- if !strings.Contains(line, "pass.timing") && !strings.Contains(line, "db.dump") {
- continue
- }
- var rec map[string]interface{}
- if json.Unmarshal([]byte(line), &rec) != nil {
- continue
- }
- msg, _ := rec["msg"].(string)
- if msg != "pass.timing" && msg != "db.dump" {
- continue
- }
- pass, _ := rec["pass"].(string)
- if msg == "db.dump" {
- pass = "db.dump"
- }
- if pass == "" {
- continue
- }
- elapsed := parseDuration(rec["elapsed"])
- timings = append(timings, passTiming{Pass: pass, Elapsed: elapsed})
- }
- return timings
-}
-
-func parseMemStats(logOutput string) []memSnapshot {
- var snapshots []memSnapshot
- for _, line := range strings.Split(logOutput, "\n") {
- if !strings.Contains(line, "mem.stats") {
- continue
- }
- var rec map[string]interface{}
- if json.Unmarshal([]byte(line), &rec) != nil {
- continue
- }
- if msg, _ := rec["msg"].(string); msg != "mem.stats" {
- continue
- }
- stage, _ := rec["stage"].(string)
- hi, _ := rec["heap_inuse_mb"].(float64)
- ha, _ := rec["heap_alloc_mb"].(float64)
- sy, _ := rec["sys_mb"].(float64)
- snapshots = append(snapshots, memSnapshot{
- Stage: stage, HeapInuse: int64(hi), HeapAlloc: int64(ha), Sys: int64(sy),
- })
- }
- return snapshots
-}
-
-func parseEdgeCounts(logOutput string) []edgeCount {
- var counts []edgeCount
- for _, line := range strings.Split(logOutput, "\n") {
- if !strings.Contains(line, "pipeline.edges") {
- continue
- }
- var rec map[string]interface{}
- if json.Unmarshal([]byte(line), &rec) != nil {
- continue
- }
- if msg, _ := rec["msg"].(string); msg != "pipeline.edges" {
- continue
- }
- ty, _ := rec["type"].(string)
- cnt, _ := rec["count"].(float64)
- if ty != "" {
- counts = append(counts, edgeCount{Type: ty, Count: int64(cnt)})
- }
- }
- return counts
-}
-
-func parseDiscovered(logOutput string) int {
- for _, line := range strings.Split(logOutput, "\n") {
- if !strings.Contains(line, "pipeline.discovered") {
- continue
- }
- var rec map[string]interface{}
- if json.Unmarshal([]byte(line), &rec) != nil {
- continue
- }
- if msg, _ := rec["msg"].(string); msg == "pipeline.discovered" {
- if f, ok := rec["files"].(float64); ok {
- return int(f)
- }
- }
- }
- return 0
-}
-
-func parseDuration(v interface{}) time.Duration {
- switch val := v.(type) {
- case float64:
- // slog encodes Duration as nanoseconds (int64) which JSON decodes as float64
- return time.Duration(int64(val))
- case string:
- // Some slog handlers format as "1.234s"
- d, err := time.ParseDuration(val)
- if err != nil {
- return 0
- }
- return d
- default:
- return 0
- }
-}
-
-// TestLinuxKernelIntegrity runs PRAGMA integrity_check on an existing db.
-// Set LINUX_DB to the path of a previously-created db file.
-//
-// Usage:
-//
-// LINUX_DB=/path/to/linux.db go test ./internal/pipeline/ -run TestLinuxKernelIntegrity -v -count=1
-func TestLinuxKernelIntegrity(t *testing.T) {
- dbPath := os.Getenv("LINUX_DB")
- if dbPath == "" {
- t.Skip("LINUX_DB not set")
- }
-
- s, err := store.OpenPath(dbPath)
- if err != nil {
- t.Fatalf("open: %v", err)
- }
- defer s.Close()
-
- // Run integrity check via raw SQL
- db := s.DB()
- var integrity string
- if err := db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil {
- t.Fatalf("integrity_check: %v", err)
- }
- if integrity != "ok" {
- t.Fatalf("integrity_check = %q", integrity)
- }
-
- // Report counts
- rows, err := db.Query("SELECT type, COUNT(*) FROM edges GROUP BY type ORDER BY COUNT(*) DESC")
- if err != nil {
- t.Fatalf("edge counts: %v", err)
- }
- defer rows.Close()
- t.Logf("integrity_check: ok")
- for rows.Next() {
- var ty string
- var cnt int
- if err := rows.Scan(&ty, &cnt); err != nil {
- t.Fatalf("scan row: %v", err)
- }
- t.Logf(" %-25s %d", ty, cnt)
- }
-
- var nc, ec int
- if err := db.QueryRow("SELECT COUNT(*) FROM nodes").Scan(&nc); err != nil {
- t.Fatalf("count nodes: %v", err)
- }
- if err := db.QueryRow("SELECT COUNT(*) FROM edges").Scan(&ec); err != nil {
- t.Fatalf("count edges: %v", err)
- }
- t.Logf("nodes=%d edges=%d", nc, ec)
-
- dbInfo, _ := os.Stat(dbPath) //nolint:gosec // G703: dbPath from tmpdir, not user input
- if dbInfo != nil {
- t.Logf("db_size=%.1f MB", float64(dbInfo.Size())/(1<<20))
- }
-
- // Spot check: verify some indexes work
- var cnt int
- for _, idx := range []string{"idx_nodes_label", "idx_nodes_name", "idx_nodes_file",
- "idx_edges_source", "idx_edges_target", "idx_edges_type"} {
- err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s INDEXED BY %s",
- tableForIndex(idx), idx)).Scan(&cnt)
- if err != nil {
- t.Errorf("index %s: %v", idx, err)
- } else {
- t.Logf(" %s: %d entries", idx, cnt)
- }
- }
-}
-
-func tableForIndex(idx string) string {
- if strings.HasPrefix(idx, "idx_nodes_") {
- return "nodes"
- }
- return "edges"
-}
diff --git a/internal/pipeline/pipeline_test.go b/internal/pipeline/pipeline_test.go
deleted file mode 100644
index a85ac69fa..000000000
--- a/internal/pipeline/pipeline_test.go
+++ /dev/null
@@ -1,867 +0,0 @@
-package pipeline
-
-import (
- "context"
- "errors"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func setupTestRepo(t *testing.T) (dir string, cleanup func()) {
- t.Helper()
- dir, err := os.MkdirTemp("", "cgm-test-*")
- if err != nil {
- t.Fatal(err)
- }
- cleanup = func() { os.RemoveAll(dir) }
-
- // Create a simple Go project
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-func main() {
- result := Add(1, 2)
- _ = result
-}
-
-func Add(a, b int) int {
- return a + b
-}
-`)
-
- writeFile(t, filepath.Join(dir, "service", "service.go"), `package service
-
-func ProcessOrder(id string) error {
- return nil
-}
-
-func SubmitOrder(order interface{}) error {
- ProcessOrder("test")
- return nil
-}
-`)
-
- return dir, cleanup
-}
-
-func writeFile(t *testing.T, path, content string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPipelineRun(t *testing.T) {
- repoDir, cleanup := setupTestRepo(t)
- defer cleanup()
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, repoDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Check node counts
- nodeCount, _ := s.CountNodes(p.ProjectName)
- if nodeCount == 0 {
- t.Fatal("expected nodes, got 0")
- }
- t.Logf("Total nodes: %d", nodeCount)
-
- // Check that Functions were found
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
- t.Logf("Functions: %d", len(funcs))
- for _, f := range funcs {
- t.Logf(" %s (qn=%s, sig=%v)", f.Name, f.QualifiedName, f.Properties["signature"])
- }
- if len(funcs) < 3 { // main, Add, at minimum
- t.Errorf("expected at least 3 functions, got %d", len(funcs))
- }
-
- // Check that ProcessOrder exists
- found, _ := s.FindNodesByName(p.ProjectName, "ProcessOrder")
- if len(found) == 0 {
- t.Error("ProcessOrder not found")
- }
-
- // Check that Module nodes exist
- modules, _ := s.FindNodesByLabel(p.ProjectName, "Module")
- if len(modules) < 2 {
- t.Errorf("expected at least 2 modules, got %d", len(modules))
- }
-
- // Check edges exist
- edgeCount, _ := s.CountEdges(p.ProjectName)
- t.Logf("Total edges: %d", edgeCount)
- if edgeCount == 0 {
- t.Error("expected edges, got 0")
- }
-
- // Check CALLS edges
- // SubmitOrder calls ProcessOrder
- sender, _ := s.FindNodesByName(p.ProjectName, "SubmitOrder")
- if len(sender) > 0 {
- edges, _ := s.FindEdgesBySourceAndType(sender[0].ID, "CALLS")
- t.Logf("SubmitOrder CALLS edges: %d", len(edges))
- }
-}
-
-func TestPipelinePythonProject(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-py-test-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "main.py"), `
-def greet(name):
- return f"Hello, {name}"
-
-def process():
- result = greet("world")
- return result
-`)
-
- writeFile(t, filepath.Join(dir, "utils.py"), `
-API_URL = "https://example.com/api"
-MAX_RETRIES = 3
-
-def fetch_data(url):
- pass
-
-class DataProcessor:
- def transform(self, data):
- return data
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
- t.Logf("Python functions: %d", len(funcs))
- if len(funcs) < 3 { // greet, process, fetch_data
- t.Errorf("expected at least 3 functions, got %d", len(funcs))
- }
-
- classes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
- if len(classes) < 1 {
- t.Errorf("expected at least 1 class, got %d", len(classes))
- }
-
- methods, _ := s.FindNodesByLabel(p.ProjectName, "Method")
- if len(methods) < 1 {
- t.Errorf("expected at least 1 method, got %d", len(methods))
- }
-}
-
-// TestGoCrossPackageCallViaImport verifies that a Go function in package A
-// that imports package B and calls B.Func() gets a CALLS edge resolved.
-func TestGoCrossPackageCallViaImport(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-go-import-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Package "svc" defines ProcessOrder
- writeFile(t, filepath.Join(dir, "svc", "handler.go"), `package svc
-
-func ProcessOrder(id string) error {
- return nil
-}
-`)
-
- // Package "main" imports "svc" and calls svc.ProcessOrder
- writeFile(t, filepath.Join(dir, "main.go"), `package main
-
-import "example.com/myapp/svc"
-
-func run() {
- svc.ProcessOrder("123")
-}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Verify ProcessOrder exists
- targets, _ := s.FindNodesByName(p.ProjectName, "ProcessOrder")
- if len(targets) == 0 {
- t.Fatal("ProcessOrder not found in store")
- }
- t.Logf("ProcessOrder QN: %s", targets[0].QualifiedName)
-
- // Verify run() exists
- callers, _ := s.FindNodesByName(p.ProjectName, "run")
- if len(callers) == 0 {
- t.Fatal("run() not found in store")
- }
-
- // Check that run() has a CALLS edge to ProcessOrder
- edges, _ := s.FindEdgesBySourceAndType(callers[0].ID, "CALLS")
- found := false
- for _, e := range edges {
- if e.TargetID == targets[0].ID {
- found = true
- break
- }
- }
- if !found {
- t.Error("expected CALLS edge from run() to ProcessOrder via import, but none found")
- t.Logf("run() CALLS edges: %d", len(edges))
- for _, e := range edges {
- t.Logf(" target_id=%d", e.TargetID)
- }
- }
-}
-
-// TestPythonCrossModuleCallViaImport verifies that a Python file that does
-// "from utils import fetch_data" and calls fetch_data() gets a CALLS edge.
-func TestPythonCrossModuleCallViaImport(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-py-import-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "utils.py"), `
-def fetch_data(url):
- return {"status": "ok"}
-`)
-
- writeFile(t, filepath.Join(dir, "main.py"), `
-from utils import fetch_data
-
-def process():
- result = fetch_data("https://example.com")
- return result
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Verify fetch_data exists
- targets, _ := s.FindNodesByName(p.ProjectName, "fetch_data")
- if len(targets) == 0 {
- t.Fatal("fetch_data not found in store")
- }
- t.Logf("fetch_data QN: %s", targets[0].QualifiedName)
-
- // Verify process() exists
- callers, _ := s.FindNodesByName(p.ProjectName, "process")
- if len(callers) == 0 {
- t.Fatal("process() not found in store")
- }
-
- // Check that process() has a CALLS edge to fetch_data
- edges, _ := s.FindEdgesBySourceAndType(callers[0].ID, "CALLS")
- found := false
- for _, e := range edges {
- if e.TargetID == targets[0].ID {
- found = true
- break
- }
- }
- if !found {
- t.Error("expected CALLS edge from process() to fetch_data via import, but none found")
- t.Logf("process() CALLS edges: %d", len(edges))
- }
-}
-
-// TestPythonMethodDispatchViaTypeInference verifies that type inference allows
-// resolving method calls: p = DataProcessor() then p.transform() -> CALLS DataProcessor.transform
-func TestPythonMethodDispatchViaTypeInference(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-py-type-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "processor.py"), `
-class DataProcessor:
- def transform(self, data):
- return data.upper()
-
- def validate(self, data):
- return len(data) > 0
-`)
-
- writeFile(t, filepath.Join(dir, "main.py"), `
-from processor import DataProcessor
-
-def run():
- p = DataProcessor()
- result = p.transform("hello")
- return result
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Verify DataProcessor.transform exists as a Method
- methods, _ := s.FindNodesByName(p.ProjectName, "transform")
- if len(methods) == 0 {
- t.Fatal("transform method not found in store")
- }
- t.Logf("transform QN: %s", methods[0].QualifiedName)
-
- // Verify run() exists
- callers, _ := s.FindNodesByName(p.ProjectName, "run")
- if len(callers) == 0 {
- t.Fatal("run() not found in store")
- }
-
- // Check that run() has a CALLS edge to DataProcessor.transform
- edges, _ := s.FindEdgesBySourceAndType(callers[0].ID, "CALLS")
- found := false
- for _, e := range edges {
- if e.TargetID == methods[0].ID {
- found = true
- break
- }
- }
- if !found {
- t.Error("expected CALLS edge from run() to DataProcessor.transform via type inference, but none found")
- t.Logf("run() CALLS edges: %d", len(edges))
- for _, e := range edges {
- t.Logf(" target_id=%d", e.TargetID)
- }
- }
-}
-
-// TestGoTypeClassification verifies that Go interfaces, structs, and type aliases
-// are correctly classified as Interface, Class, and Type respectively.
-func TestGoTypeClassification(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-go-types-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "types.go"), `package types
-
-type Reader interface {
- Read(p []byte) (n int, err error)
-}
-
-type Writer interface {
- Write(p []byte) (n int, err error)
-}
-
-type Config struct {
- Host string
- Port int
-}
-
-type ID = string
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Check Interface nodes (Reader, Writer)
- interfaces, _ := s.FindNodesByLabel(p.ProjectName, "Interface")
- if len(interfaces) != 2 {
- t.Errorf("expected 2 Interface nodes, got %d", len(interfaces))
- for _, n := range interfaces {
- t.Logf(" Interface: %s", n.Name)
- }
- }
-
- // Check Class nodes (Config struct)
- classes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
- if len(classes) != 1 {
- t.Errorf("expected 1 Class node (struct), got %d", len(classes))
- for _, n := range classes {
- t.Logf(" Class: %s", n.Name)
- }
- } else if classes[0].Name != "Config" {
- t.Errorf("expected Class name 'Config', got %q", classes[0].Name)
- }
-
- // Check Type nodes (ID type alias)
- types, _ := s.FindNodesByLabel(p.ProjectName, "Type")
- if len(types) != 1 {
- t.Errorf("expected 1 Type node (alias), got %d", len(types))
- for _, n := range types {
- t.Logf(" Type: %s", n.Name)
- }
- } else if types[0].Name != "ID" {
- t.Errorf("expected Type name 'ID', got %q", types[0].Name)
- }
-}
-
-// TestGoGroupedTypeDeclaration verifies that grouped type declarations
-// (type ( ... )) also work correctly.
-func TestGoGroupedTypeDeclaration(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-go-grouped-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "models.go"), `package models
-
-type (
- Request struct {
- URL string
- }
-
- Response struct {
- Status int
- }
-
- Handler interface {
- Handle(req Request) Response
- }
-)
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- // Should find 2 structs (Class) and 1 interface
- classes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
- if len(classes) != 2 {
- t.Errorf("expected 2 Class nodes (structs), got %d", len(classes))
- }
-
- interfaces, _ := s.FindNodesByLabel(p.ProjectName, "Interface")
- if len(interfaces) != 1 {
- t.Errorf("expected 1 Interface node, got %d", len(interfaces))
- }
-}
-
-// TestPipelineKotlinProject verifies that Kotlin files are parsed and indexed
-// correctly, producing Function, Class, and Method nodes with CALLS edges.
-func TestPipelineKotlinProject(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-kt-test-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "Main.kt"), `
-fun greet(name: String): String {
- return "Hello, $name"
-}
-
-fun main() {
- val result = greet("world")
- println(result)
-}
-`)
-
- writeFile(t, filepath.Join(dir, "Service.kt"), `
-class OrderService {
- fun processOrder(id: String): Boolean {
- return true
- }
-
- fun submitOrder(order: String): Boolean {
- return processOrder(order)
- }
-}
-
-object Config {
- val API_URL = "https://example.com/api"
-}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
- t.Logf("Kotlin functions: %d", len(funcs))
- if len(funcs) < 2 { // greet, main
- t.Errorf("expected at least 2 functions, got %d", len(funcs))
- }
-
- classes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
- t.Logf("Kotlin classes: %d", len(classes))
- // OrderService + Config (object_declaration)
- if len(classes) < 1 {
- t.Errorf("expected at least 1 class, got %d", len(classes))
- }
-
- methods, _ := s.FindNodesByLabel(p.ProjectName, "Method")
- t.Logf("Kotlin methods: %d", len(methods))
- if len(methods) < 2 { // processOrder, submitOrder
- t.Errorf("expected at least 2 methods, got %d", len(methods))
- }
-
- // Check that greet exists
- found, _ := s.FindNodesByName(p.ProjectName, "greet")
- if len(found) == 0 {
- t.Error("greet not found")
- }
-
- // Check modules exist
- modules, _ := s.FindNodesByLabel(p.ProjectName, "Module")
- if len(modules) < 2 {
- t.Errorf("expected at least 2 modules, got %d", len(modules))
- }
-
- // Check edges exist
- edgeCount, _ := s.CountEdges(p.ProjectName)
- t.Logf("Total edges: %d", edgeCount)
- if edgeCount == 0 {
- t.Error("expected edges, got 0")
- }
-}
-
-// TestLuaAnonymousFunctionExtraction verifies that MoonScript-style Lua code
-// (local f = function(...) end) extracts Function nodes correctly.
-func TestLuaAnonymousFunctionExtraction(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-lua-anon-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "app.lua"), `local run_before_filter
-run_before_filter = function(filter, r)
- return filter(r)
-end
-
-local validate = function(data)
- return data ~= nil
-end
-
-function named_func(x)
- return x + 1
-end
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
- t.Logf("Lua functions: %d", len(funcs))
- for _, f := range funcs {
- t.Logf(" %s (qn=%s)", f.Name, f.QualifiedName)
- }
-
- // Expect: run_before_filter, validate, named_func (3 functions)
- if len(funcs) < 3 {
- t.Errorf("expected at least 3 functions (incl. anonymous assigned), got %d", len(funcs))
- }
-
- // Verify specific functions exist
- for _, name := range []string{"run_before_filter", "validate", "named_func"} {
- found, _ := s.FindNodesByName(p.ProjectName, name)
- if len(found) == 0 {
- t.Errorf("function %q not found", name)
- }
- }
-}
-
-// TestCSharpModernFeatures verifies that modern C# files (file-scoped namespaces,
-// primary constructors, expression-bodied members) are fully extracted.
-func TestCSharpModernFeatures(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-csharp-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- writeFile(t, filepath.Join(dir, "Controller.cs"), `namespace Conduit.Features;
-
-public class UsersController {
- public void Get() {}
- public void Create(string name) {}
-}
-`)
-
- writeFile(t, filepath.Join(dir, "Model.cs"), `namespace Conduit.Models {
- class User {
- public string Name { get; set; }
- public int GetAge() { return 0; }
- }
-}
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- modules, _ := s.FindNodesByLabel(p.ProjectName, "Module")
- t.Logf("C# modules: %d", len(modules))
- if len(modules) < 2 {
- t.Errorf("expected at least 2 Module nodes for .cs files, got %d", len(modules))
- }
-
- classes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
- t.Logf("C# classes: %d", len(classes))
- if len(classes) < 2 {
- t.Errorf("expected at least 2 Class nodes, got %d", len(classes))
- }
-
- methods, _ := s.FindNodesByLabel(p.ProjectName, "Method")
- t.Logf("C# methods: %d", len(methods))
- if len(methods) < 3 { // Get, Create, GetAge
- t.Errorf("expected at least 3 Method nodes, got %d", len(methods))
- }
-}
-
-// TestBOMStripping verifies that files with UTF-8 BOM are parsed correctly.
-func TestBOMStripping(t *testing.T) {
- dir, err := os.MkdirTemp("", "cgm-bom-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Write a Go file WITH UTF-8 BOM prefix
- bom := []byte{0xEF, 0xBB, 0xBF}
- src := []byte("package main\n\nfunc BOMFunc() {}\n")
- content := make([]byte, 0, len(bom)+len(src))
- content = append(content, bom...)
- content = append(content, src...)
- if err := os.MkdirAll(dir, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, "bom.go"), content, 0o600); err != nil {
- t.Fatal(err)
- }
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- found, _ := s.FindNodesByName(p.ProjectName, "BOMFunc")
- if len(found) == 0 {
- t.Error("BOMFunc not found — BOM stripping may have failed")
- }
-}
-
-// TestFunctionRegistry tests the registry in isolation.
-func TestFunctionRegistry(t *testing.T) {
- r := NewFunctionRegistry()
-
- r.Register("Foo", "proj.pkg.Foo", "Function")
- r.Register("Bar", "proj.pkg.Bar", "Function")
- r.Register("Foo", "proj.other.Foo", "Function")
- r.Register("transform", "proj.utils.DataProcessor.transform", "Method")
-
- // FindByName returns all entries
- foos := r.FindByName("Foo")
- if len(foos) != 2 {
- t.Errorf("expected 2 Foo entries, got %d", len(foos))
- }
-
- // FindEndingWith
- matches := r.FindEndingWith("DataProcessor.transform")
- if len(matches) != 1 {
- t.Errorf("expected 1 match for DataProcessor.transform, got %d", len(matches))
- }
-
- // Resolve same-module
- res := r.Resolve("Foo", "proj.pkg", nil)
- if res.QualifiedName != "proj.pkg.Foo" {
- t.Errorf("expected proj.pkg.Foo, got %s", res.QualifiedName)
- }
-
- // Resolve via import map
- imports := map[string]string{"other": "proj.other"}
- res = r.Resolve("other.Foo", "proj.pkg", imports)
- if res.QualifiedName != "proj.other.Foo" {
- t.Errorf("expected proj.other.Foo, got %s", res.QualifiedName)
- }
-
- // Resolve unique name
- res = r.Resolve("Bar", "proj.unrelated", nil)
- if res.QualifiedName != "proj.pkg.Bar" {
- t.Errorf("expected proj.pkg.Bar, got %s", res.QualifiedName)
- }
-}
-
-// TestPipelineRunCancellation verifies that a pre-cancelled context makes Run() return context.Canceled.
-func TestPipelineRunCancellation(t *testing.T) {
- repoDir, cleanup := setupTestRepo(t)
- defer cleanup()
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- ctx, cancel := context.WithCancel(context.Background())
- cancel() // pre-cancel
-
- p := New(ctx, s, repoDir, discover.ModeFull)
- err = p.Run()
- if !errors.Is(err, context.Canceled) {
- t.Fatalf("expected context.Canceled, got %v", err)
- }
-}
-
-// TestProjectNameFromPath verifies unique project names from absolute paths.
-func TestProjectNameFromPath(t *testing.T) {
- tests := []struct{ path, want string }{
- {"/tmp/bench/erlang/lib/stdlib/src", "tmp-bench-erlang-lib-stdlib-src"},
- {"/Users/martin/projects/myapp", "Users-martin-projects-myapp"},
- {"/home/user/repo", "home-user-repo"},
- {"/single", "single"},
- // Windows paths (#20) — drive letter normalized to lowercase (#50)
- {"C:/Users/project", "c-Users-project"},
- {"D:\\Projects\\myapp", "d-Projects-myapp"},
- {"C:\\Temp\\codebase-memory-mcp", "c-Temp-codebase-memory-mcp"},
- }
- for _, tt := range tests {
- got := ProjectNameFromPath(tt.path)
- if got != tt.want {
- t.Errorf("ProjectNameFromPath(%q) = %q, want %q", tt.path, got, tt.want)
- }
- }
-}
-
-// TestProjectNameUniqueness verifies two paths with same base name produce different project names.
-func TestProjectNameUniqueness(t *testing.T) {
- a := ProjectNameFromPath("/tmp/bench/zig/lib/std")
- b := ProjectNameFromPath("/tmp/bench/erlang/lib/stdlib/src")
- if a == b {
- t.Errorf("collision: %q == %q", a, b)
- }
-}
-
-func TestFORMProcedureCallResolution(t *testing.T) {
- dir, err := os.MkdirTemp("", "cbm-form-test-*")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(dir)
-
- // Two procedures: caller calls callee via #call
- writeFile(t, filepath.Join(dir, "calc.frm"), `#procedure callee(x)
- id x = 0;
-#endprocedure
-#procedure caller()
- #call callee(1)
-#endprocedure
-`)
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, dir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatalf("Pipeline.Run: %v", err)
- }
-
- funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
- t.Logf("FORM functions: %d", len(funcs))
- for _, f := range funcs {
- t.Logf(" func: %s (%s)", f.Name, f.QualifiedName)
- }
-
- edges, _ := s.FindEdgesByType(p.ProjectName, "CALLS")
- t.Logf("CALLS edges: %d", len(edges))
- found := false
- for _, e := range edges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil {
- t.Logf(" CALLS: %s -> %s", src.Name, tgt.Name)
- }
- if tgt != nil && tgt.Name == "callee" {
- found = true
- }
- }
- if !found {
- t.Error("expected a CALLS edge from caller to callee, got none")
- }
-}
diff --git a/internal/pipeline/prefetch.go b/internal/pipeline/prefetch.go
deleted file mode 100644
index fc97eeefc..000000000
--- a/internal/pipeline/prefetch.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "runtime"
- "sync/atomic"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
-)
-
-// prefetcher warms the OS page cache ahead of worker consumption.
-// A goroutine opens files and issues platform-specific fadvise/fcntl hints
-// so that by the time workers mmap a file, pages are already resident.
-type prefetcher struct {
- files []discover.FileInfo
- lookahead int
- cursor atomic.Int64 // workers report progress here
- done chan struct{}
-}
-
-func newPrefetcher(files []discover.FileInfo, lookahead int) *prefetcher {
- if lookahead <= 0 {
- lookahead = 100
- }
- return &prefetcher{
- files: files,
- lookahead: lookahead,
- done: make(chan struct{}),
- }
-}
-
-// run prefetches files from the current cursor position up to lookahead ahead.
-// Call in a goroutine. Exits when ctx is cancelled or all files are prefetched.
-func (pf *prefetcher) run(ctx context.Context) {
- defer close(pf.done)
-
- prefetched := int64(0)
- n := int64(len(pf.files))
-
- for {
- if ctx.Err() != nil {
- return
- }
-
- workerPos := pf.cursor.Load()
- target := workerPos + int64(pf.lookahead)
- if target > n {
- target = n
- }
-
- if prefetched >= target {
- if prefetched >= n {
- return // all done
- }
- // Wait for workers to advance before prefetching more.
- select {
- case <-ctx.Done():
- return
- default:
- runtime.Gosched()
- time.Sleep(500 * time.Microsecond)
- }
- continue
- }
-
- // Prefetch the next file
- f, err := os.Open(pf.files[prefetched].Path)
- if err == nil {
- advisePrefetch(f)
- f.Close()
- }
- prefetched++
- }
-}
-
-// advance reports that workers have completed up to idx (exclusive).
-func (pf *prefetcher) advance(idx int) {
- for {
- cur := pf.cursor.Load()
- if int64(idx) <= cur {
- return
- }
- if pf.cursor.CompareAndSwap(cur, int64(idx)) {
- return
- }
- }
-}
-
-// stop waits for the prefetcher goroutine to finish.
-func (pf *prefetcher) stop() {
- <-pf.done
-}
diff --git a/internal/pipeline/prefetch_darwin.go b/internal/pipeline/prefetch_darwin.go
deleted file mode 100644
index ebdeb62f3..000000000
--- a/internal/pipeline/prefetch_darwin.go
+++ /dev/null
@@ -1,28 +0,0 @@
-//go:build darwin
-
-package pipeline
-
-import (
- "os"
- "syscall"
- "unsafe"
-)
-
-// F_RDADVISE tells the kernel to start reading the file into the page cache.
-const fRDADVISE = 44
-
-type radvisory struct {
- offset int64
- count int32
- _ [4]byte // padding
-}
-
-func advisePrefetch(f *os.File) {
- fi, err := f.Stat()
- if err != nil || fi.Size() == 0 {
- return
- }
- ra := radvisory{offset: 0, count: int32(fi.Size())}
- // Best-effort; ignore errors (unsupported FS, etc.)
- _, _, _ = syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(fRDADVISE), uintptr(unsafe.Pointer(&ra)))
-}
diff --git a/internal/pipeline/prefetch_linux.go b/internal/pipeline/prefetch_linux.go
deleted file mode 100644
index d1facbcb9..000000000
--- a/internal/pipeline/prefetch_linux.go
+++ /dev/null
@@ -1,18 +0,0 @@
-//go:build linux
-
-package pipeline
-
-import (
- "os"
-
- "golang.org/x/sys/unix"
-)
-
-func advisePrefetch(f *os.File) {
- fi, err := f.Stat()
- if err != nil || fi.Size() == 0 {
- return
- }
- // POSIX_FADV_WILLNEED = 3: advise kernel to read file into page cache
- _ = unix.Fadvise(int(f.Fd()), 0, fi.Size(), unix.FADV_WILLNEED)
-}
diff --git a/internal/pipeline/prefetch_windows.go b/internal/pipeline/prefetch_windows.go
deleted file mode 100644
index a7c5aab71..000000000
--- a/internal/pipeline/prefetch_windows.go
+++ /dev/null
@@ -1,9 +0,0 @@
-//go:build windows
-
-package pipeline
-
-import "os"
-
-func advisePrefetch(_ *os.File) {
- // No-op on Windows
-}
diff --git a/internal/pipeline/readwrite.go b/internal/pipeline/readwrite.go
deleted file mode 100644
index 51586f111..000000000
--- a/internal/pipeline/readwrite.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "runtime"
-
- "golang.org/x/sync/errgroup"
-)
-
-// passReadsWrites creates READS and WRITES edges from functions to Variable nodes.
-func (p *Pipeline) passReadsWrites() {
- slog.Info("pass.readwrite")
-
- type fileEntry struct {
- relPath string
- ext *cachedExtraction
- }
- var files []fileEntry
- for relPath, ext := range p.extractionCache {
- if len(ext.Result.ReadWrites) > 0 {
- files = append(files, fileEntry{relPath, ext})
- }
- }
-
- if len(files) == 0 {
- return
- }
-
- results := make([][]resolvedEdge, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g := new(errgroup.Group)
- g.SetLimit(numWorkers)
- for i, fe := range files {
- g.Go(func() error {
- results[i] = p.resolveFileReadsWritesCBM(fe.relPath, fe.ext)
- return nil
- })
- }
- _ = g.Wait()
-
- p.flushResolvedEdges(results)
-
- total := 0
- for _, r := range results {
- total += len(r)
- }
- slog.Info("pass.readwrite.done", "edges", total)
-}
diff --git a/internal/pipeline/resolver.go b/internal/pipeline/resolver.go
deleted file mode 100644
index 9efe28b4f..000000000
--- a/internal/pipeline/resolver.go
+++ /dev/null
@@ -1,415 +0,0 @@
-package pipeline
-
-import (
- "math"
- "strings"
- "sync"
-)
-
-// ResolutionResult carries the resolved QN plus quality metadata.
-// Initial confidence values are estimates — recalibrate after measuring
-// precision per strategy on real repos.
-type ResolutionResult struct {
- QualifiedName string
- Strategy string // "import_map", "import_map_suffix", "same_module", "unique_name", "suffix_match", "fuzzy", "type_dispatch"
- Confidence float64 // 0.0–1.0
- CandidateCount int // how many candidates were considered
-}
-
-// FunctionRegistry indexes all Function, Method, and Class nodes by qualified
-// name and simple name for fast call resolution.
-type FunctionRegistry struct {
- mu sync.RWMutex
- // exact maps qualifiedName -> label (Function/Method/Class)
- exact map[string]string
- // byName maps simpleName -> []qualifiedName for reverse lookup
- byName map[string][]string
-}
-
-// NewFunctionRegistry creates an empty registry.
-func NewFunctionRegistry() *FunctionRegistry {
- return &FunctionRegistry{
- exact: make(map[string]string),
- byName: make(map[string][]string),
- }
-}
-
-// Register adds a node to the registry.
-func (r *FunctionRegistry) Register(name, qualifiedName, nodeLabel string) {
- r.mu.Lock()
- defer r.mu.Unlock()
-
- r.exact[qualifiedName] = nodeLabel
-
- // Index by simple name (last segment after the final dot)
- simple := simpleName(qualifiedName)
- // Avoid duplicates in the slice
- for _, existing := range r.byName[simple] {
- if existing == qualifiedName {
- return
- }
- }
- r.byName[simple] = append(r.byName[simple], qualifiedName)
-}
-
-// Resolve attempts to find the qualified name of a callee using a prioritized
-// resolution strategy:
-// 1. Import map lookup
-// 2. Same-module match
-// 3. Project-wide single match by simple name
-// 4. Suffix match with import distance scoring
-func (r *FunctionRegistry) Resolve(calleeName, moduleQN string, importMap map[string]string) ResolutionResult {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- // Split calleeName for qualified calls like "pkg.Func" or "obj.method"
- parts := strings.SplitN(calleeName, ".", 2)
- prefix := parts[0]
- var suffix string
- if len(parts) > 1 {
- suffix = parts[1]
- }
-
- if result := r.resolveViaImportMap(prefix, suffix, importMap); result.QualifiedName != "" {
- return result
- }
-
- if result := r.resolveViaSameModule(calleeName, suffix, moduleQN); result.QualifiedName != "" {
- return result
- }
-
- return r.resolveViaNameLookup(calleeName, suffix, moduleQN, importMap)
-}
-
-// resolveViaImportMap tries to resolve a callee using the import map (Strategy 1).
-func (r *FunctionRegistry) resolveViaImportMap(prefix, suffix string, importMap map[string]string) ResolutionResult {
- if importMap == nil {
- return ResolutionResult{}
- }
- resolved, ok := importMap[prefix]
- if !ok {
- return ResolutionResult{}
- }
- var candidate string
- if suffix != "" {
- candidate = resolved + "." + suffix
- } else {
- candidate = resolved
- }
- if _, exists := r.exact[candidate]; exists {
- return ResolutionResult{QualifiedName: candidate, Strategy: "import_map", Confidence: 0.95, CandidateCount: 1}
- }
- if suffix != "" {
- for qn := range r.exact {
- if strings.HasPrefix(qn, resolved+".") && strings.HasSuffix(qn, "."+suffix) {
- return ResolutionResult{QualifiedName: qn, Strategy: "import_map_suffix", Confidence: 0.85, CandidateCount: 1}
- }
- }
- }
- return ResolutionResult{}
-}
-
-// resolveViaSameModule tries to resolve a callee within the same module (Strategy 2).
-func (r *FunctionRegistry) resolveViaSameModule(calleeName, suffix, moduleQN string) ResolutionResult {
- sameModule := moduleQN + "." + calleeName
- if _, exists := r.exact[sameModule]; exists {
- return ResolutionResult{QualifiedName: sameModule, Strategy: "same_module", Confidence: 0.90, CandidateCount: 1}
- }
- if suffix != "" {
- sameModuleQualified := moduleQN + "." + suffix
- if _, exists := r.exact[sameModuleQualified]; exists {
- return ResolutionResult{QualifiedName: sameModuleQualified, Strategy: "same_module", Confidence: 0.90, CandidateCount: 1}
- }
- }
- return ResolutionResult{}
-}
-
-// resolveViaNameLookup tries project-wide name lookup and suffix matching (Strategies 3+4).
-func (r *FunctionRegistry) resolveViaNameLookup(calleeName, suffix, moduleQN string, importMap map[string]string) ResolutionResult {
- lookupName := calleeName
- if suffix != "" {
- lookupName = suffix
- }
- simple := simpleName(lookupName)
- candidates := r.byName[simple]
-
- // Strategy 3: unique name — single candidate project-wide
- if len(candidates) == 1 {
- conf := 0.75
- if importMap != nil && !isImportReachable(candidates[0], importMap) {
- conf *= 0.5
- }
- return ResolutionResult{QualifiedName: candidates[0], Strategy: "unique_name", Confidence: conf, CandidateCount: 1}
- }
-
- // Strategy 4: suffix match with import distance scoring
- if suffix != "" {
- if res := r.resolveSuffixMatch(calleeName, suffix, moduleQN, importMap, candidates); res.QualifiedName != "" {
- return res
- }
- }
-
- return pickBestCandidate(candidates, moduleQN, importMap)
-}
-
-// resolveSuffixMatch handles Strategy 4 — suffix-based matching among multiple candidates.
-func (r *FunctionRegistry) resolveSuffixMatch(calleeName, suffix, moduleQN string, importMap map[string]string, candidates []string) ResolutionResult {
- var matches []string
- for _, qn := range candidates {
- if strings.HasSuffix(qn, "."+calleeName) {
- conf := candidateCountPenalty(importAdjustedConfidence(0.55, qn, importMap), len(candidates))
- return ResolutionResult{QualifiedName: qn, Strategy: "suffix_match", Confidence: conf, CandidateCount: len(candidates)}
- }
- if strings.HasSuffix(qn, "."+suffix) {
- matches = append(matches, qn)
- }
- }
- if importMap != nil {
- matches = filterImportReachable(matches, importMap)
- }
- if len(matches) == 1 {
- return ResolutionResult{QualifiedName: matches[0], Strategy: "suffix_match", Confidence: candidateCountPenalty(0.55, len(candidates)), CandidateCount: len(candidates)}
- }
- if len(matches) > 1 {
- best := bestByImportDistance(matches, moduleQN)
- return ResolutionResult{QualifiedName: best, Strategy: "suffix_match", Confidence: candidateCountPenalty(0.55, len(matches)), CandidateCount: len(matches)}
- }
- return ResolutionResult{}
-}
-
-// pickBestCandidate selects the best match from multiple candidates with import filtering.
-func pickBestCandidate(candidates []string, moduleQN string, importMap map[string]string) ResolutionResult {
- if len(candidates) <= 1 {
- return ResolutionResult{}
- }
- filtered := candidates
- if importMap != nil {
- filtered = filterImportReachable(candidates, importMap)
- }
- if len(filtered) == 0 {
- best := bestByImportDistance(candidates, moduleQN)
- return ResolutionResult{QualifiedName: best, Strategy: "suffix_match", Confidence: candidateCountPenalty(0.55*0.5, len(candidates)), CandidateCount: len(candidates)}
- }
- if len(filtered) == 1 {
- return ResolutionResult{QualifiedName: filtered[0], Strategy: "suffix_match", Confidence: candidateCountPenalty(0.55, len(candidates)), CandidateCount: len(candidates)}
- }
- best := bestByImportDistance(filtered, moduleQN)
- return ResolutionResult{QualifiedName: best, Strategy: "suffix_match", Confidence: candidateCountPenalty(0.55, len(filtered)), CandidateCount: len(filtered)}
-}
-
-// importAdjustedConfidence halves confidence when a candidate is not import-reachable.
-func importAdjustedConfidence(base float64, candidateQN string, importMap map[string]string) float64 {
- if importMap != nil && !isImportReachable(candidateQN, importMap) {
- return base * 0.5
- }
- return base
-}
-
-// candidateCountPenalty scales confidence inversely with candidate count.
-// Common method names (String, Get, Add, Close) have many candidates project-wide,
-// making random selection unreliable. Penalty: base * min(1.0, 3.0/count).
-// 1-3 candidates: full confidence. 6: halved. 30: 1/10th.
-func candidateCountPenalty(base float64, count int) float64 {
- if count <= 3 {
- return base
- }
- return base * math.Min(1.0, 3.0/float64(count))
-}
-
-// FuzzyResolve attempts a loose match when Resolve() returns "".
-// It searches for any registered function whose simple name matches the callee's
-// last name segment. Returns the best match (by import distance) with confidence,
-// or an empty result and false if no match is found.
-//
-// Unlike Resolve(), this does not require prefix/import agreement — it purely
-// matches on the function name.
-func (r *FunctionRegistry) FuzzyResolve(calleeName, moduleQN string, importMap map[string]string) (ResolutionResult, bool) {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- // Extract the simple name (last segment after dots)
- lookupName := simpleName(calleeName)
- candidates := r.byName[lookupName]
-
- if len(candidates) == 0 {
- return ResolutionResult{}, false
- }
-
- // If there's exactly one candidate, use it
- if len(candidates) == 1 {
- conf := 0.40
- if importMap != nil && !isImportReachable(candidates[0], importMap) {
- conf *= 0.5
- }
- return ResolutionResult{
- QualifiedName: candidates[0], Strategy: "fuzzy",
- Confidence: conf, CandidateCount: 1,
- }, true
- }
-
- // Multiple candidates: filter by import reachability, then pick best by distance
- filtered := candidates
- if importMap != nil {
- filtered = filterImportReachable(candidates, importMap)
- }
- if len(filtered) == 0 {
- // No import-reachable candidates — use original with penalty
- best := bestByImportDistance(candidates, moduleQN)
- if best == "" {
- return ResolutionResult{}, false
- }
- return ResolutionResult{
- QualifiedName: best, Strategy: "fuzzy",
- Confidence: candidateCountPenalty(0.30*0.5, len(candidates)), CandidateCount: len(candidates),
- }, true
- }
- if len(filtered) == 1 {
- return ResolutionResult{
- QualifiedName: filtered[0], Strategy: "fuzzy",
- Confidence: candidateCountPenalty(0.40, len(candidates)), CandidateCount: len(candidates),
- }, true
- }
- best := bestByImportDistance(filtered, moduleQN)
- if best == "" {
- return ResolutionResult{}, false
- }
- return ResolutionResult{
- QualifiedName: best, Strategy: "fuzzy",
- Confidence: candidateCountPenalty(0.30, len(filtered)), CandidateCount: len(filtered),
- }, true
-}
-
-// LabelOf returns the node label for a qualified name, or "" if not registered.
-func (r *FunctionRegistry) LabelOf(qualifiedName string) string {
- r.mu.RLock()
- defer r.mu.RUnlock()
- return r.exact[qualifiedName]
-}
-
-// Exists returns true if a qualified name is registered.
-// Uses RLock for concurrent read safety.
-func (r *FunctionRegistry) Exists(qualifiedName string) bool {
- r.mu.RLock()
- defer r.mu.RUnlock()
- _, ok := r.exact[qualifiedName]
- return ok
-}
-
-// FindByName returns all qualified names with the given simple name.
-func (r *FunctionRegistry) FindByName(name string) []string {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- result := make([]string, len(r.byName[name]))
- copy(result, r.byName[name])
- return result
-}
-
-// FindEndingWith returns all qualified names ending with ".suffix".
-func (r *FunctionRegistry) FindEndingWith(suffix string) []string {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- target := "." + suffix
- var result []string
- for qn := range r.exact {
- if strings.HasSuffix(qn, target) {
- result = append(result, qn)
- }
- }
- return result
-}
-
-// Size returns the number of entries in the registry.
-func (r *FunctionRegistry) Size() int {
- r.mu.RLock()
- defer r.mu.RUnlock()
- return len(r.exact)
-}
-
-// simpleName extracts the last dot-separated segment.
-func simpleName(qn string) string {
- if idx := strings.LastIndex(qn, "."); idx >= 0 {
- return qn[idx+1:]
- }
- return qn
-}
-
-// bestByImportDistance picks the candidate whose QN shares the longest common
-// prefix with the caller's module QN. This approximates "closest in the
-// project structure".
-func bestByImportDistance(candidates []string, callerModuleQN string) string {
- best := ""
- bestLen := -1
-
- for _, c := range candidates {
- prefixLen := commonPrefixLen(c, callerModuleQN)
- if prefixLen > bestLen {
- bestLen = prefixLen
- best = c
- }
- }
- return best
-}
-
-// commonPrefixLen returns the length of the common dot-segment prefix.
-func commonPrefixLen(a, b string) int {
- aParts := strings.Split(a, ".")
- bParts := strings.Split(b, ".")
-
- count := 0
- for i := 0; i < len(aParts) && i < len(bParts); i++ {
- if aParts[i] != bParts[i] {
- break
- }
- count++
- }
- return count
-}
-
-// modulePrefix extracts the module portion of a QN (everything before the last dot segment).
-func modulePrefix(qn string) string {
- if idx := strings.LastIndex(qn, "."); idx >= 0 {
- return qn[:idx]
- }
- return qn
-}
-
-// isImportReachable checks if the candidate's module prefix appears anywhere
-// in the caller's import map values.
-func isImportReachable(candidateQN string, importMap map[string]string) bool {
- candidateModule := modulePrefix(candidateQN)
- for _, importedQN := range importMap {
- if strings.HasPrefix(candidateModule, importedQN) || strings.HasPrefix(importedQN, candidateModule) {
- return true
- }
- }
- return false
-}
-
-// filterImportReachable returns only candidates reachable via the import map.
-// Returns the original slice if importMap is nil or filtering eliminates everything.
-func filterImportReachable(candidates []string, importMap map[string]string) []string {
- if importMap == nil {
- return candidates
- }
- var filtered []string
- for _, c := range candidates {
- if isImportReachable(c, importMap) {
- filtered = append(filtered, c)
- }
- }
- return filtered
-}
-
-// confidenceBand returns a human-readable band label for a confidence score.
-func confidenceBand(score float64) string {
- switch {
- case score >= 0.7:
- return "high"
- case score >= 0.45:
- return "medium"
- default:
- return "speculative"
- }
-}
diff --git a/internal/pipeline/resolver_test.go b/internal/pipeline/resolver_test.go
deleted file mode 100644
index c2abd53fb..000000000
--- a/internal/pipeline/resolver_test.go
+++ /dev/null
@@ -1,300 +0,0 @@
-package pipeline
-
-import (
- "math"
- "testing"
-)
-
-func TestFuzzyResolve_SingleCandidate(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("CreateOrder", "svcA.handlers.CreateOrder", "Function")
- reg.Register("ValidateOrder", "svcB.validators.ValidateOrder", "Function")
-
- // Normal resolve with no import map should find unique name
- result := reg.Resolve("CreateOrder", "svcC.caller", nil)
- if result.QualifiedName != "svcA.handlers.CreateOrder" {
- t.Errorf("Resolve: expected svcA.handlers.CreateOrder, got %s", result.QualifiedName)
- }
-
- // FuzzyResolve should find by simple name even with unknown prefix
- fuzzyResult, ok := reg.FuzzyResolve("unknownPkg.CreateOrder", "svcC.caller", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- if fuzzyResult.QualifiedName != "svcA.handlers.CreateOrder" {
- t.Errorf("expected svcA.handlers.CreateOrder, got %s", fuzzyResult.QualifiedName)
- }
-}
-
-func TestFuzzyResolve_NonExistentName(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("CreateOrder", "svcA.handlers.CreateOrder", "Function")
-
- _, ok := reg.FuzzyResolve("NonExistent", "svcC.caller", nil)
- if ok {
- t.Fatal("expected no fuzzy match for non-existent name")
- }
-}
-
-func TestFuzzyResolve_MultipleCandidates_BestByDistance(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Process", "svcA.handlers.Process", "Function")
- reg.Register("Process", "svcB.handlers.Process", "Function")
-
- // Caller is in svcA — should prefer svcA.handlers.Process
- fuzzyResult, ok := reg.FuzzyResolve("unknown.Process", "svcA.other", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- if fuzzyResult.QualifiedName != "svcA.handlers.Process" {
- t.Errorf("expected svcA.handlers.Process, got %s", fuzzyResult.QualifiedName)
- }
-
- // Caller is in svcB — should prefer svcB.handlers.Process
- fuzzyResult, ok = reg.FuzzyResolve("unknown.Process", "svcB.other", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- if fuzzyResult.QualifiedName != "svcB.handlers.Process" {
- t.Errorf("expected svcB.handlers.Process, got %s", fuzzyResult.QualifiedName)
- }
-}
-
-func TestFuzzyResolve_SimpleNameExtraction(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("DoWork", "myproject.utils.DoWork", "Function")
-
- // Deeply qualified callee — should extract "DoWork" as simple name
- fuzzyResult, ok := reg.FuzzyResolve("some.deep.module.DoWork", "myproject.caller", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- if fuzzyResult.QualifiedName != "myproject.utils.DoWork" {
- t.Errorf("expected myproject.utils.DoWork, got %s", fuzzyResult.QualifiedName)
- }
-}
-
-func TestFuzzyResolve_NoMatchForBareName(t *testing.T) {
- reg := NewFunctionRegistry()
- // Register nothing
-
- _, ok := reg.FuzzyResolve("SomeFunc", "myproject.caller", nil)
- if ok {
- t.Fatal("expected no fuzzy match on empty registry")
- }
-}
-
-func TestRegistryExists(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Foo", "pkg.module.Foo", "Function")
- reg.Register("Bar", "pkg.module.Bar", "Method")
-
- if !reg.Exists("pkg.module.Foo") {
- t.Error("expected Foo to exist")
- }
- if !reg.Exists("pkg.module.Bar") {
- t.Error("expected Bar to exist")
- }
- if reg.Exists("pkg.module.Missing") {
- t.Error("expected Missing to not exist")
- }
- if reg.Exists("") {
- t.Error("expected empty string to not exist")
- }
-}
-
-// --- Phase 1: Confidence scoring tests ---
-
-func assertConfidence(t *testing.T, label string, got, want float64) {
- t.Helper()
- if math.Abs(got-want) > 0.01 {
- t.Errorf("%s: confidence = %.2f, want %.2f", label, got, want)
- }
-}
-
-func TestResolveConfidence_ImportMap(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Foo", "proj.other.Foo", "Function")
-
- imports := map[string]string{"other": "proj.other"}
- result := reg.Resolve("other.Foo", "proj.pkg", imports)
- if result.QualifiedName != "proj.other.Foo" {
- t.Fatalf("expected proj.other.Foo, got %s", result.QualifiedName)
- }
- assertConfidence(t, "import_map", result.Confidence, 0.95)
- if result.Strategy != "import_map" {
- t.Errorf("strategy = %s, want import_map", result.Strategy)
- }
-}
-
-func TestResolveConfidence_ImportMapSuffix(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Foo", "proj.other.sub.Foo", "Function")
-
- imports := map[string]string{"other": "proj.other"}
- result := reg.Resolve("other.Foo", "proj.pkg", imports)
- if result.QualifiedName != "proj.other.sub.Foo" {
- t.Fatalf("expected proj.other.sub.Foo, got %s", result.QualifiedName)
- }
- assertConfidence(t, "import_map_suffix", result.Confidence, 0.85)
- if result.Strategy != "import_map_suffix" {
- t.Errorf("strategy = %s, want import_map_suffix", result.Strategy)
- }
-}
-
-func TestResolveConfidence_SameModule(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Foo", "proj.pkg.Foo", "Function")
-
- result := reg.Resolve("Foo", "proj.pkg", nil)
- if result.QualifiedName != "proj.pkg.Foo" {
- t.Fatalf("expected proj.pkg.Foo, got %s", result.QualifiedName)
- }
- assertConfidence(t, "same_module", result.Confidence, 0.90)
- if result.Strategy != "same_module" {
- t.Errorf("strategy = %s, want same_module", result.Strategy)
- }
-}
-
-func TestResolveConfidence_UniqueName(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Bar", "proj.pkg.Bar", "Function")
-
- result := reg.Resolve("Bar", "proj.unrelated", nil)
- if result.QualifiedName != "proj.pkg.Bar" {
- t.Fatalf("expected proj.pkg.Bar, got %s", result.QualifiedName)
- }
- assertConfidence(t, "unique_name", result.Confidence, 0.75)
- if result.Strategy != "unique_name" {
- t.Errorf("strategy = %s, want unique_name", result.Strategy)
- }
-}
-
-func TestResolveConfidence_SuffixMatch(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Process", "proj.svcA.Process", "Function")
- reg.Register("Process", "proj.svcB.Process", "Function")
-
- result := reg.Resolve("Process", "proj.svcA.caller", nil)
- if result.QualifiedName != "proj.svcA.Process" {
- t.Fatalf("expected proj.svcA.Process, got %s", result.QualifiedName)
- }
- assertConfidence(t, "suffix_match", result.Confidence, 0.55)
- if result.Strategy != "suffix_match" {
- t.Errorf("strategy = %s, want suffix_match", result.Strategy)
- }
-}
-
-func TestFuzzyResolveConfidence_Single(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Handler", "proj.svc.Handler", "Function")
-
- result, ok := reg.FuzzyResolve("unknownPkg.Handler", "proj.caller", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- assertConfidence(t, "fuzzy_single", result.Confidence, 0.40)
- if result.Strategy != "fuzzy" {
- t.Errorf("strategy = %s, want fuzzy", result.Strategy)
- }
-}
-
-func TestFuzzyResolveConfidence_Distance(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Process", "proj.svcA.Process", "Function")
- reg.Register("Process", "proj.svcB.Process", "Function")
-
- result, ok := reg.FuzzyResolve("unknownPkg.Process", "proj.svcA.other", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- assertConfidence(t, "fuzzy_distance", result.Confidence, 0.30)
- if result.Strategy != "fuzzy" {
- t.Errorf("strategy = %s, want fuzzy", result.Strategy)
- }
-}
-
-// --- Phase 3: Negative import evidence tests ---
-
-func TestNegativeImportEvidence_RejectsUnimported(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Process", "proj.billing.Process", "Function")
- reg.Register("Process", "proj.handler.Process", "Function")
-
- // Import only handler's module — should prefer handler
- imports := map[string]string{"handler": "proj.handler"}
- result := reg.Resolve("Process", "proj.caller", imports)
- if result.QualifiedName != "proj.handler.Process" {
- t.Errorf("expected proj.handler.Process, got %s", result.QualifiedName)
- }
-}
-
-func TestNegativeImportEvidence_FuzzyPenalty(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Handler", "proj.billing.Handler", "Function")
-
- // No import for billing module — confidence should be halved
- imports := map[string]string{"other": "proj.other"}
- result, ok := reg.FuzzyResolve("unknown.Handler", "proj.caller", imports)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- // 0.40 * 0.5 = 0.20 (penalty for unreachable import)
- assertConfidence(t, "fuzzy_penalty", result.Confidence, 0.20)
-}
-
-func TestNegativeImportEvidence_NoImportMapPassthrough(t *testing.T) {
- reg := NewFunctionRegistry()
- reg.Register("Handler", "proj.billing.Handler", "Function")
-
- // nil import map — no filtering, full confidence
- result, ok := reg.FuzzyResolve("unknown.Handler", "proj.caller", nil)
- if !ok {
- t.Fatal("expected fuzzy match")
- }
- assertConfidence(t, "no_importmap", result.Confidence, 0.40)
-}
-
-func TestConfidenceBand(t *testing.T) {
- tests := []struct {
- score float64
- want string
- }{
- {0.95, "high"},
- {0.70, "high"},
- {0.55, "medium"},
- {0.45, "medium"},
- {0.40, "speculative"},
- {0.20, "speculative"},
- }
- for _, tt := range tests {
- got := confidenceBand(tt.score)
- if got != tt.want {
- t.Errorf("confidenceBand(%.2f) = %s, want %s", tt.score, got, tt.want)
- }
- }
-}
-
-func TestIsImportReachable(t *testing.T) {
- imports := map[string]string{
- "handler": "proj.handler",
- "utils": "proj.shared.utils",
- }
-
- tests := []struct {
- candidate string
- want bool
- }{
- {"proj.handler.Process", true},
- {"proj.handler.sub.Process", true},
- {"proj.shared.utils.Helper", true},
- {"proj.billing.Process", false},
- {"unrelated.pkg.Func", false},
- }
- for _, tt := range tests {
- got := isImportReachable(tt.candidate, imports)
- if got != tt.want {
- t.Errorf("isImportReachable(%s) = %v, want %v", tt.candidate, got, tt.want)
- }
- }
-}
diff --git a/internal/pipeline/testdetect.go b/internal/pipeline/testdetect.go
deleted file mode 100644
index e882143a7..000000000
--- a/internal/pipeline/testdetect.go
+++ /dev/null
@@ -1,193 +0,0 @@
-package pipeline
-
-import (
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// testFilePattern defines how to detect test files for a language.
-type testFilePattern struct {
- // suffixes on the base filename (e.g., "_test.go")
- suffixes []string
- // prefixes on the base filename (e.g., "test_")
- prefixes []string
- // stripExtSuffixes: suffixes checked on the base name after stripping ext (e.g., ".test", ".spec")
- stripExtSuffixes []string
- // testDirs: directory patterns that indicate test files
- testDirs []string
-}
-
-// testFilePatterns maps languages to their test file detection patterns.
-var testFilePatterns = map[lang.Language]testFilePattern{
- lang.Go: {suffixes: []string{"_test.go"}},
- lang.Python: {
- prefixes: []string{"test_"},
- suffixes: []string{"_test.py"},
- testDirs: []string{"__tests__", "tests"},
- },
- lang.JavaScript: {
- stripExtSuffixes: []string{".test", ".spec"},
- testDirs: []string{"__tests__"},
- },
- lang.TypeScript: {
- stripExtSuffixes: []string{".test", ".spec"},
- testDirs: []string{"__tests__"},
- },
- lang.TSX: {
- stripExtSuffixes: []string{".test", ".spec"},
- testDirs: []string{"__tests__"},
- },
- lang.Java: {
- suffixes: []string{"Test.java", "Tests.java"},
- testDirs: []string{"src/test"},
- },
- lang.Rust: {
- suffixes: []string{"_test.rs"},
- testDirs: []string{"tests"},
- },
- lang.CPP: {
- stripExtSuffixes: []string{"_test"},
- testDirs: []string{"test", "tests"},
- },
- lang.PHP: {
- suffixes: []string{"Test.php"},
- testDirs: []string{"tests"},
- },
- lang.Scala: {
- stripExtSuffixes: []string{"Spec", "Test"},
- testDirs: []string{"src/test"},
- },
- lang.CSharp: {
- stripExtSuffixes: []string{"Test", "Tests"},
- testDirs: []string{"Tests", "tests"},
- },
- lang.Kotlin: {
- stripExtSuffixes: []string{"Test", "Tests", "Spec"},
- testDirs: []string{"src/test"},
- },
- lang.Lua: {
- suffixes: []string{"_test.lua", "_spec.lua"},
- prefixes: []string{"test_"},
- testDirs: []string{"spec"},
- },
- lang.Julia: {
- testDirs: []string{"test"},
- },
- lang.FSharp: {
- stripExtSuffixes: []string{"Test", "Tests"},
- testDirs: []string{"tests"},
- },
- lang.Elm: {
- testDirs: []string{"tests"},
- },
- lang.Fortran: {
- prefixes: []string{"test_"},
- testDirs: []string{"test", "tests"},
- },
- lang.CUDA: {
- stripExtSuffixes: []string{"_test"},
- testDirs: []string{"test", "tests"},
- },
- lang.Verilog: {
- suffixes: []string{"_tb.v", "_tb.sv"},
- testDirs: []string{"testbench", "tb"},
- },
-}
-
-// isTestFile returns true if the file path indicates a test file for the given language.
-func isTestFile(relPath string, language lang.Language) bool {
- pattern, ok := testFilePatterns[language]
- if !ok {
- return false
- }
-
- base := filepath.Base(relPath)
-
- for _, s := range pattern.suffixes {
- if strings.HasSuffix(base, s) {
- return true
- }
- }
- for _, p := range pattern.prefixes {
- if strings.HasPrefix(base, p) {
- return true
- }
- }
- if len(pattern.stripExtSuffixes) > 0 {
- noExt := strings.TrimSuffix(base, filepath.Ext(base))
- for _, s := range pattern.stripExtSuffixes {
- if strings.HasSuffix(noExt, s) {
- return true
- }
- }
- }
- if len(pattern.testDirs) > 0 {
- return containsTestDir(filepath.Dir(relPath), pattern.testDirs...)
- }
- return false
-}
-
-// containsTestDir returns true if any segment of dir matches one of the patterns.
-func containsTestDir(dir string, patterns ...string) bool {
- normalised := filepath.ToSlash(dir)
- for _, p := range patterns {
- if strings.Contains(normalised, p+"/") || strings.HasSuffix(normalised, p) {
- return true
- }
- }
- return false
-}
-
-// testFuncPrefixes maps language → accepted test function name prefixes.
-var testFuncPrefixes = map[lang.Language][]string{
- lang.Go: {"Test", "Benchmark", "Example"},
- lang.Python: {"test_", "Test"},
- lang.Java: {"test"},
- lang.Rust: {"test_", "Test"},
- lang.CPP: {"Test", "test_"},
- lang.CSharp: {"Test"},
- lang.PHP: {"test", "Test"},
- lang.Scala: {"test"},
- lang.Kotlin: {"test"},
- lang.Lua: {"test_", "test"},
- lang.FSharp: {"test"},
- lang.Fortran: {"test_", "Test"},
- lang.CUDA: {"Test", "test_"},
-}
-
-// testFuncSuffixes maps language → accepted test function name suffixes.
-var testFuncSuffixes = map[lang.Language][]string{
- lang.Java: {"Test"},
- lang.Scala: {"Spec"},
- lang.CSharp: {"Test"},
- lang.Kotlin: {"Test"},
- lang.FSharp: {"Test"},
-}
-
-// isTestFunction returns true if the function name indicates a test entry point
-// (as opposed to a test helper). Used by passTests to gate TESTS edge creation.
-func isTestFunction(funcName string, language lang.Language) bool {
- for _, p := range testFuncPrefixes[language] {
- if strings.HasPrefix(funcName, p) {
- return true
- }
- }
- for _, s := range testFuncSuffixes[language] {
- if strings.HasSuffix(funcName, s) {
- return true
- }
- }
- // Special cases not covered by simple prefix/suffix rules.
- switch language {
- case lang.JavaScript, lang.TypeScript, lang.TSX:
- switch funcName {
- case "describe", "it", "test", "beforeAll", "afterAll", "beforeEach", "afterEach":
- return true
- }
- case lang.Julia:
- return funcName == "@testset" || funcName == "@test"
- }
- return false
-}
diff --git a/internal/pipeline/testdetect_test.go b/internal/pipeline/testdetect_test.go
deleted file mode 100644
index 432a85e9e..000000000
--- a/internal/pipeline/testdetect_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package pipeline
-
-import (
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-func TestIsTestFileAllLanguages(t *testing.T) {
- tests := []struct {
- name string
- language lang.Language
- testPath string // should return true
- srcPath string // should return false
- }{
- {"Go", lang.Go, "foo_test.go", "foo.go"},
- {"Python", lang.Python, "test_handler.py", "handler.py"},
- {"JavaScript", lang.JavaScript, "handler.test.js", "handler.js"},
- {"TypeScript", lang.TypeScript, "handler.spec.ts", "handler.ts"},
- {"TSX", lang.TSX, "Component.test.tsx", "Component.tsx"},
- {"Java", lang.Java, "OrderTest.java", "Order.java"},
- {"Rust", lang.Rust, "handler_test.rs", "handler.rs"},
- {"CPP", lang.CPP, "handler_test.cpp", "handler.cpp"},
- {"CSharp", lang.CSharp, "OrderTest.cs", "Order.cs"},
- {"PHP", lang.PHP, "OrderTest.php", "Order.php"},
- {"Scala", lang.Scala, "OrderSpec.scala", "Order.scala"},
- {"Kotlin", lang.Kotlin, "OrderTest.kt", "Order.kt"},
- {"Lua", lang.Lua, "handler_test.lua", "handler.lua"},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if !isTestFile(tt.testPath, tt.language) {
- t.Errorf("isTestFile(%q, %s) = false, want true", tt.testPath, tt.language)
- }
- if isTestFile(tt.srcPath, tt.language) {
- t.Errorf("isTestFile(%q, %s) = true, want false", tt.srcPath, tt.language)
- }
- })
- }
-}
-
-func TestIsTestFunctionAllLanguages(t *testing.T) {
- tests := []struct {
- name string
- language lang.Language
- testFunc string // should return true
- srcFunc string // should return false
- }{
- {"Go", lang.Go, "TestCreate", "create"},
- {"Python", lang.Python, "test_create", "create"},
- {"JavaScript", lang.JavaScript, "test", "create"},
- {"TypeScript", lang.TypeScript, "describe", "create"},
- {"TSX", lang.TSX, "it", "create"},
- {"Java", lang.Java, "testCreate", "create"},
- {"Rust", lang.Rust, "test_create", "create"},
- {"CPP", lang.CPP, "TestCreate", "create"},
- {"CSharp", lang.CSharp, "TestCreate", "create"},
- {"PHP", lang.PHP, "testCreate", "create"},
- {"Scala", lang.Scala, "testCreate", "create"},
- {"Kotlin", lang.Kotlin, "testCreate", "create"},
- {"Lua", lang.Lua, "test_create", "create"},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if !isTestFunction(tt.testFunc, tt.language) {
- t.Errorf("isTestFunction(%q, %s) = false, want true", tt.testFunc, tt.language)
- }
- if isTestFunction(tt.srcFunc, tt.language) {
- t.Errorf("isTestFunction(%q, %s) = true, want false", tt.srcFunc, tt.language)
- }
- })
- }
-}
diff --git a/internal/pipeline/tests.go b/internal/pipeline/tests.go
deleted file mode 100644
index 39b2f53dd..000000000
--- a/internal/pipeline/tests.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// passTests derives TESTS and TESTS_FILE edges from existing CALLS/IMPORTS data.
-// No AST needed — purely DB-driven post-processing.
-func (p *Pipeline) passTests() {
- slog.Info("pass.tests")
- testsCount := p.createTestsEdges()
- testsFileCount := p.createTestsFileEdges()
- slog.Info("pass.tests.done", "tests", testsCount, "tests_file", testsFileCount)
-}
-
-// createTestsEdges finds CALLS edges from test functions to production functions
-// and creates TESTS edges.
-func (p *Pipeline) createTestsEdges() int {
- callEdges, err := p.Store.FindEdgesByType(p.ProjectName, "CALLS")
- if err != nil {
- slog.Warn("pass.tests.calls.err", "err", err)
- return 0
- }
-
- if len(callEdges) == 0 {
- return 0
- }
-
- // Collect all unique source/target node IDs
- nodeIDs := make(map[int64]bool)
- for _, e := range callEdges {
- nodeIDs[e.SourceID] = true
- nodeIDs[e.TargetID] = true
- }
-
- // Batch-load all nodes
- idList := make([]int64, 0, len(nodeIDs))
- for id := range nodeIDs {
- idList = append(idList, id)
- }
- nodeMap := p.batchLoadNodes(idList)
-
- edges := make([]*store.Edge, 0, len(callEdges)/4)
- for _, e := range callEdges {
- srcNode := nodeMap[e.SourceID]
- tgtNode := nodeMap[e.TargetID]
- if srcNode == nil || tgtNode == nil {
- continue
- }
-
- srcLang := langFromFilePath(srcNode.FilePath)
- tgtLang := langFromFilePath(tgtNode.FilePath)
-
- // Source must be in a test file, target must NOT be
- if !isTestFile(srcNode.FilePath, srcLang) {
- continue
- }
- if isTestFile(tgtNode.FilePath, tgtLang) {
- continue
- }
-
- // Test helper gate: only Test*/test_* named functions produce TESTS edges
- if !isTestFunction(srcNode.Name, srcLang) {
- continue
- }
-
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: srcNode.ID,
- TargetID: tgtNode.ID,
- Type: "TESTS",
- })
- }
-
- if len(edges) > 0 {
- if err := p.Store.InsertEdgeBatch(edges); err != nil {
- slog.Warn("pass.tests.insert.err", "err", err)
- }
- }
- return len(edges)
-}
-
-// createTestsFileEdges creates TESTS_FILE edges from test modules to production modules.
-func (p *Pipeline) createTestsFileEdges() int {
- modules, err := p.Store.FindNodesByLabel(p.ProjectName, "Module")
- if err != nil {
- return 0
- }
-
- testModules := make(map[int64]*store.Node)
- prodModules := make(map[string]*store.Node) // keyed by file path
- for _, m := range modules {
- modLang := langFromFilePath(m.FilePath)
- if isTestFile(m.FilePath, modLang) {
- testModules[m.ID] = m
- } else {
- prodModules[m.FilePath] = m
- }
- }
-
- var edges []*store.Edge
- for _, testMod := range testModules {
- // Strategy 1: naming convention
- prodPath := testFileToProductionFile(testMod.FilePath)
- if prodPath != "" {
- if prodMod, ok := prodModules[prodPath]; ok {
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: testMod.ID,
- TargetID: prodMod.ID,
- Type: "TESTS_FILE",
- })
- continue
- }
- }
-
- // Strategy 2: IMPORTS from test module to production modules
- importEdges, _ := p.Store.FindEdgesBySourceAndType(testMod.ID, "IMPORTS")
- for _, ie := range importEdges {
- targetNode, _ := p.Store.FindNodeByID(ie.TargetID)
- if targetNode == nil || targetNode.Label != "Module" {
- continue
- }
- tgtLang := langFromFilePath(targetNode.FilePath)
- if !isTestFile(targetNode.FilePath, tgtLang) {
- edges = append(edges, &store.Edge{
- Project: p.ProjectName,
- SourceID: testMod.ID,
- TargetID: targetNode.ID,
- Type: "TESTS_FILE",
- })
- }
- }
- }
-
- if len(edges) > 0 {
- if err := p.Store.InsertEdgeBatch(edges); err != nil {
- slog.Warn("pass.tests_file.insert.err", "err", err)
- }
- }
- return len(edges)
-}
-
-// testFileToProductionFile returns the expected production file path for a test file.
-func testFileToProductionFile(testPath string) string {
- base := filepath.Base(testPath)
- dir := filepath.Dir(testPath)
- ext := filepath.Ext(base)
- noExt := strings.TrimSuffix(base, ext)
-
- // Go: foo_test.go → foo.go
- if strings.HasSuffix(noExt, "_test") && ext == ".go" {
- return filepath.Join(dir, strings.TrimSuffix(noExt, "_test")+ext)
- }
-
- // Python: test_foo.py → foo.py
- if strings.HasPrefix(noExt, "test_") && ext == ".py" {
- return filepath.Join(dir, strings.TrimPrefix(noExt, "test_")+ext)
- }
-
- // JS/TS: foo.test.ts → foo.ts, foo.spec.ts → foo.ts
- for _, suffix := range []string{".test", ".spec"} {
- if strings.HasSuffix(noExt, suffix) {
- return filepath.Join(dir, strings.TrimSuffix(noExt, suffix)+ext)
- }
- }
-
- return ""
-}
-
-// batchLoadNodes loads nodes by ID using batch queries.
-func (p *Pipeline) batchLoadNodes(ids []int64) map[int64]*store.Node {
- result := make(map[int64]*store.Node, len(ids))
- nodes, err := p.Store.FindNodesByIDs(ids)
- if err != nil {
- // Fallback to individual lookups
- for _, id := range ids {
- if n, err := p.Store.FindNodeByID(id); err == nil && n != nil {
- result[n.ID] = n
- }
- }
- return result
- }
- for _, n := range nodes {
- result[n.ID] = n
- }
- return result
-}
-
-// langFromFilePath determines the language from a file extension.
-func langFromFilePath(filePath string) lang.Language {
- ext := filepath.Ext(filePath)
- l, _ := lang.LanguageForExtension(ext)
- return l
-}
diff --git a/internal/pipeline/throws.go b/internal/pipeline/throws.go
deleted file mode 100644
index b04e6ebda..000000000
--- a/internal/pipeline/throws.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "runtime"
-
- "golang.org/x/sync/errgroup"
-)
-
-// passThrows creates THROWS/RAISES edges using pre-extracted CBM data.
-func (p *Pipeline) passThrows() {
- slog.Info("pass.throws")
-
- type fileEntry struct {
- relPath string
- ext *cachedExtraction
- }
- var files []fileEntry
- for relPath, ext := range p.extractionCache {
- if len(ext.Result.Throws) > 0 {
- files = append(files, fileEntry{relPath, ext})
- }
- }
-
- if len(files) == 0 {
- return
- }
-
- results := make([][]resolvedEdge, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g, gctx := errgroup.WithContext(p.ctx)
- g.SetLimit(numWorkers)
- for i, fe := range files {
- g.Go(func() error {
- if gctx.Err() != nil {
- return gctx.Err()
- }
- results[i] = p.resolveFileThrowsCBM(fe.relPath, fe.ext)
- return nil
- })
- }
- _ = g.Wait()
-
- p.flushResolvedEdges(results)
-
- total := 0
- for _, r := range results {
- total += len(r)
- }
- slog.Info("pass.throws.done", "edges", total)
-}
diff --git a/internal/pipeline/typeinfer.go b/internal/pipeline/typeinfer.go
deleted file mode 100644
index e84f4a0ba..000000000
--- a/internal/pipeline/typeinfer.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package pipeline
-
-// TypeMap maps variable names to their resolved class QN.
-type TypeMap map[string]string
-
-// ReturnTypeMap maps function QN to the return type name.
-type ReturnTypeMap map[string]string
-
-// resolveAsClass checks if a name refers to a Class/Type node in the registry.
-func resolveAsClass(name string, registry *FunctionRegistry, moduleQN string, importMap map[string]string) string {
- result := registry.Resolve(name, moduleQN, importMap)
- if result.QualifiedName == "" {
- return ""
- }
-
- registry.mu.RLock()
- defer registry.mu.RUnlock()
-
- label, exists := registry.exact[result.QualifiedName]
- if !exists {
- return ""
- }
-
- // Only return if it's a class-like node
- switch label {
- case "Class", "Type", "Interface", "Enum":
- return result.QualifiedName
- }
- return ""
-}
diff --git a/internal/pipeline/usages.go b/internal/pipeline/usages.go
deleted file mode 100644
index 39ecdace5..000000000
--- a/internal/pipeline/usages.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "runtime"
-
- "golang.org/x/sync/errgroup"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// passUsages creates USAGE edges using pre-extracted CBM data.
-// Uses parallel per-file resolution (Stage 1) followed by batch DB writes (Stage 2).
-func (p *Pipeline) passUsages() {
- slog.Info("pass3b.usages")
-
- type fileEntry struct {
- relPath string
- ext *cachedExtraction
- }
- var files []fileEntry
- for relPath, ext := range p.extractionCache {
- if lang.ForLanguage(ext.Language) != nil {
- files = append(files, fileEntry{relPath, ext})
- }
- }
-
- if len(files) == 0 {
- return
- }
-
- // Stage 1: Parallel per-file usage resolution using CBM data
- results := make([][]resolvedEdge, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g, gctx := errgroup.WithContext(p.ctx)
- g.SetLimit(numWorkers)
- for i, fe := range files {
- g.Go(func() error {
- if gctx.Err() != nil {
- return gctx.Err()
- }
- results[i] = p.resolveFileUsagesCBM(fe.relPath, fe.ext)
- return nil
- })
- }
- _ = g.Wait()
-
- // Stage 2: Batch write
- p.flushResolvedEdges(results)
-
- total := 0
- for _, r := range results {
- total += len(r)
- }
- slog.Info("pass3b.usages.done", "edges", total)
-}
-
-// passUsagesForFiles runs usage detection only for the specified files (incremental).
-func (p *Pipeline) passUsagesForFiles(files []discover.FileInfo) {
- slog.Info("pass3b.usages.incremental", "files", len(files))
- count := 0
- for _, f := range files {
- if p.ctx.Err() != nil {
- return
- }
- ext, ok := p.extractionCache[f.RelPath]
- if !ok {
- continue
- }
- edges := p.resolveFileUsagesCBM(f.RelPath, ext)
- // Write edges directly for incremental (small count)
- for _, re := range edges {
- callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.CallerQN)
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.TargetQN)
- if callerNode != nil && targetNode != nil {
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: callerNode.ID,
- TargetID: targetNode.ID,
- Type: re.Type,
- })
- count++
- }
- }
- }
- slog.Info("pass3b.usages.incremental.done", "edges", count)
-}
diff --git a/internal/pipeline/usages_test.go b/internal/pipeline/usages_test.go
deleted file mode 100644
index b45c8e7e1..000000000
--- a/internal/pipeline/usages_test.go
+++ /dev/null
@@ -1,235 +0,0 @@
-package pipeline
-
-import (
- "context"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func TestPassUsagesCreatesEdges(t *testing.T) {
- // Create a Go file that defines two functions, where one references
- // the other as a variable (callback) rather than calling it.
- goSource := `package mypkg
-
-func Process(data string) string {
- return data
-}
-
-func Register() {
- handler := Process
- _ = handler
-}
-`
- tmpDir := t.TempDir()
- if err := os.MkdirAll(filepath.Join(tmpDir, "mypkg"), 0o755); err != nil {
- t.Fatal(err)
- }
- goPath := filepath.Join(tmpDir, "mypkg", "main.go")
- if err := os.WriteFile(goPath, []byte(goSource), 0o600); err != nil {
- t.Fatal(err)
- }
- // Need go.mod for discover
- if err := os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module testmod\ngo 1.21\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, tmpDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatal(err)
- }
-
- // Look for USAGE edges
- edges, err := s.FindEdgesByType(p.ProjectName, "USAGE")
- if err != nil {
- t.Fatal(err)
- }
-
- // Register should have a USAGE edge to Process (identifier reference, not a call)
- found := false
- for _, e := range edges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil {
- if src.Name == "Register" && tgt.Name == "Process" {
- found = true
- }
- }
- }
- if !found {
- t.Error("expected USAGE edge from Register to Process (callback reference)")
- for _, e := range edges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil {
- t.Logf(" USAGE: %s -> %s", src.Name, tgt.Name)
- }
- }
- }
-}
-
-func TestPassUsagesDoesNotDuplicateCalls(t *testing.T) {
- // When a function is called (not just referenced), only a CALLS edge
- // should exist, not a USAGE edge for the call expression.
- goSource := `package mypkg
-
-func Helper() string {
- return "ok"
-}
-
-func Main() {
- Helper()
-}
-`
- tmpDir := t.TempDir()
- if err := os.MkdirAll(filepath.Join(tmpDir, "mypkg"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(tmpDir, "mypkg", "main.go"), []byte(goSource), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module testmod\ngo 1.21\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, tmpDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatal(err)
- }
-
- // Should have CALLS edge from Main to Helper
- callEdges, _ := s.FindEdgesByType(p.ProjectName, "CALLS")
- foundCall := false
- for _, e := range callEdges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil && src.Name == "Main" && tgt.Name == "Helper" {
- foundCall = true
- }
- }
- if !foundCall {
- t.Error("expected CALLS edge from Main to Helper")
- }
-
- // Should NOT have USAGE edge from Main to Helper (it's a call, not a reference)
- usageEdges, _ := s.FindEdgesByType(p.ProjectName, "USAGE")
- for _, e := range usageEdges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil && src.Name == "Main" && tgt.Name == "Helper" {
- t.Error("should NOT have USAGE edge from Main to Helper — it's a call, not a reference")
- }
- }
-}
-
-func TestPassUsagesKotlinCreatesEdges(t *testing.T) {
- // Create a Kotlin file that defines two functions, where one references
- // the other as a variable (callback) rather than calling it.
- ktSource := `fun process(data: String): String {
- return data
-}
-
-fun register() {
- val handler = ::process
-}
-`
- tmpDir := t.TempDir()
- ktPath := filepath.Join(tmpDir, "Main.kt")
- if err := os.WriteFile(ktPath, []byte(ktSource), 0o600); err != nil {
- t.Fatal(err)
- }
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, tmpDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatal(err)
- }
-
- // Look for USAGE edges
- edges, err := s.FindEdgesByType(p.ProjectName, "USAGE")
- if err != nil {
- t.Fatal(err)
- }
-
- t.Logf("USAGE edges: %d", len(edges))
- for _, e := range edges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil {
- t.Logf(" USAGE: %s -> %s", src.Name, tgt.Name)
- }
- }
-}
-
-func TestPassUsagesKotlinDoesNotDuplicateCalls(t *testing.T) {
- // When a Kotlin function is called (not just referenced), only a CALLS edge
- // should exist, not a USAGE edge for the call expression.
- ktSource := `fun helper(): String {
- return "ok"
-}
-
-fun main() {
- helper()
-}
-`
- tmpDir := t.TempDir()
- ktPath := filepath.Join(tmpDir, "Main.kt")
- if err := os.WriteFile(ktPath, []byte(ktSource), 0o600); err != nil {
- t.Fatal(err)
- }
-
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- p := New(context.Background(), s, tmpDir, discover.ModeFull)
- if err := p.Run(); err != nil {
- t.Fatal(err)
- }
-
- // Should have CALLS edge from main to helper
- callEdges, _ := s.FindEdgesByType(p.ProjectName, "CALLS")
- foundCall := false
- for _, e := range callEdges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil && src.Name == "main" && tgt.Name == "helper" {
- foundCall = true
- }
- }
- if !foundCall {
- t.Error("expected CALLS edge from main to helper")
- }
-
- // Should NOT have USAGE edge from main to helper (it's a call, not a reference)
- usageEdges, _ := s.FindEdgesByType(p.ProjectName, "USAGE")
- for _, e := range usageEdges {
- src, _ := s.FindNodeByID(e.SourceID)
- tgt, _ := s.FindNodeByID(e.TargetID)
- if src != nil && tgt != nil && src.Name == "main" && tgt.Name == "helper" {
- t.Error("should NOT have USAGE edge from main to helper — it's a call, not a reference")
- }
- }
-}
diff --git a/internal/pipeline/usestype.go b/internal/pipeline/usestype.go
deleted file mode 100644
index cbf216236..000000000
--- a/internal/pipeline/usestype.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package pipeline
-
-import (
- "log/slog"
- "runtime"
-
- "golang.org/x/sync/errgroup"
-
- "github.com/DeusData/codebase-memory-mcp/internal/lang"
-)
-
-// passUsesType creates USES_TYPE edges using pre-extracted CBM data.
-func (p *Pipeline) passUsesType() {
- slog.Info("pass.usestype")
-
- type fileEntry struct {
- relPath string
- ext *cachedExtraction
- }
- var files []fileEntry
- for relPath, ext := range p.extractionCache {
- if lang.ForLanguage(ext.Language) != nil && len(ext.Result.TypeRefs) > 0 {
- files = append(files, fileEntry{relPath, ext})
- }
- }
-
- if len(files) == 0 {
- return
- }
-
- // Stage 1: Parallel per-file type reference resolution using CBM data
- results := make([][]resolvedEdge, len(files))
- numWorkers := runtime.NumCPU()
- if numWorkers > len(files) {
- numWorkers = len(files)
- }
-
- g := new(errgroup.Group)
- g.SetLimit(numWorkers)
- for i, fe := range files {
- g.Go(func() error {
- results[i] = p.resolveFileTypeRefsCBM(fe.relPath, fe.ext)
- return nil
- })
- }
- _ = g.Wait()
-
- // Stage 2: Batch write
- p.flushResolvedEdges(results)
-
- total := 0
- for _, r := range results {
- total += len(r)
- }
- slog.Info("pass.usestype.done", "edges", total)
-}
diff --git a/internal/selfupdate/selfupdate.go b/internal/selfupdate/selfupdate.go
deleted file mode 100644
index cf67d8363..000000000
--- a/internal/selfupdate/selfupdate.go
+++ /dev/null
@@ -1,189 +0,0 @@
-package selfupdate
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "runtime"
- "strconv"
- "strings"
- "time"
-)
-
-// ReleaseURL is the GitHub API endpoint for latest release. Exported for test injection.
-var ReleaseURL = "https://api.github.com/repos/DeusData/codebase-memory-mcp/releases/latest"
-
-// Release holds parsed GitHub release metadata.
-type Release struct {
- TagName string `json:"tag_name"`
- Assets []Asset `json:"assets"`
-}
-
-// Asset holds a single release artifact.
-type Asset struct {
- Name string `json:"name"`
- BrowserDownloadURL string `json:"browser_download_url"`
- Size int64 `json:"size"`
-}
-
-// FetchLatestRelease fetches release metadata from GitHub.
-func FetchLatestRelease(ctx context.Context) (*Release, error) {
- ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
- defer cancel()
-
- req, err := http.NewRequestWithContext(ctx, "GET", ReleaseURL, http.NoBody)
- if err != nil {
- return nil, fmt.Errorf("create request: %w", err)
- }
- req.Header.Set("Accept", "application/vnd.github+json")
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("http request: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != 200 {
- return nil, fmt.Errorf("github api status=%d", resp.StatusCode)
- }
-
- body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
- if err != nil {
- return nil, fmt.Errorf("read body: %w", err)
- }
-
- var release Release
- if err := json.Unmarshal(body, &release); err != nil {
- return nil, fmt.Errorf("parse json: %w", err)
- }
- return &release, nil
-}
-
-// LatestVersion returns the version string from the latest release (without "v" prefix).
-func (r *Release) LatestVersion() string {
- return strings.TrimPrefix(r.TagName, "v")
-}
-
-// FindAsset finds a release asset by name.
-func (r *Release) FindAsset(name string) *Asset {
- for i := range r.Assets {
- if r.Assets[i].Name == name {
- return &r.Assets[i]
- }
- }
- return nil
-}
-
-// AssetName returns the expected release asset name for the current platform.
-func AssetName() string {
- if runtime.GOOS == "windows" {
- return fmt.Sprintf("codebase-memory-mcp-%s-%s.zip", runtime.GOOS, runtime.GOARCH)
- }
- return fmt.Sprintf("codebase-memory-mcp-%s-%s.tar.gz", runtime.GOOS, runtime.GOARCH)
-}
-
-// CompareVersions compares two semver strings (e.g. "0.2.1" vs "0.2.0").
-// Returns >0 if a > b, <0 if a < b, 0 if equal.
-func CompareVersions(a, b string) int {
- a = strings.TrimPrefix(a, "v")
- b = strings.TrimPrefix(b, "v")
-
- // Strip pre-release suffixes for comparison (e.g. "0.2.1-dev" → "0.2.1")
- aBase := strings.SplitN(a, "-", 2)[0]
- bBase := strings.SplitN(b, "-", 2)[0]
-
- aParts := strings.Split(aBase, ".")
- bParts := strings.Split(bBase, ".")
- for i := 0; i < len(aParts) && i < len(bParts); i++ {
- ai, _ := strconv.Atoi(aParts[i])
- bi, _ := strconv.Atoi(bParts[i])
- if ai != bi {
- return ai - bi
- }
- }
- if len(aParts) != len(bParts) {
- return len(aParts) - len(bParts)
- }
-
- // Same base version — non-dev beats dev (e.g. "0.2.1" > "0.2.1-dev")
- aHasPre := strings.Contains(a, "-")
- bHasPre := strings.Contains(b, "-")
- if aHasPre && !bHasPre {
- return -1
- }
- if !aHasPre && bHasPre {
- return 1
- }
- return 0
-}
-
-// AllowedDownloadPrefixes controls which URL prefixes are accepted by DownloadAsset.
-// Exported for test injection only.
-var AllowedDownloadPrefixes = []string{
- "https://github.com/",
- "https://api.github.com/",
-}
-
-// DownloadAsset downloads a release asset and returns the full body as bytes.
-// The response body is fully read before returning to avoid premature context cancellation.
-func DownloadAsset(ctx context.Context, rawURL string) ([]byte, error) {
- allowed := false
- for _, prefix := range AllowedDownloadPrefixes {
- if strings.HasPrefix(rawURL, prefix) {
- allowed = true
- break
- }
- }
- if !allowed {
- return nil, fmt.Errorf("refusing to download from non-GitHub URL: %s", rawURL)
- }
-
- ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
- defer cancel()
-
- req, err := http.NewRequestWithContext(ctx, "GET", rawURL, http.NoBody)
- if err != nil {
- return nil, fmt.Errorf("create request: %w", err)
- }
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("download: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != 200 {
- return nil, fmt.Errorf("download status=%d", resp.StatusCode)
- }
-
- return io.ReadAll(io.LimitReader(resp.Body, 500<<20)) // 500 MB safety limit
-}
-
-// DownloadChecksums downloads and parses the checksums.txt file from a release.
-// Returns a map of filename → hex-encoded SHA-256 hash.
-func DownloadChecksums(ctx context.Context, release *Release) (map[string]string, error) {
- asset := release.FindAsset("checksums.txt")
- if asset == nil {
- return nil, fmt.Errorf("checksums.txt not found in release")
- }
-
- data, err := DownloadAsset(ctx, asset.BrowserDownloadURL)
- if err != nil {
- return nil, fmt.Errorf("download checksums: %w", err)
- }
-
- checksums := make(map[string]string)
- for _, line := range strings.Split(string(data), "\n") {
- line = strings.TrimSpace(line)
- if line == "" {
- continue
- }
- parts := strings.Fields(line)
- if len(parts) >= 2 {
- checksums[parts[1]] = parts[0]
- }
- }
- return checksums, nil
-}
diff --git a/internal/selfupdate/selfupdate_test.go b/internal/selfupdate/selfupdate_test.go
deleted file mode 100644
index 832324d91..000000000
--- a/internal/selfupdate/selfupdate_test.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package selfupdate
-
-import (
- "context"
- "fmt"
- "net/http"
- "net/http/httptest"
- "runtime"
- "testing"
-)
-
-func TestCompareVersions(t *testing.T) {
- tests := []struct {
- a, b string
- want int // >0, <0, or 0
- }{
- {"0.2.1", "0.2.0", 1},
- {"0.2.0", "0.2.0", 0},
- {"0.1.9", "0.2.0", -1},
- {"0.10.0", "0.2.0", 1},
- {"1.0.0", "0.99.99", 1},
- {"0.0.1", "0.0.2", -1},
- {"v0.2.1", "0.2.1", 0},
- {"0.2.1", "v0.2.1", 0},
- {"0.2.1-dev", "0.2.1", -1},
- {"0.2.1", "0.2.1-dev", 1},
- {"0.2.1-dev", "0.2.1-dev", 0},
- {"0.3.0", "0.2.1-dev", 1},
- {"0.2.0", "0.2.1-dev", -1},
- }
- for _, tt := range tests {
- t.Run(fmt.Sprintf("%s_vs_%s", tt.a, tt.b), func(t *testing.T) {
- got := CompareVersions(tt.a, tt.b)
- switch {
- case tt.want > 0 && got <= 0:
- t.Fatalf("CompareVersions(%q, %q) = %d, want > 0", tt.a, tt.b, got)
- case tt.want < 0 && got >= 0:
- t.Fatalf("CompareVersions(%q, %q) = %d, want < 0", tt.a, tt.b, got)
- case tt.want == 0 && got != 0:
- t.Fatalf("CompareVersions(%q, %q) = %d, want 0", tt.a, tt.b, got)
- }
- })
- }
-}
-
-func TestAssetName(t *testing.T) {
- name := AssetName()
- expected := fmt.Sprintf("codebase-memory-mcp-%s-%s", runtime.GOOS, runtime.GOARCH)
- if runtime.GOOS == "windows" {
- expected += ".zip"
- } else {
- expected += ".tar.gz"
- }
- if name != expected {
- t.Fatalf("AssetName() = %q, want %q", name, expected)
- }
-}
-
-func TestFetchLatestRelease(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, `{
- "tag_name": "v1.0.0",
- "assets": [
- {"name": "codebase-memory-mcp-linux-amd64.tar.gz", "browser_download_url": "https://example.com/linux.tar.gz", "size": 1024},
- {"name": "checksums.txt", "browser_download_url": "https://example.com/checksums.txt", "size": 256}
- ]
- }`)
- }))
- defer ts.Close()
-
- old := ReleaseURL
- ReleaseURL = ts.URL
- defer func() { ReleaseURL = old }()
-
- release, err := FetchLatestRelease(context.Background())
- if err != nil {
- t.Fatalf("FetchLatestRelease() error: %v", err)
- }
-
- if release.LatestVersion() != "1.0.0" {
- t.Fatalf("LatestVersion() = %q, want %q", release.LatestVersion(), "1.0.0")
- }
-
- if len(release.Assets) != 2 {
- t.Fatalf("expected 2 assets, got %d", len(release.Assets))
- }
-}
-
-func TestFetchLatestRelease_ServerError(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(500)
- }))
- defer ts.Close()
-
- old := ReleaseURL
- ReleaseURL = ts.URL
- defer func() { ReleaseURL = old }()
-
- _, err := FetchLatestRelease(context.Background())
- if err == nil {
- t.Fatal("expected error for 500 response")
- }
-}
-
-func TestRelease_FindAsset(t *testing.T) {
- release := &Release{
- Assets: []Asset{
- {Name: "file-a.tar.gz"},
- {Name: "file-b.tar.gz"},
- {Name: "checksums.txt"},
- },
- }
-
- if a := release.FindAsset("file-b.tar.gz"); a == nil {
- t.Fatal("expected to find file-b.tar.gz")
- }
- if a := release.FindAsset("nonexistent"); a != nil {
- t.Fatal("expected nil for nonexistent asset")
- }
-}
-
-func TestDownloadChecksums(t *testing.T) {
- checksumServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "abc123 file-a.tar.gz\ndef456 file-b.tar.gz\n")
- }))
- defer checksumServer.Close()
-
- // Allow local test server URLs
- orig := AllowedDownloadPrefixes
- AllowedDownloadPrefixes = append(AllowedDownloadPrefixes, checksumServer.URL)
- t.Cleanup(func() { AllowedDownloadPrefixes = orig })
-
- release := &Release{
- Assets: []Asset{
- {Name: "checksums.txt", BrowserDownloadURL: checksumServer.URL},
- },
- }
-
- checksums, err := DownloadChecksums(context.Background(), release)
- if err != nil {
- t.Fatalf("DownloadChecksums() error: %v", err)
- }
-
- if checksums["file-a.tar.gz"] != "abc123" {
- t.Fatalf("expected abc123 for file-a.tar.gz, got %q", checksums["file-a.tar.gz"])
- }
- if checksums["file-b.tar.gz"] != "def456" {
- t.Fatalf("expected def456 for file-b.tar.gz, got %q", checksums["file-b.tar.gz"])
- }
-}
-
-func TestDownloadChecksums_NoChecksumsFile(t *testing.T) {
- release := &Release{
- Assets: []Asset{
- {Name: "file-a.tar.gz"},
- },
- }
-
- _, err := DownloadChecksums(context.Background(), release)
- if err == nil {
- t.Fatal("expected error when checksums.txt is missing")
- }
-}
diff --git a/internal/store/architecture.go b/internal/store/architecture.go
deleted file mode 100644
index 60b9387c9..000000000
--- a/internal/store/architecture.go
+++ /dev/null
@@ -1,1126 +0,0 @@
-package store
-
-import (
- "fmt"
- "path/filepath"
- "sort"
- "strings"
-)
-
-// ArchitectureInfo holds the result of a codebase architecture analysis.
-type ArchitectureInfo struct {
- Languages []LanguageCount `json:"languages,omitempty"`
- Packages []PackageSummary `json:"packages,omitempty"`
- EntryPoints []EntryPointInfo `json:"entry_points,omitempty"`
- Routes []RouteInfo `json:"routes,omitempty"`
- Hotspots []HotspotFunction `json:"hotspots,omitempty"`
- Boundaries []CrossPkgBoundary `json:"boundaries,omitempty"`
- Services []ServiceLink `json:"services,omitempty"`
- Layers []PackageLayer `json:"layers,omitempty"`
- Clusters []ClusterInfo `json:"clusters,omitempty"`
- FileTree []FileTreeEntry `json:"file_tree,omitempty"`
-}
-
-// LanguageCount counts files per language.
-type LanguageCount struct {
- Language string `json:"language"`
- FileCount int `json:"file_count"`
-}
-
-// PackageSummary summarizes a package with its connectivity.
-type PackageSummary struct {
- Name string `json:"name"`
- NodeCount int `json:"node_count"`
- FanIn int `json:"fan_in"`
- FanOut int `json:"fan_out"`
-}
-
-// EntryPointInfo describes an entry point function.
-type EntryPointInfo struct {
- Name string `json:"name"`
- QualifiedName string `json:"qualified_name"`
- File string `json:"file"`
-}
-
-// RouteInfo describes an HTTP route.
-type RouteInfo struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Handler string `json:"handler"`
-}
-
-// HotspotFunction is a function with high fan-in.
-type HotspotFunction struct {
- Name string `json:"name"`
- QualifiedName string `json:"qualified_name"`
- FanIn int `json:"fan_in"`
-}
-
-// CrossPkgBoundary represents cross-package call volume.
-type CrossPkgBoundary struct {
- From string `json:"from"`
- To string `json:"to"`
- CallCount int `json:"call_count"`
-}
-
-// ServiceLink represents a cross-service link (HTTP or async).
-type ServiceLink struct {
- From string `json:"from"`
- To string `json:"to"`
- Type string `json:"type"`
- Count int `json:"count"`
-}
-
-// PackageLayer classifies a package into an architectural layer.
-type PackageLayer struct {
- Name string `json:"name"`
- Layer string `json:"layer"`
- Reason string `json:"reason"`
-}
-
-// ClusterInfo describes a community detected by the Louvain algorithm.
-type ClusterInfo struct {
- ID int `json:"id"`
- Label string `json:"label"`
- Members int `json:"members"`
- Cohesion float64 `json:"cohesion"`
- TopNodes []string `json:"top_nodes"`
- Packages []string `json:"packages"`
- EdgeTypes []string `json:"edge_types"`
-}
-
-// FileTreeEntry describes a node in the condensed file tree.
-type FileTreeEntry struct {
- Path string `json:"path"`
- Type string `json:"type"`
- Children int `json:"children"`
-}
-
-// buildAspectSet converts the aspects slice into a lookup set.
-// An empty list or a list containing "all" means every aspect is wanted.
-func buildAspectSet(aspects []string) map[string]bool {
- set := make(map[string]bool, len(aspects))
- for _, a := range aspects {
- set[a] = true
- }
- if len(set) == 0 || set["all"] {
- for _, name := range []string{
- "languages", "packages", "entry_points", "routes", "hotspots",
- "boundaries", "services", "layers", "clusters", "file_tree",
- } {
- set[name] = true
- }
- }
- return set
-}
-
-// fetchAspects dispatches each requested aspect to its query method.
-func (s *Store) fetchAspects(project string, info *ArchitectureInfo, want map[string]bool) error {
- type aspectEntry struct {
- name string
- fn func() error
- }
- entries := []aspectEntry{
- {"languages", func() error { var e error; info.Languages, e = s.archLanguages(project); return e }},
- {"packages", func() error { var e error; info.Packages, e = s.archPackages(project); return e }},
- {"entry_points", func() error { var e error; info.EntryPoints, e = s.archEntryPoints(project); return e }},
- {"routes", func() error { var e error; info.Routes, e = s.archRoutes(project); return e }},
- {"hotspots", func() error { var e error; info.Hotspots, e = s.archHotspots(project); return e }},
- {"boundaries", func() error { var e error; info.Boundaries, e = s.archBoundaries(project); return e }},
- {"services", func() error { var e error; info.Services, e = s.archServices(project); return e }},
- {"layers", func() error { var e error; info.Layers, e = s.archLayers(project); return e }},
- {"clusters", func() error { var e error; info.Clusters, e = s.archClusters(project); return e }},
- {"file_tree", func() error { var e error; info.FileTree, e = s.archFileTree(project); return e }},
- }
- for _, entry := range entries {
- if !want[entry.name] {
- continue
- }
- if err := entry.fn(); err != nil {
- return fmt.Errorf("%s: %w", entry.name, err)
- }
- }
- return nil
-}
-
-// GetArchitecture computes architecture aspects for a project.
-// When aspects contains "all" or is empty, all aspects are computed.
-func (s *Store) GetArchitecture(project string, aspects []string) (*ArchitectureInfo, error) {
- want := buildAspectSet(aspects)
- info := &ArchitectureInfo{}
- if err := s.fetchAspects(project, info, want); err != nil {
- return nil, err
- }
- return info, nil
-}
-
-// --- Aspect implementations ---
-
-// extToLang maps file extensions to language names.
-var extToLang = map[string]string{
- ".py": "Python", ".go": "Go", ".js": "JavaScript", ".ts": "TypeScript",
- ".tsx": "TypeScript", ".jsx": "JavaScript", ".rs": "Rust", ".java": "Java",
- ".cpp": "C++", ".cc": "C++", ".cxx": "C++", ".c": "C", ".h": "C",
- ".cs": "C#", ".php": "PHP", ".lua": "Lua", ".scala": "Scala",
- ".kt": "Kotlin", ".rb": "Ruby", ".sh": "Bash", ".bash": "Bash",
- ".zig": "Zig", ".ex": "Elixir", ".exs": "Elixir", ".hs": "Haskell",
- ".ml": "OCaml", ".mli": "OCaml", ".html": "HTML", ".css": "CSS",
- ".yaml": "YAML", ".yml": "YAML", ".toml": "TOML", ".hcl": "HCL",
- ".tf": "HCL", ".sql": "SQL", ".erl": "Erlang", ".swift": "Swift",
- ".dart": "Dart", ".groovy": "Groovy", ".pl": "Perl", ".r": "R",
- ".scss": "SCSS", ".vue": "Vue", ".svelte": "Svelte",
-}
-
-func (s *Store) archLanguages(project string) ([]LanguageCount, error) {
- rows, err := s.q.Query(`SELECT file_path FROM nodes WHERE project=? AND label='File'`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- counts := map[string]int{}
- for rows.Next() {
- var fp string
- if err := rows.Scan(&fp); err != nil {
- return nil, err
- }
- ext := strings.ToLower(filepath.Ext(fp))
- lang := extToLang[ext]
- if lang == "" {
- continue
- }
- counts[lang]++
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- result := make([]LanguageCount, 0, len(counts))
- for lang, cnt := range counts {
- result = append(result, LanguageCount{Language: lang, FileCount: cnt})
- }
- sort.Slice(result, func(i, j int) bool { return result[i].FileCount > result[j].FileCount })
- if len(result) > 10 {
- result = result[:10]
- }
- return result, nil
-}
-
-func (s *Store) archPackages(project string) ([]PackageSummary, error) {
- // Get all packages with node counts
- rows, err := s.q.Query(`
- SELECT n.name, COUNT(*) as cnt
- FROM nodes n
- WHERE n.project=? AND n.label='Package'
- GROUP BY n.name
- ORDER BY cnt DESC LIMIT 15`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- // First get package names
- type pkgRaw struct {
- name string
- count int
- }
- var pkgs []pkgRaw
- for rows.Next() {
- var p pkgRaw
- if err := rows.Scan(&p.name, &p.count); err != nil {
- return nil, err
- }
- pkgs = append(pkgs, p)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- // Fallback: count nodes per QN prefix segment if no Package nodes
- if len(pkgs) == 0 {
- return s.archPackagesByQN(project)
- }
-
- result := make([]PackageSummary, len(pkgs))
- for i, p := range pkgs {
- result[i] = PackageSummary{Name: p.name, NodeCount: p.count}
- }
- return result, nil
-}
-
-// archPackagesByQN groups nodes by the sub-package segment of their qualified name.
-func (s *Store) archPackagesByQN(project string) ([]PackageSummary, error) {
- rows, err := s.q.Query(`SELECT qualified_name FROM nodes WHERE project=? AND label IN ('Function','Method','Class')`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- counts := map[string]int{}
- for rows.Next() {
- var qn string
- if err := rows.Scan(&qn); err != nil {
- return nil, err
- }
- pkg := qnToPackage(qn)
- if pkg == "" {
- continue
- }
- counts[pkg]++
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- result := make([]PackageSummary, 0, len(counts))
- for name, cnt := range counts {
- result = append(result, PackageSummary{Name: name, NodeCount: cnt})
- }
- sort.Slice(result, func(i, j int) bool { return result[i].NodeCount > result[j].NodeCount })
- if len(result) > 15 {
- result = result[:15]
- }
- return result, nil
-}
-
-func (s *Store) archEntryPoints(project string) ([]EntryPointInfo, error) {
- rows, err := s.q.Query(`
- SELECT name, qualified_name, file_path FROM nodes
- WHERE project=? AND json_extract(properties, '$.is_entry_point') = 1
- AND (json_extract(properties, '$.is_test') IS NULL OR json_extract(properties, '$.is_test') != 1)
- AND file_path NOT LIKE '%test%'
- LIMIT 20`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var result []EntryPointInfo
- for rows.Next() {
- var ep EntryPointInfo
- if err := rows.Scan(&ep.Name, &ep.QualifiedName, &ep.File); err != nil {
- return nil, err
- }
- result = append(result, ep)
- }
- return result, rows.Err()
-}
-
-func (s *Store) archRoutes(project string) ([]RouteInfo, error) {
- rows, err := s.q.Query(`
- SELECT name, properties, COALESCE(file_path, '') FROM nodes
- WHERE project=? AND label='Route'
- AND (json_extract(properties, '$.is_test') IS NULL OR json_extract(properties, '$.is_test') != 1)
- LIMIT 20`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var result []RouteInfo
- for rows.Next() {
- var name, props, fp string
- if err := rows.Scan(&name, &props, &fp); err != nil {
- return nil, err
- }
- if isTestFilePath(fp) {
- continue
- }
- p := unmarshalProps(props)
- ri := RouteInfo{
- Path: name,
- }
- if m, ok := p["method"].(string); ok {
- ri.Method = m
- }
- if path, ok := p["path"].(string); ok {
- ri.Path = path
- }
- if h, ok := p["handler"].(string); ok {
- ri.Handler = h
- }
- result = append(result, ri)
- }
- return result, rows.Err()
-}
-
-func (s *Store) archHotspots(project string) ([]HotspotFunction, error) {
- rows, err := s.q.Query(`
- SELECT n.name, n.qualified_name, COUNT(*) as fan_in
- FROM nodes n
- JOIN edges e ON e.target_id = n.id AND e.type = 'CALLS'
- WHERE n.project=? AND n.label IN ('Function', 'Method')
- AND (json_extract(n.properties, '$.is_test') IS NULL OR json_extract(n.properties, '$.is_test') != 1)
- AND n.file_path NOT LIKE '%test%'
- GROUP BY n.id
- ORDER BY fan_in DESC
- LIMIT 10`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var result []HotspotFunction
- for rows.Next() {
- var h HotspotFunction
- if err := rows.Scan(&h.Name, &h.QualifiedName, &h.FanIn); err != nil {
- return nil, err
- }
- result = append(result, h)
- }
- return result, rows.Err()
-}
-
-func (s *Store) archBoundaries(project string) ([]CrossPkgBoundary, error) {
- // Build node ID → package name map via QN prefix (only callable nodes)
- nodeRows, err := s.q.Query(`SELECT id, qualified_name FROM nodes WHERE project=? AND label IN ('Function','Method','Class')`, project)
- if err != nil {
- return nil, err
- }
- defer nodeRows.Close()
-
- nodePkg := map[int64]string{}
- for nodeRows.Next() {
- var id int64
- var qn string
- if err := nodeRows.Scan(&id, &qn); err != nil {
- return nil, err
- }
- nodePkg[id] = qnToPackage(qn)
- }
- if err := nodeRows.Err(); err != nil {
- return nil, err
- }
-
- // Single-pass edge scan grouping cross-package calls
- edgeRows, err := s.q.Query(`SELECT source_id, target_id FROM edges WHERE project=? AND type='CALLS'`, project)
- if err != nil {
- return nil, err
- }
- defer edgeRows.Close()
-
- type boundaryKey struct{ from, to string }
- counts := map[boundaryKey]int{}
- for edgeRows.Next() {
- var srcID, tgtID int64
- if err := edgeRows.Scan(&srcID, &tgtID); err != nil {
- return nil, err
- }
- srcPkg := nodePkg[srcID]
- tgtPkg := nodePkg[tgtID]
- if srcPkg != tgtPkg && srcPkg != "" && tgtPkg != "" {
- counts[boundaryKey{srcPkg, tgtPkg}]++
- }
- }
- if err := edgeRows.Err(); err != nil {
- return nil, err
- }
-
- result := make([]CrossPkgBoundary, 0, len(counts))
- for k, cnt := range counts {
- result = append(result, CrossPkgBoundary{From: k.from, To: k.to, CallCount: cnt})
- }
- sort.Slice(result, func(i, j int) bool { return result[i].CallCount > result[j].CallCount })
- if len(result) > 10 {
- result = result[:10]
- }
- return result, nil
-}
-
-func (s *Store) archServices(project string) ([]ServiceLink, error) {
- // Build node ID → top-level package map first (before opening edge cursor)
- nodePkg, err := s.loadNodePackageMap(project)
- if err != nil {
- return nil, err
- }
-
- // Query edges
- type linkKey struct{ from, to, typ string }
- counts := map[linkKey]int{}
-
- edgeRows, err := s.q.Query(`
- SELECT source_id, target_id, type
- FROM edges WHERE project=? AND type IN ('HTTP_CALLS', 'ASYNC_CALLS')`, project)
- if err != nil {
- return nil, err
- }
- defer edgeRows.Close()
-
- for edgeRows.Next() {
- var srcID, tgtID int64
- var edgeType string
- if err := edgeRows.Scan(&srcID, &tgtID, &edgeType); err != nil {
- return nil, err
- }
- from := nodePkg[srcID]
- to := nodePkg[tgtID]
- if from != "" && to != "" {
- counts[linkKey{from, to, edgeType}]++
- }
- }
- if err := edgeRows.Err(); err != nil {
- return nil, err
- }
-
- result := make([]ServiceLink, 0, len(counts))
- for k, cnt := range counts {
- result = append(result, ServiceLink{From: k.from, To: k.to, Type: k.typ, Count: cnt})
- }
- sort.Slice(result, func(i, j int) bool { return result[i].Count > result[j].Count })
- if len(result) > 10 {
- result = result[:10]
- }
- return result, nil
-}
-
-func (s *Store) archLayers(project string) ([]PackageLayer, error) {
- // Get boundaries for fan-in/out analysis
- boundaries, err := s.archBoundaries(project)
- if err != nil {
- return nil, err
- }
-
- // Check which packages have Route nodes
- routePkgs := map[string]bool{}
- routeRows, err := s.q.Query(`SELECT qualified_name FROM nodes WHERE project=? AND label='Route'`, project)
- if err != nil {
- return nil, err
- }
- defer routeRows.Close()
- for routeRows.Next() {
- var qn string
- if err := routeRows.Scan(&qn); err != nil {
- return nil, err
- }
- routePkgs[qnToPackage(qn)] = true
- }
- if err := routeRows.Err(); err != nil {
- return nil, err
- }
-
- // Check which packages have entry points
- entryPkgs := map[string]bool{}
- entryRows, err := s.q.Query(`
- SELECT qualified_name FROM nodes
- WHERE project=? AND json_extract(properties, '$.is_entry_point') = 1`, project)
- if err != nil {
- return nil, err
- }
- defer entryRows.Close()
- for entryRows.Next() {
- var qn string
- if err := entryRows.Scan(&qn); err != nil {
- return nil, err
- }
- entryPkgs[qnToPackage(qn)] = true
- }
- if err := entryRows.Err(); err != nil {
- return nil, err
- }
-
- // Compute fan-in/out per package from boundaries
- fanIn := map[string]int{}
- fanOut := map[string]int{}
- allPkgs := map[string]bool{}
- for _, b := range boundaries {
- fanOut[b.From] += b.CallCount
- fanIn[b.To] += b.CallCount
- allPkgs[b.From] = true
- allPkgs[b.To] = true
- }
-
- // Also include packages from entry points and routes
- for pkg := range entryPkgs {
- allPkgs[pkg] = true
- }
- for pkg := range routePkgs {
- allPkgs[pkg] = true
- }
-
- var result []PackageLayer
- for pkg := range allPkgs {
- layer, reason := classifyLayer(pkg, fanIn[pkg], fanOut[pkg], routePkgs[pkg], entryPkgs[pkg])
- result = append(result, PackageLayer{Name: pkg, Layer: layer, Reason: reason})
- }
- sort.Slice(result, func(i, j int) bool { return result[i].Name < result[j].Name })
- return result, nil
-}
-
-func classifyLayer(_ string, in, out int, hasRoutes, hasEntryPoints bool) (layer, reason string) {
- if hasEntryPoints && out > 0 && in == 0 {
- return "entry", "has entry points, only outbound calls"
- }
- if hasRoutes {
- return "api", "has HTTP route definitions"
- }
- if in > out && in > 3 {
- return "core", fmt.Sprintf("high fan-in (%d in, %d out)", in, out)
- }
- if out == 0 && in > 0 {
- return "leaf", "only inbound calls, no outbound"
- }
- if in == 0 && out > 0 {
- return "entry", "only outbound calls"
- }
- return "internal", fmt.Sprintf("fan-in=%d, fan-out=%d", in, out)
-}
-
-// clusterNodeInfo holds node metadata for the clustering algorithm.
-type clusterNodeInfo struct {
- id int64
- name string
- qn string
-}
-
-func (s *Store) archClusters(project string) ([]ClusterInfo, error) {
- // Load all function/method nodes
- nodeRows, err := s.q.Query(`SELECT id, name, qualified_name FROM nodes WHERE project=? AND label IN ('Function', 'Method')`, project)
- if err != nil {
- return nil, err
- }
- defer nodeRows.Close()
-
- var nodeList []clusterNodeInfo
- nodeIDSet := map[int64]bool{}
- for nodeRows.Next() {
- var ni clusterNodeInfo
- if err := nodeRows.Scan(&ni.id, &ni.name, &ni.qn); err != nil {
- return nil, err
- }
- nodeList = append(nodeList, ni)
- nodeIDSet[ni.id] = true
- }
- if err := nodeRows.Err(); err != nil {
- return nil, err
- }
-
- if len(nodeList) < 3 {
- return nil, nil // too few nodes for meaningful clustering
- }
-
- // Load edges (CALLS + HTTP_CALLS + ASYNC_CALLS)
- edgeRows, err := s.q.Query(`
- SELECT source_id, target_id, type FROM edges
- WHERE project=? AND type IN ('CALLS', 'HTTP_CALLS', 'ASYNC_CALLS')`, project)
- if err != nil {
- return nil, err
- }
- defer edgeRows.Close()
-
- var edges []louvainEdge
- for edgeRows.Next() {
- var e louvainEdge
- if err := edgeRows.Scan(&e.src, &e.dst, &e.edgeType); err != nil {
- return nil, err
- }
- // Only include edges between function/method nodes
- if nodeIDSet[e.src] && nodeIDSet[e.dst] {
- edges = append(edges, e)
- }
- }
- if err := edgeRows.Err(); err != nil {
- return nil, err
- }
-
- if len(edges) < 3 {
- return nil, nil
- }
-
- // Build node ID list
- nodeIDs := make([]int64, len(nodeList))
- for i, ni := range nodeList {
- nodeIDs[i] = ni.id
- }
-
- // Run Louvain algorithm
- partition := louvain(nodeIDs, edges)
-
- // Build lookup maps
- nodeByID := map[int64]clusterNodeInfo{}
- for _, ni := range nodeList {
- nodeByID[ni.id] = ni
- }
-
- // Group nodes by community
- communities := map[int][]int64{}
- for nodeID, comm := range partition {
- communities[comm] = append(communities[comm], nodeID)
- }
-
- // Build edge type sets per community
- commEdgeTypes := map[int]map[string]bool{}
- for _, e := range edges {
- srcComm := partition[e.src]
- dstComm := partition[e.dst]
- if srcComm == dstComm {
- if commEdgeTypes[srcComm] == nil {
- commEdgeTypes[srcComm] = map[string]bool{}
- }
- commEdgeTypes[srcComm][e.edgeType] = true
- }
- }
-
- // Compute fan-in per node for ranking
- fanIn := map[int64]int{}
- for _, e := range edges {
- fanIn[e.dst]++
- }
-
- clusters := buildClusterInfos(communities, edges, commEdgeTypes, fanIn, nodeByID)
- return clusters, nil
-}
-
-// buildClusterInfos converts community assignments into sorted, capped ClusterInfo slices.
-func buildClusterInfos(communities map[int][]int64, edges []louvainEdge, commEdgeTypes map[int]map[string]bool, fanIn map[int64]int, nodeByID map[int64]clusterNodeInfo) []ClusterInfo {
- var clusters []ClusterInfo
- for commID, members := range communities {
- if len(members) < 2 {
- continue
- }
- ci := buildOneCluster(commID, members, edges, commEdgeTypes[commID], fanIn, nodeByID)
- clusters = append(clusters, ci)
- }
- sort.Slice(clusters, func(i, j int) bool { return clusters[i].Members > clusters[j].Members })
- if len(clusters) > 15 {
- clusters = clusters[:15]
- }
- for i := range clusters {
- clusters[i].ID = i + 1
- }
- return clusters
-}
-
-// buildOneCluster computes a ClusterInfo for a single community.
-func buildOneCluster(commID int, members []int64, edges []louvainEdge, edgeTypes map[string]bool, fanIn map[int64]int, nodeByID map[int64]clusterNodeInfo) ClusterInfo {
- memberSet := map[int64]bool{}
- for _, id := range members {
- memberSet[id] = true
- }
-
- var internalEdges, totalEdges int
- for _, e := range edges {
- isSrc := memberSet[e.src]
- isDst := memberSet[e.dst]
- if isSrc || isDst {
- totalEdges++
- }
- if isSrc && isDst {
- internalEdges++
- }
- }
- cohesion := 0.0
- if totalEdges > 0 {
- cohesion = float64(internalEdges) / float64(totalEdges)
- }
-
- sort.Slice(members, func(i, j int) bool { return fanIn[members[i]] > fanIn[members[j]] })
- topN := 5
- if len(members) < topN {
- topN = len(members)
- }
- topNodes := make([]string, topN)
- for i := 0; i < topN; i++ {
- topNodes[i] = nodeByID[members[i]].name
- }
-
- pkgSet := map[string]bool{}
- for _, id := range members {
- if pkg := qnToPackage(nodeByID[id].qn); pkg != "" {
- pkgSet[pkg] = true
- }
- }
- pkgs := make([]string, 0, len(pkgSet))
- for pkg := range pkgSet {
- pkgs = append(pkgs, pkg)
- }
- sort.Strings(pkgs)
-
- etypes := make([]string, 0, len(edgeTypes))
- for et := range edgeTypes {
- etypes = append(etypes, et)
- }
- sort.Strings(etypes)
-
- return ClusterInfo{
- ID: commID,
- Label: autoNameCluster(members, nodeByID),
- Members: len(members),
- Cohesion: cohesion,
- TopNodes: topNodes,
- Packages: pkgs,
- EdgeTypes: etypes,
- }
-}
-
-func autoNameCluster(members []int64, nodeByID map[int64]clusterNodeInfo) string {
- pkgCounts := map[string]int{}
- for _, id := range members {
- pkg := qnToPackage(nodeByID[id].qn)
- if pkg != "" {
- pkgCounts[pkg]++
- }
- }
- bestPkg := ""
- bestCount := 0
- for pkg, cnt := range pkgCounts {
- if cnt > bestCount {
- bestPkg = pkg
- bestCount = cnt
- }
- }
- if bestPkg != "" {
- return bestPkg
- }
- return fmt.Sprintf("cluster-%d", len(members))
-}
-
-func (s *Store) archFileTree(project string) ([]FileTreeEntry, error) {
- rows, err := s.q.Query(`SELECT file_path FROM nodes WHERE project=? AND label='File'`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- dirChildren := map[string]map[string]bool{}
- fileSet := map[string]bool{}
-
- for rows.Next() {
- var fp string
- if err := rows.Scan(&fp); err != nil {
- return nil, err
- }
- fileSet[fp] = true
- registerFilePath(fp, dirChildren)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- result := collectTreeEntries(dirChildren, fileSet)
- sort.Slice(result, func(i, j int) bool { return result[i].Path < result[j].Path })
- return result, nil
-}
-
-// registerFilePath registers a file path in the directory tree up to 3 levels deep.
-func registerFilePath(fp string, dirChildren map[string]map[string]bool) {
- parts := strings.Split(fp, "/")
- for depth := 0; depth < len(parts)-1 && depth < 3; depth++ {
- dir := strings.Join(parts[:depth+1], "/")
- child := ""
- if depth+1 < len(parts) {
- child = parts[depth+1]
- }
- if dirChildren[dir] == nil {
- dirChildren[dir] = map[string]bool{}
- }
- if child != "" {
- dirChildren[dir][child] = true
- }
- }
- if len(parts) > 0 {
- if dirChildren[""] == nil {
- dirChildren[""] = map[string]bool{}
- }
- dirChildren[""][parts[0]] = true
- }
-}
-
-// collectTreeEntries builds FileTreeEntry slices from the directory map.
-func collectTreeEntries(dirChildren map[string]map[string]bool, fileSet map[string]bool) []FileTreeEntry {
- var result []FileTreeEntry
- if rootChildren, ok := dirChildren[""]; ok {
- for child := range rootChildren {
- entryType := "dir"
- if fileSet[child] {
- entryType = "file"
- }
- result = append(result, FileTreeEntry{Path: child, Type: entryType, Children: len(dirChildren[child])})
- }
- }
- for dir, children := range dirChildren {
- if dir == "" || strings.Count(dir, "/") >= 3 {
- continue
- }
- for child := range children {
- path := dir + "/" + child
- entryType := "dir"
- if fileSet[path] {
- entryType = "file"
- }
- result = append(result, FileTreeEntry{Path: path, Type: entryType, Children: len(dirChildren[path])})
- }
- }
- return result
-}
-
-// --- Helpers ---
-
-// loadNodePackageMap returns nodeID → top-level package for all nodes in a project.
-func (s *Store) loadNodePackageMap(project string) (map[int64]string, error) {
- nodePkg := map[int64]string{}
- rows, err := s.q.Query(`SELECT id, qualified_name FROM nodes WHERE project=?`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- for rows.Next() {
- var id int64
- var qn string
- if err := rows.Scan(&id, &qn); err != nil {
- return nil, err
- }
- nodePkg[id] = qnToTopPackage(qn)
- }
- return nodePkg, rows.Err()
-}
-
-// qnToPackage extracts the meaningful sub-package from a qualified name.
-// QN format: project.dir1.dir2.filestem.Symbol — segment[2] is the sub-package.
-// For shallow layouts (project.dir.symbol), falls back to segment[1].
-func qnToPackage(qn string) string {
- parts := strings.SplitN(qn, ".", 5)
- if len(parts) >= 4 {
- return parts[2] // sub-package (e.g., "store" from "project.internal.store.search.Search")
- }
- if len(parts) >= 2 {
- return parts[1] // flat layout fallback
- }
- return ""
-}
-
-// qnToTopPackage extracts the top-level directory from a qualified name (segment[1]).
-// Used for coarse-grained grouping in service detection.
-func qnToTopPackage(qn string) string {
- parts := strings.SplitN(qn, ".", 3)
- if len(parts) >= 2 {
- return parts[1]
- }
- return ""
-}
-
-// --- Architecture Decision Record (ADR) ---
-
-// maxADRLength is the maximum allowed length for an ADR in characters.
-const maxADRLength = 8000
-
-// MaxADRLength returns the maximum allowed ADR length for use by tool handlers.
-func MaxADRLength() int { return maxADRLength }
-
-// canonicalSections defines the fixed set of ADR section headers in canonical order.
-var canonicalSections = []string{"PURPOSE", "STACK", "ARCHITECTURE", "PATTERNS", "TRADEOFFS", "PHILOSOPHY"}
-
-// canonicalSet is a lookup for canonical section names.
-var canonicalSet = map[string]bool{
- "PURPOSE": true, "STACK": true, "ARCHITECTURE": true,
- "PATTERNS": true, "TRADEOFFS": true, "PHILOSOPHY": true,
-}
-
-// ValidateADRContent checks that content contains all 6 canonical sections.
-// Returns an error listing any missing sections.
-func ValidateADRContent(content string) error {
- sections := ParseADRSections(content)
- var missing []string
- for _, name := range canonicalSections {
- if _, ok := sections[name]; !ok {
- missing = append(missing, name)
- }
- }
- if len(missing) > 0 {
- return fmt.Errorf("missing required sections: %s. All 6 required: %s",
- strings.Join(missing, ", "), strings.Join(canonicalSections, ", "))
- }
- return nil
-}
-
-// ValidateADRSectionKeys checks that all keys in the map are canonical section names.
-// Returns an error listing any invalid keys.
-func ValidateADRSectionKeys(sections map[string]string) error {
- var invalid []string
- for k := range sections {
- if !canonicalSet[k] {
- invalid = append(invalid, k)
- }
- }
- if len(invalid) > 0 {
- sort.Strings(invalid)
- return fmt.Errorf("invalid section names: %s. Valid sections: %s",
- strings.Join(invalid, ", "), strings.Join(canonicalSections, ", "))
- }
- return nil
-}
-
-// CanonicalSectionNames returns the ordered list of canonical ADR section names.
-func CanonicalSectionNames() []string { return canonicalSections }
-
-// ADRecord holds a stored Architecture Decision Record.
-type ADRecord struct {
- Project string `json:"project"`
- Content string `json:"content"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
-}
-
-// StoreADR persists an ADR (upsert). The source_hash column is kept as a dead
-// column to avoid ALTER TABLE issues — we write an empty string.
-func (s *Store) StoreADR(project, content string) error {
- now := Now()
- _, err := s.q.Exec(`
- INSERT INTO project_summaries (project, summary, source_hash, created_at, updated_at)
- VALUES (?, ?, '', ?, ?)
- ON CONFLICT(project) DO UPDATE SET
- summary = excluded.summary,
- updated_at = excluded.updated_at`,
- project, content, now, now)
- return err
-}
-
-// GetADR retrieves a stored ADR for a project.
-func (s *Store) GetADR(project string) (*ADRecord, error) {
- row := s.q.QueryRow(`SELECT project, summary, created_at, updated_at FROM project_summaries WHERE project=?`, project)
- var r ADRecord
- if err := row.Scan(&r.Project, &r.Content, &r.CreatedAt, &r.UpdatedAt); err != nil {
- return nil, err
- }
- return &r, nil
-}
-
-// DeleteADR removes a stored ADR for a project.
-func (s *Store) DeleteADR(project string) error {
- res, err := s.q.Exec(`DELETE FROM project_summaries WHERE project=?`, project)
- if err != nil {
- return err
- }
- n, _ := res.RowsAffected()
- if n == 0 {
- return fmt.Errorf("no ADR found for project %q", project)
- }
- return nil
-}
-
-// UpdateADRSections merges the provided sections into the existing ADR.
-// Unmentioned sections are preserved. Returns the updated record.
-// Returns an error if the merged content exceeds maxADRLength.
-func (s *Store) UpdateADRSections(project string, sections map[string]string) (*ADRecord, error) {
- existing, err := s.GetADR(project)
- if err != nil {
- return nil, fmt.Errorf("no existing ADR to update: %w", err)
- }
-
- parsed := ParseADRSections(existing.Content)
- for k, v := range sections {
- parsed[k] = v
- }
-
- merged := RenderADR(parsed)
- if len(merged) > maxADRLength {
- return nil, fmt.Errorf("merged ADR exceeds %d chars (%d chars); reduce section content before updating", maxADRLength, len(merged))
- }
-
- if err := s.StoreADR(project, merged); err != nil {
- return nil, err
- }
-
- return s.GetADR(project)
-}
-
-// ParseADRSections splits ADR content by canonical section headers.
-// Only canonical headers (PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY)
-// are recognized as split boundaries. Other ## headers within content are treated as
-// literal text within the current section.
-func ParseADRSections(content string) map[string]string {
- sections := make(map[string]string)
- if content == "" {
- return sections
- }
-
- lines := strings.Split(content, "\n")
- currentSection := ""
- var currentContent []string
-
- for _, line := range lines {
- if strings.HasPrefix(line, "## ") {
- header := strings.TrimSpace(strings.TrimPrefix(line, "## "))
- if canonicalSet[header] {
- if currentSection != "" {
- sections[currentSection] = strings.TrimSpace(strings.Join(currentContent, "\n"))
- }
- currentSection = header
- currentContent = nil
- continue
- }
- }
- currentContent = append(currentContent, line)
- }
-
- if currentSection != "" {
- sections[currentSection] = strings.TrimSpace(strings.Join(currentContent, "\n"))
- }
-
- return sections
-}
-
-// RenderADR joins sections into markdown with canonical sections first (in order),
-// followed by any non-canonical sections alphabetically.
-func RenderADR(sections map[string]string) string {
- var parts []string
- rendered := make(map[string]bool)
-
- // Canonical sections first, in order
- for _, name := range canonicalSections {
- if content, ok := sections[name]; ok {
- parts = append(parts, "## "+name+"\n"+content)
- rendered[name] = true
- }
- }
-
- // Non-canonical sections alphabetically
- var extra []string
- for name := range sections {
- if !rendered[name] {
- extra = append(extra, name)
- }
- }
- sort.Strings(extra)
- for _, name := range extra {
- parts = append(parts, "## "+name+"\n"+sections[name])
- }
-
- return strings.Join(parts, "\n\n")
-}
-
-// isTestFilePath returns true if the file path appears to be in a test directory.
-// Used as a fallback for nodes that may not have the is_test property set.
-func isTestFilePath(fp string) bool {
- return fp != "" && strings.Contains(fp, "test")
-}
-
-// FindArchitectureDocs discovers existing architecture documentation files in a project.
-// Returns file paths matching common architecture doc patterns.
-func (s *Store) FindArchitectureDocs(project string) ([]string, error) {
- rows, err := s.q.Query(`
- SELECT file_path FROM nodes
- WHERE project=? AND label='File'
- AND (
- file_path LIKE '%ARCHITECTURE.md' OR
- file_path LIKE '%ADR.md' OR
- file_path LIKE '%DECISIONS.md' OR
- file_path LIKE 'docs/adr/%' OR
- file_path LIKE 'doc/adr/%' OR
- file_path LIKE 'adr/%'
- )
- ORDER BY file_path LIMIT 20`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var docs []string
- for rows.Next() {
- var fp string
- if err := rows.Scan(&fp); err != nil {
- return nil, err
- }
- docs = append(docs, fp)
- }
- return docs, rows.Err()
-}
diff --git a/internal/store/architecture_test.go b/internal/store/architecture_test.go
deleted file mode 100644
index 01751949f..000000000
--- a/internal/store/architecture_test.go
+++ /dev/null
@@ -1,1048 +0,0 @@
-package store
-
-import (
- "strings"
- "testing"
-)
-
-// setupArchTestStore creates a store with representative nodes and edges for architecture tests.
-func setupArchTestStore(t *testing.T) *Store {
- t.Helper()
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
-
- // Files
- for _, fp := range []string{"main.go", "handler.go", "service.go", "model.py", "utils.js"} {
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "File", Name: fp, QualifiedName: "test." + fp, FilePath: fp})
- }
-
- // Packages
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Package", Name: "cmd", QualifiedName: "test.cmd"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Package", Name: "handler", QualifiedName: "test.handler"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Package", Name: "service", QualifiedName: "test.service"})
-
- // Functions with different packages (4-segment QNs for realistic sub-package extraction)
- idMain, _ := s.UpsertNode(&Node{
- Project: "test", Label: "Function", Name: "main",
- QualifiedName: "test.cmd.server.main", FilePath: "cmd/server/main.go",
- Properties: map[string]any{"is_entry_point": true},
- })
- idHandleReq, _ := s.UpsertNode(&Node{
- Project: "test", Label: "Function", Name: "HandleRequest",
- QualifiedName: "test.internal.handler.HandleRequest", FilePath: "internal/handler/handler.go",
- Properties: map[string]any{"is_entry_point": true},
- })
- idProcess, _ := s.UpsertNode(&Node{
- Project: "test", Label: "Function", Name: "ProcessOrder",
- QualifiedName: "test.internal.service.ProcessOrder", FilePath: "internal/service/service.go",
- })
- idValidate, _ := s.UpsertNode(&Node{
- Project: "test", Label: "Function", Name: "ValidateOrder",
- QualifiedName: "test.internal.service.ValidateOrder", FilePath: "internal/service/service.go",
- })
- idHelper, _ := s.UpsertNode(&Node{
- Project: "test", Label: "Function", Name: "formatDate",
- QualifiedName: "test.internal.service.formatDate", FilePath: "internal/service/service.go",
- })
-
- // Test function (should be excluded from entry_points/hotspots)
- idTestFunc, _ := s.UpsertNode(&Node{
- Project: "test", Label: "Function", Name: "TestHandleRequest",
- QualifiedName: "test.internal.handler.handler_test.TestHandleRequest",
- FilePath: "internal/handler/handler_test.go",
- Properties: map[string]any{"is_entry_point": true},
- })
-
- // Route
- _, _ = s.UpsertNode(&Node{
- Project: "test", Label: "Route", Name: "/api/orders",
- QualifiedName: "test.internal.handler.route./api/orders",
- Properties: map[string]any{"method": "POST", "path": "/api/orders", "handler": "HandleRequest"},
- })
-
- // Edges: main → HandleRequest → ProcessOrder → ValidateOrder
- // ProcessOrder → formatDate
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idMain, TargetID: idHandleReq, Type: "CALLS"})
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idHandleReq, TargetID: idProcess, Type: "CALLS"})
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idProcess, TargetID: idValidate, Type: "CALLS"})
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idProcess, TargetID: idHelper, Type: "CALLS"})
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idTestFunc, TargetID: idHandleReq, Type: "CALLS"})
-
- return s
-}
-
-func TestGetArchitectureAll(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- info, err := s.GetArchitecture("test", nil) // nil = all aspects
- if err != nil {
- t.Fatalf("GetArchitecture: %v", err)
- }
-
- if len(info.Languages) == 0 {
- t.Error("expected languages to be populated")
- }
- if len(info.Packages) == 0 {
- t.Error("expected packages to be populated")
- }
- if len(info.EntryPoints) == 0 {
- t.Error("expected entry_points to be populated")
- }
- if len(info.Routes) == 0 {
- t.Error("expected routes to be populated")
- }
- if len(info.Hotspots) == 0 {
- t.Error("expected hotspots to be populated")
- }
- if len(info.Boundaries) == 0 {
- t.Error("expected boundaries to be populated")
- }
-}
-
-func TestArchEntryPointsExcludeTests(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- eps, err := s.archEntryPoints("test")
- if err != nil {
- t.Fatal(err)
- }
-
- for _, ep := range eps {
- if strings.Contains(ep.File, "test") {
- t.Errorf("test function leaked into entry_points: %s (%s)", ep.Name, ep.File)
- }
- }
- if len(eps) != 2 {
- t.Errorf("expected 2 entry points (main, HandleRequest), got %d", len(eps))
- }
-}
-
-func TestArchHotspotsExcludeTests(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- hotspots, err := s.archHotspots("test")
- if err != nil {
- t.Fatal(err)
- }
-
- for _, h := range hotspots {
- if strings.Contains(h.Name, "Test") {
- t.Errorf("test function leaked into hotspots: %s", h.Name)
- }
- }
-}
-
-func TestGetArchitectureSpecificAspects(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- info, err := s.GetArchitecture("test", []string{"languages", "hotspots"})
- if err != nil {
- t.Fatalf("GetArchitecture: %v", err)
- }
-
- if len(info.Languages) == 0 {
- t.Error("expected languages populated")
- }
- if len(info.Hotspots) == 0 {
- t.Error("expected hotspots populated")
- }
-
- // These should be nil because not requested
- if info.Packages != nil {
- t.Error("expected packages to be nil")
- }
- if info.EntryPoints != nil {
- t.Error("expected entry_points to be nil")
- }
- if info.Routes != nil {
- t.Error("expected routes to be nil")
- }
-}
-
-func TestGetArchitectureEmpty(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("empty", "/tmp/empty"); err != nil {
- t.Fatal(err)
- }
-
- info, err := s.GetArchitecture("empty", []string{"all"})
- if err != nil {
- t.Fatalf("GetArchitecture: %v", err)
- }
-
- // All should be empty/nil but no errors
- if info == nil {
- t.Fatal("expected non-nil ArchitectureInfo")
- }
-}
-
-func TestArchLanguages(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- langs, err := s.archLanguages("test")
- if err != nil {
- t.Fatal(err)
- }
-
- langMap := map[string]int{}
- for _, l := range langs {
- langMap[l.Language] = l.FileCount
- }
-
- if langMap["Go"] != 3 {
- t.Errorf("expected 3 Go files, got %d", langMap["Go"])
- }
- if langMap["Python"] != 1 {
- t.Errorf("expected 1 Python file, got %d", langMap["Python"])
- }
- if langMap["JavaScript"] != 1 {
- t.Errorf("expected 1 JavaScript file, got %d", langMap["JavaScript"])
- }
-}
-
-func TestArchLayers(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- layers, err := s.archLayers("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if len(layers) == 0 {
- t.Fatal("expected layer classifications")
- }
-
- layerMap := map[string]string{}
- for _, l := range layers {
- layerMap[l.Name] = l.Layer
- }
-
- // Service package has high fan-in from handler, should be core or internal
- // Handler package has routes, should be api
- if layerMap["handler"] != "api" {
- t.Logf("handler layer: %q (expected api)", layerMap["handler"])
- }
-}
-
-func TestArchClusters(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- clusters, err := s.archClusters("test")
- if err != nil {
- t.Fatal(err)
- }
-
- // With 5 functions and 4 edges, Louvain should find at least 1 cluster
- if clusters == nil {
- t.Log("clusters returned nil — may need more nodes for meaningful clustering")
- return
- }
-
- for _, c := range clusters {
- if c.Members < 2 {
- t.Errorf("cluster %d has only %d members, expected >= 2", c.ID, c.Members)
- }
- if c.Label == "" {
- t.Errorf("cluster %d has empty label", c.ID)
- }
- }
-}
-
-func TestArchFileTree(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- tree, err := s.archFileTree("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if len(tree) == 0 {
- t.Fatal("expected file tree entries")
- }
-
- // Check that entries have valid types
- for _, entry := range tree {
- if entry.Type != "dir" && entry.Type != "file" {
- t.Errorf("unexpected type %q for %s", entry.Type, entry.Path)
- }
- }
-}
-
-func TestArchRoutes(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- routes, err := s.archRoutes("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if len(routes) != 1 {
- t.Fatalf("expected 1 route, got %d", len(routes))
- }
- if routes[0].Method != "POST" {
- t.Errorf("expected POST, got %s", routes[0].Method)
- }
- if routes[0].Path != "/api/orders" {
- t.Errorf("expected /api/orders, got %s", routes[0].Path)
- }
- if routes[0].Handler != "HandleRequest" {
- t.Errorf("expected HandleRequest, got %s", routes[0].Handler)
- }
-}
-
-func TestArchHotspots(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- hotspots, err := s.archHotspots("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if len(hotspots) == 0 {
- t.Fatal("expected hotspots")
- }
-
- // ProcessOrder should be a hotspot (called by HandleRequest)
- found := false
- for _, h := range hotspots {
- if h.Name == "ProcessOrder" {
- found = true
- if h.FanIn < 1 {
- t.Errorf("ProcessOrder fan-in: %d, expected >= 1", h.FanIn)
- }
- }
- }
- if !found {
- t.Log("ProcessOrder not in hotspots — may be expected with few edges")
- }
-}
-
-func TestArchBoundaries(t *testing.T) {
- s := setupArchTestStore(t)
- defer s.Close()
-
- boundaries, err := s.archBoundaries("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if len(boundaries) == 0 {
- t.Fatal("expected cross-package boundaries")
- }
-
- // server → handler and handler → service should be present
- foundServerHandler := false
- foundHandlerService := false
- for _, b := range boundaries {
- if b.From == "server" && b.To == "handler" {
- foundServerHandler = true
- }
- if b.From == "handler" && b.To == "service" {
- foundHandlerService = true
- }
- }
- if !foundServerHandler {
- t.Error("missing server → handler boundary")
- }
- if !foundHandlerService {
- t.Error("missing handler → service boundary")
- }
-}
-
-// --- Case-insensitive search tests ---
-
-func TestSearchCaseInsensitiveDefault(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "FooBar", QualifiedName: "test.FooBar"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "foobar", QualifiedName: "test.foobar"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "FOOBAR", QualifiedName: "test.FOOBAR"})
-
- // Default (CaseSensitive=false) should match all 3
- output, err := s.Search(&SearchParams{
- Project: "test",
- NamePattern: "foobar",
- MinDegree: -1,
- MaxDegree: -1,
- })
- if err != nil {
- t.Fatal(err)
- }
- if len(output.Results) != 3 {
- t.Errorf("case-insensitive default: expected 3 matches, got %d", len(output.Results))
- }
-}
-
-func TestSearchCaseSensitiveExplicit(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "FooBar", QualifiedName: "test.FooBar"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "foobar", QualifiedName: "test.foobar"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "FOOBAR", QualifiedName: "test.FOOBAR"})
-
- // Explicit case-sensitive should match only exact case
- output, err := s.Search(&SearchParams{
- Project: "test",
- NamePattern: "foobar",
- CaseSensitive: true,
- MinDegree: -1,
- MaxDegree: -1,
- })
- if err != nil {
- t.Fatal(err)
- }
- if len(output.Results) != 1 {
- t.Errorf("case-sensitive: expected 1 match, got %d", len(output.Results))
- }
- if len(output.Results) > 0 && output.Results[0].Node.Name != "foobar" {
- t.Errorf("case-sensitive: expected 'foobar', got %q", output.Results[0].Node.Name)
- }
-}
-
-func TestEnsureCaseInsensitive(t *testing.T) {
- tests := []struct {
- input string
- want string
- }{
- {"handler", "(?i)handler"},
- {"(?i)handler", "(?i)handler"}, // idempotent
- {".*Order.*", "(?i).*Order.*"},
- {"", "(?i)"},
- }
- for _, tt := range tests {
- got := ensureCaseInsensitive(tt.input)
- if got != tt.want {
- t.Errorf("ensureCaseInsensitive(%q) = %q, want %q", tt.input, got, tt.want)
- }
- }
-}
-
-func TestStripCaseFlag(t *testing.T) {
- tests := []struct {
- input string
- want string
- }{
- {"(?i)handler", "handler"},
- {"handler", "handler"},
- {"(?i)(?i)double", "(?i)double"},
- }
- for _, tt := range tests {
- got := stripCaseFlag(tt.input)
- if got != tt.want {
- t.Errorf("stripCaseFlag(%q) = %q, want %q", tt.input, got, tt.want)
- }
- }
-}
-
-// --- ADR tests ---
-
-func TestStoreAndRetrieveADR(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- content := "## PURPOSE\nTest project for unit tests.\n\n## STACK\n- Go: speed"
- if err := s.StoreADR("test", content); err != nil {
- t.Fatal(err)
- }
-
- adr, err := s.GetADR("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if adr.Content != content {
- t.Errorf("content mismatch: %q", adr.Content)
- }
- if adr.Project != "test" {
- t.Errorf("project mismatch: %q", adr.Project)
- }
- if adr.CreatedAt == "" {
- t.Error("created_at empty")
- }
- if adr.UpdatedAt == "" {
- t.Error("updated_at empty")
- }
-}
-
-func TestStoreADRUpsert(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- if err := s.StoreADR("test", "v1"); err != nil {
- t.Fatal(err)
- }
- if err := s.StoreADR("test", "v2"); err != nil {
- t.Fatal(err)
- }
-
- adr, err := s.GetADR("test")
- if err != nil {
- t.Fatal(err)
- }
- if adr.Content != "v2" {
- t.Errorf("expected v2, got %q", adr.Content)
- }
-}
-
-func TestDeleteADR(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- if err := s.StoreADR("test", "## PURPOSE\nTest"); err != nil {
- t.Fatal(err)
- }
-
- if err := s.DeleteADR("test"); err != nil {
- t.Fatal(err)
- }
-
- _, err = s.GetADR("test")
- if err == nil {
- t.Error("expected error after delete, got nil")
- }
-}
-
-func TestDeleteADRNotFound(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- err = s.DeleteADR("nonexistent")
- if err == nil {
- t.Error("expected error for nonexistent ADR")
- }
-}
-
-func TestParseADRSections(t *testing.T) {
- tests := []struct {
- name string
- input string
- want map[string]string
- }{
- {
- name: "basic two sections",
- input: "## PURPOSE\nFoo\n\n## STACK\nBar",
- want: map[string]string{"PURPOSE": "Foo", "STACK": "Bar"},
- },
- {
- name: "all six sections",
- input: "## PURPOSE\nA\n\n## STACK\nB\n\n## ARCHITECTURE\nC\n\n## PATTERNS\nD\n\n## TRADEOFFS\nE\n\n## PHILOSOPHY\nF",
- want: map[string]string{"PURPOSE": "A", "STACK": "B", "ARCHITECTURE": "C", "PATTERNS": "D", "TRADEOFFS": "E", "PHILOSOPHY": "F"},
- },
- {
- name: "non-canonical header preserved as text",
- input: "## PURPOSE\nFoo\n## CUSTOM\nStill in PURPOSE\n\n## STACK\nBar",
- want: map[string]string{"PURPOSE": "Foo\n## CUSTOM\nStill in PURPOSE", "STACK": "Bar"},
- },
- {
- name: "empty content",
- input: "",
- want: map[string]string{},
- },
- {
- name: "content before first section",
- input: "preamble\n## PURPOSE\nFoo",
- want: map[string]string{"PURPOSE": "Foo"},
- },
- {
- name: "multiline section content",
- input: "## PURPOSE\nLine 1\nLine 2\nLine 3\n\n## STACK\n- Go\n- SQLite",
- want: map[string]string{"PURPOSE": "Line 1\nLine 2\nLine 3", "STACK": "- Go\n- SQLite"},
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := ParseADRSections(tt.input)
- if len(got) != len(tt.want) {
- t.Errorf("section count: got %d, want %d\ngot: %v", len(got), len(tt.want), got)
- return
- }
- for k, wantV := range tt.want {
- if gotV, ok := got[k]; !ok {
- t.Errorf("missing section %q", k)
- } else if gotV != wantV {
- t.Errorf("section %q:\n got: %q\n want: %q", k, gotV, wantV)
- }
- }
- })
- }
-}
-
-func TestRenderADR(t *testing.T) {
- tests := []struct {
- name string
- sections map[string]string
- want string
- }{
- {
- name: "canonical order",
- sections: map[string]string{"STACK": "Bar", "PURPOSE": "Foo"},
- want: "## PURPOSE\nFoo\n\n## STACK\nBar",
- },
- {
- name: "all sections in order",
- sections: map[string]string{"PHILOSOPHY": "F", "PURPOSE": "A", "STACK": "B", "ARCHITECTURE": "C", "PATTERNS": "D", "TRADEOFFS": "E"},
- want: "## PURPOSE\nA\n\n## STACK\nB\n\n## ARCHITECTURE\nC\n\n## PATTERNS\nD\n\n## TRADEOFFS\nE\n\n## PHILOSOPHY\nF",
- },
- {
- name: "non-canonical sections appended alphabetically",
- sections: map[string]string{"PURPOSE": "Foo", "ZEBRA": "Z", "ALPHA": "A"},
- want: "## PURPOSE\nFoo\n\n## ALPHA\nA\n\n## ZEBRA\nZ",
- },
- {
- name: "empty map",
- sections: map[string]string{},
- want: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := RenderADR(tt.sections)
- if got != tt.want {
- t.Errorf("RenderADR:\n got: %q\n want: %q", got, tt.want)
- }
- })
- }
-}
-
-func TestParseRenderRoundTrip(t *testing.T) {
- original := "## PURPOSE\nTest project\n\n## STACK\n- Go: speed\n- SQLite: embedded\n\n## ARCHITECTURE\nPipeline pattern\n\n## PATTERNS\n- Convention over config\n\n## TRADEOFFS\n- Speed over features\n\n## PHILOSOPHY\n- Keep it simple"
- sections := ParseADRSections(original)
- rendered := RenderADR(sections)
- if rendered != original {
- t.Errorf("round-trip mismatch:\n got: %q\n want: %q", rendered, original)
- }
-}
-
-func TestUpdateADRSections(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Store initial ADR
- initial := "## PURPOSE\nOriginal purpose\n\n## STACK\n- Go"
- if err := s.StoreADR("test", initial); err != nil {
- t.Fatal(err)
- }
-
- // Update only PATTERNS section
- updated, err := s.UpdateADRSections("test", map[string]string{
- "PATTERNS": "- Pipeline pattern",
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Verify all sections are present
- sections := ParseADRSections(updated.Content)
- if sections["PURPOSE"] != "Original purpose" {
- t.Errorf("PURPOSE changed: %q", sections["PURPOSE"])
- }
- if sections["STACK"] != "- Go" {
- t.Errorf("STACK changed: %q", sections["STACK"])
- }
- if sections["PATTERNS"] != "- Pipeline pattern" {
- t.Errorf("PATTERNS not updated: %q", sections["PATTERNS"])
- }
-}
-
-func TestUpdateADRSectionsOverflow(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- if err := s.StoreADR("test", "## PURPOSE\nShort"); err != nil {
- t.Fatal(err)
- }
-
- // Try to update with content that exceeds the limit
- hugeContent := make([]byte, maxADRLength+1)
- for i := range hugeContent {
- hugeContent[i] = 'x'
- }
-
- _, err = s.UpdateADRSections("test", map[string]string{
- "STACK": string(hugeContent),
- })
- if err == nil {
- t.Error("expected overflow error")
- }
-}
-
-func TestUpdateADRSectionsNoExisting(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- _, err = s.UpdateADRSections("test", map[string]string{
- "PURPOSE": "New purpose",
- })
- if err == nil {
- t.Error("expected error when no existing ADR")
- }
-}
-
-// --- ADR validation tests ---
-
-func TestValidateADRContentAllSections(t *testing.T) {
- content := "## PURPOSE\nA\n\n## STACK\nB\n\n## ARCHITECTURE\nC\n\n## PATTERNS\nD\n\n## TRADEOFFS\nE\n\n## PHILOSOPHY\nF"
- if err := ValidateADRContent(content); err != nil {
- t.Errorf("expected no error for complete ADR, got: %v", err)
- }
-}
-
-func TestValidateADRContentMissingSections(t *testing.T) {
- content := "## PURPOSE\nA\n\n## STACK\nB"
- err := ValidateADRContent(content)
- if err == nil {
- t.Fatal("expected error for incomplete ADR")
- }
- // Error should mention the missing sections
- for _, missing := range []string{"ARCHITECTURE", "PATTERNS", "TRADEOFFS", "PHILOSOPHY"} {
- if !strings.Contains(err.Error(), missing) {
- t.Errorf("error should mention missing section %q: %v", missing, err)
- }
- }
-}
-
-func TestValidateADRContentEmpty(t *testing.T) {
- err := ValidateADRContent("")
- if err == nil {
- t.Fatal("expected error for empty content")
- }
-}
-
-func TestValidateADRSectionKeysValid(t *testing.T) {
- sections := map[string]string{
- "PURPOSE": "updated",
- "STACK": "updated",
- }
- if err := ValidateADRSectionKeys(sections); err != nil {
- t.Errorf("expected no error for valid keys, got: %v", err)
- }
-}
-
-func TestValidateADRSectionKeysInvalid(t *testing.T) {
- sections := map[string]string{
- "PURPOSE": "ok",
- "STACKS": "typo",
- "CUSTOM": "invalid",
- }
- err := ValidateADRSectionKeys(sections)
- if err == nil {
- t.Fatal("expected error for invalid keys")
- }
- if !strings.Contains(err.Error(), "STACKS") {
- t.Errorf("error should mention invalid key STACKS: %v", err)
- }
- if !strings.Contains(err.Error(), "CUSTOM") {
- t.Errorf("error should mention invalid key CUSTOM: %v", err)
- }
-}
-
-func TestValidateADRSectionKeysEmpty(t *testing.T) {
- if err := ValidateADRSectionKeys(map[string]string{}); err != nil {
- t.Errorf("expected no error for empty map, got: %v", err)
- }
-}
-
-// --- Louvain algorithm tests ---
-
-func TestLouvainBasic(t *testing.T) {
- // Triangle: A-B, B-C, A-C (should form one community)
- // Isolated: D-E (should form another)
- nodes := []int64{1, 2, 3, 4, 5}
- edges := []louvainEdge{
- {src: 1, dst: 2},
- {src: 2, dst: 3},
- {src: 1, dst: 3},
- {src: 4, dst: 5},
- }
-
- partition := louvain(nodes, edges)
-
- // A, B, C should be in the same community
- if partition[1] != partition[2] || partition[2] != partition[3] {
- t.Errorf("triangle nodes should be in same community: %v", partition)
- }
-
- // D, E should be in the same community
- if partition[4] != partition[5] {
- t.Errorf("pair nodes should be in same community: %v", partition)
- }
-
- // Triangle and pair should be in different communities
- if partition[1] == partition[4] {
- t.Errorf("triangle and pair should be in different communities: %v", partition)
- }
-}
-
-func TestLouvainEmpty(t *testing.T) {
- partition := louvain(nil, nil)
- if len(partition) != 0 {
- t.Errorf("expected empty partition, got %v", partition)
- }
-}
-
-func TestLouvainSingleNode(t *testing.T) {
- partition := louvain([]int64{42}, nil)
- if len(partition) != 1 {
- t.Fatalf("expected 1 entry, got %d", len(partition))
- }
- if _, ok := partition[42]; !ok {
- t.Error("expected node 42 in partition")
- }
-}
-
-func TestLouvainConverges(t *testing.T) {
- // Larger test: two clear clusters connected by a thin bridge
- var nodes []int64
- var edges []louvainEdge
-
- // Cluster 1: nodes 1-10, fully connected
- for i := int64(1); i <= 10; i++ {
- nodes = append(nodes, i)
- for j := i + 1; j <= 10; j++ {
- edges = append(edges, louvainEdge{src: i, dst: j})
- }
- }
-
- // Cluster 2: nodes 11-20, fully connected
- for i := int64(11); i <= 20; i++ {
- nodes = append(nodes, i)
- for j := i + 1; j <= 20; j++ {
- edges = append(edges, louvainEdge{src: i, dst: j})
- }
- }
-
- // Bridge: single edge between clusters
- edges = append(edges, louvainEdge{src: 5, dst: 15})
-
- partition := louvain(nodes, edges)
-
- // Count communities
- communities := map[int]int{}
- for _, comm := range partition {
- communities[comm]++
- }
-
- // Should find exactly 2 communities (or close to it)
- if len(communities) < 2 {
- t.Errorf("expected at least 2 communities, got %d", len(communities))
- }
-
- // Nodes 1-10 should mostly be in the same community
- comm1 := partition[int64(1)]
- sameCount := 0
- for i := int64(1); i <= 10; i++ {
- if partition[i] == comm1 {
- sameCount++
- }
- }
- if sameCount < 8 {
- t.Errorf("expected cluster 1 nodes mostly in same community, got %d/10", sameCount)
- }
-}
-
-// --- qnToPackage regression tests ---
-
-func TestQnToPackage(t *testing.T) {
- tests := []struct {
- qn string
- want string
- }{
- // 4+ segment QNs — returns segment[2] (sub-package)
- {"project.internal.store.search.Search", "store"},
- {"project.src.utils.helper.foo", "utils"},
- {"project.src.components.Button.render", "components"},
- {"project.cmd.server.main", "server"},
- // 3-segment QNs — falls back to segment[1]
- {"project.main.foo", "main"},
- {"project.cmd", "cmd"},
- // Edge cases
- {"standalone", ""},
- {"", ""},
- }
- for _, tt := range tests {
- got := qnToPackage(tt.qn)
- if got != tt.want {
- t.Errorf("qnToPackage(%q) = %q, want %q", tt.qn, got, tt.want)
- }
- }
-}
-
-func TestQnToTopPackage(t *testing.T) {
- tests := []struct {
- qn string
- want string
- }{
- {"project.internal.store.search.Search", "internal"},
- {"project.src.components.Button", "src"},
- {"project.cmd", "cmd"},
- {"standalone", ""},
- }
- for _, tt := range tests {
- got := qnToTopPackage(tt.qn)
- if got != tt.want {
- t.Errorf("qnToTopPackage(%q) = %q, want %q", tt.qn, got, tt.want)
- }
- }
-}
-
-func TestFindArchitectureDocs(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Add some file nodes, including architecture docs
- for _, fp := range []string{"main.go", "ARCHITECTURE.md", "docs/adr/001-use-sqlite.md", "README.md"} {
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "File", Name: fp, QualifiedName: "test." + fp, FilePath: fp})
- }
-
- docs, err := s.FindArchitectureDocs("test")
- if err != nil {
- t.Fatal(err)
- }
-
- if len(docs) != 2 {
- t.Fatalf("expected 2 architecture docs, got %d: %v", len(docs), docs)
- }
-
- // Should find ARCHITECTURE.md and docs/adr/001-use-sqlite.md
- found := map[string]bool{}
- for _, d := range docs {
- found[d] = true
- }
- if !found["ARCHITECTURE.md"] {
- t.Error("missing ARCHITECTURE.md")
- }
- if !found["docs/adr/001-use-sqlite.md"] {
- t.Error("missing docs/adr/001-use-sqlite.md")
- }
-}
-
-func TestFindArchitectureDocsEmpty(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- docs, err := s.FindArchitectureDocs("test")
- if err != nil {
- t.Fatal(err)
- }
- if len(docs) != 0 {
- t.Errorf("expected 0 docs, got %d", len(docs))
- }
-}
-
-func TestIsTestFilePath(t *testing.T) {
- tests := []struct {
- fp string
- want bool
- }{
- {"internal/handler/handler.go", false},
- {"src/__tests__/handler.test.ts", true},
- {"src/test/java/com/example/Test.java", true},
- {"tests/test_handler.py", true},
- {"testdata/fixture.json", true},
- {"", false},
- }
- for _, tt := range tests {
- got := isTestFilePath(tt.fp)
- if got != tt.want {
- t.Errorf("isTestFilePath(%q) = %v, want %v", tt.fp, got, tt.want)
- }
- }
-}
diff --git a/internal/store/bulk.go b/internal/store/bulk.go
deleted file mode 100644
index 9d7d01359..000000000
--- a/internal/store/bulk.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package store
-
-import (
- "context"
- "fmt"
- "strings"
-)
-
-// userIndexes lists all user-created indexes (excluding UNIQUE autoindexes on tables).
-var userIndexes = []string{
- "idx_nodes_label",
- "idx_nodes_name",
- "idx_nodes_file",
- "idx_edges_source",
- "idx_edges_target",
- "idx_edges_type",
- "idx_edges_target_type",
- "idx_edges_source_type",
- "idx_edges_url_path",
-}
-
-// DropUserIndexes drops all user-created indexes for faster bulk writes.
-func (s *Store) DropUserIndexes(ctx context.Context) error {
- for _, idx := range userIndexes {
- if _, err := s.q.Exec("DROP INDEX IF EXISTS " + idx); err != nil {
- return fmt.Errorf("drop index %s: %w", idx, err)
- }
- }
- return nil
-}
-
-// CreateUserIndexes recreates all user-created indexes (single sorted pass, O(N)).
-func (s *Store) CreateUserIndexes(ctx context.Context) error {
- indexes := []string{
- "CREATE INDEX IF NOT EXISTS idx_nodes_label ON nodes(project, label)",
- "CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(project, name)",
- "CREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(project, file_path)",
- "CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_id, type)",
- "CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_id, type)",
- "CREATE INDEX IF NOT EXISTS idx_edges_type ON edges(project, type)",
- "CREATE INDEX IF NOT EXISTS idx_edges_target_type ON edges(project, target_id, type)",
- "CREATE INDEX IF NOT EXISTS idx_edges_source_type ON edges(project, source_id, type)",
- "CREATE INDEX IF NOT EXISTS idx_edges_url_path ON edges(project, url_path_gen)",
- }
- for _, ddl := range indexes {
- if _, err := s.q.Exec(ddl); err != nil {
- return fmt.Errorf("create index: %w", err)
- }
- }
- return nil
-}
-
-// BulkInsertNodes inserts nodes in batches using plain INSERT (no ON CONFLICT).
-// Assumes no duplicates exist for the project after a prior DELETE.
-func (s *Store) BulkInsertNodes(ctx context.Context, nodes []*Node) error {
- for i := 0; i < len(nodes); i += nodesBatchSize {
- end := i + nodesBatchSize
- if end > len(nodes) {
- end = len(nodes)
- }
- if err := s.bulkInsertNodeChunk(nodes[i:end]); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *Store) bulkInsertNodeChunk(batch []*Node) error {
- var sb strings.Builder
- sb.WriteString("INSERT INTO nodes (project, label, name, qualified_name, file_path, start_line, end_line, properties) VALUES ")
-
- args := make([]any, 0, len(batch)*numNodeCols)
- for i, n := range batch {
- if i > 0 {
- sb.WriteByte(',')
- }
- sb.WriteString("(?,?,?,?,?,?,?,?)")
- args = append(args, n.Project, n.Label, n.Name, n.QualifiedName, n.FilePath, n.StartLine, n.EndLine, marshalProps(n.Properties))
- }
-
- if _, err := s.q.Exec(sb.String(), args...); err != nil {
- return fmt.Errorf("bulk insert nodes: %w", err)
- }
- return nil
-}
-
-// BulkInsertEdges inserts edges in batches using plain INSERT (no ON CONFLICT).
-// Assumes no duplicates exist for the project after a prior DELETE.
-func (s *Store) BulkInsertEdges(ctx context.Context, edges []*Edge) error {
- for i := 0; i < len(edges); i += edgesBatchSize {
- end := i + edgesBatchSize
- if end > len(edges) {
- end = len(edges)
- }
- if err := s.bulkInsertEdgeChunk(edges[i:end]); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *Store) bulkInsertEdgeChunk(batch []*Edge) error {
- var sb strings.Builder
- sb.WriteString("INSERT INTO edges (project, source_id, target_id, type, properties) VALUES ")
-
- args := make([]any, 0, len(batch)*numEdgeCols)
- for i, e := range batch {
- if i > 0 {
- sb.WriteByte(',')
- }
- sb.WriteString("(?,?,?,?,?)")
- args = append(args, e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties))
- }
-
- if _, err := s.q.Exec(sb.String(), args...); err != nil {
- return fmt.Errorf("bulk insert edges: %w", err)
- }
- return nil
-}
-
-// LoadNodeIDMap returns a map of qualified_name → SQLite ID for all nodes in a project.
-func (s *Store) LoadNodeIDMap(ctx context.Context, project string) (map[string]int64, error) {
- rows, err := s.q.Query("SELECT id, qualified_name FROM nodes WHERE project=?", project)
- if err != nil {
- return nil, fmt.Errorf("load node id map: %w", err)
- }
- defer rows.Close()
-
- result := make(map[string]int64)
- for rows.Next() {
- var id int64
- var qn string
- if err := rows.Scan(&id, &qn); err != nil {
- return nil, err
- }
- result[qn] = id
- }
- return result, rows.Err()
-}
diff --git a/internal/store/config.go b/internal/store/config.go
deleted file mode 100644
index 76523ae03..000000000
--- a/internal/store/config.go
+++ /dev/null
@@ -1,146 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "strconv"
-
- _ "github.com/mattn/go-sqlite3"
-)
-
-// ConfigStore provides persistent key-value configuration backed by SQLite.
-// Stored in _config.db in the cache directory (separate from per-project DBs).
-type ConfigStore struct {
- db *sql.DB
-}
-
-// OpenConfig opens or creates the global config database.
-func OpenConfig() (*ConfigStore, error) {
- dir, err := cacheDir()
- if err != nil {
- return nil, err
- }
- return OpenConfigInDir(dir)
-}
-
-// OpenConfigInDir opens the config database in a specific directory (for testing).
-func OpenConfigInDir(dir string) (*ConfigStore, error) {
- if err := os.MkdirAll(dir, 0o750); err != nil {
- return nil, fmt.Errorf("mkdir: %w", err)
- }
- dbPath := filepath.Join(dir, "_config.db")
- db, err := sql.Open("sqlite3", dbPath+"?_busy_timeout=2000")
- if err != nil {
- return nil, fmt.Errorf("open config db: %w", err)
- }
- db.SetMaxOpenConns(1)
-
- _, err = db.ExecContext(context.Background(), `
- CREATE TABLE IF NOT EXISTS config (
- key TEXT PRIMARY KEY,
- value TEXT NOT NULL
- )
- `)
- if err != nil {
- db.Close()
- return nil, fmt.Errorf("init config schema: %w", err)
- }
-
- return &ConfigStore{db: db}, nil
-}
-
-// Get returns the value for a key, or defaultVal if not set.
-func (c *ConfigStore) Get(key, defaultVal string) string {
- var val string
- err := c.db.QueryRowContext(context.Background(),
- "SELECT value FROM config WHERE key = ?", key).Scan(&val)
- if err != nil {
- return defaultVal
- }
- return val
-}
-
-// GetBool returns a boolean config value (stored as "true"/"false").
-func (c *ConfigStore) GetBool(key string, defaultVal bool) bool {
- raw := c.Get(key, "")
- if raw == "" {
- return defaultVal
- }
- b, err := strconv.ParseBool(raw)
- if err != nil {
- return defaultVal
- }
- return b
-}
-
-// GetInt returns an integer config value.
-func (c *ConfigStore) GetInt(key string, defaultVal int) int {
- raw := c.Get(key, "")
- if raw == "" {
- return defaultVal
- }
- n, err := strconv.Atoi(raw)
- if err != nil {
- return defaultVal
- }
- return n
-}
-
-// Set stores a key-value pair (upsert).
-func (c *ConfigStore) Set(key, value string) error {
- _, err := c.db.ExecContext(context.Background(),
- "INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
- key, value)
- return err
-}
-
-// Delete removes a config key.
-func (c *ConfigStore) Delete(key string) error {
- _, err := c.db.ExecContext(context.Background(),
- "DELETE FROM config WHERE key = ?", key)
- return err
-}
-
-// All returns all config key-value pairs.
-func (c *ConfigStore) All() (map[string]string, error) {
- rows, err := c.db.QueryContext(context.Background(),
- "SELECT key, value FROM config ORDER BY key")
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- result := make(map[string]string)
- for rows.Next() {
- var k, v string
- if err := rows.Scan(&k, &v); err != nil {
- continue
- }
- result[k] = v
- }
- return result, rows.Err()
-}
-
-// Close closes the config database.
-func (c *ConfigStore) Close() error {
- return c.db.Close()
-}
-
-// Known config keys and their defaults.
-const (
- // ConfigAutoIndex controls whether the server auto-indexes on startup.
- // Default: false (off). Enable with: codebase-memory-mcp config set auto_index true
- ConfigAutoIndex = "auto_index"
-
- // ConfigAutoIndexLimit is the max file count for auto-indexing new projects.
- // Default: 50000. Projects above this limit require explicit index_repository.
- ConfigAutoIndexLimit = "auto_index_limit"
-
- // ConfigMemLimit sets GOMEMLIMIT for the server process.
- // Accepts human-readable sizes: "2G", "512M", "4096M".
- // Default: empty (no limit). Applied on server startup.
- ConfigMemLimit = "mem_limit"
-)
diff --git a/internal/store/edges.go b/internal/store/edges.go
deleted file mode 100644
index 09db07a86..000000000
--- a/internal/store/edges.go
+++ /dev/null
@@ -1,405 +0,0 @@
-package store
-
-import (
- "database/sql"
- "fmt"
- "log/slog"
- "strings"
-)
-
-// InsertEdge inserts an edge (dedup by source_id, target_id, type).
-func (s *Store) InsertEdge(e *Edge) (int64, error) {
- res, err := s.q.Exec(`
- INSERT INTO edges (project, source_id, target_id, type, properties)
- VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=json_patch(properties, excluded.properties)`,
- e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties))
- if err != nil {
- return 0, fmt.Errorf("insert edge: %w", err)
- }
- return res.LastInsertId()
-}
-
-// FindEdgesBySource finds all edges from a given source node.
-func (s *Store) FindEdgesBySource(sourceID int64) ([]*Edge, error) {
- rows, err := s.q.Query(`SELECT id, project, source_id, target_id, type, properties
- FROM edges WHERE source_id=?`, sourceID)
- if err != nil {
- return nil, fmt.Errorf("find edges by source: %w", err)
- }
- defer rows.Close()
- return scanEdges(rows)
-}
-
-// FindEdgesByTarget finds all edges to a given target node.
-func (s *Store) FindEdgesByTarget(targetID int64) ([]*Edge, error) {
- rows, err := s.q.Query(`SELECT id, project, source_id, target_id, type, properties
- FROM edges WHERE target_id=?`, targetID)
- if err != nil {
- return nil, fmt.Errorf("find edges by target: %w", err)
- }
- defer rows.Close()
- return scanEdges(rows)
-}
-
-// FindEdgesBySourceAndType finds edges from a source with a specific type.
-func (s *Store) FindEdgesBySourceAndType(sourceID int64, edgeType string) ([]*Edge, error) {
- rows, err := s.q.Query(`SELECT id, project, source_id, target_id, type, properties
- FROM edges WHERE source_id=? AND type=?`, sourceID, edgeType)
- if err != nil {
- return nil, fmt.Errorf("find edges by source+type: %w", err)
- }
- defer rows.Close()
- return scanEdges(rows)
-}
-
-// FindEdgesByTargetAndType finds edges to a target with a specific type.
-func (s *Store) FindEdgesByTargetAndType(targetID int64, edgeType string) ([]*Edge, error) {
- rows, err := s.q.Query(`SELECT id, project, source_id, target_id, type, properties
- FROM edges WHERE target_id=? AND type=?`, targetID, edgeType)
- if err != nil {
- return nil, fmt.Errorf("find edges by target+type: %w", err)
- }
- defer rows.Close()
- return scanEdges(rows)
-}
-
-// FindEdgesByType returns all edges of a given type for a project.
-func (s *Store) FindEdgesByType(project, edgeType string) ([]*Edge, error) {
- rows, err := s.q.Query(`SELECT id, project, source_id, target_id, type, properties
- FROM edges WHERE project=? AND type=?`, project, edgeType)
- if err != nil {
- return nil, fmt.Errorf("find edges by type: %w", err)
- }
- defer rows.Close()
- return scanEdges(rows)
-}
-
-// CountEdges returns the number of edges in a project.
-func (s *Store) CountEdges(project string) (int, error) {
- var count int
- err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE project=?", project).Scan(&count)
- return count, err
-}
-
-// DeleteEdgesByProject deletes all edges for a project.
-func (s *Store) DeleteEdgesByProject(project string) error {
- _, err := s.q.Exec("DELETE FROM edges WHERE project=?", project)
- return err
-}
-
-// CountEdgesByType returns the number of edges of a given type for a project.
-func (s *Store) CountEdgesByType(project, edgeType string) (int, error) {
- var count int
- err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE project=? AND type=?", project, edgeType).Scan(&count)
- return count, err
-}
-
-// EdgeCountsByType returns edge counts grouped by edge type.
-func (s *Store) EdgeCountsByType(project string) (map[string]int, error) {
- rows, err := s.q.Query(`SELECT type, COUNT(*) FROM edges WHERE project=? GROUP BY type ORDER BY COUNT(*) DESC`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- result := make(map[string]int)
- for rows.Next() {
- var edgeType string
- var count int
- if err := rows.Scan(&edgeType, &count); err != nil {
- return nil, err
- }
- result[edgeType] = count
- }
- return result, rows.Err()
-}
-
-// CallsResolutionStats returns CALLS edge counts grouped by resolution_strategy.
-func (s *Store) CallsResolutionStats(project string) (map[string]int, error) {
- rows, err := s.q.Query(`
- SELECT json_extract(properties, '$.resolution_strategy') AS strategy, COUNT(*) AS cnt
- FROM edges WHERE project=? AND type='CALLS'
- GROUP BY strategy ORDER BY cnt DESC`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- result := make(map[string]int)
- for rows.Next() {
- var strategy sql.NullString
- var count int
- if err := rows.Scan(&strategy, &count); err != nil {
- return nil, err
- }
- key := strategy.String
- if key == "" {
- key = "unset"
- }
- result[key] = count
- }
- return result, rows.Err()
-}
-
-// DeleteEdgesByType deletes all edges of a given type for a project.
-func (s *Store) DeleteEdgesByType(project, edgeType string) error {
- _, err := s.q.Exec("DELETE FROM edges WHERE project=? AND type=?", project, edgeType)
- return err
-}
-
-// DeleteEdgesBySourceFile deletes edges of a given type where the source node
-// belongs to a specific file. Used for incremental re-indexing of CALLS edges.
-func (s *Store) DeleteEdgesBySourceFile(project, filePath, edgeType string) error {
- _, err := s.q.Exec(`
- DELETE FROM edges WHERE id IN (
- SELECT e.id FROM edges e
- JOIN nodes n ON e.source_id = n.id
- WHERE e.project=? AND n.file_path=? AND e.type=?
- )`, project, filePath, edgeType)
- return err
-}
-
-// FindEdgesByURLPath returns edges where url_path contains the given substring.
-// Uses the generated column index for prefix matches, falls back to json_extract for substring.
-func (s *Store) FindEdgesByURLPath(project, pathSubstring string) ([]*Edge, error) {
- rows, err := s.q.Query(`
- SELECT id, project, source_id, target_id, type, properties
- FROM edges
- WHERE project = ? AND url_path_gen LIKE ?`,
- project, "%"+pathSubstring+"%")
- if err != nil {
- return nil, fmt.Errorf("find edges by url_path: %w", err)
- }
- defer rows.Close()
- return scanEdges(rows)
-}
-
-// Formula-derived batch size: SQLite has a 999 bind variable limit.
-const numEdgeCols = 5
-const edgesBatchSize = 999 / numEdgeCols // = 199
-
-// InsertEdgeBatch inserts multiple edges in batched multi-row INSERTs.
-func (s *Store) InsertEdgeBatch(edges []*Edge) error {
- if len(edges) == 0 {
- return nil
- }
-
- for i := 0; i < len(edges); i += edgesBatchSize {
- end := i + edgesBatchSize
- if end > len(edges) {
- end = len(edges)
- }
- if err := s.insertEdgeChunk(edges[i:end]); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *Store) insertEdgeChunk(batch []*Edge) error {
- var sb strings.Builder
- sb.WriteString(`INSERT INTO edges (project, source_id, target_id, type, properties) VALUES `)
-
- args := make([]any, 0, len(batch)*5)
- for i, e := range batch {
- if i > 0 {
- sb.WriteByte(',')
- }
- sb.WriteString("(?,?,?,?,?)")
- args = append(args, e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties))
- }
- sb.WriteString(` ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=json_patch(properties, excluded.properties)`)
-
- _, err := s.q.Exec(sb.String(), args...)
- if err == nil {
- return nil
- }
-
- // Batch failed (likely FK constraint from stale LastInsertId) — fall back
- // to one-at-a-time inserts so one bad edge doesn't break the entire batch.
- skipped := 0
- for _, e := range batch {
- if _, err2 := s.q.Exec(`
- INSERT INTO edges (project, source_id, target_id, type, properties)
- VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=json_patch(properties, excluded.properties)`,
- e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties)); err2 != nil {
- skipped++
- }
- }
- if skipped > 0 {
- slog.Info("edges.batch.fk_skip", "skipped", skipped, "total", len(batch))
- }
- return nil
-}
-
-// FindEdgesBySourceIDs returns all edges where source_id is in the given set,
-// optionally filtered by edge types. Groups results by source_id for efficient lookup.
-func (s *Store) FindEdgesBySourceIDs(sourceIDs []int64, edgeTypes []string) (map[int64][]*Edge, error) {
- if len(sourceIDs) == 0 {
- return map[int64][]*Edge{}, nil
- }
-
- result := make(map[int64][]*Edge, len(sourceIDs))
- const batchSize = 500 // leave room for type args
-
- for i := 0; i < len(sourceIDs); i += batchSize {
- end := i + batchSize
- if end > len(sourceIDs) {
- end = len(sourceIDs)
- }
- chunk := sourceIDs[i:end]
-
- placeholders := make([]string, len(chunk))
- args := make([]any, 0, len(chunk)+len(edgeTypes))
- for j, id := range chunk {
- placeholders[j] = "?"
- args = append(args, id)
- }
-
- query := fmt.Sprintf(
- "SELECT id, project, source_id, target_id, type, properties FROM edges WHERE source_id IN (%s)",
- strings.Join(placeholders, ","))
-
- if len(edgeTypes) > 0 {
- typePH := make([]string, len(edgeTypes))
- for j, et := range edgeTypes {
- typePH[j] = "?"
- args = append(args, et)
- }
- query += " AND type IN (" + strings.Join(typePH, ",") + ")"
- }
-
- if err := func() error {
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return fmt.Errorf("find edges by source ids: %w", err)
- }
- defer rows.Close()
- edges, err := scanEdges(rows)
- if err != nil {
- return err
- }
- for _, e := range edges {
- result[e.SourceID] = append(result[e.SourceID], e)
- }
- return nil
- }(); err != nil {
- return nil, err
- }
- }
- return result, nil
-}
-
-// FindEdgesByTargetIDs returns all edges where target_id is in the given set,
-// optionally filtered by edge types. Groups results by target_id.
-func (s *Store) FindEdgesByTargetIDs(targetIDs []int64, edgeTypes []string) (map[int64][]*Edge, error) {
- if len(targetIDs) == 0 {
- return map[int64][]*Edge{}, nil
- }
-
- result := make(map[int64][]*Edge, len(targetIDs))
- const batchSize = 500
-
- for i := 0; i < len(targetIDs); i += batchSize {
- end := i + batchSize
- if end > len(targetIDs) {
- end = len(targetIDs)
- }
- chunk := targetIDs[i:end]
-
- placeholders := make([]string, len(chunk))
- args := make([]any, 0, len(chunk)+len(edgeTypes))
- for j, id := range chunk {
- placeholders[j] = "?"
- args = append(args, id)
- }
-
- query := fmt.Sprintf(
- "SELECT id, project, source_id, target_id, type, properties FROM edges WHERE target_id IN (%s)",
- strings.Join(placeholders, ","))
-
- if len(edgeTypes) > 0 {
- typePH := make([]string, len(edgeTypes))
- for j, et := range edgeTypes {
- typePH[j] = "?"
- args = append(args, et)
- }
- query += " AND type IN (" + strings.Join(typePH, ",") + ")"
- }
-
- if err := func() error {
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return fmt.Errorf("find edges by target ids: %w", err)
- }
- defer rows.Close()
- edges, err := scanEdges(rows)
- if err != nil {
- return err
- }
- for _, e := range edges {
- result[e.TargetID] = append(result[e.TargetID], e)
- }
- return nil
- }(); err != nil {
- return nil, err
- }
- }
- return result, nil
-}
-
-// NodeDegree returns inbound and outbound CALLS edge counts for a node.
-func (s *Store) NodeDegree(nodeID int64) (inbound, outbound int) {
- _ = s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE target_id=? AND type='CALLS'", nodeID).Scan(&inbound)
- _ = s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE source_id=? AND type='CALLS'", nodeID).Scan(&outbound)
- return
-}
-
-// NodeNeighborNames returns the names of callers and callees for a node,
-// considering CALLS, HTTP_CALLS, and ASYNC_CALLS edge types.
-func (s *Store) NodeNeighborNames(nodeID int64, limit int) (callerNames, calleeNames []string) {
- callerNames = queryNeighborNames(s.q,
- `SELECT DISTINCT n.name FROM edges e JOIN nodes n ON e.source_id = n.id
- WHERE e.target_id = ? AND e.type IN ('CALLS','HTTP_CALLS','ASYNC_CALLS')
- ORDER BY n.name LIMIT ?`, nodeID, limit)
- calleeNames = queryNeighborNames(s.q,
- `SELECT DISTINCT n.name FROM edges e JOIN nodes n ON e.target_id = n.id
- WHERE e.source_id = ? AND e.type IN ('CALLS','HTTP_CALLS','ASYNC_CALLS')
- ORDER BY n.name LIMIT ?`, nodeID, limit)
- return
-}
-
-// queryNeighborNames runs a query returning a single name column.
-func queryNeighborNames(q Querier, query string, args ...any) []string {
- rows, err := q.Query(query, args...)
- if err != nil {
- return nil
- }
- defer rows.Close()
- var names []string
- for rows.Next() {
- var name string
- if err := rows.Scan(&name); err != nil {
- continue
- }
- names = append(names, name)
- }
- if err := rows.Err(); err != nil {
- return nil
- }
- return names
-}
-
-func scanEdges(rows *sql.Rows) ([]*Edge, error) {
- var result []*Edge
- for rows.Next() {
- var e Edge
- var props string
- if err := rows.Scan(&e.ID, &e.Project, &e.SourceID, &e.TargetID, &e.Type, &props); err != nil {
- return nil, err
- }
- e.Properties = unmarshalProps(props)
- result = append(result, &e)
- }
- return result, rows.Err()
-}
diff --git a/internal/store/impact.go b/internal/store/impact.go
deleted file mode 100644
index 4ac29ea02..000000000
--- a/internal/store/impact.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package store
-
-// RiskLevel classifies impact based on BFS hop depth.
-type RiskLevel string
-
-const (
- RiskCritical RiskLevel = "CRITICAL"
- RiskHigh RiskLevel = "HIGH"
- RiskMedium RiskLevel = "MEDIUM"
- RiskLow RiskLevel = "LOW"
-)
-
-// HopToRisk maps a BFS hop depth to a risk level.
-func HopToRisk(hop int) RiskLevel {
- switch hop {
- case 1:
- return RiskCritical
- case 2:
- return RiskHigh
- case 3:
- return RiskMedium
- default:
- return RiskLow
- }
-}
-
-// ImpactSummary aggregates risk counts from a BFS traversal.
-type ImpactSummary struct {
- Critical int `json:"critical"`
- High int `json:"high"`
- Medium int `json:"medium"`
- Low int `json:"low"`
- Total int `json:"total"`
- HasCrossService bool `json:"has_cross_service"`
-}
-
-// BuildImpactSummary computes risk distribution from deduplicated node hops.
-func BuildImpactSummary(hops []*NodeHop, edges []EdgeInfo) ImpactSummary {
- var s ImpactSummary
- for _, nh := range hops {
- switch HopToRisk(nh.Hop) {
- case RiskCritical:
- s.Critical++
- case RiskHigh:
- s.High++
- case RiskMedium:
- s.Medium++
- case RiskLow:
- s.Low++
- }
- s.Total++
- }
- for _, e := range edges {
- if e.Type == "HTTP_CALLS" || e.Type == "ASYNC_CALLS" {
- s.HasCrossService = true
- break
- }
- }
- return s
-}
-
-// DeduplicateHops removes duplicate nodes from BFS results, keeping the
-// minimum hop (highest risk) for each node.
-func DeduplicateHops(hops []*NodeHop) []*NodeHop {
- best := make(map[int64]*NodeHop)
- for _, nh := range hops {
- if existing, ok := best[nh.Node.ID]; !ok || nh.Hop < existing.Hop {
- best[nh.Node.ID] = nh
- }
- }
- result := make([]*NodeHop, 0, len(best))
- for _, nh := range best {
- result = append(result, nh)
- }
- return result
-}
diff --git a/internal/store/impact_test.go b/internal/store/impact_test.go
deleted file mode 100644
index 3ecbd3d2c..000000000
--- a/internal/store/impact_test.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package store
-
-import (
- "sort"
- "testing"
-)
-
-func TestHopToRisk(t *testing.T) {
- tests := []struct {
- hop int
- want RiskLevel
- }{
- {1, RiskCritical},
- {2, RiskHigh},
- {3, RiskMedium},
- {4, RiskLow},
- {5, RiskLow},
- {10, RiskLow},
- }
- for _, tt := range tests {
- got := HopToRisk(tt.hop)
- if got != tt.want {
- t.Errorf("HopToRisk(%d) = %s, want %s", tt.hop, got, tt.want)
- }
- }
-}
-
-func TestBuildImpactSummary(t *testing.T) {
- hops := []*NodeHop{
- {Node: &Node{ID: 1}, Hop: 1},
- {Node: &Node{ID: 2}, Hop: 1},
- {Node: &Node{ID: 3}, Hop: 2},
- {Node: &Node{ID: 4}, Hop: 3},
- {Node: &Node{ID: 5}, Hop: 4},
- }
- edges := []EdgeInfo{
- {FromName: "A", ToName: "B", Type: "CALLS"},
- }
-
- s := BuildImpactSummary(hops, edges)
-
- if s.Critical != 2 {
- t.Errorf("critical = %d, want 2", s.Critical)
- }
- if s.High != 1 {
- t.Errorf("high = %d, want 1", s.High)
- }
- if s.Medium != 1 {
- t.Errorf("medium = %d, want 1", s.Medium)
- }
- if s.Low != 1 {
- t.Errorf("low = %d, want 1", s.Low)
- }
- if s.Total != 5 {
- t.Errorf("total = %d, want 5", s.Total)
- }
- if s.HasCrossService {
- t.Error("expected has_cross_service=false")
- }
-}
-
-func TestCrossServiceDetection(t *testing.T) {
- hops := []*NodeHop{{Node: &Node{ID: 1}, Hop: 1}}
- edges := []EdgeInfo{
- {FromName: "A", ToName: "B", Type: "HTTP_CALLS"},
- }
- s := BuildImpactSummary(hops, edges)
- if !s.HasCrossService {
- t.Error("expected has_cross_service=true for HTTP_CALLS")
- }
-
- edges2 := []EdgeInfo{
- {FromName: "A", ToName: "B", Type: "ASYNC_CALLS"},
- }
- s2 := BuildImpactSummary(hops, edges2)
- if !s2.HasCrossService {
- t.Error("expected has_cross_service=true for ASYNC_CALLS")
- }
-}
-
-func TestDeduplicateHops(t *testing.T) {
- hops := []*NodeHop{
- {Node: &Node{ID: 1, Name: "A"}, Hop: 2},
- {Node: &Node{ID: 1, Name: "A"}, Hop: 3}, // duplicate at higher hop
- {Node: &Node{ID: 2, Name: "B"}, Hop: 1},
- {Node: &Node{ID: 3, Name: "C"}, Hop: 3},
- }
-
- result := DeduplicateHops(hops)
-
- // Sort for deterministic comparison
- sort.Slice(result, func(i, j int) bool {
- return result[i].Node.ID < result[j].Node.ID
- })
-
- if len(result) != 3 {
- t.Fatalf("expected 3 nodes, got %d", len(result))
- }
- if result[0].Node.ID != 1 || result[0].Hop != 2 {
- t.Errorf("node 1: expected hop=2, got hop=%d", result[0].Hop)
- }
- if result[1].Node.ID != 2 || result[1].Hop != 1 {
- t.Errorf("node 2: expected hop=1, got hop=%d", result[1].Hop)
- }
- if result[2].Node.ID != 3 || result[2].Hop != 3 {
- t.Errorf("node 3: expected hop=3, got hop=%d", result[2].Hop)
- }
-}
diff --git a/internal/store/louvain.go b/internal/store/louvain.go
deleted file mode 100644
index 6b7637038..000000000
--- a/internal/store/louvain.go
+++ /dev/null
@@ -1,224 +0,0 @@
-package store
-
-import "math/rand" // WHY: graph algorithm randomness — not cryptographic use, math/rand is correct here
-
-// louvainEdge represents an edge for the Louvain algorithm.
-type louvainEdge struct {
- src int64
- dst int64
- edgeType string // for post-processing only
-}
-
-// louvain implements community detection using the Louvain algorithm.
-// Input: node IDs + edges (treated as undirected).
-// Output: map[nodeID] → communityID.
-func louvain(nodes []int64, edges []louvainEdge) map[int64]int {
- const resolution = 1.0
- if len(nodes) == 0 {
- return map[int64]int{}
- }
-
- // Build compact index: nodeID → sequential index
- idxOf := make(map[int64]int, len(nodes))
- for i, id := range nodes {
- idxOf[id] = i
- }
- n := len(nodes)
-
- // Build adjacency list (undirected, weighted by edge count)
- adj := make([][]int, n)
- weight := make([][]float64, n)
- totalWeight := 0.0
-
- edgeWeight := map[[2]int]float64{}
- for _, e := range edges {
- si, ok1 := idxOf[e.src]
- di, ok2 := idxOf[e.dst]
- if !ok1 || !ok2 || si == di {
- continue
- }
- key := [2]int{si, di}
- if si > di {
- key = [2]int{di, si}
- }
- edgeWeight[key]++
- }
-
- for key, w := range edgeWeight {
- si, di := key[0], key[1]
- adj[si] = append(adj[si], di)
- weight[si] = append(weight[si], w)
- adj[di] = append(adj[di], si)
- weight[di] = append(weight[di], w)
- totalWeight += w
- }
-
- if totalWeight == 0 {
- // No edges: each node is its own community
- result := make(map[int64]int, n)
- for i, id := range nodes {
- result[id] = i
- }
- return result
- }
-
- // Initialize: each node in its own community
- community := make([]int, n)
- for i := range community {
- community[i] = i
- }
-
- // Degree (weighted sum for each node)
- degree := make([]float64, n)
- for i := 0; i < n; i++ {
- for _, w := range weight[i] {
- degree[i] += w
- }
- }
-
- // Main Louvain loop
- maxIter := 10
- for iter := 0; iter < maxIter; iter++ {
- improved := louvainLocalMoving(n, adj, weight, degree, community, totalWeight, resolution)
- louvainRefine(n, adj, weight, degree, community, totalWeight, resolution)
-
- if !improved {
- break
- }
- }
-
- // Map back to original IDs
- result := make(map[int64]int, n)
- for i, id := range nodes {
- result[id] = community[i]
- }
- return result
-}
-
-// louvainLocalMoving greedily moves each node to the community that maximizes modularity gain.
-// Returns true if any node was moved.
-func louvainLocalMoving(n int, adj [][]int, weight [][]float64, degree []float64, community []int, totalWeight, resolution float64) bool {
- improved := false
-
- // Community total degree
- commDegree := make(map[int]float64)
- for i := 0; i < n; i++ {
- commDegree[community[i]] += degree[i]
- }
-
- // Random order for convergence stability
- order := make([]int, n)
- for i := range order {
- order[i] = i
- }
- rand.Shuffle(n, func(i, j int) { order[i], order[j] = order[j], order[i] })
-
- for _, i := range order {
- curComm := community[i]
-
- // Compute weights to each neighboring community
- neighborComm := map[int]float64{}
- for j, neighbor := range adj[i] {
- nc := community[neighbor]
- neighborComm[nc] += weight[i][j]
- }
-
- // Remove node from its community
- commDegree[curComm] -= degree[i]
-
- bestComm := curComm
- bestGain := 0.0
-
- for comm, wIn := range neighborComm {
- // Modularity gain formula
- gain := wIn - resolution*degree[i]*commDegree[comm]/(2*totalWeight)
- if gain > bestGain {
- bestGain = gain
- bestComm = comm
- }
- }
-
- // Also consider staying in current community
- wInCur := neighborComm[curComm]
- curGain := wInCur - resolution*degree[i]*commDegree[curComm]/(2*totalWeight)
- if curGain >= bestGain {
- bestComm = curComm
- }
-
- community[i] = bestComm
- commDegree[bestComm] += degree[i]
-
- if bestComm != curComm {
- improved = true
- }
- }
-
- return improved
-}
-
-// louvainRefine checks each community for well-connectedness and potentially splits
-// poorly-connected ones.
-func louvainRefine(n int, adj [][]int, weight [][]float64, degree []float64, community []int, totalWeight, resolution float64) {
- commMembers := map[int][]int{}
- for i := 0; i < n; i++ {
- commMembers[community[i]] = append(commMembers[community[i]], i)
- }
- for _, members := range commMembers {
- if len(members) <= 2 {
- continue
- }
- refineCommunity(members, adj, weight, degree, community, n, totalWeight, resolution)
- }
-}
-
-// refineCommunity checks one community for well-connectedness and splits if density is too low.
-func refineCommunity(members []int, adj [][]int, weight [][]float64, degree []float64, community []int, n int, totalWeight, resolution float64) {
- memberSet := map[int]bool{}
- for _, m := range members {
- memberSet[m] = true
- }
-
- var internalWeight float64
- for _, m := range members {
- for j, neighbor := range adj[m] {
- if memberSet[neighbor] {
- internalWeight += weight[m][j]
- }
- }
- }
- internalWeight /= 2 // each edge counted twice
-
- maxInternal := float64(len(members)*(len(members)-1)) / 2
- if maxInternal == 0 {
- return
- }
- density := internalWeight / maxInternal
- if density >= 0.01 || len(members) <= 5 {
- return
- }
-
- nextComm := maxCommunity(community, n) + 1
- for _, m := range members {
- var wInternal float64
- for j, neighbor := range adj[m] {
- if memberSet[neighbor] {
- wInternal += weight[m][j]
- }
- }
- expectedInternal := resolution * degree[m] * (internalWeight * 2 / totalWeight)
- if wInternal < expectedInternal*0.5 {
- community[m] = nextComm
- nextComm++
- }
- }
-}
-
-func maxCommunity(community []int, n int) int {
- maxVal := 0
- for i := 0; i < n; i++ {
- if community[i] > maxVal {
- maxVal = community[i]
- }
- }
- return maxVal
-}
diff --git a/internal/store/migrate.go b/internal/store/migrate.go
deleted file mode 100644
index ae7698da8..000000000
--- a/internal/store/migrate.go
+++ /dev/null
@@ -1,188 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "io"
- "log/slog"
- "os"
- "path/filepath"
-
- _ "github.com/mattn/go-sqlite3"
-)
-
-// migrate performs a one-time migration from the legacy single-DB layout
-// (codebase-memory.db) to per-project .db files.
-// Safe to call multiple times — it's a no-op if the legacy DB doesn't exist
-// or has already been migrated.
-func (r *StoreRouter) migrate() error {
- legacyPath := filepath.Join(r.dir, "codebase-memory.db")
- if _, err := os.Stat(legacyPath); os.IsNotExist(err) {
- return nil // nothing to migrate
- }
-
- slog.Info("migrate.start", "legacy_db", legacyPath)
-
- // Backup the legacy DB before any modification
- backupPath := legacyPath + ".backup"
- if _, err := os.Stat(backupPath); os.IsNotExist(err) {
- if err := copyFile(legacyPath, backupPath); err != nil {
- return fmt.Errorf("backup: %w", err)
- }
- slog.Info("migrate.backup", "path", backupPath)
- }
-
- // Open legacy DB
- legacyDB, err := sql.Open("sqlite3", legacyPath+"?_journal_mode=WAL&_busy_timeout=5000")
- if err != nil {
- return fmt.Errorf("open legacy: %w", err)
- }
- defer legacyDB.Close()
-
- // Get list of projects
- ctx := context.Background()
- rows, err := legacyDB.QueryContext(ctx, "SELECT name FROM projects")
- if err != nil {
- return fmt.Errorf("list projects: %w", err)
- }
- defer rows.Close()
-
- var projectNames []string
- for rows.Next() {
- var name string
- if err := rows.Scan(&name); err != nil {
- return fmt.Errorf("scan project: %w", err)
- }
- projectNames = append(projectNames, name)
- }
- if err := rows.Err(); err != nil {
- return fmt.Errorf("rows iteration: %w", err)
- }
-
- if len(projectNames) == 0 {
- slog.Info("migrate.skip", "reason", "no_projects")
- return r.renameLegacy(legacyPath)
- }
-
- // Migrate each project
- migrated := 0
- for _, name := range projectNames {
- targetPath := filepath.Join(r.dir, name+".db")
- if _, err := os.Stat(targetPath); err == nil {
- slog.Info("migrate.project.exists", "project", name)
- migrated++
- continue
- }
-
- if err := r.migrateProject(legacyDB, name, targetPath); err != nil {
- slog.Warn("migrate.project.err", "project", name, "err", err)
- continue // skip failed projects, user can re-index
- }
- migrated++
- }
-
- slog.Info("migrate.done", "total", len(projectNames), "migrated", migrated)
- return r.renameLegacy(legacyPath)
-}
-
-// migrateProject copies one project's data from the legacy DB into a new per-project DB.
-func (r *StoreRouter) migrateProject(legacyDB *sql.DB, projectName, targetPath string) error {
- // Create the target DB with schema
- targetStore, err := OpenPath(targetPath)
- if err != nil {
- return fmt.Errorf("open target: %w", err)
- }
- targetStore.Close()
-
- // Use ATTACH DATABASE for efficient bulk copy
- ctx := context.Background()
- _, err = legacyDB.ExecContext(ctx, "ATTACH DATABASE ? AS target", targetPath)
- if err != nil {
- return fmt.Errorf("attach: %w", err)
- }
- defer func() {
- _, _ = legacyDB.ExecContext(ctx, "DETACH DATABASE target")
- }()
-
- // Copy projects
- _, err = legacyDB.ExecContext(ctx, `INSERT OR REPLACE INTO target.projects (name, indexed_at, root_path)
- SELECT name, indexed_at, root_path FROM projects WHERE name=?`, projectName)
- if err != nil {
- return fmt.Errorf("copy projects: %w", err)
- }
-
- // Copy nodes (preserving IDs)
- _, err = legacyDB.ExecContext(ctx, `INSERT OR REPLACE INTO target.nodes (id, project, label, name, qualified_name, file_path, start_line, end_line, properties)
- SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties FROM nodes WHERE project=?`, projectName)
- if err != nil {
- return fmt.Errorf("copy nodes: %w", err)
- }
-
- // Copy edges (preserving IDs)
- _, err = legacyDB.ExecContext(ctx, `INSERT OR REPLACE INTO target.edges (id, project, source_id, target_id, type, properties)
- SELECT id, project, source_id, target_id, type, properties FROM edges WHERE project=?`, projectName)
- if err != nil {
- return fmt.Errorf("copy edges: %w", err)
- }
-
- // Copy file_hashes
- _, err = legacyDB.ExecContext(ctx, `INSERT OR REPLACE INTO target.file_hashes (project, rel_path, sha256)
- SELECT project, rel_path, sha256 FROM file_hashes WHERE project=?`, projectName)
- if err != nil {
- return fmt.Errorf("copy file_hashes: %w", err)
- }
-
- // Verify row counts
- var srcNodes, tgtNodes int
- _ = legacyDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM nodes WHERE project=?", projectName).Scan(&srcNodes)
- _ = legacyDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM target.nodes WHERE project=?", projectName).Scan(&tgtNodes)
- if srcNodes != tgtNodes {
- return fmt.Errorf("node count mismatch: src=%d tgt=%d", srcNodes, tgtNodes)
- }
-
- var srcEdges, tgtEdges int
- _ = legacyDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM edges WHERE project=?", projectName).Scan(&srcEdges)
- _ = legacyDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM target.edges WHERE project=?", projectName).Scan(&tgtEdges)
- if srcEdges != tgtEdges {
- return fmt.Errorf("edge count mismatch: src=%d tgt=%d", srcEdges, tgtEdges)
- }
-
- slog.Info("migrate.project.ok", "project", projectName, "nodes", srcNodes, "edges", srcEdges)
- return nil
-}
-
-// renameLegacy renames the legacy DB to mark migration as complete.
-func (r *StoreRouter) renameLegacy(legacyPath string) error {
- migratedPath := legacyPath + ".migrated"
- if err := os.Rename(legacyPath, migratedPath); err != nil {
- return fmt.Errorf("rename legacy: %w", err)
- }
- // Also clean up WAL/SHM files
- for _, suffix := range []string{"-wal", "-shm"} {
- _ = os.Remove(legacyPath + suffix)
- }
- slog.Info("migrate.renamed", "from", legacyPath, "to", migratedPath)
- return nil
-}
-
-// copyFile copies a file from src to dst.
-func copyFile(src, dst string) error {
- in, err := os.Open(src)
- if err != nil {
- return err
- }
- defer in.Close()
-
- out, err := os.Create(dst)
- if err != nil {
- return err
- }
- defer out.Close()
-
- _, err = io.Copy(out, in)
- if err != nil {
- return err
- }
- return out.Sync()
-}
diff --git a/internal/store/nodes.go b/internal/store/nodes.go
deleted file mode 100644
index 6bf512d4b..000000000
--- a/internal/store/nodes.go
+++ /dev/null
@@ -1,347 +0,0 @@
-package store
-
-import (
- "database/sql"
- "fmt"
- "strings"
-)
-
-// UpsertNode inserts or replaces a node (dedup by qualified_name).
-// Note: LastInsertId() can return stale IDs for ON CONFLICT DO UPDATE,
-// causing occasional FK failures in downstream edge inserts. This is
-// accepted for performance — the fallback SELECT only runs when id==0.
-func (s *Store) UpsertNode(n *Node) (int64, error) {
- res, err := s.q.Exec(`
- INSERT INTO nodes (project, label, name, qualified_name, file_path, start_line, end_line, properties)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(project, qualified_name) DO UPDATE SET
- label=excluded.label, name=excluded.name, file_path=excluded.file_path,
- start_line=excluded.start_line, end_line=excluded.end_line, properties=excluded.properties`,
- n.Project, n.Label, n.Name, n.QualifiedName, n.FilePath, n.StartLine, n.EndLine, marshalProps(n.Properties))
- if err != nil {
- return 0, fmt.Errorf("upsert node: %w", err)
- }
- id, err := res.LastInsertId()
- if err != nil {
- return 0, err
- }
- // On conflict, LastInsertId may return 0; query the actual id
- if id == 0 {
- err = s.q.QueryRow("SELECT id FROM nodes WHERE project=? AND qualified_name=?", n.Project, n.QualifiedName).Scan(&id)
- if err != nil {
- return 0, fmt.Errorf("get node id: %w", err)
- }
- }
- return id, nil
-}
-
-// FindNodeByID finds a node by its primary key ID.
-func (s *Store) FindNodeByID(id int64) (*Node, error) {
- row := s.q.QueryRow(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE id=?`, id)
- return scanNode(row)
-}
-
-// FindNodeByQN finds a node by project and qualified name.
-func (s *Store) FindNodeByQN(project, qualifiedName string) (*Node, error) {
- row := s.q.QueryRow(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=? AND qualified_name=?`, project, qualifiedName)
- return scanNode(row)
-}
-
-// FindNodesByName finds nodes by project and name.
-func (s *Store) FindNodesByName(project, name string) ([]*Node, error) {
- rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=? AND name=?`, project, name)
- if err != nil {
- return nil, fmt.Errorf("find by name: %w", err)
- }
- defer rows.Close()
- return scanNodes(rows)
-}
-
-// FindNodesByQNSuffix finds nodes whose qualified_name ends with "."+suffix.
-// Matches at QN segment boundaries to prevent partial word matches.
-func (s *Store) FindNodesByQNSuffix(project, suffix string) ([]*Node, error) {
- rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=? AND qualified_name LIKE ?`,
- project, "%."+suffix)
- if err != nil {
- return nil, fmt.Errorf("find by qn suffix: %w", err)
- }
- defer rows.Close()
- return scanNodes(rows)
-}
-
-// FindNodesByLabel finds all nodes with a given label in a project.
-func (s *Store) FindNodesByLabel(project, label string) ([]*Node, error) {
- rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=? AND label=?`, project, label)
- if err != nil {
- return nil, fmt.Errorf("find by label: %w", err)
- }
- defer rows.Close()
- return scanNodes(rows)
-}
-
-// FindNodesByFile finds all nodes in a given file.
-func (s *Store) FindNodesByFile(project, filePath string) ([]*Node, error) {
- rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=? AND file_path=?`, project, filePath)
- if err != nil {
- return nil, fmt.Errorf("find by file: %w", err)
- }
- defer rows.Close()
- return scanNodes(rows)
-}
-
-// CountNodes returns the number of nodes in a project.
-func (s *Store) CountNodes(project string) (int, error) {
- var count int
- err := s.q.QueryRow("SELECT COUNT(*) FROM nodes WHERE project=?", project).Scan(&count)
- return count, err
-}
-
-// DeleteNodesByProject deletes all nodes for a project.
-func (s *Store) DeleteNodesByProject(project string) error {
- _, err := s.q.Exec("DELETE FROM nodes WHERE project=?", project)
- return err
-}
-
-// DeleteNodesByFile deletes all nodes for a specific file in a project.
-func (s *Store) DeleteNodesByFile(project, filePath string) error {
- _, err := s.q.Exec("DELETE FROM nodes WHERE project=? AND file_path=?", project, filePath)
- return err
-}
-
-// DeleteNodesByLabel deletes all nodes with a given label in a project.
-func (s *Store) DeleteNodesByLabel(project, label string) error {
- _, err := s.q.Exec("DELETE FROM nodes WHERE project=? AND label=?", project, label)
- return err
-}
-
-// FindNodesByIDs returns a map of nodeID → *Node for the given IDs.
-func (s *Store) FindNodesByIDs(ids []int64) (map[int64]*Node, error) {
- if len(ids) == 0 {
- return map[int64]*Node{}, nil
- }
- result := make(map[int64]*Node, len(ids))
- const batchSize = 998 // leave room under 999 limit
-
- for i := 0; i < len(ids); i += batchSize {
- end := i + batchSize
- if end > len(ids) {
- end = len(ids)
- }
- chunk := ids[i:end]
-
- placeholders := make([]string, len(chunk))
- args := make([]any, len(chunk))
- for j, id := range chunk {
- placeholders[j] = "?"
- args[j] = id
- }
-
- query := fmt.Sprintf(
- "SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties FROM nodes WHERE id IN (%s)",
- strings.Join(placeholders, ","))
-
- if err := func() error {
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return fmt.Errorf("find nodes by ids: %w", err)
- }
- defer rows.Close()
- nodes, err := scanNodes(rows)
- if err != nil {
- return err
- }
- for _, n := range nodes {
- result[n.ID] = n
- }
- return nil
- }(); err != nil {
- return nil, err
- }
- }
- return result, nil
-}
-
-// FindNodesByFileOverlap returns nodes whose line range overlaps [startLine, endLine].
-// The fileSuffix is matched with LIKE '%' || ? against the file_path column to handle
-// relative/absolute path differences.
-func (s *Store) FindNodesByFileOverlap(project, fileSuffix string, startLine, endLine int) ([]*Node, error) {
- rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=? AND file_path LIKE '%' || ? AND start_line <= ? AND end_line >= ?
- AND label NOT IN ('Project', 'Package', 'Folder', 'File', 'Module')`,
- project, fileSuffix, endLine, startLine)
- if err != nil {
- return nil, fmt.Errorf("find by file overlap: %w", err)
- }
- defer rows.Close()
- return scanNodes(rows)
-}
-
-// AllNodes returns all nodes for a project.
-func (s *Store) AllNodes(project string) ([]*Node, error) {
- rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
- FROM nodes WHERE project=?`, project)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- return scanNodes(rows)
-}
-
-type scanner interface {
- Scan(dest ...any) error
-}
-
-func scanNode(row scanner) (*Node, error) {
- var n Node
- var props string
- err := row.Scan(&n.ID, &n.Project, &n.Label, &n.Name, &n.QualifiedName, &n.FilePath, &n.StartLine, &n.EndLine, &props)
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
- }
- return nil, err
- }
- n.Properties = unmarshalProps(props)
- return &n, nil
-}
-
-func scanNodes(rows *sql.Rows) ([]*Node, error) {
- var result []*Node
- for rows.Next() {
- var n Node
- var props string
- if err := rows.Scan(&n.ID, &n.Project, &n.Label, &n.Name, &n.QualifiedName, &n.FilePath, &n.StartLine, &n.EndLine, &props); err != nil {
- return nil, err
- }
- n.Properties = unmarshalProps(props)
- result = append(result, &n)
- }
- return result, rows.Err()
-}
-
-// Formula-derived batch size: SQLite has a 999 bind variable limit.
-const numNodeCols = 8
-const nodesBatchSize = 999 / numNodeCols // = 124
-
-// UpsertNodeBatch inserts or updates multiple nodes in batched multi-row INSERTs.
-// Returns a map of qualifiedName → ID for all upserted nodes.
-func (s *Store) UpsertNodeBatch(nodes []*Node) (map[string]int64, error) {
- if len(nodes) == 0 {
- return map[string]int64{}, nil
- }
-
- result := make(map[string]int64, len(nodes))
-
- for i := 0; i < len(nodes); i += nodesBatchSize {
- end := i + nodesBatchSize
- if end > len(nodes) {
- end = len(nodes)
- }
- batch := nodes[i:end]
-
- if err := s.upsertNodeChunk(batch, result); err != nil {
- return nil, err
- }
- }
- return result, nil
-}
-
-func (s *Store) upsertNodeChunk(batch []*Node, idMap map[string]int64) error {
- // Build multi-row INSERT
- var sb strings.Builder
- sb.WriteString(`INSERT INTO nodes (project, label, name, qualified_name, file_path, start_line, end_line, properties) VALUES `)
-
- args := make([]any, 0, len(batch)*8)
- for i, n := range batch {
- if i > 0 {
- sb.WriteByte(',')
- }
- sb.WriteString("(?,?,?,?,?,?,?,?)")
- args = append(args, n.Project, n.Label, n.Name, n.QualifiedName, n.FilePath, n.StartLine, n.EndLine, marshalProps(n.Properties))
- }
- sb.WriteString(` ON CONFLICT(project, qualified_name) DO UPDATE SET
- label=excluded.label, name=excluded.name, file_path=excluded.file_path,
- start_line=excluded.start_line, end_line=excluded.end_line, properties=excluded.properties`)
-
- if _, err := s.q.Exec(sb.String(), args...); err != nil {
- return fmt.Errorf("upsert node batch: %w", err)
- }
-
- // Recover IDs via SELECT ... IN (...)
- // Group by project since the UNIQUE constraint is (project, qualified_name)
- byProject := make(map[string][]string)
- for _, n := range batch {
- byProject[n.Project] = append(byProject[n.Project], n.QualifiedName)
- }
-
- for project, qns := range byProject {
- if err := s.resolveNodeIDs(project, qns, idMap); err != nil {
- return err
- }
- }
- return nil
-}
-
-// resolveNodeIDs fetches IDs for a set of qualified names in a single project.
-// Respects the 999-var limit by batching the IN clause.
-func (s *Store) resolveNodeIDs(project string, qns []string, idMap map[string]int64) error {
- // 1 var for project + N vars for QNs; batch to stay under 999
- const maxQNsPerQuery = 998
-
- for i := 0; i < len(qns); i += maxQNsPerQuery {
- end := i + maxQNsPerQuery
- if end > len(qns) {
- end = len(qns)
- }
- chunk := qns[i:end]
-
- placeholders := make([]string, len(chunk))
- args := make([]any, 0, len(chunk)+1)
- args = append(args, project)
- for j, qn := range chunk {
- placeholders[j] = "?"
- args = append(args, qn)
- }
-
- query := fmt.Sprintf("SELECT id, qualified_name FROM nodes WHERE project = ? AND qualified_name IN (%s)",
- strings.Join(placeholders, ","))
-
- if err := func() error {
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return fmt.Errorf("resolve node IDs: %w", err)
- }
- 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
- }
- }
- return nil
-}
-
-// FindNodeIDsByQNs returns a map of qualifiedName → ID for the given QNs in a project.
-func (s *Store) FindNodeIDsByQNs(project string, qns []string) (map[string]int64, error) {
- if len(qns) == 0 {
- return map[string]int64{}, nil
- }
- idMap := make(map[string]int64, len(qns))
- if err := s.resolveNodeIDs(project, qns, idMap); err != nil {
- return nil, err
- }
- return idMap, nil
-}
diff --git a/internal/store/projects.go b/internal/store/projects.go
deleted file mode 100644
index 0f344d4c5..000000000
--- a/internal/store/projects.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package store
-
-import (
- "fmt"
- "strings"
-)
-
-// Project represents an indexed project.
-type Project struct {
- Name string
- IndexedAt string
- RootPath string
-}
-
-// UpsertProject creates or updates a project record.
-func (s *Store) UpsertProject(name, rootPath string) error {
- _, err := s.q.Exec(`
- INSERT INTO projects (name, indexed_at, root_path) VALUES (?, ?, ?)
- ON CONFLICT(name) DO UPDATE SET indexed_at=excluded.indexed_at, root_path=excluded.root_path`,
- name, Now(), rootPath)
- return err
-}
-
-// GetProject returns a project by name.
-func (s *Store) GetProject(name string) (*Project, error) {
- var p Project
- err := s.q.QueryRow("SELECT name, indexed_at, root_path FROM projects WHERE name=?", name).
- Scan(&p.Name, &p.IndexedAt, &p.RootPath)
- if err != nil {
- return nil, err
- }
- return &p, nil
-}
-
-// ListProjects returns all indexed projects.
-func (s *Store) ListProjects() ([]*Project, error) {
- rows, err := s.q.Query("SELECT name, indexed_at, root_path FROM projects ORDER BY name")
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- var result []*Project
- for rows.Next() {
- var p Project
- if err := rows.Scan(&p.Name, &p.IndexedAt, &p.RootPath); err != nil {
- return nil, err
- }
- result = append(result, &p)
- }
- return result, rows.Err()
-}
-
-// DeleteProject deletes a project and all associated data (CASCADE).
-func (s *Store) DeleteProject(name string) error {
- _, err := s.q.Exec("DELETE FROM projects WHERE name=?", name)
- return err
-}
-
-// FileHash represents a stored file content hash with stat metadata for incremental reindex.
-type FileHash struct {
- Project string
- RelPath string
- SHA256 string
- MtimeNs int64 // file mtime in nanoseconds (for stat pre-filter)
- Size int64 // file size in bytes (for stat pre-filter)
-}
-
-// UpsertFileHash stores a file's content hash with stat metadata.
-func (s *Store) UpsertFileHash(project, relPath, sha256 string, mtimeNs, size int64) error {
- _, err := s.q.Exec(`
- INSERT INTO file_hashes (project, rel_path, sha256, mtime_ns, size) VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(project, rel_path) DO UPDATE SET sha256=excluded.sha256, mtime_ns=excluded.mtime_ns, size=excluded.size`,
- project, relPath, sha256, mtimeNs, size)
- return err
-}
-
-// GetFileHashes returns all file hashes with stat metadata for a project.
-func (s *Store) GetFileHashes(project string) (map[string]FileHash, error) {
- rows, err := s.q.Query("SELECT rel_path, sha256, mtime_ns, size FROM file_hashes WHERE project=?", project)
- if err != nil {
- return nil, fmt.Errorf("get file hashes: %w", err)
- }
- defer rows.Close()
- result := make(map[string]FileHash)
- for rows.Next() {
- var fh FileHash
- if err := rows.Scan(&fh.RelPath, &fh.SHA256, &fh.MtimeNs, &fh.Size); err != nil {
- return nil, err
- }
- result[fh.RelPath] = fh
- }
- return result, rows.Err()
-}
-
-// ListFilesForProject returns all distinct file paths indexed for a project.
-func (s *Store) ListFilesForProject(project string) ([]string, error) {
- rows, err := s.q.Query("SELECT DISTINCT file_path FROM nodes WHERE project=? AND file_path != ''", project)
- if err != nil {
- return nil, fmt.Errorf("list files: %w", err)
- }
- defer rows.Close()
- var result []string
- for rows.Next() {
- var path string
- if err := rows.Scan(&path); err != nil {
- return nil, err
- }
- result = append(result, path)
- }
- return result, rows.Err()
-}
-
-// fileHashBatchSize is the max rows per batch INSERT for file hashes (5 cols × 190 = 950 vars < 999).
-const fileHashBatchSize = 190
-
-// UpsertFileHashBatch inserts or updates multiple file hashes in batched multi-row INSERTs.
-func (s *Store) UpsertFileHashBatch(hashes []FileHash) error {
- if len(hashes) == 0 {
- return nil
- }
-
- for i := 0; i < len(hashes); i += fileHashBatchSize {
- end := i + fileHashBatchSize
- if end > len(hashes) {
- end = len(hashes)
- }
- if err := s.upsertFileHashChunk(hashes[i:end]); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *Store) upsertFileHashChunk(batch []FileHash) error {
- var sb strings.Builder
- sb.WriteString(`INSERT INTO file_hashes (project, rel_path, sha256, mtime_ns, size) VALUES `)
-
- args := make([]any, 0, len(batch)*5)
- for i, h := range batch {
- if i > 0 {
- sb.WriteByte(',')
- }
- sb.WriteString("(?,?,?,?,?)")
- args = append(args, h.Project, h.RelPath, h.SHA256, h.MtimeNs, h.Size)
- }
- sb.WriteString(` ON CONFLICT(project, rel_path) DO UPDATE SET sha256=excluded.sha256, mtime_ns=excluded.mtime_ns, size=excluded.size`)
-
- if _, err := s.q.Exec(sb.String(), args...); err != nil {
- return fmt.Errorf("upsert file hash batch: %w", err)
- }
- return nil
-}
-
-// DeleteFileHash deletes a single file hash entry.
-func (s *Store) DeleteFileHash(project, relPath string) error {
- _, err := s.q.Exec("DELETE FROM file_hashes WHERE project=? AND rel_path=?", project, relPath)
- return err
-}
-
-// DeleteFileHashes deletes all file hashes for a project.
-func (s *Store) DeleteFileHashes(project string) error {
- _, err := s.q.Exec("DELETE FROM file_hashes WHERE project=?", project)
- return err
-}
diff --git a/internal/store/router.go b/internal/store/router.go
deleted file mode 100644
index 881aeed48..000000000
--- a/internal/store/router.go
+++ /dev/null
@@ -1,324 +0,0 @@
-package store
-
-import (
- "context"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-)
-
-// ProjectInfo holds metadata about a discovered project database.
-type ProjectInfo struct {
- Name string
- DBPath string
- RootPath string
-}
-
-// storeEntry wraps a Store with idle-tracking and reference counting.
-type storeEntry struct {
- store *Store
- lastUsed time.Time
- refs atomic.Int32 // eviction blocked while >0
-}
-
-// ReleaseFunc must be called when the caller is done with the store.
-type ReleaseFunc func()
-
-// StoreRouter manages per-project SQLite databases.
-// Each project gets its own .db file in the cache directory.
-// Idle stores are evicted after idleTimeout (configurable) to free memory.
-type StoreRouter struct {
- dir string // ~/.cache/codebase-memory-mcp/
- entries map[string]*storeEntry // project name → entry (lazy)
- mu sync.Mutex
- idleTimeout time.Duration
- onDelete func(name string) // optional callback on project deletion
-}
-
-const defaultIdleTimeout = 30 * time.Second
-
-// NewRouter creates a StoreRouter, ensuring the cache directory exists.
-// Runs migration from single-DB layout if needed.
-func NewRouter() (*StoreRouter, error) {
- dir, err := cacheDir()
- if err != nil {
- return nil, err
- }
-
- r := &StoreRouter{
- dir: dir,
- entries: make(map[string]*storeEntry),
- idleTimeout: defaultIdleTimeout,
- }
-
- // Run one-time migration from single DB to per-project DBs
- if err := r.migrate(); err != nil {
- slog.Warn("router.migrate.err", "err", err)
- }
-
- return r, nil
-}
-
-// NewRouterWithDir creates a StoreRouter using a custom directory (for testing).
-// No migration is run.
-func NewRouterWithDir(dir string) (*StoreRouter, error) {
- if err := os.MkdirAll(dir, 0o750); err != nil {
- return nil, fmt.Errorf("mkdir: %w", err)
- }
- return &StoreRouter{
- dir: dir,
- entries: make(map[string]*storeEntry),
- idleTimeout: defaultIdleTimeout,
- }, nil
-}
-
-// OnDelete registers a callback invoked after a project is deleted.
-func (r *StoreRouter) OnDelete(fn func(name string)) {
- r.onDelete = fn
-}
-
-// ForProject returns the Store for the given project, opening it lazily.
-// Updates lastUsed and increments the ref count. Callers SHOULD use
-// UseStore or AcquireStore instead for automatic ref management.
-func (r *StoreRouter) ForProject(name string) (*Store, error) {
- if name == "*" || name == "all" {
- return nil, fmt.Errorf("invalid project name: %q", name)
- }
- r.mu.Lock()
- defer r.mu.Unlock()
-
- return r.getOrOpenLocked(name)
-}
-
-// getOrOpenLocked returns the store, opening it if needed. Must hold r.mu.
-func (r *StoreRouter) getOrOpenLocked(name string) (*Store, error) {
- if e, ok := r.entries[name]; ok {
- e.lastUsed = time.Now()
- return e.store, nil
- }
-
- s, err := OpenInDir(r.dir, name)
- if err != nil {
- return nil, fmt.Errorf("open store %q: %w", name, err)
- }
- r.entries[name] = &storeEntry{
- store: s,
- lastUsed: time.Now(),
- }
- return s, nil
-}
-
-// UseStore opens the store for project, calls fn, then releases. Handles ref counting.
-func (r *StoreRouter) UseStore(project string, fn func(*Store) error) error {
- st, release, err := r.AcquireStore(project)
- if err != nil {
- return err
- }
- defer release()
- return fn(st)
-}
-
-// AcquireStore returns a store with an incremented ref count plus a release function.
-// The evictor will not close the store while refs > 0.
-func (r *StoreRouter) AcquireStore(project string) (*Store, ReleaseFunc, error) {
- if project == "*" || project == "all" {
- return nil, nil, fmt.Errorf("invalid project name: %q", project)
- }
- r.mu.Lock()
- defer r.mu.Unlock()
-
- st, err := r.getOrOpenLocked(project)
- if err != nil {
- return nil, nil, err
- }
-
- e := r.entries[project]
- e.refs.Add(1)
-
- released := false
- return st, func() {
- if !released {
- released = true
- e.refs.Add(-1)
- }
- }, nil
-}
-
-// AllStores opens all .db files in the cache dir and returns a name→Store map.
-func (r *StoreRouter) AllStores() map[string]*Store {
- r.mu.Lock()
- defer r.mu.Unlock()
-
- entries, err := os.ReadDir(r.dir)
- if err != nil {
- slog.Warn("router.all_stores.readdir", "err", err)
- result := make(map[string]*Store, len(r.entries))
- for k, v := range r.entries {
- result[k] = v.store
- }
- return result
- }
-
- for _, e := range entries {
- if e.IsDir() || !strings.HasSuffix(e.Name(), ".db") {
- continue
- }
- name := strings.TrimSuffix(e.Name(), ".db")
- if name == "codebase-memory" {
- continue // skip legacy single DB
- }
- if _, ok := r.entries[name]; ok {
- continue
- }
- s, err := OpenInDir(r.dir, name)
- if err != nil {
- slog.Warn("router.all_stores.open", "project", name, "err", err)
- continue
- }
- r.entries[name] = &storeEntry{
- store: s,
- lastUsed: time.Now(),
- }
- }
-
- result := make(map[string]*Store, len(r.entries))
- for k, v := range r.entries {
- result[k] = v.store
- }
- return result
-}
-
-// ListProjects scans .db files and queries each for metadata.
-// Uses AcquireStore to prevent the evictor from closing stores mid-query.
-// Individual DB failures are logged and skipped (never block the full list).
-func (r *StoreRouter) ListProjects() ([]*ProjectInfo, error) {
- entries, err := os.ReadDir(r.dir)
- if err != nil {
- return nil, fmt.Errorf("readdir: %w", err)
- }
-
- result := make([]*ProjectInfo, 0, len(entries))
- for _, e := range entries {
- if e.IsDir() || !strings.HasSuffix(e.Name(), ".db") {
- continue
- }
- name := strings.TrimSuffix(e.Name(), ".db")
- if name == "codebase-memory" {
- continue // skip legacy single DB
- }
- info := &ProjectInfo{
- Name: name,
- DBPath: filepath.Join(r.dir, e.Name()),
- }
-
- // Try to get root_path from the projects table.
- // AcquireStore increments refs so the evictor can't close mid-query.
- s, release, acqErr := r.AcquireStore(name)
- if acqErr == nil {
- projects, listErr := s.ListProjects()
- release()
- if listErr == nil && len(projects) > 0 {
- info.RootPath = projects[0].RootPath
- }
- }
-
- result = append(result, info)
- }
- return result, nil
-}
-
-// DeleteProject closes the Store connection and removes the .db + WAL/SHM files.
-func (r *StoreRouter) DeleteProject(name string) error {
- r.mu.Lock()
- if e, ok := r.entries[name]; ok {
- e.store.Close()
- delete(r.entries, name)
- }
- r.mu.Unlock()
-
- dbPath := filepath.Join(r.dir, name+".db")
- for _, suffix := range []string{"", "-wal", "-shm"} {
- p := dbPath + suffix
- if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
- return fmt.Errorf("remove %s: %w", p, err)
- }
- }
- slog.Info("router.delete", "project", name)
-
- if r.onDelete != nil {
- r.onDelete(name)
- }
- return nil
-}
-
-// HasProject checks if a .db file exists for the given project (without opening it).
-func (r *StoreRouter) HasProject(name string) bool {
- dbPath := filepath.Join(r.dir, name+".db")
- _, err := os.Stat(dbPath)
- return err == nil
-}
-
-// Dir returns the cache directory path.
-func (r *StoreRouter) Dir() string {
- return r.dir
-}
-
-// CloseAll closes all open Store connections.
-func (r *StoreRouter) CloseAll() {
- r.mu.Lock()
- defer r.mu.Unlock()
-
- for name, e := range r.entries {
- if err := e.store.Close(); err != nil {
- slog.Warn("router.close", "project", name, "err", err)
- }
- }
- r.entries = make(map[string]*storeEntry)
-}
-
-// StartEvictor runs a background goroutine that closes idle stores.
-// Ticks every 5 seconds. Evicts stores idle for > idleTimeout with refs == 0.
-// Exits when ctx is cancelled.
-func (r *StoreRouter) StartEvictor(ctx context.Context) {
- go func() {
- ticker := time.NewTicker(5 * time.Second)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- r.evictIdle()
- }
- }
- }()
-}
-
-// evictIdle closes stores that have been idle longer than idleTimeout and have no refs.
-func (r *StoreRouter) evictIdle() {
- r.mu.Lock()
- defer r.mu.Unlock()
-
- now := time.Now()
- for name, e := range r.entries {
- idle := now.Sub(e.lastUsed)
- if idle <= r.idleTimeout {
- continue
- }
- if e.refs.Load() > 0 {
- continue // in use — skip
- }
- e.store.Checkpoint(context.Background())
- if err := e.store.Close(); err != nil {
- slog.Warn("store.evict.close", "project", name, "err", err)
- }
- delete(r.entries, name)
- slog.Info("store.evict", "project", name, "idle_s", int(idle.Seconds()))
- }
-}
diff --git a/internal/store/schema.go b/internal/store/schema.go
deleted file mode 100644
index 368df7018..000000000
--- a/internal/store/schema.go
+++ /dev/null
@@ -1,182 +0,0 @@
-package store
-
-import (
- "fmt"
- "sort"
-)
-
-// SchemaInfo contains graph schema statistics.
-type SchemaInfo struct {
- NodeLabels []LabelCount `json:"node_labels"`
- RelationshipTypes []TypeCount `json:"relationship_types"`
- RelationshipPatterns []string `json:"relationship_patterns"`
- SampleFunctionNames []string `json:"sample_function_names"`
- SampleClassNames []string `json:"sample_class_names"`
- SampleQualifiedNames []string `json:"sample_qualified_names"`
-}
-
-// LabelCount is a label with its count.
-type LabelCount struct {
- Label string `json:"label"`
- Count int `json:"count"`
-}
-
-// TypeCount is a relationship type with its count.
-type TypeCount struct {
- Type string `json:"type"`
- Count int `json:"count"`
-}
-
-// GetSchema returns graph schema statistics for a project.
-func (s *Store) GetSchema(project string) (*SchemaInfo, error) {
- info := &SchemaInfo{}
-
- 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
- }
- labels = append(labels, lc)
- }
- return labels, rows.Err()
-}
-
-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 rows.Close()
- var types []TypeCount
- for rows.Next() {
- var tc TypeCount
- if err := rows.Scan(&tc.Type, &tc.Count); err != nil {
- return nil, err
- }
- types = append(types, tc)
- }
- return types, rows.Err()
-}
-
-// 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)
- 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)
- }
- defer rows.Close()
- for rows.Next() {
- var id int64
- var label string
- if err := rows.Scan(&id, &label); err != nil {
- return nil, err
- }
- idLabel[id] = label
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- type patternKey struct{ src, rel, tgt string }
- patternCounts := make(map[patternKey]int)
- 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)
- }
- defer rows2.Close()
- for rows2.Next() {
- var srcID, tgtID int64
- var edgeType string
- if err := rows2.Scan(&srcID, &tgtID, &edgeType); err != nil {
- return nil, err
- }
- pk := patternKey{src: idLabel[srcID], rel: edgeType, tgt: idLabel[tgtID]}
- patternCounts[pk]++
- }
- if err := rows2.Err(); err != nil {
- return nil, err
- }
-
- type patternEntry struct {
- key patternKey
- cnt int
- }
- entries := make([]patternEntry, 0, len(patternCounts))
- for k, v := range patternCounts {
- entries = append(entries, patternEntry{k, v})
- }
- sort.Slice(entries, func(i, j int) bool { return entries[i].cnt > entries[j].cnt })
- if len(entries) > 25 {
- entries = entries[:25]
- }
- patterns := make([]string, 0, len(entries))
- for _, e := range entries {
- patterns = append(patterns, fmt.Sprintf("(:%s)-[:%s]->(:%s) [%dx]", e.key.src, e.key.rel, e.key.tgt, e.cnt))
- }
- return patterns, nil
-}
-
-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 %s: %w", label, err)
- }
- defer rows.Close()
- var names []string
- for rows.Next() {
- var name string
- if err := rows.Scan(&name); err != nil {
- return nil, err
- }
- names = append(names, name)
- }
- return names, rows.Err()
-}
-
-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 rows.Close()
- var qns []string
- for rows.Next() {
- var qn string
- if err := rows.Scan(&qn); err != nil {
- return nil, err
- }
- qns = append(qns, qn)
- }
- return qns, rows.Err()
-}
diff --git a/internal/store/search.go b/internal/store/search.go
deleted file mode 100644
index a65e1be42..000000000
--- a/internal/store/search.go
+++ /dev/null
@@ -1,573 +0,0 @@
-package store
-
-import (
- "fmt"
- "regexp"
- "slices"
- "strings"
-)
-
-// SearchParams defines structured search parameters.
-type SearchParams struct {
- Project string
- Label string
- NamePattern string // regex matched against short name only
- QNPattern string // regex matched against qualified name only
- FilePattern string
- Relationship string
- Direction string // "inbound", "outbound", "any"
- MinDegree int
- MaxDegree int
- Limit int
- Offset int
- ExcludeEntryPoints bool // when true, exclude nodes with is_entry_point=true
- IncludeConnected bool // when true, load connected node names (expensive, off by default)
- ExcludeLabels []string // labels to exclude from results
- SortBy string // "relevance" (default), "name", "degree"
- CaseSensitive bool // false (zero value) = case-insensitive by default
-}
-
-// SearchResult is a node with edge degree info.
-type SearchResult struct {
- Node *Node
- InDegree int
- OutDegree int
- ConnectedNames []string
-}
-
-// SearchOutput wraps search results with total count for pagination.
-type SearchOutput struct {
- Results []*SearchResult
- Total int
-}
-
-// loadConnectedNames fetches up to 10 connected node names for display.
-func (s *Store) loadConnectedNames(sr *SearchResult, nodeID int64) {
- connRows, connErr := s.q.Query(`
- SELECT DISTINCT n2.name FROM edges e
- JOIN nodes n2 ON (e.target_id = n2.id OR e.source_id = n2.id)
- WHERE (e.source_id = ? OR e.target_id = ?) AND n2.id != ?
- LIMIT 10`, nodeID, nodeID, nodeID)
- if connErr != nil {
- return
- }
- defer connRows.Close()
- for connRows.Next() {
- var name string
- if err := connRows.Scan(&name); err != nil {
- break
- }
- sr.ConnectedNames = append(sr.ConnectedNames, name)
- }
- _ = connRows.Err()
-}
-
-// Search executes a parameterized search query with pagination support.
-func (s *Store) Search(params *SearchParams) (*SearchOutput, error) {
- if params.Limit <= 0 {
- params.Limit = 100000
- }
-
- conditions, args, nameHasLikeHints, qnHasLikeHints := buildSearchConditions(params)
- where := strings.Join(conditions, " AND ")
- sqlLimit := computeSQLLimit(params, nameHasLikeHints, qnHasLikeHints)
-
- nodes, err := s.executeSearchQuery(where, args, sqlLimit)
- if err != nil {
- return nil, err
- }
-
- nodes, err = applyPatternFilters(nodes, params)
- if err != nil {
- return nil, err
- }
-
- allResults, err := s.buildFilteredResults(nodes, params)
- if err != nil {
- return nil, err
- }
-
- sortBy := params.SortBy
- if sortBy == "" {
- sortBy = "relevance"
- }
- sortSearchResults(allResults, sortBy, params.NamePattern)
-
- return paginateResults(allResults, params.Offset, params.Limit), nil
-}
-
-// buildSearchConditions builds SQL WHERE conditions and args from search params.
-// Returns conditions, args, and whether LIKE hints were pushed for name/qn patterns.
-func buildSearchConditions(params *SearchParams) (conditions []string, args []any, nameHasLikeHints, qnHasLikeHints bool) {
- conditions = append(conditions, "n.project = ?")
- args = append(args, params.Project)
-
- if params.Label != "" {
- conditions = append(conditions, "n.label = ?")
- args = append(args, params.Label)
- }
-
- if params.FilePattern != "" {
- likePattern := globToLike(params.FilePattern)
- conditions = append(conditions, "n.file_path LIKE ?")
- args = append(args, likePattern)
- }
-
- if len(params.ExcludeLabels) > 0 {
- placeholders := make([]string, len(params.ExcludeLabels))
- for i, label := range params.ExcludeLabels {
- placeholders[i] = "?"
- args = append(args, label)
- }
- conditions = append(conditions, "n.label NOT IN ("+strings.Join(placeholders, ",")+")")
- }
-
- // When a name pattern is provided, try to extract literal substrings for SQL LIKE
- // pre-filtering. This drastically reduces the rows Go needs to regex-match.
- // The full regex is still applied in Go for correctness.
- if params.NamePattern != "" {
- if cond, condArgs := buildLikeHintCondition(params.NamePattern, "n.name", params.CaseSensitive); cond != "" {
- nameHasLikeHints = true
- conditions = append(conditions, cond)
- args = append(args, condArgs...)
- }
- }
-
- // QN pattern: same LIKE hint optimization but against qualified_name only
- if params.QNPattern != "" {
- if cond, condArgs := buildLikeHintCondition(params.QNPattern, "n.qualified_name", params.CaseSensitive); cond != "" {
- qnHasLikeHints = true
- conditions = append(conditions, cond)
- args = append(args, condArgs...)
- }
- }
-
- return conditions, args, nameHasLikeHints, qnHasLikeHints
-}
-
-// buildLikeHintCondition extracts literal substrings from a regex pattern and returns
-// a SQL condition with LIKE clauses for pre-filtering. Returns empty string if no hints.
-// When caseSensitive is false, appends COLLATE NOCASE to each LIKE clause.
-func buildLikeHintCondition(pattern, column string, caseSensitive bool) (condition string, args []any) {
- // Strip (?i) prefix before extracting hints — metacharacters confuse extractLikeHints
- cleanPattern := stripCaseFlag(pattern)
- hints := extractLikeHints(cleanPattern)
- if len(hints) == 0 {
- return "", nil
- }
- collate := ""
- if !caseSensitive {
- collate = " COLLATE NOCASE"
- }
- likeParts := make([]string, 0, len(hints))
- for _, hint := range hints {
- likeVal := "%" + hint + "%"
- likeParts = append(likeParts, column+" LIKE ?"+collate)
- args = append(args, likeVal)
- }
- return "(" + strings.Join(likeParts, " AND ") + ")", args
-}
-
-// computeSQLLimit determines how many rows to fetch from SQL based on filtering needs.
-func computeSQLLimit(params *SearchParams, nameHasLikeHints, qnHasLikeHints bool) int {
- hasDegreeFilter := params.MinDegree >= 0 || params.MaxDegree >= 0
- needsNameScan := (params.NamePattern != "" && !nameHasLikeHints) || (params.QNPattern != "" && !qnHasLikeHints)
-
- if needsNameScan || hasDegreeFilter {
- return 200000 // must cover full dataset for accurate Go-side filtering
- }
- // Scan beyond offset+limit so total/has_more are accurate.
- // The +1000 buffer ensures has_more is correct for result sets
- // up to ~1000 beyond the requested page, at negligible cost
- // (~2 extra batch degree queries ≈ 20ms worst case).
- sqlLimit := params.Offset + params.Limit + 1000
- if sqlLimit > 200000 {
- sqlLimit = 200000
- }
- return sqlLimit
-}
-
-// executeSearchQuery runs the SQL search query and returns matching nodes.
-func (s *Store) executeSearchQuery(where string, args []any, sqlLimit int) ([]*Node, error) {
- query := fmt.Sprintf(`
- SELECT n.id, n.project, n.label, n.name, n.qualified_name, n.file_path, n.start_line, n.end_line, n.properties
- FROM nodes n
- WHERE %s
- LIMIT ?`, where)
- args = append(args, sqlLimit)
-
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return nil, fmt.Errorf("search: %w", err)
- }
- defer rows.Close()
-
- var nodes []*Node
- for rows.Next() {
- var n Node
- var props string
- if err := rows.Scan(&n.ID, &n.Project, &n.Label, &n.Name, &n.QualifiedName, &n.FilePath, &n.StartLine, &n.EndLine, &props); err != nil {
- return nil, err
- }
- n.Properties = unmarshalProps(props)
- nodes = append(nodes, &n)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return nodes, nil
-}
-
-// applyPatternFilters applies name and QN regex filters in Go.
-func applyPatternFilters(nodes []*Node, params *SearchParams) ([]*Node, error) {
- var err error
- if params.NamePattern != "" {
- pattern := params.NamePattern
- if !params.CaseSensitive {
- pattern = ensureCaseInsensitive(pattern)
- }
- nodes, err = filterByNamePattern(nodes, pattern)
- if err != nil {
- return nil, err
- }
- }
- if params.QNPattern != "" {
- pattern := params.QNPattern
- if !params.CaseSensitive {
- pattern = ensureCaseInsensitive(pattern)
- }
- nodes, err = filterByQNPattern(nodes, pattern)
- if err != nil {
- return nil, err
- }
- }
- return nodes, nil
-}
-
-// paginateResults applies offset and limit to results and returns the output.
-func paginateResults(allResults []*SearchResult, offset, limit int) *SearchOutput {
- total := len(allResults)
- start := offset
- if start > total {
- start = total
- }
- end := start + limit
- if end > total {
- end = total
- }
- return &SearchOutput{
- Results: allResults[start:end],
- Total: total,
- }
-}
-
-// globToLike converts a glob pattern to SQL LIKE pattern.
-func globToLike(pattern string) string {
- // Handle **/ (zero-or-more directory prefix) and /** (zero-or-more directory suffix)
- // before single * to avoid double-replacement
- result := strings.ReplaceAll(pattern, "**/", "%")
- result = strings.ReplaceAll(result, "/**", "%")
- result = strings.ReplaceAll(result, "*", "%")
- result = strings.ReplaceAll(result, "?", "_")
- return result
-}
-
-// isEntryPoint returns true if a node has is_entry_point=true in its properties.
-func isEntryPoint(n *Node) bool {
- if n.Properties == nil {
- return false
- }
- ep, ok := n.Properties["is_entry_point"]
- if !ok {
- return false
- }
- b, ok := ep.(bool)
- return ok && b
-}
-
-// degreePair stores in-degree and out-degree for a node.
-type degreePair struct {
- InDegree int
- OutDegree int
-}
-
-// batchCountDegrees counts in/out degrees for a batch of node IDs.
-// Returns map[nodeID] → degreePair. Respects the 999-var limit.
-func (s *Store) batchCountDegrees(nodeIDs []int64, relationship string) (map[int64]degreePair, error) {
- if len(nodeIDs) == 0 {
- return map[int64]degreePair{}, nil
- }
-
- result := make(map[int64]degreePair, len(nodeIDs))
- const maxIDsPerQuery = 998
-
- for i := 0; i < len(nodeIDs); i += maxIDsPerQuery {
- end := i + maxIDsPerQuery
- if end > len(nodeIDs) {
- end = len(nodeIDs)
- }
- chunk := nodeIDs[i:end]
-
- placeholders := make([]string, len(chunk))
- inArgs := make([]any, len(chunk))
- for j, id := range chunk {
- placeholders[j] = "?"
- inArgs[j] = id
- }
- inClause := strings.Join(placeholders, ",")
-
- // Count inbound (target_id)
- var inQuery string
- 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(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
- }
-
- if err := s.scanDegrees(inQuery, inQueryArgs, result, true); err != nil {
- return nil, fmt.Errorf("batch count in-degree: %w", err)
- }
-
- // Count outbound (source_id)
- var outQuery string
- var outQueryArgs []any
- if relationship != "" {
- outQuery = fmt.Sprintf("SELECT source_id, COUNT(*) FROM edges WHERE source_id IN (%s) AND type=? GROUP BY source_id", inClause)
- outQueryArgs = append(append([]any{}, inArgs...), relationship)
- } else {
- outQuery = fmt.Sprintf("SELECT source_id, COUNT(*) FROM edges WHERE source_id IN (%s) GROUP BY source_id", inClause)
- outQueryArgs = inArgs
- }
-
- if err := s.scanDegrees(outQuery, outQueryArgs, result, false); err != nil {
- return nil, fmt.Errorf("batch count out-degree: %w", err)
- }
- }
-
- 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) {
- // Batch count degrees for all nodes at once
- nodeIDs := make([]int64, len(nodes))
- for i, n := range nodes {
- nodeIDs[i] = n.ID
- }
-
- degrees, err := s.batchCountDegrees(nodeIDs, params.Relationship)
- if err != nil {
- return nil, err
- }
-
- results := make([]*SearchResult, 0, len(nodes))
- for _, n := range nodes {
- dp := degrees[n.ID]
- sr := &SearchResult{
- Node: n,
- InDegree: dp.InDegree,
- OutDegree: dp.OutDegree,
- }
-
- degree := sr.InDegree
- if params.Direction == "outbound" {
- degree = sr.OutDegree
- }
- if params.MinDegree >= 0 && degree < params.MinDegree {
- continue
- }
- if params.MaxDegree >= 0 && degree > params.MaxDegree {
- continue
- }
-
- if params.ExcludeEntryPoints && isEntryPoint(n) {
- continue
- }
-
- if params.IncludeConnected {
- s.loadConnectedNames(sr, n.ID)
- }
- results = append(results, sr)
- }
- return results, nil
-}
-
-// extractLikeHints extracts literal substrings from a regex pattern for SQL LIKE pre-filtering.
-// Returns substrings that MUST appear in matching text (concatenated via .* or similar).
-// Conservative: returns nil for patterns with alternation (|) since AND LIKE is incorrect for OR semantics.
-func extractLikeHints(pattern string) []string {
- // Bail out on alternation — can't safely convert OR regex to AND LIKE
- if strings.Contains(pattern, "|") {
- return nil
- }
-
- var hints []string
- var current strings.Builder
- i := 0
- for i < len(pattern) {
- ch := pattern[i]
- switch ch {
- case '\\':
- // Escaped character — the next char is literal
- if i+1 < len(pattern) {
- current.WriteByte(pattern[i+1])
- i += 2
- } else {
- i++
- }
- case '.', '*', '+', '?', '^', '$', '(', ')', '[', ']', '{', '}':
- // Meta character — flush current literal segment
- if current.Len() >= 3 { // only use hints >= 3 chars to be selective
- hints = append(hints, current.String())
- }
- current.Reset()
- i++
- default:
- current.WriteByte(ch)
- i++
- }
- }
- if current.Len() >= 3 {
- hints = append(hints, current.String())
- }
- return hints
-}
-
-// sortSearchResults sorts results based on the requested sort mode.
-func sortSearchResults(results []*SearchResult, sortBy, namePattern string) {
- switch sortBy {
- case "name":
- slices.SortStableFunc(results, func(a, b *SearchResult) int {
- return strings.Compare(a.Node.Name, b.Node.Name)
- })
- case "degree":
- slices.SortStableFunc(results, func(a, b *SearchResult) int {
- return (b.InDegree + b.OutDegree) - (a.InDegree + a.OutDegree) // descending
- })
- default: // "relevance"
- literalQuery := extractLiteralQuery(namePattern)
- lowerQuery := strings.ToLower(literalQuery)
- slices.SortStableFunc(results, func(a, b *SearchResult) int {
- return compareRelevance(a, b, literalQuery, lowerQuery)
- })
- }
-}
-
-// compareRelevance implements tiered relevance: exact match > prefix match > degree.
-func compareRelevance(a, b *SearchResult, literalQuery, lowerQuery string) int {
- if literalQuery == "" {
- return compareDegree(a, b)
- }
- // Tier 1: Exact name match (case-insensitive)
- if cmp := compareBool(strings.EqualFold(a.Node.Name, literalQuery), strings.EqualFold(b.Node.Name, literalQuery)); cmp != 0 {
- return cmp
- }
- // Tier 2: Prefix match
- if cmp := compareBool(strings.HasPrefix(strings.ToLower(a.Node.Name), lowerQuery), strings.HasPrefix(strings.ToLower(b.Node.Name), lowerQuery)); cmp != 0 {
- return cmp
- }
- return compareDegree(a, b)
-}
-
-// compareBool returns -1 if a is true and b is false, 1 if opposite, 0 if equal.
-func compareBool(a, b bool) int {
- if a == b {
- return 0
- }
- if a {
- return -1
- }
- return 1
-}
-
-// compareDegree compares total degree descending (higher degree first).
-func compareDegree(a, b *SearchResult) int {
- return (b.InDegree + b.OutDegree) - (a.InDegree + a.OutDegree)
-}
-
-// extractLiteralQuery returns the literal string from a regex pattern if it contains
-// no special regex syntax beyond leading/trailing .* anchors and (?i) flag.
-func extractLiteralQuery(pattern string) string {
- if pattern == "" {
- return ""
- }
- p := strings.TrimPrefix(pattern, "(?i)")
- p = strings.TrimPrefix(p, ".*")
- p = strings.TrimSuffix(p, ".*")
- if strings.ContainsAny(p, ".*+?^${}()|[]\\") {
- return ""
- }
- return p
-}
-
-// filterByNamePattern filters nodes by a regex pattern against the short name only.
-func filterByNamePattern(nodes []*Node, pattern string) ([]*Node, error) {
- re, err := regexp.Compile(pattern)
- if err != nil {
- return nil, fmt.Errorf("invalid name pattern: %w", err)
- }
- var filtered []*Node
- for _, n := range nodes {
- if re.MatchString(n.Name) {
- filtered = append(filtered, n)
- }
- }
- return filtered, nil
-}
-
-// ensureCaseInsensitive prepends (?i) to a regex pattern if not already present.
-func ensureCaseInsensitive(pattern string) string {
- if strings.HasPrefix(pattern, "(?i)") {
- return pattern
- }
- return "(?i)" + pattern
-}
-
-// stripCaseFlag removes a leading (?i) prefix from a regex pattern.
-func stripCaseFlag(pattern string) string {
- return strings.TrimPrefix(pattern, "(?i)")
-}
-
-// filterByQNPattern filters nodes by a regex pattern against the qualified name.
-func filterByQNPattern(nodes []*Node, pattern string) ([]*Node, error) {
- re, err := regexp.Compile(pattern)
- if err != nil {
- return nil, fmt.Errorf("invalid qn_pattern: %w", err)
- }
- var filtered []*Node
- for _, n := range nodes {
- if re.MatchString(n.QualifiedName) {
- filtered = append(filtered, n)
- }
- }
- return filtered, nil
-}
diff --git a/internal/store/search_bench_test.go b/internal/store/search_bench_test.go
deleted file mode 100644
index 87456a0e0..000000000
--- a/internal/store/search_bench_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package store
-
-import (
- "fmt"
- "testing"
-)
-
-// populateSearchBench creates a project with ~500 nodes and ~1000 edges.
-func populateSearchBench(b *testing.B) *Store {
- b.Helper()
- s, err := OpenMemory()
- if err != nil {
- b.Fatal(err)
- }
- if err := s.UpsertProject("bench", "/tmp/bench"); err != nil {
- b.Fatal(err)
- }
-
- labels := []string{"Function", "Method", "Class", "Module"}
- nodeIDs := make([]int64, 0, 500)
-
- for i := 0; i < 500; i++ {
- label := labels[i%len(labels)]
- id, err := s.UpsertNode(&Node{
- Project: "bench",
- Label: label,
- Name: fmt.Sprintf("Node%d", i),
- QualifiedName: fmt.Sprintf("bench.pkg%d.Node%d", i/50, i),
- FilePath: fmt.Sprintf("pkg%d/file%d.go", i/50, i%50),
- StartLine: i*10 + 1,
- EndLine: i*10 + 8,
- Properties: map[string]any{"index": i},
- })
- if err != nil {
- b.Fatal(err)
- }
- nodeIDs = append(nodeIDs, id)
- }
-
- // Create ~1000 edges: each node calls 2 others, modules define functions
- for i := 0; i < 500; i++ {
- target1 := (i + 1) % 500
- target2 := (i + 7) % 500
- edgeType := "CALLS"
- if i%4 == 3 {
- edgeType = "DEFINES"
- }
- if _, err := s.InsertEdge(&Edge{
- Project: "bench",
- SourceID: nodeIDs[i],
- TargetID: nodeIDs[target1],
- Type: edgeType,
- }); err != nil {
- b.Fatal(err)
- }
- if _, err := s.InsertEdge(&Edge{
- Project: "bench",
- SourceID: nodeIDs[i],
- TargetID: nodeIDs[target2],
- Type: "CALLS",
- }); err != nil {
- b.Fatal(err)
- }
- }
-
- return s
-}
-
-func BenchmarkSearch100Results(b *testing.B) {
- s := populateSearchBench(b)
- defer s.Close()
-
- params := SearchParams{
- Project: "bench",
- Label: "Function",
- MinDegree: -1,
- MaxDegree: -1,
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- out, err := s.Search(&params)
- if err != nil {
- b.Fatal(err)
- }
- if len(out.Results) == 0 {
- b.Fatal("expected results")
- }
- }
-}
-
-func BenchmarkSearchWithDegreeFilter(b *testing.B) {
- s := populateSearchBench(b)
- defer s.Close()
-
- params := SearchParams{
- Project: "bench",
- Relationship: "CALLS",
- Direction: "outbound",
- MinDegree: 1,
- MaxDegree: -1,
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- out, err := s.Search(&params)
- if err != nil {
- b.Fatal(err)
- }
- if len(out.Results) == 0 {
- b.Fatal("expected results")
- }
- }
-}
-
-func BenchmarkSearchNamePattern(b *testing.B) {
- s := populateSearchBench(b)
- defer s.Close()
-
- params := SearchParams{
- Project: "bench",
- NamePattern: ".*Node1[0-9]{2}.*",
- MinDegree: -1,
- MaxDegree: -1,
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- out, err := s.Search(&params)
- if err != nil {
- b.Fatal(err)
- }
- if len(out.Results) == 0 {
- b.Fatal("expected results")
- }
- }
-}
-
-func BenchmarkSearchPagination(b *testing.B) {
- s := populateSearchBench(b)
- defer s.Close()
-
- params := SearchParams{
- Project: "bench",
- Limit: 20,
- Offset: 100,
- MinDegree: -1,
- MaxDegree: -1,
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- out, err := s.Search(&params)
- if err != nil {
- b.Fatal(err)
- }
- if out.Total == 0 {
- b.Fatal("expected results")
- }
- }
-}
diff --git a/internal/store/store.go b/internal/store/store.go
deleted file mode 100644
index d8fd2ec07..000000000
--- a/internal/store/store.go
+++ /dev/null
@@ -1,552 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "time"
-
- "github.com/mattn/go-sqlite3"
-)
-
-// Querier abstracts *sql.DB and *sql.Tx so store methods work in both contexts.
-type Querier interface {
- Exec(query string, args ...any) (sql.Result, error)
- Query(query string, args ...any) (*sql.Rows, error)
- QueryRow(query string, args ...any) *sql.Row
-}
-
-// StoreBackend abstracts the graph store so pipeline passes can run against
-// either a SQLite-backed Store or an in-memory GraphBuffer. Methods cover
-// all node/edge CRUD needed by pipeline passes + httplink.
-type StoreBackend interface {
- // Nodes
- UpsertNode(n *Node) (int64, error)
- UpsertNodeBatch(nodes []*Node) (map[string]int64, error)
- FindNodeByID(id int64) (*Node, error)
- FindNodeByQN(project, qn string) (*Node, error)
- FindNodesByLabel(project, label string) ([]*Node, error)
- FindNodesByName(project, name string) ([]*Node, error)
- FindNodesByIDs(ids []int64) (map[int64]*Node, error)
- FindNodeIDsByQNs(project string, qns []string) (map[string]int64, error)
- DeleteNodesByLabel(project, label string) error
- CountNodes(project string) (int, error)
- // Edges
- InsertEdge(e *Edge) (int64, error)
- InsertEdgeBatch(edges []*Edge) error
- FindEdgesBySourceAndType(sourceID int64, edgeType string) ([]*Edge, error)
- FindEdgesByTargetAndType(targetID int64, edgeType string) ([]*Edge, error)
- FindEdgesByType(project, edgeType string) ([]*Edge, error)
- DeleteEdgesByType(project, edgeType string) error
- CountEdgesByType(project, edgeType string) (int, error)
- CountEdges(project string) (int, error)
- // Project
- GetProject(name string) (*Project, error)
-}
-
-// Compile-time assertion: *Store implements StoreBackend.
-var _ StoreBackend = (*Store)(nil)
-
-// Store wraps a SQLite connection for graph storage.
-type Store struct {
- db *sql.DB
- q Querier // active querier: db or tx
- dbPath string
-}
-
-// Node represents a graph node stored in SQLite.
-type Node struct {
- ID int64
- Project string
- Label string
- Name string
- QualifiedName string
- FilePath string
- StartLine int
- EndLine int
- Properties map[string]any
-}
-
-// Edge represents a graph edge stored in SQLite.
-type Edge struct {
- ID int64
- Project string
- SourceID int64
- TargetID int64
- Type string
- Properties map[string]any
-}
-
-// cacheDir returns the default cache directory for databases.
-func cacheDir() (string, error) {
- home, err := os.UserHomeDir()
- if err != nil {
- return "", fmt.Errorf("home dir: %w", err)
- }
- dir := filepath.Join(home, ".cache", "codebase-memory-mcp")
- if err := os.MkdirAll(dir, 0o750); err != nil {
- return "", fmt.Errorf("mkdir cache: %w", err)
- }
- return dir, nil
-}
-
-// Open opens or creates a SQLite database for the given project in the default cache dir.
-func Open(project string) (*Store, error) {
- dir, err := cacheDir()
- if err != nil {
- return nil, err
- }
- dbPath := filepath.Join(dir, project+".db")
- return OpenPath(dbPath)
-}
-
-// OpenInDir opens or creates a SQLite database for the given project in a specific directory.
-func OpenInDir(dir, project string) (*Store, error) {
- dbPath := filepath.Join(dir, project+".db")
- return OpenPath(dbPath)
-}
-
-// OpenPath opens a SQLite database at the given path.
-func OpenPath(dbPath string) (*Store, error) {
- // Recover from stale SHM left by SIGKILL: if WAL is empty/missing but SHM exists,
- // the SHM has stale lock state that can deadlock new connections. Safe to remove.
- recoverStaleSHM(dbPath)
-
- dsn := dbPath + "?_journal_mode=WAL" +
- "&_busy_timeout=10000" +
- "&_foreign_keys=1" +
- "&_synchronous=NORMAL" +
- "&_txlock=immediate"
- db, err := sql.Open("sqlite3", dsn)
- if err != nil {
- return nil, fmt.Errorf("open db: %w", err)
- }
- // Single connection: SQLite is single-writer, pool adds lock contention.
- db.SetMaxOpenConns(1)
- db.SetMaxIdleConns(1)
-
- // PRAGMAs not supported in mattn DSN — set via Exec after Open.
- ctx := context.Background()
- _, _ = db.ExecContext(ctx, "PRAGMA temp_store = MEMORY")
- _, _ = db.ExecContext(ctx, "PRAGMA mmap_size = 67108864") // 64 MB
-
- // Adaptive cache: 10% of DB file size, clamped to 2-64 MB.
- cacheMB := adaptiveCacheMB(dbPath)
- cacheKB := cacheMB * 1024
- _, _ = db.ExecContext(ctx, fmt.Sprintf("PRAGMA cache_size = -%d", cacheKB))
-
- s := &Store{db: db, dbPath: dbPath}
- s.q = s.db
- if err := s.initSchema(); err != nil {
- db.Close()
- return nil, fmt.Errorf("init schema: %w", err)
- }
- slog.Debug("store.open", "path", dbPath, "cache_mb", cacheMB)
- return s, nil
-}
-
-// recoverStaleSHM removes stale SHM files left by unclean shutdowns (SIGKILL).
-// If the WAL file is empty or missing but the SHM file exists, the SHM contains
-// stale lock state that can deadlock new connections. Removing it lets SQLite
-// rebuild clean shared memory on next open.
-func recoverStaleSHM(dbPath string) {
- shmPath := dbPath + "-shm"
- walPath := dbPath + "-wal"
-
- shmInfo, shmErr := os.Stat(shmPath)
- if shmErr != nil {
- return // no SHM file — nothing to recover
- }
-
- walInfo, walErr := os.Stat(walPath)
- walEmpty := walErr != nil || walInfo.Size() == 0
-
- if walEmpty && shmInfo.Size() > 0 {
- slog.Info("store.recover_shm", "path", dbPath, "shm_bytes", shmInfo.Size())
- _ = os.Remove(shmPath)
- // Also remove empty WAL to let SQLite start fresh
- if walErr == nil {
- _ = os.Remove(walPath)
- }
- }
-}
-
-// adaptiveCacheMB returns a cache size in MB proportional to the DB file size.
-// 10% of DB size, clamped to [2, 64] MB. Returns 2 for missing/small files.
-func adaptiveCacheMB(dbPath string) int {
- fi, err := os.Stat(dbPath)
- if err != nil {
- return 2
- }
- dbSizeMB := int(fi.Size() / (1 << 20))
- cacheMB := dbSizeMB / 10
- if cacheMB < 2 {
- return 2
- }
- if cacheMB > 64 {
- return 64
- }
- return cacheMB
-}
-
-// OpenMemory opens an in-memory SQLite database (for testing).
-func OpenMemory() (*Store, error) {
- dsn := ":memory:?_foreign_keys=1" +
- "&_synchronous=OFF"
- db, err := sql.Open("sqlite3", dsn)
- if err != nil {
- return nil, fmt.Errorf("open memory db: %w", err)
- }
- _, _ = db.ExecContext(context.Background(), "PRAGMA temp_store = MEMORY")
- s := &Store{db: db, dbPath: ":memory:"}
- s.q = s.db
- if err := s.initSchema(); err != nil {
- db.Close()
- return nil, fmt.Errorf("init schema: %w", err)
- }
- return s, nil
-}
-
-// WithTransaction executes fn within a single SQLite transaction.
-// The callback receives a transaction-scoped Store — all store methods called on
-// txStore use the transaction. The receiver's q field is never mutated, so
-// concurrent read-only handlers (using s.q == s.db) are unaffected.
-func (s *Store) WithTransaction(ctx context.Context, fn func(txStore *Store) error) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return fmt.Errorf("begin tx: %w", err)
- }
- txStore := &Store{db: s.db, q: tx, dbPath: s.dbPath}
- if err := fn(txStore); err != nil {
- _ = tx.Rollback()
- return err
- }
- return tx.Commit()
-}
-
-// Checkpoint forces a WAL checkpoint, moving pages from WAL to the main DB,
-// then runs PRAGMA optimize so the query planner has up-to-date statistics.
-// PRAGMA optimize (SQLite 3.46+) auto-limits sampling per index, only re-analyzing
-// stale stats. Cost is absorbed during indexing rather than the first read query.
-func (s *Store) Checkpoint(ctx context.Context) {
- _, _ = s.db.ExecContext(ctx, "PRAGMA wal_checkpoint(TRUNCATE)")
- _, _ = s.db.ExecContext(ctx, "PRAGMA optimize")
-}
-
-// WALSize returns the current WAL file size in bytes, or -1 if unavailable.
-// Useful for diagnosing memory bloat from un-checkpointed WAL files.
-func (s *Store) WALSize() int64 {
- walPath := s.dbPath + "-wal"
- fi, err := os.Stat(walPath)
- if err != nil {
- return -1
- }
- return fi.Size()
-}
-
-// BeginBulkWrite switches to MEMORY journal mode for faster bulk writes.
-// Also boosts cache to 64 MB for write throughput.
-// Call EndBulkWrite when done to restore WAL mode and adaptive cache.
-func (s *Store) BeginBulkWrite(ctx context.Context) {
- _, _ = s.db.ExecContext(ctx, "PRAGMA journal_mode = MEMORY")
- _, _ = s.db.ExecContext(ctx, "PRAGMA synchronous = OFF")
- _, _ = s.db.ExecContext(ctx, "PRAGMA cache_size = -65536") // 64 MB
-}
-
-// EndBulkWrite restores WAL journal mode, NORMAL synchronous, and adaptive cache.
-func (s *Store) EndBulkWrite(ctx context.Context) {
- _, _ = s.db.ExecContext(ctx, "PRAGMA synchronous = NORMAL")
- _, _ = s.db.ExecContext(ctx, "PRAGMA journal_mode = WAL")
- s.restoreDefaultCache(ctx)
-}
-
-// WithLargeCache temporarily boosts the page cache to 64 MB for heavy read operations
-// (e.g. GetSchema, Louvain clustering), then restores the adaptive default.
-func (s *Store) WithLargeCache(ctx context.Context, fn func() error) error {
- _, _ = s.db.ExecContext(ctx, "PRAGMA cache_size = -65536") // 64 MB
- defer s.restoreDefaultCache(ctx)
- return fn()
-}
-
-// restoreDefaultCache recalculates and applies the adaptive cache size from DB file size.
-func (s *Store) restoreDefaultCache(ctx context.Context) {
- cacheMB := adaptiveCacheMB(s.dbPath)
- cacheKB := cacheMB * 1024
- _, _ = s.db.ExecContext(ctx, fmt.Sprintf("PRAGMA cache_size = -%d", cacheKB))
-}
-
-// DumpToFile copies the in-memory database to a file using SQLite's Backup API.
-// Writes atomically: the destination file is fully consistent after this call.
-// Only useful when the Store was opened with OpenMemory().
-func (s *Store) DumpToFile(destPath string) error {
- // Ensure parent directory exists
- if err := os.MkdirAll(filepath.Dir(destPath), 0o750); err != nil {
- return fmt.Errorf("mkdir for dump: %w", err)
- }
-
- // Open destination database
- destDB, err := sql.Open("sqlite3", destPath+"?_journal_mode=OFF&_synchronous=OFF")
- if err != nil {
- return fmt.Errorf("open dest db: %w", err)
- }
- defer destDB.Close()
- destDB.SetMaxOpenConns(1)
-
- ctx := context.Background()
-
- // Get raw SQLiteConn for source (in-memory)
- srcConn, err := s.db.Conn(ctx)
- if err != nil {
- return fmt.Errorf("src conn: %w", err)
- }
- defer srcConn.Close()
-
- // Get raw SQLiteConn for destination
- dstConn, err := destDB.Conn(ctx)
- if err != nil {
- return fmt.Errorf("dst conn: %w", err)
- }
- defer dstConn.Close()
-
- // Perform backup via raw driver connections
- var backupErr error
- err = dstConn.Raw(func(dstDriverConn any) error {
- dstSQLiteConn, ok := dstDriverConn.(*sqlite3.SQLiteConn)
- if !ok {
- return fmt.Errorf("dest is not SQLiteConn")
- }
- return srcConn.Raw(func(srcDriverConn any) error {
- srcSQLiteConn, ok := srcDriverConn.(*sqlite3.SQLiteConn)
- if !ok {
- return fmt.Errorf("src is not SQLiteConn")
- }
- backup, err := dstSQLiteConn.Backup("main", srcSQLiteConn, "main")
- if err != nil {
- return fmt.Errorf("backup init: %w", err)
- }
- // Step(-1) copies all pages in one call
- done, stepErr := backup.Step(-1)
- finishErr := backup.Finish()
- if stepErr != nil {
- backupErr = fmt.Errorf("backup step: %w", stepErr)
- return backupErr
- }
- if finishErr != nil {
- backupErr = fmt.Errorf("backup finish: %w", finishErr)
- return backupErr
- }
- if !done {
- backupErr = fmt.Errorf("backup incomplete")
- return backupErr
- }
- return nil
- })
- })
- if err != nil {
- return err
- }
- return backupErr
-}
-
-// RestoreFrom copies all data from src (typically in-memory) into this store
-// using the SQLite Backup API. This replaces all content in the destination.
-// The destination store's connection remains valid after the operation.
-func (s *Store) RestoreFrom(src *Store) error {
- ctx := context.Background()
-
- srcConn, err := src.db.Conn(ctx)
- if err != nil {
- return fmt.Errorf("src conn: %w", err)
- }
- defer srcConn.Close()
-
- dstConn, err := s.db.Conn(ctx)
- if err != nil {
- return fmt.Errorf("dst conn: %w", err)
- }
- defer dstConn.Close()
-
- var backupErr error
- err = dstConn.Raw(func(dstDriverConn any) error {
- dstSQLiteConn, ok := dstDriverConn.(*sqlite3.SQLiteConn)
- if !ok {
- return fmt.Errorf("dest is not SQLiteConn")
- }
- return srcConn.Raw(func(srcDriverConn any) error {
- srcSQLiteConn, ok := srcDriverConn.(*sqlite3.SQLiteConn)
- if !ok {
- return fmt.Errorf("src is not SQLiteConn")
- }
- backup, err := dstSQLiteConn.Backup("main", srcSQLiteConn, "main")
- if err != nil {
- return fmt.Errorf("backup init: %w", err)
- }
- done, stepErr := backup.Step(-1)
- finishErr := backup.Finish()
- if stepErr != nil {
- backupErr = fmt.Errorf("backup step: %w", stepErr)
- return backupErr
- }
- if finishErr != nil {
- backupErr = fmt.Errorf("backup finish: %w", finishErr)
- return backupErr
- }
- if !done {
- backupErr = fmt.Errorf("backup incomplete")
- return backupErr
- }
- return nil
- })
- })
- if err != nil {
- return err
- }
- return backupErr
-}
-
-// Close closes the database connection.
-func (s *Store) Close() error {
- return s.db.Close()
-}
-
-// DB returns the underlying sql.DB (for advanced queries).
-func (s *Store) DB() *sql.DB {
- return s.db
-}
-
-// DBPath returns the filesystem path to the SQLite database.
-func (s *Store) DBPath() string {
- return s.dbPath
-}
-
-func (s *Store) initSchema() error {
- ctx := context.Background()
- schema := `
- CREATE TABLE IF NOT EXISTS projects (
- name TEXT PRIMARY KEY,
- indexed_at TEXT NOT NULL,
- root_path TEXT NOT NULL
- );
-
- CREATE TABLE IF NOT EXISTS file_hashes (
- project TEXT NOT NULL REFERENCES projects(name) ON DELETE CASCADE,
- rel_path TEXT NOT NULL,
- sha256 TEXT NOT NULL,
- mtime_ns INTEGER NOT NULL DEFAULT 0,
- size INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (project, rel_path)
- );
-
- CREATE TABLE IF NOT EXISTS nodes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- project TEXT NOT NULL REFERENCES projects(name) ON DELETE CASCADE,
- label TEXT NOT NULL,
- name TEXT NOT NULL,
- qualified_name TEXT NOT NULL,
- file_path TEXT DEFAULT '',
- start_line INTEGER DEFAULT 0,
- end_line INTEGER DEFAULT 0,
- properties TEXT DEFAULT '{}',
- UNIQUE(project, qualified_name)
- );
-
- CREATE INDEX IF NOT EXISTS idx_nodes_label ON nodes(project, label);
- CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(project, name);
- CREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(project, file_path);
-
- CREATE TABLE IF NOT EXISTS edges (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- project TEXT NOT NULL REFERENCES projects(name) ON DELETE CASCADE,
- source_id INTEGER NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
- target_id INTEGER NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
- type TEXT NOT NULL,
- properties TEXT DEFAULT '{}',
- UNIQUE(source_id, target_id, type)
- );
-
- CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_id, type);
- CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_id, type);
- CREATE INDEX IF NOT EXISTS idx_edges_type ON edges(project, type);
-
- CREATE INDEX IF NOT EXISTS idx_edges_target_type ON edges(project, target_id, type);
- CREATE INDEX IF NOT EXISTS idx_edges_source_type ON edges(project, source_id, type);
- `
- _, err := s.db.ExecContext(ctx, schema)
- if err != nil {
- return err
- }
-
- // Migration: project_summaries table for ADR storage.
- _, _ = s.db.ExecContext(ctx, `
- CREATE TABLE IF NOT EXISTS project_summaries (
- project TEXT PRIMARY KEY,
- summary TEXT NOT NULL,
- source_hash TEXT NOT NULL,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
- )`)
-
- // Migration: add url_path generated column to edges table.
- // Generated columns require SQLite 3.31.0+ (mattn/go-sqlite3 supports this).
- // We check if the column already exists to make this idempotent.
- var colCount int
- _ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM pragma_table_xinfo('edges') WHERE name='url_path_gen'`).Scan(&colCount)
- if colCount == 0 {
- _, err = s.db.ExecContext(ctx, `ALTER TABLE edges ADD COLUMN url_path_gen TEXT GENERATED ALWAYS AS (json_extract(properties, '$.url_path'))`)
- if err != nil {
- // If generated columns aren't supported, skip gracefully
- slog.Warn("schema.url_path_gen.skip", "err", err)
- }
- }
-
- // Index on generated column (safe to CREATE IF NOT EXISTS)
- _, _ = s.db.ExecContext(ctx, `CREATE INDEX IF NOT EXISTS idx_edges_url_path ON edges(project, url_path_gen)`)
-
- // Migration: add mtime_ns and size columns to file_hashes for stat pre-filtering.
- var mtimeCol int
- _ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM pragma_table_xinfo('file_hashes') WHERE name='mtime_ns'`).Scan(&mtimeCol)
- if mtimeCol == 0 {
- _, _ = s.db.ExecContext(ctx, `ALTER TABLE file_hashes ADD COLUMN mtime_ns INTEGER NOT NULL DEFAULT 0`)
- _, _ = s.db.ExecContext(ctx, `ALTER TABLE file_hashes ADD COLUMN size INTEGER NOT NULL DEFAULT 0`)
- }
-
- return nil
-}
-
-// marshalProps serializes properties to JSON.
-func marshalProps(props map[string]any) string {
- if props == nil {
- return "{}"
- }
- b, err := json.Marshal(props)
- if err != nil {
- return "{}"
- }
- return string(b)
-}
-
-// UnmarshalProps deserializes JSON properties. Exported for use by cypher executor.
-func UnmarshalProps(data string) map[string]any {
- return unmarshalProps(data)
-}
-
-// unmarshalProps deserializes JSON properties.
-func unmarshalProps(data string) map[string]any {
- if data == "" {
- return map[string]any{}
- }
- var m map[string]any
- if err := json.Unmarshal([]byte(data), &m); err != nil {
- return map[string]any{}
- }
- return m
-}
-
-// Now returns the current time in ISO 8601 format.
-func Now() string {
- return time.Now().UTC().Format(time.RFC3339)
-}
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
deleted file mode 100644
index 053b7609e..000000000
--- a/internal/store/store_test.go
+++ /dev/null
@@ -1,1256 +0,0 @@
-package store
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestOpenMemory(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- s.Close()
-}
-
-func TestNodeCRUD(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- // Create project first
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
-
- // Insert node
- n := &Node{
- Project: "test",
- Label: "Function",
- Name: "Foo",
- QualifiedName: "test.main.Foo",
- FilePath: "main.go",
- StartLine: 10,
- EndLine: 20,
- Properties: map[string]any{"signature": "func Foo(x int) error"},
- }
- id, err := s.UpsertNode(n)
- if err != nil {
- t.Fatalf("UpsertNode: %v", err)
- }
- if id == 0 {
- t.Fatal("expected non-zero id")
- }
-
- // Find by QN
- found, err := s.FindNodeByQN("test", "test.main.Foo")
- if err != nil {
- t.Fatalf("FindNodeByQN: %v", err)
- }
- if found == nil {
- t.Fatal("expected node, got nil")
- }
- if found.Name != "Foo" {
- t.Errorf("expected Foo, got %s", found.Name)
- }
- if found.Properties["signature"] != "func Foo(x int) error" {
- t.Errorf("unexpected signature: %v", found.Properties["signature"])
- }
-
- // Find by name
- nodes, err := s.FindNodesByName("test", "Foo")
- if err != nil {
- t.Fatalf("FindNodesByName: %v", err)
- }
- if len(nodes) != 1 {
- t.Fatalf("expected 1 node, got %d", len(nodes))
- }
-
- // Count
- count, err := s.CountNodes("test")
- if err != nil {
- t.Fatalf("CountNodes: %v", err)
- }
- if count != 1 {
- t.Errorf("expected 1, got %d", count)
- }
-}
-
-func TestNodeDedup(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
-
- // Insert same qualified_name twice — should update, not duplicate
- n1 := &Node{Project: "test", Label: "Function", Name: "Foo", QualifiedName: "test.main.Foo"}
- n2 := &Node{Project: "test", Label: "Function", Name: "Foo", QualifiedName: "test.main.Foo", Properties: map[string]any{"updated": true}}
-
- if _, err := s.UpsertNode(n1); err != nil {
- t.Fatalf("UpsertNode n1: %v", err)
- }
- if _, err := s.UpsertNode(n2); err != nil {
- t.Fatalf("UpsertNode n2: %v", err)
- }
-
- count, _ := s.CountNodes("test")
- if count != 1 {
- t.Errorf("expected 1 node after dedup, got %d", count)
- }
-
- // Verify it was updated
- found, _ := s.FindNodeByQN("test", "test.main.Foo")
- if found.Properties["updated"] != true {
- t.Error("expected updated property")
- }
-}
-
-func TestEdgeCRUD(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
-
- // Create two nodes
- id1, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- id2, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
-
- // Insert edge
- _, err = s.InsertEdge(&Edge{Project: "test", SourceID: id1, TargetID: id2, Type: "CALLS"})
- if err != nil {
- t.Fatalf("InsertEdge: %v", err)
- }
-
- // Find by source
- edges, err := s.FindEdgesBySource(id1)
- if err != nil {
- t.Fatalf("FindEdgesBySource: %v", err)
- }
- if len(edges) != 1 {
- t.Fatalf("expected 1 edge, got %d", len(edges))
- }
- if edges[0].Type != "CALLS" {
- t.Errorf("expected CALLS, got %s", edges[0].Type)
- }
-
- // Count
- count, _ := s.CountEdges("test")
- if count != 1 {
- t.Errorf("expected 1, got %d", count)
- }
-}
-
-func TestCascadeDelete(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- // Create project with nodes and edges
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
- id1, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- id2, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
- if _, err := s.InsertEdge(&Edge{Project: "test", SourceID: id1, TargetID: id2, Type: "CALLS"}); err != nil {
- t.Fatalf("InsertEdge: %v", err)
- }
-
- // Delete project — should cascade
- if err := s.DeleteProject("test"); err != nil {
- t.Fatalf("DeleteProject: %v", err)
- }
-
- nodes, _ := s.CountNodes("test")
- edges, _ := s.CountEdges("test")
- if nodes != 0 {
- t.Errorf("expected 0 nodes after cascade, got %d", nodes)
- }
- if edges != 0 {
- t.Errorf("expected 0 edges after cascade, got %d", edges)
- }
-}
-
-func TestProjectCRUD(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- // Create
- if err := s.UpsertProject("myproject", "/home/user/myproject"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
-
- // Get
- p, err := s.GetProject("myproject")
- if err != nil {
- t.Fatalf("GetProject: %v", err)
- }
- if p.Name != "myproject" {
- t.Errorf("expected myproject, got %s", p.Name)
- }
- if p.RootPath != "/home/user/myproject" {
- t.Errorf("unexpected root: %s", p.RootPath)
- }
-
- // List
- projects, err := s.ListProjects()
- if err != nil {
- t.Fatalf("ListProjects: %v", err)
- }
- if len(projects) != 1 {
- t.Fatalf("expected 1 project, got %d", len(projects))
- }
-}
-
-func TestFileHashes(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
-
- // Upsert
- if err := s.UpsertFileHash("test", "main.go", "abc123", 1000000, 512); err != nil {
- t.Fatalf("UpsertFileHash: %v", err)
- }
-
- // Get
- hashes, err := s.GetFileHashes("test")
- if err != nil {
- t.Fatalf("GetFileHashes: %v", err)
- }
- if hashes["main.go"].SHA256 != "abc123" {
- t.Errorf("expected abc123, got %s", hashes["main.go"].SHA256)
- }
- if hashes["main.go"].MtimeNs != 1000000 {
- t.Errorf("expected mtime_ns 1000000, got %d", hashes["main.go"].MtimeNs)
- }
- if hashes["main.go"].Size != 512 {
- t.Errorf("expected size 512, got %d", hashes["main.go"].Size)
- }
-
- // Update
- if err := s.UpsertFileHash("test", "main.go", "def456", 2000000, 1024); err != nil {
- t.Fatalf("UpsertFileHash update: %v", err)
- }
- hashes, _ = s.GetFileHashes("test")
- if hashes["main.go"].SHA256 != "def456" {
- t.Errorf("expected def456, got %s", hashes["main.go"].SHA256)
- }
- if hashes["main.go"].MtimeNs != 2000000 {
- t.Errorf("expected mtime_ns 2000000, got %d", hashes["main.go"].MtimeNs)
- }
-}
-
-func TestSearch(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatalf("OpenMemory: %v", err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatalf("UpsertProject: %v", err)
- }
- if _, err := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "SubmitOrder", QualifiedName: "test.main.SubmitOrder", FilePath: "main.go"}); err != nil {
- t.Fatalf("UpsertNode SubmitOrder: %v", err)
- }
- if _, err := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "ProcessOrder", QualifiedName: "test.service.ProcessOrder", FilePath: "service.go"}); err != nil {
- t.Fatalf("UpsertNode ProcessOrder: %v", err)
- }
- if _, err := s.UpsertNode(&Node{Project: "test", Label: "Class", Name: "OrderService", QualifiedName: "test.service.OrderService", FilePath: "service.go"}); err != nil {
- t.Fatalf("UpsertNode OrderService: %v", err)
- }
-
- // Search by label
- output, err := s.Search(&SearchParams{Project: "test", Label: "Function"})
- if err != nil {
- t.Fatalf("Search: %v", err)
- }
- if len(output.Results) != 2 {
- t.Errorf("expected 2 functions, got %d", len(output.Results))
- }
- if output.Total != 2 {
- t.Errorf("expected total=2, got %d", output.Total)
- }
-
- // Search by name pattern
- output, err = s.Search(&SearchParams{Project: "test", NamePattern: ".*Submit.*"})
- if err != nil {
- t.Fatalf("Search: %v", err)
- }
- if len(output.Results) != 1 {
- t.Errorf("expected 1 match, got %d", len(output.Results))
- }
-
- // Search by file pattern
- output, err = s.Search(&SearchParams{Project: "test", FilePattern: "service*"})
- if err != nil {
- t.Fatalf("Search: %v", err)
- }
- if len(output.Results) != 2 {
- t.Errorf("expected 2 nodes in service.go, got %d", len(output.Results))
- }
-
- // Search with offset/limit pagination
- output, err = s.Search(&SearchParams{Project: "test", Limit: 1})
- if err != nil {
- t.Fatalf("Search: %v", err)
- }
- if len(output.Results) != 1 {
- t.Errorf("expected 1 result with limit=1, got %d", len(output.Results))
- }
- if output.Total != 3 {
- t.Errorf("expected total=3, got %d", output.Total)
- }
-
- output, err = s.Search(&SearchParams{Project: "test", Limit: 1, Offset: 1})
- if err != nil {
- t.Fatalf("Search: %v", err)
- }
- if len(output.Results) != 1 {
- t.Errorf("expected 1 result with limit=1 offset=1, got %d", len(output.Results))
- }
- if output.Total != 3 {
- t.Errorf("expected total=3, got %d", output.Total)
- }
-}
-
-func TestGlobToLike(t *testing.T) {
- tests := []struct {
- pattern string
- want string
- }{
- {"**/*.py", "%%.py"},
- {"**/dir/**", "%dir%"},
- {"*.go", "%.go"},
- {"src/**", "src%"},
- {"**/test_*.py", "%test_%.py"},
- {"file?.txt", "file_.txt"},
- {"exact.go", "exact.go"},
- {"**/custom-pip-package/**", "%custom-pip-package%"},
- }
- for _, tt := range tests {
- t.Run(tt.pattern, func(t *testing.T) {
- got := globToLike(tt.pattern)
- if got != tt.want {
- t.Errorf("globToLike(%q) = %q, want %q", tt.pattern, got, tt.want)
- }
- })
- }
-}
-
-func TestExtractLikeHints(t *testing.T) {
- tests := []struct {
- pattern string
- want []string
- }{
- {".*handler.*", []string{"handler"}},
- {".*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
- {".*Order.*|.*Handler.*", nil}, // alternation → bail out
- {"\\.", nil}, // escaped dot is ".", only 1 char
- {".*test_.*helper.*", []string{"test_", "helper"}},
- }
- for _, tt := range tests {
- t.Run(tt.pattern, func(t *testing.T) {
- got := extractLikeHints(tt.pattern)
- if len(got) != len(tt.want) {
- t.Errorf("extractLikeHints(%q) = %v, want %v", tt.pattern, got, tt.want)
- return
- }
- for i := range got {
- if got[i] != tt.want[i] {
- t.Errorf("extractLikeHints(%q)[%d] = %q, want %q", tt.pattern, i, got[i], tt.want[i])
- }
- }
- })
- }
-}
-
-func TestGeneratedColumnURLPath(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- // Check that the generated column exists
- var colCount int
- err = s.DB().QueryRowContext(context.Background(), `SELECT COUNT(*) FROM pragma_table_xinfo('edges') WHERE name='url_path_gen'`).Scan(&colCount)
- if err != nil {
- t.Fatal(err)
- }
- if colCount != 1 {
- t.Skip("url_path_gen column not available (SQLite version may not support generated columns)")
- }
-}
-
-func TestFindEdgesByURLPath(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- // Create project
- if err := s.UpsertProject("test-proj", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create two nodes
- srcID, _ := s.UpsertNode(&Node{
- Project: "test-proj", Label: "Function", Name: "caller",
- QualifiedName: "test.caller",
- })
- tgtID, _ := s.UpsertNode(&Node{
- Project: "test-proj", Label: "Function", Name: "handler",
- QualifiedName: "test.handler",
- })
-
- // Create HTTP_CALLS edge with url_path
- _, err = s.InsertEdge(&Edge{
- Project: "test-proj",
- SourceID: srcID,
- TargetID: tgtID,
- Type: "HTTP_CALLS",
- Properties: map[string]any{"url_path": "/api/orders/create", "confidence": 0.8},
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Search for edges containing "orders"
- edges, err := s.FindEdgesByURLPath("test-proj", "orders")
- if err != nil {
- t.Fatal(err)
- }
- if len(edges) != 1 {
- t.Fatalf("expected 1 edge, got %d", len(edges))
- }
- if edges[0].Properties["url_path"] != "/api/orders/create" {
- t.Errorf("unexpected url_path: %v", edges[0].Properties["url_path"])
- }
-
- // Search for non-matching
- edges, err = s.FindEdgesByURLPath("test-proj", "users")
- if err != nil {
- t.Fatal(err)
- }
- if len(edges) != 0 {
- t.Fatalf("expected 0 edges, got %d", len(edges))
- }
-}
-
-func TestPragmaSettings(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- tests := []struct {
- pragma string
- want string
- }{
- {"synchronous", "0"}, // OFF for in-memory
- {"temp_store", "2"}, // MEMORY
- {"foreign_keys", "1"}, // ON
- }
- for _, tt := range tests {
- var val string
- err := s.DB().QueryRowContext(context.Background(), "PRAGMA "+tt.pragma).Scan(&val)
- if err != nil {
- t.Fatalf("PRAGMA %s: %v", tt.pragma, err)
- }
- if val != tt.want {
- t.Errorf("PRAGMA %s = %q, want %q", tt.pragma, val, tt.want)
- }
- }
-}
-
-func TestUpsertNodeBatch(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create 150 nodes (triggers two batches: 100 + 50)
- nodes := make([]*Node, 150)
- for i := range nodes {
- nodes[i] = &Node{
- Project: "test",
- Label: "Function",
- Name: fmt.Sprintf("func_%d", i),
- QualifiedName: fmt.Sprintf("test.pkg.func_%d", i),
- FilePath: "pkg.go",
- StartLine: i * 10,
- EndLine: i*10 + 9,
- }
- }
-
- idMap, err := s.UpsertNodeBatch(nodes)
- if err != nil {
- t.Fatalf("UpsertNodeBatch: %v", err)
- }
-
- if len(idMap) != 150 {
- t.Fatalf("expected 150 IDs, got %d", len(idMap))
- }
-
- // Verify all IDs are non-zero and unique
- seen := make(map[int64]bool)
- for qn, id := range idMap {
- if id == 0 {
- t.Errorf("zero ID for %s", qn)
- }
- if seen[id] {
- t.Errorf("duplicate ID %d", id)
- }
- seen[id] = true
- }
-
- // Verify count
- count, _ := s.CountNodes("test")
- if count != 150 {
- t.Errorf("expected 150 nodes, got %d", count)
- }
-
- // Upsert again (should update, not duplicate)
- for _, n := range nodes {
- n.Properties = map[string]any{"updated": true}
- }
- idMap2, err := s.UpsertNodeBatch(nodes)
- if err != nil {
- t.Fatalf("UpsertNodeBatch re-upsert: %v", err)
- }
- count, _ = s.CountNodes("test")
- if count != 150 {
- t.Errorf("expected 150 after re-upsert, got %d", count)
- }
- // IDs should be the same
- for qn, id := range idMap {
- if idMap2[qn] != id {
- t.Errorf("ID changed for %s: %d -> %d", qn, id, idMap2[qn])
- }
- }
-}
-
-func TestUpsertNodeBatchEmpty(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- idMap, err := s.UpsertNodeBatch(nil)
- if err != nil {
- t.Fatal(err)
- }
- if len(idMap) != 0 {
- t.Errorf("expected empty map, got %d entries", len(idMap))
- }
-}
-
-func TestInsertEdgeBatch(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create nodes
- ids := make([]int64, 10)
- for i := range ids {
- ids[i], _ = s.UpsertNode(&Node{
- Project: "test",
- Label: "Function",
- Name: fmt.Sprintf("f%d", i),
- QualifiedName: fmt.Sprintf("test.f%d", i),
- })
- }
-
- // Create 200 edges (triggers two batches: 150 + 50)
- edges := make([]*Edge, 0, 200)
- for i := 0; i < 200 && i < len(ids)*len(ids); i++ {
- src := i / len(ids)
- tgt := i % len(ids)
- if src == tgt {
- continue
- }
- edges = append(edges, &Edge{
- Project: "test",
- SourceID: ids[src],
- TargetID: ids[tgt],
- Type: "CALLS",
- })
- if len(edges) >= 200 {
- break
- }
- }
-
- if err := s.InsertEdgeBatch(edges); err != nil {
- t.Fatalf("InsertEdgeBatch: %v", err)
- }
-
- count, _ := s.CountEdges("test")
- if count != len(edges) {
- t.Errorf("expected %d edges, got %d", len(edges), count)
- }
-
- // Re-insert with properties (should update via ON CONFLICT)
- for _, e := range edges {
- e.Properties = map[string]any{"updated": true}
- }
- if err := s.InsertEdgeBatch(edges); err != nil {
- t.Fatalf("InsertEdgeBatch re-insert: %v", err)
- }
- count, _ = s.CountEdges("test")
- if count != len(edges) {
- t.Errorf("expected %d edges after re-insert, got %d", len(edges), count)
- }
-}
-
-func TestUpsertFileHashBatch(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create 250 file hashes (triggers two batches: 190 + 60)
- hashes := make([]FileHash, 250)
- for i := range hashes {
- hashes[i] = FileHash{
- Project: "test",
- RelPath: fmt.Sprintf("file_%d.go", i),
- SHA256: fmt.Sprintf("hash_%d", i),
- MtimeNs: int64(i * 1000),
- Size: int64(i * 100),
- }
- }
-
- if err := s.UpsertFileHashBatch(hashes); err != nil {
- t.Fatalf("UpsertFileHashBatch: %v", err)
- }
-
- stored, err := s.GetFileHashes("test")
- if err != nil {
- t.Fatal(err)
- }
- if len(stored) != 250 {
- t.Fatalf("expected 250 hashes, got %d", len(stored))
- }
-
- // Verify values
- for _, h := range hashes {
- if stored[h.RelPath].SHA256 != h.SHA256 {
- t.Errorf("hash mismatch for %s: got %s, want %s", h.RelPath, stored[h.RelPath].SHA256, h.SHA256)
- }
- if stored[h.RelPath].MtimeNs != h.MtimeNs {
- t.Errorf("mtime mismatch for %s: got %d, want %d", h.RelPath, stored[h.RelPath].MtimeNs, h.MtimeNs)
- }
- }
-
- // Update hashes (should not duplicate)
- for i := range hashes {
- hashes[i].SHA256 = fmt.Sprintf("updated_%d", i)
- hashes[i].MtimeNs = int64(i * 2000)
- }
- if err := s.UpsertFileHashBatch(hashes); err != nil {
- t.Fatal(err)
- }
- stored, _ = s.GetFileHashes("test")
- if len(stored) != 250 {
- t.Errorf("expected 250 after update, got %d", len(stored))
- }
- if stored["file_0.go"].SHA256 != "updated_0" {
- t.Errorf("expected updated hash, got %s", stored["file_0.go"].SHA256)
- }
-}
-
-func TestFindNodeIDsByQNs(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Insert nodes
- id1, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- id2, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
-
- // Lookup
- idMap, err := s.FindNodeIDsByQNs("test", []string{"test.A", "test.B", "test.missing"})
- if err != nil {
- t.Fatal(err)
- }
- if idMap["test.A"] != id1 {
- t.Errorf("test.A: expected %d, got %d", id1, idMap["test.A"])
- }
- if idMap["test.B"] != id2 {
- t.Errorf("test.B: expected %d, got %d", id2, idMap["test.B"])
- }
- if _, ok := idMap["test.missing"]; ok {
- t.Error("expected missing QN to not be in map")
- }
-}
-
-func TestBatchCountDegrees(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create A -> B, A -> C, B -> C
- idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- 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"})
-
- // Batch count all types
- degrees, err := s.batchCountDegrees([]int64{idA, idB, idC}, "")
- if err != nil {
- t.Fatal(err)
- }
- // A: in=0, out=3 (2 CALLS + 1 USAGE)
- if degrees[idA].InDegree != 0 || degrees[idA].OutDegree != 3 {
- t.Errorf("A: in=%d out=%d, want in=0 out=3", degrees[idA].InDegree, degrees[idA].OutDegree)
- }
- // B: in=1, out=1
- if degrees[idB].InDegree != 1 || degrees[idB].OutDegree != 1 {
- t.Errorf("B: in=%d out=%d, want in=1 out=1", degrees[idB].InDegree, degrees[idB].OutDegree)
- }
- // C: in=3, out=0
- if degrees[idC].InDegree != 3 || degrees[idC].OutDegree != 0 {
- t.Errorf("C: in=%d out=%d, want in=3 out=0", degrees[idC].InDegree, degrees[idC].OutDegree)
- }
-
- // Batch count filtered by CALLS
- degrees, err = s.batchCountDegrees([]int64{idA, idC}, "CALLS")
- if err != nil {
- t.Fatal(err)
- }
- // A: in=0, out=2 (CALLS only)
- if degrees[idA].InDegree != 0 || degrees[idA].OutDegree != 2 {
- t.Errorf("A CALLS: in=%d out=%d, want in=0 out=2", degrees[idA].InDegree, degrees[idA].OutDegree)
- }
- // C: in=2, out=0 (CALLS only)
- if degrees[idC].InDegree != 2 || degrees[idC].OutDegree != 0 {
- t.Errorf("C CALLS: in=%d out=%d, want in=2 out=0", degrees[idC].InDegree, degrees[idC].OutDegree)
- }
-}
-
-func TestBatchSizeSafety(t *testing.T) {
- // Verify formula-derived batch sizes stay under SQLite's 999 bind variable limit.
- if numNodeCols*nodesBatchSize >= 999 {
- t.Errorf("node batch exceeds limit: %d cols × %d rows = %d (max 998)",
- numNodeCols, nodesBatchSize, numNodeCols*nodesBatchSize)
- }
- if numEdgeCols*edgesBatchSize >= 999 {
- t.Errorf("edge batch exceeds limit: %d cols × %d rows = %d (max 998)",
- numEdgeCols, edgesBatchSize, numEdgeCols*edgesBatchSize)
- }
-}
-
-func TestSearchExcludeLabels(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create nodes with different labels
- for i, label := range []string{"Function", "Route", "Method", "Route"} {
- _, _ = s.UpsertNode(&Node{
- Project: "test",
- Label: label,
- Name: "node_" + label,
- QualifiedName: fmt.Sprintf("test.%s.node_%d", label, i),
- FilePath: "test.go",
- })
- }
-
- // Search without exclusion
- output, err := s.Search(&SearchParams{
- Project: "test",
- Limit: 100,
- })
- if err != nil {
- t.Fatal(err)
- }
- total := output.Total
-
- // Search with Route excluded
- output2, err := s.Search(&SearchParams{
- Project: "test",
- ExcludeLabels: []string{"Route"},
- Limit: 100,
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Should have fewer results
- if output2.Total >= total {
- t.Errorf("exclude_labels didn't reduce results: before=%d, after=%d", total, output2.Total)
- }
-
- // Verify no Route nodes in results
- for _, r := range output2.Results {
- if r.Node.Label == "Route" {
- t.Errorf("found Route node despite exclude_labels")
- }
- }
-}
-
-func TestFindNodesByFileOverlap(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Create nodes with different line ranges in the same file
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "funcA", QualifiedName: "test.main.funcA", FilePath: "main.go", StartLine: 1, EndLine: 10})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "funcB", QualifiedName: "test.main.funcB", FilePath: "main.go", StartLine: 12, EndLine: 25})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "funcC", QualifiedName: "test.main.funcC", FilePath: "other.go", StartLine: 1, EndLine: 50})
- // Module node should be excluded from overlap results
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Module", Name: "main", QualifiedName: "test.main", FilePath: "main.go", StartLine: 1, EndLine: 100})
-
- // Overlap with funcA (lines 5-8)
- nodes, err := s.FindNodesByFileOverlap("test", "main.go", 5, 8)
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 1 || nodes[0].Name != "funcA" {
- t.Errorf("expected funcA, got %d nodes", len(nodes))
- }
-
- // Overlap spanning funcA and funcB (lines 8-15)
- nodes, err = s.FindNodesByFileOverlap("test", "main.go", 8, 15)
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 2 {
- t.Errorf("expected 2 nodes (funcA + funcB), got %d", len(nodes))
- }
-
- // No overlap (lines 26-30)
- nodes, err = s.FindNodesByFileOverlap("test", "main.go", 26, 30)
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 0 {
- t.Errorf("expected 0 nodes, got %d", len(nodes))
- }
-
- // Different file
- nodes, err = s.FindNodesByFileOverlap("test", "other.go", 1, 50)
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 1 || nodes[0].Name != "funcC" {
- t.Errorf("expected funcC, got %d nodes", len(nodes))
- }
-}
-
-func TestFindNodesByQNSuffix_Single(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "HandleRequest", QualifiedName: "test.cmd.server.main.HandleRequest"})
-
- nodes, err := s.FindNodesByQNSuffix("test", "main.HandleRequest")
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 1 {
- t.Fatalf("expected 1 match, got %d", len(nodes))
- }
- if nodes[0].Name != "HandleRequest" {
- t.Errorf("expected HandleRequest, got %s", nodes[0].Name)
- }
-}
-
-func TestFindNodesByQNSuffix_NoMatch(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "Foo", QualifiedName: "test.main.Foo"})
-
- nodes, err := s.FindNodesByQNSuffix("test", "main.Bar")
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 0 {
- t.Fatalf("expected 0 matches, got %d", len(nodes))
- }
-}
-
-func TestFindNodesByQNSuffix_Multiple(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "Run", QualifiedName: "test.cmd.server.Run"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "Run", QualifiedName: "test.cmd.worker.Run"})
-
- // Suffix "Run" should match both (both end with ".Run")
- nodes, err := s.FindNodesByQNSuffix("test", "Run")
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 2 {
- t.Fatalf("expected 2 matches, got %d", len(nodes))
- }
-}
-
-func TestFindNodesByQNSuffix_DotBoundary(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "HandleRequest", QualifiedName: "test.main.HandleRequest"})
- _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "MyHandleRequestHelper", QualifiedName: "test.main.MyHandleRequestHelper"})
-
- // Should only match the one with ".HandleRequest" suffix, not partial word
- nodes, err := s.FindNodesByQNSuffix("test", "HandleRequest")
- if err != nil {
- t.Fatal(err)
- }
- if len(nodes) != 1 {
- t.Fatalf("expected 1 match (dot-boundary), got %d", len(nodes))
- }
- if nodes[0].Name != "HandleRequest" {
- t.Errorf("expected HandleRequest, got %s", nodes[0].Name)
- }
-}
-
-func TestNodeDegree(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- 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"})
-
- // A -> B (CALLS), A -> C (CALLS), B -> C (CALLS), A -> C (USAGE — not counted)
- _, _ = 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"})
-
- inA, outA := s.NodeDegree(idA)
- if inA != 0 || outA != 2 {
- t.Errorf("A: in=%d out=%d, want in=0 out=2", inA, outA)
- }
-
- inB, outB := s.NodeDegree(idB)
- if inB != 1 || outB != 1 {
- t.Errorf("B: in=%d out=%d, want in=1 out=1", inB, outB)
- }
-
- inC, outC := s.NodeDegree(idC)
- if inC != 2 || outC != 0 {
- t.Errorf("C: in=%d out=%d, want in=2 out=0", inC, outC)
- }
-}
-
-func TestBFSWithRiskLabels(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- // Build chain: A -> B -> C -> D
- idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- 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"})
- idD, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "D", QualifiedName: "test.D"})
-
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "CALLS"})
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idB, TargetID: idC, Type: "CALLS"})
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idC, TargetID: idD, Type: "CALLS"})
-
- // BFS from A outbound, depth=3
- result, err := s.BFS(idA, "outbound", []string{"CALLS"}, 3, 200)
- if err != nil {
- t.Fatal(err)
- }
-
- // Deduplicate (needed for risk labels)
- deduped := DeduplicateHops(result.Visited)
- if len(deduped) != 3 {
- t.Fatalf("expected 3 visited nodes (B,C,D), got %d", len(deduped))
- }
-
- // Verify risk labels
- riskByName := make(map[string]RiskLevel)
- for _, nh := range deduped {
- riskByName[nh.Node.Name] = HopToRisk(nh.Hop)
- }
- if riskByName["B"] != RiskCritical {
- t.Errorf("B: expected CRITICAL, got %s", riskByName["B"])
- }
- if riskByName["C"] != RiskHigh {
- t.Errorf("C: expected HIGH, got %s", riskByName["C"])
- }
- if riskByName["D"] != RiskMedium {
- t.Errorf("D: expected MEDIUM, got %s", riskByName["D"])
- }
-
- // Build summary
- summary := BuildImpactSummary(deduped, result.Edges)
- if summary.Critical != 1 || summary.High != 1 || summary.Medium != 1 {
- t.Errorf("summary: critical=%d high=%d medium=%d, want 1/1/1", summary.Critical, summary.High, summary.Medium)
- }
- if summary.Total != 3 {
- t.Errorf("total=%d, want 3", summary.Total)
- }
-}
-
-func TestBFSWithCrossServiceEdges(t *testing.T) {
- s, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
-
- idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
- idB, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
-
- _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "HTTP_CALLS"})
-
- result, err := s.BFS(idA, "outbound", []string{"CALLS", "HTTP_CALLS"}, 1, 200)
- if err != nil {
- t.Fatal(err)
- }
-
- summary := BuildImpactSummary(result.Visited, result.Edges)
- if !summary.HasCrossService {
- t.Error("expected has_cross_service=true for HTTP_CALLS edge")
- }
-}
-
-func TestDumpToFile(t *testing.T) {
- // Create in-memory store with test data
- mem, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer mem.Close()
-
- if err := mem.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
- id, err := mem.UpsertNode(&Node{
- Project: "test",
- Label: "Function",
- Name: "Hello",
- QualifiedName: "test.main.Hello",
- FilePath: "main.go",
- StartLine: 1,
- EndLine: 5,
- Properties: map[string]any{"sig": "func Hello()"},
- })
- if err != nil || id == 0 {
- t.Fatalf("UpsertNode: id=%d err=%v", id, err)
- }
-
- // Dump to temp file
- dir := t.TempDir()
- destPath := filepath.Join(dir, "dump.db")
- if err := mem.DumpToFile(destPath); err != nil {
- t.Fatalf("DumpToFile: %v", err)
- }
-
- // Verify file exists and has content
- fi, err := os.Stat(destPath)
- if err != nil {
- t.Fatalf("stat: %v", err)
- }
- if fi.Size() == 0 {
- t.Fatal("dumped DB is empty")
- }
-
- // Open the dumped file and verify data survived
- disk, err := OpenPath(destPath)
- if err != nil {
- t.Fatalf("OpenPath dumped: %v", err)
- }
- defer disk.Close()
-
- found, err := disk.FindNodeByQN("test", "test.main.Hello")
- if err != nil {
- t.Fatalf("FindNodeByQN: %v", err)
- }
- if found == nil {
- t.Fatal("node not found in dumped DB")
- }
- if found.Name != "Hello" {
- t.Errorf("expected Hello, got %s", found.Name)
- }
- if found.Properties["sig"] != "func Hello()" {
- t.Errorf("properties mismatch: %v", found.Properties)
- }
-}
-
-func TestRestoreFrom(t *testing.T) {
- // Create in-memory store with test data
- mem, err := OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer mem.Close()
-
- if err := mem.UpsertProject("test", "/tmp/test"); err != nil {
- t.Fatal(err)
- }
- for i := 0; i < 100; i++ {
- _, err := mem.UpsertNode(&Node{
- Project: "test",
- Label: "Function",
- Name: fmt.Sprintf("Func%d", i),
- QualifiedName: fmt.Sprintf("test.main.Func%d", i),
- FilePath: "main.go",
- StartLine: i * 10,
- EndLine: i*10 + 5,
- })
- if err != nil {
- t.Fatal(err)
- }
- }
-
- // Create disk store as destination
- dir := t.TempDir()
- diskPath := filepath.Join(dir, "restore.db")
- disk, err := OpenPath(diskPath)
- if err != nil {
- t.Fatal(err)
- }
- defer disk.Close()
-
- // Restore: copy from in-memory → disk
- if err := disk.RestoreFrom(mem); err != nil {
- t.Fatalf("RestoreFrom: %v", err)
- }
-
- // Verify data landed in the disk store
- found, err := disk.FindNodeByQN("test", "test.main.Func42")
- if err != nil {
- t.Fatalf("FindNodeByQN: %v", err)
- }
- if found == nil {
- t.Fatal("node not found after restore")
- }
- if found.Name != "Func42" {
- t.Errorf("expected Func42, got %s", found.Name)
- }
-
- // Verify count
- nc, _ := disk.CountNodes("test")
- if nc != 100 {
- t.Errorf("expected 100 nodes, got %d", nc)
- }
-}
diff --git a/internal/store/traverse.go b/internal/store/traverse.go
deleted file mode 100644
index 37e2ab8a4..000000000
--- a/internal/store/traverse.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package store
-
-import (
- "fmt"
- "strings"
-)
-
-// TraverseResult holds BFS traversal results.
-type TraverseResult struct {
- Root *Node
- Visited []*NodeHop
- Edges []EdgeInfo
-}
-
-// NodeHop is a node with its BFS hop distance.
-type NodeHop struct {
- Node *Node
- Hop int
-}
-
-// EdgeInfo is a simplified edge for output.
-type EdgeInfo struct {
- FromName string
- ToName string
- Type string
- Confidence float64
-}
-
-// BFS performs breadth-first traversal following edges of given types using a
-// recursive CTE, replacing the previous per-node Go-side loop with a single
-// SQL round-trip.
-// direction: "outbound" follows source->target, "inbound" follows target->source.
-// maxDepth caps the BFS depth, maxResults caps total visited nodes.
-func (s *Store) BFS(startNodeID int64, direction string, edgeTypes []string, maxDepth, maxResults int) (*TraverseResult, error) {
- if maxDepth <= 0 {
- maxDepth = 3
- }
- if maxResults <= 0 {
- maxResults = 200
- }
- if len(edgeTypes) == 0 {
- edgeTypes = []string{"CALLS"}
- }
-
- // Build type filter placeholders
- typePlaceholders := make([]string, len(edgeTypes))
- typeArgs := make([]any, len(edgeTypes))
- for i, et := range edgeTypes {
- typePlaceholders[i] = "?"
- typeArgs[i] = et
- }
- typeFilter := strings.Join(typePlaceholders, ",")
-
- // Determine join columns based on direction
- var joinCol, nextCol string
- if direction == "inbound" {
- joinCol, nextCol = "target_id", "source_id"
- } else {
- joinCol, nextCol = "source_id", "target_id"
- }
-
- // Recursive CTE: traverse edges up to maxDepth hops, collect node IDs + edges
- query := fmt.Sprintf(`
- WITH RECURSIVE bfs(node_id, hop) AS (
- SELECT ?, 0
- UNION ALL
- SELECT e.%s, b.hop + 1
- FROM bfs b
- JOIN edges e ON e.%s = b.node_id AND e.type IN (%s)
- WHERE b.hop < ?
- )
- SELECT DISTINCT n.id, n.project, n.label, n.name, n.qualified_name,
- n.file_path, n.start_line, n.end_line, n.properties, bfs.hop
- FROM bfs
- JOIN nodes n ON n.id = bfs.node_id
- WHERE bfs.hop > 0
- ORDER BY bfs.hop, n.name
- LIMIT ?`,
- nextCol, joinCol, typeFilter)
-
- // Build args: startNodeID, ...typeArgs, maxDepth, maxResults
- args := make([]any, 0, 3+len(typeArgs))
- args = append(args, startNodeID)
- args = append(args, typeArgs...)
- args = append(args, maxDepth, maxResults)
-
- rows, err := s.q.Query(query, args...)
- if err != nil {
- return nil, fmt.Errorf("bfs cte: %w", err)
- }
- defer rows.Close()
-
- result := &TraverseResult{}
- for rows.Next() {
- var n Node
- var props string
- var hop int
- if err := rows.Scan(&n.ID, &n.Project, &n.Label, &n.Name, &n.QualifiedName,
- &n.FilePath, &n.StartLine, &n.EndLine, &props, &hop); err != nil {
- return nil, err
- }
- n.Properties = unmarshalProps(props)
- result.Visited = append(result.Visited, &NodeHop{Node: &n, Hop: hop})
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- // Collect edge info with a second CTE query that returns actual edges
- edgeQuery := fmt.Sprintf(`
- WITH RECURSIVE bfs(node_id, hop) AS (
- SELECT ?, 0
- UNION ALL
- SELECT e.%s, b.hop + 1
- FROM bfs b
- JOIN edges e ON e.%s = b.node_id AND e.type IN (%s)
- WHERE b.hop < ?
- )
- SELECT DISTINCT src.name, tgt.name, e.type,
- COALESCE(json_extract(e.properties, '$.confidence'), 0) as confidence
- FROM bfs b
- JOIN edges e ON e.%s = b.node_id AND e.type IN (%s)
- JOIN nodes src ON src.id = e.source_id
- JOIN nodes tgt ON tgt.id = e.target_id
- WHERE b.hop < ?`,
- nextCol, joinCol, typeFilter,
- joinCol, typeFilter)
-
- // Build edge args: startNodeID, ...typeArgs, maxDepth, ...typeArgs, maxDepth
- edgeArgs := make([]any, 0, 4+2*len(typeArgs))
- edgeArgs = append(edgeArgs, startNodeID)
- edgeArgs = append(edgeArgs, typeArgs...)
- edgeArgs = append(edgeArgs, maxDepth)
- edgeArgs = append(edgeArgs, typeArgs...)
- edgeArgs = append(edgeArgs, maxDepth)
-
- edgeRows, err := s.q.Query(edgeQuery, edgeArgs...)
- if err != nil {
- return nil, fmt.Errorf("bfs edges: %w", err)
- }
- defer edgeRows.Close()
-
- for edgeRows.Next() {
- var ei EdgeInfo
- if err := edgeRows.Scan(&ei.FromName, &ei.ToName, &ei.Type, &ei.Confidence); err != nil {
- return nil, err
- }
- result.Edges = append(result.Edges, ei)
- }
-
- return result, edgeRows.Err()
-}
diff --git a/internal/store/traverse_bench_test.go b/internal/store/traverse_bench_test.go
deleted file mode 100644
index 9da3a5982..000000000
--- a/internal/store/traverse_bench_test.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package store
-
-import (
- "fmt"
- "testing"
-)
-
-// populateTraverseBench creates a graph with controlled fan-out for BFS benchmarks.
-// Root node calls nodes 1-fanOut, each of which calls fanOut more nodes (depth 2).
-func populateTraverseBench(b *testing.B, fanOut int) (s *Store, rootID int64) {
- b.Helper()
- var err error
- s, err = OpenMemory()
- if err != nil {
- b.Fatal(err)
- }
- if err := s.UpsertProject("bench", "/tmp/bench"); err != nil {
- b.Fatal(err)
- }
-
- nextID := 0
- makeNode := func(name string) int64 {
- id, nodeErr := s.UpsertNode(&Node{
- Project: "bench",
- Label: "Function",
- Name: name,
- QualifiedName: fmt.Sprintf("bench.pkg.%s", name),
- FilePath: "pkg/funcs.go",
- StartLine: nextID*5 + 1,
- EndLine: nextID*5 + 4,
- })
- if nodeErr != nil {
- b.Fatal(nodeErr)
- }
- nextID++
- return id
- }
-
- rootID = makeNode("Root")
-
- // Depth 1: root -> children
- depth1IDs := make([]int64, fanOut)
- for i := 0; i < fanOut; i++ {
- depth1IDs[i] = makeNode(fmt.Sprintf("Child%d", i))
- if _, err := s.InsertEdge(&Edge{
- Project: "bench",
- SourceID: rootID,
- TargetID: depth1IDs[i],
- Type: "CALLS",
- }); err != nil {
- b.Fatal(err)
- }
- }
-
- // Depth 2: each depth-1 node -> fanOut leaf nodes
- for i, parentID := range depth1IDs {
- for j := 0; j < fanOut; j++ {
- leafID := makeNode(fmt.Sprintf("Leaf%d_%d", i, j))
- if _, err := s.InsertEdge(&Edge{
- Project: "bench",
- SourceID: parentID,
- TargetID: leafID,
- Type: "CALLS",
- }); err != nil {
- b.Fatal(err)
- }
- }
- }
-
- return s, rootID
-}
-
-func BenchmarkBFS50Edges(b *testing.B) {
- // fanOut=7 gives 1 + 7 + 49 = 57 nodes and 56 edges (close to 50)
- s, rootID := populateTraverseBench(b, 7)
- defer s.Close()
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- result, err := s.BFS(rootID, "outbound", []string{"CALLS"}, 3, 200)
- if err != nil {
- b.Fatal(err)
- }
- if len(result.Visited) == 0 {
- b.Fatal("expected visited nodes")
- }
- }
-}
-
-func BenchmarkBFS200Edges(b *testing.B) {
- // fanOut=14 gives 1 + 14 + 196 = 211 nodes, 210 edges
- s, rootID := populateTraverseBench(b, 14)
- defer s.Close()
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- result, err := s.BFS(rootID, "outbound", []string{"CALLS"}, 3, 300)
- if err != nil {
- b.Fatal(err)
- }
- if len(result.Visited) == 0 {
- b.Fatal("expected visited nodes")
- }
- }
-}
-
-func BenchmarkBFSInbound(b *testing.B) {
- s, err := OpenMemory()
- if err != nil {
- b.Fatal(err)
- }
- defer s.Close()
-
- if err := s.UpsertProject("bench", "/tmp/bench"); err != nil {
- b.Fatal(err)
- }
-
- // Create a "popular" function called by 50 callers
- targetID, _ := s.UpsertNode(&Node{
- Project: "bench",
- Label: "Function",
- Name: "PopularFunc",
- QualifiedName: "bench.pkg.PopularFunc",
- FilePath: "pkg/popular.go",
- })
-
- for i := 0; i < 50; i++ {
- callerID, _ := s.UpsertNode(&Node{
- Project: "bench",
- Label: "Function",
- Name: fmt.Sprintf("Caller%d", i),
- QualifiedName: fmt.Sprintf("bench.callers.Caller%d", i),
- FilePath: fmt.Sprintf("callers/caller%d.go", i),
- })
- if _, err := s.InsertEdge(&Edge{
- Project: "bench",
- SourceID: callerID,
- TargetID: targetID,
- Type: "CALLS",
- }); err != nil {
- b.Fatal(err)
- }
- }
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- result, err := s.BFS(targetID, "inbound", []string{"CALLS"}, 2, 200)
- if err != nil {
- b.Fatal(err)
- }
- if len(result.Visited) == 0 {
- b.Fatal("expected visited nodes")
- }
- }
-}
-
-func BenchmarkBFSDepthScaled(b *testing.B) {
- for _, depth := range []int{1, 2, 3, 5} {
- b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) {
- s, rootID := populateTraverseBench(b, 5)
- defer s.Close()
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- _, err := s.BFS(rootID, "outbound", []string{"CALLS"}, depth, 500)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
- }
-}
diff --git a/internal/tools/architecture.go b/internal/tools/architecture.go
deleted file mode 100644
index c6ddcc613..000000000
--- a/internal/tools/architecture.go
+++ /dev/null
@@ -1,326 +0,0 @@
-package tools
-
-import (
- "context"
- "database/sql"
- "errors"
- "fmt"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-// validArchAspects lists all recognized aspect names.
-var validArchAspects = map[string]bool{
- "all": true, "languages": true, "packages": true, "entry_points": true,
- "routes": true, "hotspots": true, "boundaries": true, "services": true,
- "layers": true, "clusters": true, "file_tree": true, "adr": true,
-}
-
-func (s *Server) handleGetArchitecture(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- aspects, validErr := parseAspects(args)
- if validErr != nil {
- return errResult(validErr.Error()), nil
- }
-
- project := getStringArg(args, "project")
- st, err := s.resolveStore(project)
- if err != nil {
- return errResult(fmt.Sprintf("resolve store: %v", err)), nil
- }
-
- projName := s.resolveProjectName(project)
- projects, _ := st.ListProjects()
- if len(projects) > 0 {
- projName = projects[0].Name
- }
-
- info, err := st.GetArchitecture(projName, aspects)
- if err != nil {
- return errResult(fmt.Sprintf("architecture: %v", err)), nil
- }
-
- responseData := buildArchResponse(projName, info)
- addADRToResponse(responseData, aspects, st, projName)
-
- s.addIndexStatus(responseData)
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result, nil
-}
-
-// parseAspects extracts and validates the aspects array from tool arguments.
-func parseAspects(args map[string]any) ([]string, error) {
- rawAspects, ok := args["aspects"]
- if !ok {
- return []string{"all"}, nil
- }
- arr, ok := rawAspects.([]any)
- if !ok {
- return []string{"all"}, nil
- }
- var aspects []string
- for _, a := range arr {
- str, ok := a.(string)
- if !ok {
- continue
- }
- if !validArchAspects[str] {
- return nil, fmt.Errorf("unknown aspect: %q", str)
- }
- aspects = append(aspects, str)
- }
- if len(aspects) == 0 {
- return []string{"all"}, nil
- }
- return aspects, nil
-}
-
-// buildArchResponse converts ArchitectureInfo fields into a response map,
-// including only non-nil aspects.
-func buildArchResponse(projName string, info *store.ArchitectureInfo) map[string]any {
- data := map[string]any{"project": projName}
- if info.Languages != nil {
- data["languages"] = info.Languages
- }
- if info.Packages != nil {
- data["packages"] = info.Packages
- }
- if info.EntryPoints != nil {
- data["entry_points"] = info.EntryPoints
- }
- if info.Routes != nil {
- data["routes"] = info.Routes
- }
- if info.Hotspots != nil {
- data["hotspots"] = info.Hotspots
- }
- if info.Boundaries != nil {
- data["boundaries"] = info.Boundaries
- }
- if info.Services != nil {
- data["services"] = info.Services
- }
- if info.Layers != nil {
- data["layers"] = info.Layers
- }
- if info.Clusters != nil {
- data["clusters"] = info.Clusters
- }
- if info.FileTree != nil {
- data["file_tree"] = info.FileTree
- }
- return data
-}
-
-// addADRToResponse includes the stored ADR in the response when requested.
-func addADRToResponse(data map[string]any, aspects []string, st *store.Store, projName string) {
- wantADR := false
- for _, a := range aspects {
- if a == "adr" || a == "all" {
- wantADR = true
- break
- }
- }
- if !wantADR {
- return
- }
- adr, getErr := st.GetADR(projName)
- if getErr != nil || adr == nil {
- data["adr"] = nil
- hint := "No ADR yet. Create one with manage_adr(mode='store', content='## PURPOSE\\n...\\n\\n## STACK\\n...'). For guided creation: explore the codebase, enter plan mode, draft collaboratively, then store. Sections: PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY."
- if docs, err := st.FindArchitectureDocs(projName); err == nil && len(docs) > 0 {
- hint += fmt.Sprintf(" Existing architecture docs found: %v — consider reading these first.", docs)
- }
- data["adr_hint"] = hint
- return
- }
- data["adr"] = map[string]any{
- "text": adr.Content,
- "updated_at": adr.UpdatedAt,
- }
-}
-
-func (s *Server) handleManageADR(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- mode := getStringArg(args, "mode")
- if mode == "" {
- return errResult("mode is required ('get', 'store', 'update', or 'delete')"), nil
- }
-
- project := getStringArg(args, "project")
- st, err := s.resolveStore(project)
- if err != nil {
- return errResult(fmt.Sprintf("resolve store: %v", err)), nil
- }
-
- projName := s.resolveProjectName(project)
- projects, _ := st.ListProjects()
- if len(projects) > 0 {
- projName = projects[0].Name
- }
-
- switch mode {
- case "get":
- include := parseStringArray(args, "include")
- if err := validateSectionFilter(include); err != nil {
- return errResult(err.Error()), nil
- }
- return s.handleADRGet(st, projName, include)
- case "store":
- content := getStringArg(args, "content")
- return s.handleADRStore(st, projName, content)
- case "update":
- sections := getMapStringArg(args, "sections")
- return s.handleADRUpdate(st, projName, sections)
- case "delete":
- return s.handleADRDelete(st, projName)
- default:
- return errResult(fmt.Sprintf("invalid mode: %q (use 'get', 'store', 'update', or 'delete')", mode)), nil
- }
-}
-
-func (s *Server) handleADRGet(st *store.Store, projName string, include []string) (*mcp.CallToolResult, error) {
- adr, err := st.GetADR(projName)
- if err != nil {
- if !errors.Is(err, sql.ErrNoRows) {
- return nil, fmt.Errorf("get ADR: %w", err)
- }
- hint := "No ADR yet. Create one with manage_adr(mode='store', content='## PURPOSE\\n...\\n\\n## STACK\\n...\\n\\n## ARCHITECTURE\\n...\\n\\n## PATTERNS\\n...\\n\\n## TRADEOFFS\\n...\\n\\n## PHILOSOPHY\\n...'). All 6 sections required: PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY."
- if docs, findErr := st.FindArchitectureDocs(projName); findErr == nil && len(docs) > 0 {
- hint += fmt.Sprintf(" Existing architecture docs found: %v — consider reading these first.", docs)
- }
- return jsonResult(map[string]any{
- "project": projName,
- "adr": nil,
- "adr_hint": hint,
- }), nil
- }
-
- sections := store.ParseADRSections(adr.Content)
-
- const alignHint = "If you are drafting or finalizing a plan, validate it against the ADR: " +
- "check ARCHITECTURE for structural fit, PATTERNS for convention compliance, " +
- "STACK for technology alignment, and PHILOSOPHY for principle adherence. " +
- "Flag any conflicts before proceeding."
-
- // Filter sections if include list is provided.
- if len(include) > 0 {
- filtered := make(map[string]string, len(include))
- for _, name := range include {
- if content, ok := sections[name]; ok {
- filtered[name] = content
- }
- }
- return jsonResult(map[string]any{
- "project": projName,
- "sections": filtered,
- "updated_at": adr.UpdatedAt,
- "alignment_hint": alignHint,
- }), nil
- }
-
- return jsonResult(map[string]any{
- "project": projName,
- "sections": sections,
- "text": adr.Content,
- "updated_at": adr.UpdatedAt,
- "alignment_hint": alignHint,
- }), nil
-}
-
-func (s *Server) handleADRStore(st *store.Store, projName, content string) (*mcp.CallToolResult, error) {
- if content == "" {
- return errResult("content is required for mode='store'"), nil
- }
- if len(content) > store.MaxADRLength() {
- return errResult(fmt.Sprintf("ADR too long (%d chars, max %d)", len(content), store.MaxADRLength())), nil
- }
- if err := store.ValidateADRContent(content); err != nil {
- return errResult(err.Error()), nil
- }
- if err := st.StoreADR(projName, content); err != nil {
- return errResult(fmt.Sprintf("store ADR: %v", err)), nil
- }
- return jsonResult(map[string]any{
- "status": "stored",
- "project": projName,
- "updated_at": store.Now(),
- }), nil
-}
-
-func (s *Server) handleADRUpdate(st *store.Store, projName string, sections map[string]string) (*mcp.CallToolResult, error) {
- if len(sections) == 0 {
- return errResult("sections is required for mode='update' — e.g. {\"PURPOSE\": \"...\", \"STACK\": \"...\"}"), nil
- }
- if err := store.ValidateADRSectionKeys(sections); err != nil {
- return errResult(err.Error()), nil
- }
- adr, err := st.UpdateADRSections(projName, sections)
- if err != nil {
- return errResult(fmt.Sprintf("update ADR: %v", err)), nil
- }
- parsed := store.ParseADRSections(adr.Content)
- return jsonResult(map[string]any{
- "status": "updated",
- "project": projName,
- "sections": parsed,
- "text": adr.Content,
- "updated_at": adr.UpdatedAt,
- }), nil
-}
-
-func (s *Server) handleADRDelete(st *store.Store, projName string) (*mcp.CallToolResult, error) {
- if err := st.DeleteADR(projName); err != nil {
- return errResult(fmt.Sprintf("delete ADR: %v", err)), nil
- }
- return jsonResult(map[string]any{
- "status": "deleted",
- "project": projName,
- }), nil
-}
-
-// parseStringArray extracts a string array from tool arguments.
-func parseStringArray(args map[string]any, key string) []string {
- raw, ok := args[key]
- if !ok {
- return nil
- }
- arr, ok := raw.([]any)
- if !ok {
- return nil
- }
- var result []string
- for _, v := range arr {
- if s, ok := v.(string); ok {
- result = append(result, s)
- }
- }
- return result
-}
-
-// validateSectionFilter checks that all names in the include filter are canonical sections.
-func validateSectionFilter(include []string) error {
- if len(include) == 0 {
- return nil
- }
- return store.ValidateADRSectionKeys(stringsToMap(include))
-}
-
-// stringsToMap converts a string slice to a map[string]string for key validation.
-func stringsToMap(ss []string) map[string]string {
- m := make(map[string]string, len(ss))
- for _, s := range ss {
- m[s] = ""
- }
- return m
-}
diff --git a/internal/tools/code_search.go b/internal/tools/code_search.go
deleted file mode 100644
index f3c464161..000000000
--- a/internal/tools/code_search.go
+++ /dev/null
@@ -1,232 +0,0 @@
-package tools
-
-import (
- "bufio"
- "context"
- "fmt"
- "os"
- "path/filepath"
- "regexp"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-type codeMatch struct {
- File string `json:"file"`
- Line int `json:"line"`
- Content string `json:"content"`
-}
-
-// searchCodeParams holds parsed parameters for a code search request.
-type searchCodeParams struct {
- pattern string
- fileGlob string
- maxResults int
- offset int
- isRegex bool
- caseSensitive bool
- re *regexp.Regexp
- project string
-}
-
-// parseSearchCodeParams extracts and validates search_code parameters from the request.
-func parseSearchCodeParams(req *mcp.CallToolRequest) (*searchCodeParams, *mcp.CallToolResult) {
- args, err := parseArgs(req)
- if err != nil {
- return nil, errResult(err.Error())
- }
-
- p := &searchCodeParams{
- pattern: getStringArg(args, "pattern"),
- fileGlob: getStringArg(args, "file_pattern"),
- maxResults: getIntArg(args, "max_results", 10),
- offset: getIntArg(args, "offset", 0),
- isRegex: getBoolArg(args, "regex"),
- caseSensitive: getBoolArg(args, "case_sensitive"),
- project: getStringArg(args, "project"),
- }
-
- if p.pattern == "" {
- return nil, errResult("pattern is required")
- }
-
- if p.isRegex {
- pattern := p.pattern
- if !p.caseSensitive && !strings.HasPrefix(pattern, "(?i)") {
- pattern = "(?i)" + pattern
- }
- p.re, err = regexp.Compile(pattern)
- if err != nil {
- return nil, errResult(fmt.Sprintf("invalid regex: %v", err))
- }
- } else if !p.caseSensitive {
- // For literal mode, lowercase the pattern; matching done case-insensitively
- p.pattern = strings.ToLower(p.pattern)
- }
-
- return p, nil
-}
-
-func (s *Server) handleSearchCode(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- params, errRes := parseSearchCodeParams(req)
- if errRes != nil {
- return errRes, nil
- }
-
- // Resolve project root
- root, err := s.resolveProjectRoot(params.project)
- if err != nil {
- return errResult(fmt.Sprintf("resolve root: %v", err)), nil
- }
-
- filePaths := s.collectSearchFilePaths(params.fileGlob, params.project)
-
- // Collect all matches up to offset+maxResults for accurate total count
- fetchLimit := params.offset + params.maxResults
- var allMatches []codeMatch
- for _, relPath := range filePaths {
- if len(allMatches) >= fetchLimit {
- break
- }
-
- absPath := filepath.Join(root, relPath)
- fileMatches := searchFile(absPath, relPath, params.pattern, params.re, params.isRegex, params.caseSensitive, fetchLimit-len(allMatches))
- allMatches = append(allMatches, fileMatches...)
- }
-
- total := len(allMatches)
- hasMore := total >= fetchLimit
-
- // Apply offset and limit
- start := params.offset
- if start > total {
- start = total
- }
- end := start + params.maxResults
- if end > total {
- end = total
- }
- pageMatches := allMatches[start:end]
-
- responseData := map[string]any{
- "pattern": params.pattern,
- "total": total,
- "limit": params.maxResults,
- "offset": params.offset,
- "has_more": hasMore,
- "matches": pageMatches,
- "files_count": len(filePaths),
- }
- s.addIndexStatus(responseData)
-
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result, nil
-}
-
-// collectSearchFilePaths gathers indexed file paths, optionally filtered by a glob pattern.
-func (s *Server) collectSearchFilePaths(fileGlob, project string) []string {
- var filePaths []string
-
- collectFromStore := func(st *store.Store, projName string) {
- files, _ := st.FindNodesByLabel(projName, "File")
- for _, f := range files {
- if f.FilePath == "" {
- continue
- }
- if fileGlob != "" {
- matched, _ := filepath.Match(fileGlob, filepath.Base(f.FilePath))
- if !matched {
- matched = globMatch(fileGlob, f.FilePath)
- }
- if !matched {
- continue
- }
- }
- filePaths = append(filePaths, f.FilePath)
- }
- }
-
- st, err := s.resolveStore(project)
- if err != nil {
- return filePaths
- }
-
- projName := s.resolveProjectName(project)
- projects, _ := st.ListProjects()
- if len(projects) > 0 {
- projName = projects[0].Name
- }
- collectFromStore(st, projName)
-
- return filePaths
-}
-
-func searchFile(absPath, relPath, pattern string, re *regexp.Regexp, isRegex, caseSensitive bool, limit int) []codeMatch {
- f, err := os.Open(absPath)
- if err != nil {
- return nil
- }
- defer f.Close()
-
- var matches []codeMatch
- scanner := bufio.NewScanner(f)
- scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
- lineNum := 0
-
- for scanner.Scan() {
- lineNum++
- line := scanner.Text()
-
- var found bool
- switch {
- case isRegex:
- found = re.MatchString(line)
- case caseSensitive:
- found = strings.Contains(line, pattern)
- default:
- // pattern already lowercased in parseSearchCodeParams
- found = strings.Contains(strings.ToLower(line), pattern)
- }
-
- if found {
- content := strings.TrimSpace(line)
- if len(content) > 200 {
- content = content[:200] + "..."
- }
- matches = append(matches, codeMatch{
- File: relPath,
- Line: lineNum,
- Content: content,
- })
- if len(matches) >= limit {
- break
- }
- }
- }
-
- return matches
-}
-
-// globMatch does a simple glob match supporting ** patterns.
-func globMatch(pattern, path string) bool {
- if strings.Contains(pattern, "**") {
- // Split pattern on **
- parts := strings.SplitN(pattern, "**", 2)
- prefix := strings.TrimRight(parts[0], "/")
- suffix := strings.TrimLeft(parts[1], "/")
-
- if prefix != "" && !strings.HasPrefix(path, prefix) {
- return false
- }
- if suffix != "" {
- matched, _ := filepath.Match(suffix, filepath.Base(path))
- return matched
- }
- return true
- }
- matched, _ := filepath.Match(pattern, path)
- return matched
-}
diff --git a/internal/tools/detect_changes.go b/internal/tools/detect_changes.go
deleted file mode 100644
index 7780233fb..000000000
--- a/internal/tools/detect_changes.go
+++ /dev/null
@@ -1,363 +0,0 @@
-package tools
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "sort"
-
- "github.com/DeusData/codebase-memory-mcp/internal/pipeline"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) registerDetectChanges() {
- s.addTool(&mcp.Tool{
- Name: "detect_changes",
- Description: "Detect uncommitted or branch changes and map them to affected graph symbols + blast radius. Runs git diff, maps changed hunks to functions/classes in the graph, then traces inbound callers with risk classification (CRITICAL/HIGH/MEDIUM/LOW). Requires git in PATH. Risk is topology-based: hop 1=CRITICAL (direct callers), 2=HIGH, 3=MEDIUM, 4+=LOW.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "scope": {
- "type": "string",
- "description": "Which changes to analyze: 'unstaged' (working tree), 'staged' (git add), 'all' (HEAD, default), 'branch' (compare with base_branch)",
- "enum": ["unstaged", "staged", "all", "branch"]
- },
- "base_branch": {
- "type": "string",
- "description": "Base branch for scope=branch comparison (default: main)"
- },
- "depth": {
- "type": "integer",
- "description": "Maximum BFS depth for impact tracing (1-5, default 3)"
- },
- "project": {
- "type": "string",
- "description": "Project to analyze. Defaults to session project."
- }
- }
- }`),
- }, s.handleDetectChanges)
-}
-
-func (s *Server) handleDetectChanges(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- scopeStr := getStringArg(args, "scope")
- if scopeStr == "" {
- scopeStr = "all"
- }
- scope := pipeline.DiffScope(scopeStr)
-
- baseBranch := getStringArg(args, "base_branch")
- depth := getIntArg(args, "depth", 3)
- if depth < 1 {
- depth = 1
- }
- if depth > 5 {
- depth = 5
- }
-
- project := getStringArg(args, "project")
- effectiveProject := s.resolveProjectName(project)
-
- st, repoPath, projName, resolveErr := s.resolveDetectRepo(effectiveProject)
- if resolveErr != nil {
- return resolveErr, nil
- }
-
- // Parse changed files
- changedFiles, err := pipeline.ParseGitDiffFiles(repoPath, scope, baseBranch)
- if err != nil {
- return errResult(fmt.Sprintf("git diff: %v", err)), nil
- }
-
- if len(changedFiles) == 0 {
- return s.emptyDetectResponse(), nil
- }
-
- // Parse hunks for line-level mapping
- hunks, err := pipeline.ParseGitDiffHunks(repoPath, scope, baseBranch)
- if err != nil {
- slog.Warn("detect_changes.hunks.err", "err", err)
- }
-
- changedSymbols := mapChangesToSymbols(st, projName, changedFiles, hunks)
- impactedSymbols, allEdges := traceImpact(st, changedSymbols, depth)
- summary := buildDetectSummary(changedFiles, changedSymbols, impactedSymbols, allEdges)
-
- responseData := map[string]any{
- "changed_files": buildFileList(changedFiles),
- "changed_symbols": buildSymbolList(changedSymbols),
- "impacted_symbols": buildImpactList(impactedSymbols),
- "summary": summary,
- }
- s.addIndexStatus(responseData)
-
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result, nil
-}
-
-// resolveDetectRepo resolves the store, repo path, and project name for detect_changes.
-func (s *Server) resolveDetectRepo(effectiveProject string) (st *store.Store, repoPath, projName string, toolErr *mcp.CallToolResult) {
- var err error
- st, err = s.resolveStore(effectiveProject)
- if err != nil {
- return nil, "", "", errResult(err.Error())
- }
-
- projects, _ := st.ListProjects()
- if len(projects) == 0 {
- return nil, "", "", errResult("no projects indexed")
- }
- projName = projects[0].Name
- proj, err := st.GetProject(projName)
- if err != nil {
- return nil, "", "", errResult(fmt.Sprintf("project %q: %v", effectiveProject, err))
- }
- if proj == nil {
- return nil, "", "", errResult(fmt.Sprintf("project %q not found", effectiveProject))
- }
- if proj.RootPath == "" {
- return nil, "", "", errResult("project has no root_path — reindex with repo_path")
- }
- return st, proj.RootPath, projName, nil
-}
-
-func (s *Server) emptyDetectResponse() *mcp.CallToolResult {
- responseData := map[string]any{
- "changed_files": []any{},
- "changed_symbols": []any{},
- "impacted_symbols": []any{},
- "summary": map[string]any{
- "changed_files": 0,
- "changed_symbols": 0,
- "critical": 0,
- "high": 0,
- "medium": 0,
- "low": 0,
- "total": 0,
- "has_cross_service": false,
- },
- }
- s.addIndexStatus(responseData)
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result
-}
-
-func buildFileList(files []pipeline.ChangedFile) []map[string]any {
- result := make([]map[string]any, len(files))
- for i, f := range files {
- entry := map[string]any{"status": f.Status, "path": f.Path}
- if f.OldPath != "" {
- entry["old_path"] = f.OldPath
- }
- result[i] = entry
- }
- return result
-}
-
-func buildSymbolList(symbols []*store.Node) []map[string]any {
- result := make([]map[string]any, len(symbols))
- for i, n := range symbols {
- result[i] = map[string]any{
- "name": n.Name,
- "qualified_name": n.QualifiedName,
- "label": n.Label,
- "file_path": n.FilePath,
- "start_line": n.StartLine,
- "end_line": n.EndLine,
- }
- }
- return result
-}
-
-func buildImpactList(impacted []impactedSymbol) []map[string]any {
- result := make([]map[string]any, len(impacted))
- for i, is := range impacted {
- result[i] = map[string]any{
- "name": is.Node.Name,
- "qualified_name": is.Node.QualifiedName,
- "label": is.Node.Label,
- "file_path": is.Node.FilePath,
- "risk": string(store.HopToRisk(is.Hop)),
- "hop": is.Hop,
- "changed_by": is.ChangedBy,
- }
- }
- return result
-}
-
-// impactedSymbol extends NodeHop with the symbol that caused the impact.
-type impactedSymbol struct {
- Node *store.Node
- Hop int
- ChangedBy string // name of the changed symbol that led to this impact
-}
-
-// mapChangesToSymbols finds graph nodes affected by the changed hunks.
-func mapChangesToSymbols(st *store.Store, project string, files []pipeline.ChangedFile, hunks []pipeline.ChangedHunk) []*store.Node {
- seen := make(map[int64]bool)
- var result []*store.Node
-
- hunksByFile := make(map[string][]pipeline.ChangedHunk)
- for _, h := range hunks {
- hunksByFile[h.Path] = append(hunksByFile[h.Path], h)
- }
-
- for _, f := range files {
- if f.Status == "D" {
- continue
- }
- nodes := resolveFileSymbols(st, project, f.Path, hunksByFile[f.Path])
- for _, n := range nodes {
- if !seen[n.ID] {
- seen[n.ID] = true
- result = append(result, n)
- }
- }
- }
-
- if len(result) == 0 && len(files) > 0 {
- logZeroSymbolsDiag(files)
- }
-
- return result
-}
-
-// resolveFileSymbols finds symbols for a single file, using hunk-level overlap when available.
-func resolveFileSymbols(st *store.Store, project, path string, hunks []pipeline.ChangedHunk) []*store.Node {
- if len(hunks) > 0 {
- return resolveByHunks(st, project, path, hunks)
- }
- return resolveByFile(st, project, path)
-}
-
-func resolveByHunks(st *store.Store, project, path string, hunks []pipeline.ChangedHunk) []*store.Node {
- var result []*store.Node
- for _, h := range hunks {
- nodes, err := st.FindNodesByFileOverlap(project, path, h.StartLine, h.EndLine)
- if err != nil {
- slog.Debug("detect_changes.overlap.err", "path", path, "err", err)
- continue
- }
- result = append(result, nodes...)
- }
- return result
-}
-
-func resolveByFile(st *store.Store, project, path string) []*store.Node {
- nodes, err := st.FindNodesByFile(project, path)
- if err != nil {
- slog.Debug("detect_changes.file.err", "path", path, "err", err)
- return nil
- }
- if len(nodes) == 0 {
- nodes, err = st.FindNodesByFileOverlap(project, path, 0, 999999)
- if err != nil {
- return nil
- }
- }
- return nodes
-}
-
-func logZeroSymbolsDiag(files []pipeline.ChangedFile) {
- paths := make([]string, 0, 3)
- for i, f := range files {
- if i >= 3 {
- break
- }
- paths = append(paths, f.Path)
- }
- slog.Warn("detect_changes.zero_symbols", "diff_paths", paths)
-}
-
-// traceImpact runs inbound BFS from each changed symbol and deduplicates results.
-func traceImpact(st *store.Store, changedSymbols []*store.Node, depth int) ([]impactedSymbol, []store.EdgeInfo) {
- edgeTypes := []string{"CALLS", "HTTP_CALLS", "ASYNC_CALLS"}
- bestHop := make(map[int64]*impactedSymbol)
- changedIDs := make(map[int64]bool)
- var allEdges []store.EdgeInfo
-
- for _, sym := range changedSymbols {
- changedIDs[sym.ID] = true
- }
-
- for _, sym := range changedSymbols {
- result, err := st.BFS(sym.ID, "inbound", edgeTypes, depth, 200)
- if err != nil {
- slog.Debug("detect_changes.bfs.err", "sym", sym.Name, "err", err)
- continue
- }
-
- for _, nh := range result.Visited {
- if changedIDs[nh.Node.ID] {
- continue // skip the changed symbols themselves
- }
- existing, ok := bestHop[nh.Node.ID]
- if !ok || nh.Hop < existing.Hop {
- bestHop[nh.Node.ID] = &impactedSymbol{
- Node: nh.Node,
- Hop: nh.Hop,
- ChangedBy: sym.Name,
- }
- }
- }
- allEdges = append(allEdges, result.Edges...)
- }
-
- // Sort by risk (hop ascending)
- sorted := make([]impactedSymbol, 0, len(bestHop))
- for _, is := range bestHop {
- sorted = append(sorted, *is)
- }
- sort.Slice(sorted, func(i, j int) bool {
- if sorted[i].Hop != sorted[j].Hop {
- return sorted[i].Hop < sorted[j].Hop
- }
- return sorted[i].Node.Name < sorted[j].Node.Name
- })
-
- return sorted, allEdges
-}
-
-func buildDetectSummary(files []pipeline.ChangedFile, symbols []*store.Node, impacted []impactedSymbol, edges []store.EdgeInfo) map[string]any {
- var critical, high, medium, low int
- for _, is := range impacted {
- switch store.HopToRisk(is.Hop) {
- case store.RiskCritical:
- critical++
- case store.RiskHigh:
- high++
- case store.RiskMedium:
- medium++
- case store.RiskLow:
- low++
- }
- }
-
- hasCrossService := false
- for _, e := range edges {
- if e.Type == "HTTP_CALLS" || e.Type == "ASYNC_CALLS" {
- hasCrossService = true
- break
- }
- }
-
- return map[string]any{
- "changed_files": len(files),
- "changed_symbols": len(symbols),
- "critical": critical,
- "high": high,
- "medium": medium,
- "low": low,
- "total": len(impacted),
- "has_cross_service": hasCrossService,
- }
-}
diff --git a/internal/tools/file.go b/internal/tools/file.go
deleted file mode 100644
index c7781982c..000000000
--- a/internal/tools/file.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package tools
-
-import "fmt"
-
-// resolveProjectRoot finds a project root path by name or from session.
-func (s *Server) resolveProjectRoot(project string) (string, error) {
- if project == "*" || project == "all" {
- return "", fmt.Errorf("cross-project queries are not supported; use list_projects to find a specific project name, or omit the project parameter to use the current session project")
- }
-
- // Use session root if available and no specific project requested
- if project == "" && s.sessionRoot != "" {
- return s.sessionRoot, nil
- }
-
- projName := s.resolveProjectName(project)
- if projName == "" {
- return "", fmt.Errorf("no projects indexed")
- }
- if !s.router.HasProject(projName) {
- return "", fmt.Errorf("project %q not found; use list_projects to see available projects", projName)
- }
-
- st, err := s.router.ForProject(projName)
- if err != nil {
- return "", err
- }
-
- projects, err := st.ListProjects()
- if err != nil {
- return "", err
- }
- if len(projects) == 0 {
- return "", fmt.Errorf("no projects indexed")
- }
- return projects[0].RootPath, nil
-}
diff --git a/internal/tools/index.go b/internal/tools/index.go
deleted file mode 100644
index 0bb357225..000000000
--- a/internal/tools/index.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package tools
-
-import (
- "context"
- "fmt"
- "path/filepath"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/pipeline"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) handleIndexRepository(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- repoPath := getStringArg(args, "repo_path")
- if repoPath == "" {
- repoPath = s.sessionRoot // auto-detected from session
- }
- if repoPath == "" {
- return errResult("repo_path is required (no session root detected)"), nil
- }
-
- // Parse and validate mode parameter
- modeStr := getStringArg(args, "mode")
- mode := discover.ModeFull
- if modeStr != "" {
- switch discover.IndexMode(modeStr) {
- case discover.ModeFull, discover.ModeFast:
- mode = discover.IndexMode(modeStr)
- default:
- return errResult(fmt.Sprintf("invalid mode %q: must be \"full\" or \"fast\"", modeStr)), nil
- }
- }
-
- // Resolve to absolute path
- absPath, err := filepath.Abs(repoPath)
- if err != nil {
- return errResult(fmt.Sprintf("invalid path: %v", err)), nil
- }
-
- projectName := pipeline.ProjectNameFromPath(absPath)
-
- // Lock to prevent concurrent indexing with auto-sync watcher
- s.indexMu.Lock()
- defer s.indexMu.Unlock()
-
- // Get per-project store
- st, err := s.router.ForProject(projectName)
- if err != nil {
- return errResult(fmt.Sprintf("store: %v", err)), nil
- }
-
- // Run the indexing pipeline
- p := pipeline.New(ctx, st, absPath, mode)
- if err := p.Run(); err != nil {
- return errResult(fmt.Sprintf("indexing failed: %v", err)), nil
- }
-
- // Add to watcher so auto-sync keeps this project fresh.
- s.watcher.Watch(projectName, absPath)
-
- // Update session state if this is the session project
- if projectName == s.sessionProject {
- s.indexStatus.Store("ready")
- }
-
- // Gather stats
- nodeCount, _ := st.CountNodes(projectName)
- edgeCount, _ := st.CountEdges(projectName)
-
- proj, _ := st.GetProject(projectName)
- indexedAt := store.Now()
- if proj != nil {
- indexedAt = proj.IndexedAt
- }
-
- result := map[string]any{
- "project": projectName,
- "mode": string(mode),
- "nodes": nodeCount,
- "edges": edgeCount,
- "indexed_at": indexedAt,
- }
-
- // Check for ADR presence and suggest creation if missing
- adr, _ := st.GetADR(projectName)
- result["adr_present"] = adr != nil
- if adr == nil {
- result["adr_hint"] = "Project indexed. Consider creating an Architecture Decision Record: explore the codebase with get_architecture(aspects=['all']), then use manage_adr(mode='store') to persist architectural insights across sessions."
- }
-
- return jsonResult(result), nil
-}
diff --git a/internal/tools/projects.go b/internal/tools/projects.go
deleted file mode 100644
index a4fd5ecea..000000000
--- a/internal/tools/projects.go
+++ /dev/null
@@ -1,202 +0,0 @@
-package tools
-
-import (
- "context"
- "fmt"
- "math"
- "path/filepath"
- "time"
-
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) handleListProjects(_ context.Context, _ *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- projectInfos, err := s.router.ListProjects()
- if err != nil {
- return errResult(fmt.Sprintf("list projects: %v", err)), nil
- }
-
- type projectEntry struct {
- Name string `json:"name"`
- RootPath string `json:"root_path"`
- IndexedAt string `json:"indexed_at"`
- Nodes int `json:"nodes"`
- Edges int `json:"edges"`
- DBPath string `json:"db_path"`
- ADRPresent bool `json:"adr_present"`
- IsSessionProject bool `json:"is_session_project,omitempty"`
- }
-
- result := make([]projectEntry, 0, len(projectInfos))
- for _, info := range projectInfos {
- st, err := s.router.ForProject(info.Name)
- if err != nil {
- continue
- }
-
- nc, _ := st.CountNodes(info.Name)
- ec, _ := st.CountEdges(info.Name)
-
- indexedAt := ""
- rootPath := info.RootPath
- proj, _ := st.GetProject(info.Name)
- if proj != nil {
- indexedAt = proj.IndexedAt
- rootPath = proj.RootPath
- }
-
- adr, _ := st.GetADR(info.Name)
-
- entry := projectEntry{
- Name: info.Name,
- RootPath: rootPath,
- IndexedAt: indexedAt,
- Nodes: nc,
- Edges: ec,
- DBPath: info.DBPath,
- ADRPresent: adr != nil,
- }
- if info.Name == s.sessionProject {
- entry.IsSessionProject = true
- }
- result = append(result, entry)
- }
-
- return jsonResult(result), nil
-}
-
-func (s *Server) handleDeleteProject(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- name := getStringArg(args, "project_name")
- if name == "" {
- return errResult("project_name is required"), nil
- }
-
- // Verify project exists
- if !s.router.HasProject(name) {
- return errResult(fmt.Sprintf("project not found: %s", name)), nil
- }
-
- if err := s.router.DeleteProject(name); err != nil {
- return errResult(fmt.Sprintf("delete failed: %v", err)), nil
- }
- s.watcher.Unwatch(name)
-
- return jsonResult(map[string]any{
- "deleted": name,
- "status": "ok",
- }), nil
-}
-
-func (s *Server) handleIndexStatus(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- projectName := getStringArg(args, "project")
- if projectName == "" {
- projectName = s.sessionProject
- }
- if projectName == "" {
- return jsonResult(map[string]any{
- "status": "no_session",
- "message": "No session project detected. Pass 'project' parameter or ensure the MCP client provides roots.",
- }), nil
- }
-
- // Check if DB file exists
- if !s.router.HasProject(projectName) {
- return jsonResult(map[string]any{
- "project": projectName,
- "status": "not_indexed",
- "message": fmt.Sprintf("No index found for project %q. Call index_repository to create one.", projectName),
- "db_path": filepath.Join(s.router.Dir(), projectName+".db"),
- }), nil
- }
-
- // Get store and project metadata
- st, err := s.router.ForProject(projectName)
- if err != nil {
- return errResult(fmt.Sprintf("open store: %v", err)), nil
- }
-
- proj, _ := st.GetProject(projectName)
- if proj == nil {
- // DB file exists but no project row — partially indexed or corrupted
- return jsonResult(map[string]any{
- "project": projectName,
- "status": "partial",
- "message": "Database file exists but project metadata is missing. Re-run index_repository.",
- "db_path": filepath.Join(s.router.Dir(), projectName+".db"),
- }), nil
- }
-
- nodeCount, _ := st.CountNodes(projectName)
- edgeCount, _ := st.CountEdges(projectName)
-
- // Determine current indexing state
- currentStatus, _ := s.indexStatus.Load().(string)
- isSessionProject := projectName == s.sessionProject
-
- result := map[string]any{
- "project": projectName,
- "status": "ready",
- "indexed_at": proj.IndexedAt,
- "root_path": proj.RootPath,
- "nodes": nodeCount,
- "edges": edgeCount,
- "is_session_project": isSessionProject,
- "db_path": filepath.Join(s.router.Dir(), projectName+".db"),
- }
-
- // Determine index type (initial vs incremental)
- if nodeCount == 0 && edgeCount == 0 {
- result["index_type"] = "none"
- } else {
- result["index_type"] = "incremental"
- }
-
- // Add edge type breakdown
- if edgeTypes, err := st.EdgeCountsByType(projectName); err == nil && len(edgeTypes) > 0 {
- result["edges_by_type"] = edgeTypes
- }
-
- // Add LSP coverage metrics for CALLS edges
- if stats, err := st.CallsResolutionStats(projectName); err == nil && len(stats) > 0 {
- totalCalls := 0
- lspCalls := 0
- for strategy, count := range stats {
- totalCalls += count
- if len(strategy) >= 4 && strategy[:4] == "lsp_" {
- lspCalls += count
- }
- }
- lspPct := 0.0
- if totalCalls > 0 {
- lspPct = float64(lspCalls) / float64(totalCalls) * 100
- }
- result["calls_total"] = totalCalls
- result["calls_lsp"] = lspCalls
- result["calls_lsp_pct"] = math.Round(lspPct*10) / 10
- result["calls_by_strategy"] = stats
- }
-
- // If this is the session project and indexing is in progress
- if isSessionProject && currentStatus == "indexing" {
- result["status"] = "indexing"
- if startedAt, ok := s.indexStartedAt.Load().(time.Time); ok {
- result["index_started_at"] = startedAt.UTC().Format(time.RFC3339)
- result["index_elapsed_seconds"] = int(time.Since(startedAt).Seconds())
- }
- if nodeCount == 0 {
- result["index_type"] = "initial"
- }
- }
-
- return jsonResult(result), nil
-}
diff --git a/internal/tools/query.go b/internal/tools/query.go
deleted file mode 100644
index 550108a8a..000000000
--- a/internal/tools/query.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package tools
-
-import (
- "context"
- "fmt"
-
- "github.com/DeusData/codebase-memory-mcp/internal/cypher"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) handleQueryGraph(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- query := getStringArg(args, "query")
- if query == "" {
- return errResult("missing required 'query' parameter"), nil
- }
-
- st, err := s.resolveStore(getStringArg(args, "project"))
- if err != nil {
- return errResult(fmt.Sprintf("resolve store: %v", err)), nil
- }
-
- exec := &cypher.Executor{Store: st, MaxRows: getIntArg(args, "max_rows", 0)}
- result, err := exec.Execute(query)
- if err != nil {
- return errResult(fmt.Sprintf("query error: %v", err)), nil
- }
-
- responseData := map[string]any{
- "columns": result.Columns,
- "rows": result.Rows,
- "total": len(result.Rows),
- }
- s.addIndexStatus(responseData)
-
- res := jsonResult(responseData)
- s.addUpdateNotice(res)
- return res, nil
-}
diff --git a/internal/tools/schema.go b/internal/tools/schema.go
deleted file mode 100644
index c769544fb..000000000
--- a/internal/tools/schema.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package tools
-
-import (
- "context"
- "fmt"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) handleGetGraphSchema(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- project := getStringArg(args, "project")
- st, err := s.resolveStore(project)
- if err != nil {
- return errResult(fmt.Sprintf("resolve store: %v", err)), nil
- }
-
- projName := s.resolveProjectName(project)
- projects, _ := st.ListProjects()
- if len(projects) > 0 {
- projName = projects[0].Name
- }
-
- schema, schemaErr := st.GetSchema(projName)
- if schemaErr != nil {
- return errResult(fmt.Sprintf("schema: %v", schemaErr)), nil
- }
-
- type projectSchema struct {
- Project string `json:"project"`
- Schema *store.SchemaInfo `json:"schema"`
- ADRPresent bool `json:"adr_present"`
- }
-
- adr, _ := st.GetADR(projName)
-
- return jsonResult(map[string]any{
- "projects": []projectSchema{{Project: projName, Schema: schema, ADRPresent: adr != nil}},
- }), nil
-}
diff --git a/internal/tools/search.go b/internal/tools/search.go
deleted file mode 100644
index 980a4f4c6..000000000
--- a/internal/tools/search.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package tools
-
-import (
- "context"
- "fmt"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) handleSearchGraph(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- params := &store.SearchParams{
- Label: getStringArg(args, "label"),
- NamePattern: getStringArg(args, "name_pattern"),
- QNPattern: getStringArg(args, "qn_pattern"),
- FilePattern: getStringArg(args, "file_pattern"),
- Relationship: getStringArg(args, "relationship"),
- Direction: getStringArg(args, "direction"),
- MinDegree: getIntArg(args, "min_degree", -1),
- MaxDegree: getIntArg(args, "max_degree", -1),
- Limit: getIntArg(args, "limit", 10),
- Offset: getIntArg(args, "offset", 0),
- ExcludeEntryPoints: getBoolArg(args, "exclude_entry_points"),
- IncludeConnected: getBoolArg(args, "include_connected"),
- CaseSensitive: getBoolArg(args, "case_sensitive"),
- }
-
- // Parse exclude_labels array; default to excluding Community nodes
- if rawLabels, ok := args["exclude_labels"]; ok {
- if labelArr, ok := rawLabels.([]any); ok {
- for _, l := range labelArr {
- if str, ok := l.(string); ok {
- params.ExcludeLabels = append(params.ExcludeLabels, str)
- }
- }
- }
- } else {
- params.ExcludeLabels = []string{"Community"}
- }
-
- params.SortBy = getStringArg(args, "sort_by")
-
- st, err := s.resolveStore(getStringArg(args, "project"))
- if err != nil {
- return errResult(fmt.Sprintf("resolve store: %v", err)), nil
- }
-
- projName := s.resolveProjectName(getStringArg(args, "project"))
- projects, _ := st.ListProjects()
- if len(projects) > 0 {
- projName = projects[0].Name
- }
-
- params.Project = projName
- output, searchErr := st.Search(params)
- if searchErr != nil {
- return errResult(fmt.Sprintf("search: %v", searchErr)), nil
- }
-
- type resultEntry struct {
- Project string `json:"project"`
- Name string `json:"name"`
- QualifiedName string `json:"qualified_name"`
- Label string `json:"label"`
- FilePath string `json:"file_path"`
- StartLine int `json:"start_line"`
- EndLine int `json:"end_line"`
- InDegree int `json:"in_degree"`
- OutDegree int `json:"out_degree"`
- ConnectedNames []string `json:"connected_names,omitempty"`
- }
-
- results := make([]resultEntry, 0, len(output.Results))
- for _, r := range output.Results {
- results = append(results, resultEntry{
- Project: projName,
- Name: r.Node.Name,
- QualifiedName: r.Node.QualifiedName,
- Label: r.Node.Label,
- FilePath: r.Node.FilePath,
- StartLine: r.Node.StartLine,
- EndLine: r.Node.EndLine,
- InDegree: r.InDegree,
- OutDegree: r.OutDegree,
- ConnectedNames: r.ConnectedNames,
- })
- }
-
- responseData := map[string]any{
- "total": output.Total,
- "limit": params.Limit,
- "offset": params.Offset,
- "has_more": params.Offset+params.Limit < output.Total,
- "results": results,
- }
- s.addIndexStatus(responseData)
-
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result, nil
-}
diff --git a/internal/tools/snippet.go b/internal/tools/snippet.go
deleted file mode 100644
index 6da31d5fb..000000000
--- a/internal/tools/snippet.go
+++ /dev/null
@@ -1,336 +0,0 @@
-package tools
-
-import (
- "bufio"
- "context"
- "fmt"
- "log/slog"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-// snippetMatch holds a resolved node with metadata about how it was found.
-type snippetMatch struct {
- node *store.Node
- project string
- method string // "exact", "suffix", "name"
-}
-
-func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- qn := getStringArg(args, "qualified_name")
- if qn == "" {
- return errResult("qualified_name is required"), nil
- }
-
- project := getStringArg(args, "project")
- effectiveProject := s.resolveProjectName(project)
- autoResolve := getBoolArg(args, "auto_resolve")
- includeNeighbors := getBoolArg(args, "include_neighbors")
-
- // 4-tier resolution: exact QN -> suffix -> short name -> fuzzy suggestions
- match, candidates, resolveErr := s.resolveSnippetNode(qn, effectiveProject)
- if resolveErr != nil {
- return errResult(resolveErr.Error()), nil
- }
-
- // Ambiguous: try auto-resolve or return suggestions
- if match == nil && len(candidates) > 0 {
- if autoResolve && len(candidates) <= 2 {
- match = s.autoResolveBest(candidates, effectiveProject)
- }
- if match == nil {
- return s.snippetSuggestions(qn, candidates), nil
- }
- // Build alternatives list (candidates that were NOT picked)
- alternatives := make([]map[string]string, 0, len(candidates)-1)
- for _, c := range candidates {
- if c.ID != match.node.ID {
- alternatives = append(alternatives, map[string]string{
- "qualified_name": c.QualifiedName,
- "file_path": c.FilePath,
- })
- }
- }
- return s.buildSnippetResponse(match, includeNeighbors, alternatives)
- }
-
- // Nothing found at all: try fuzzy suggestions (with last-segment extraction)
- if match == nil {
- searchName := qn
- if idx := strings.LastIndex(qn, "."); idx >= 0 {
- searchName = qn[idx+1:]
- }
- suggestions := s.findSimilarNodes(searchName, effectiveProject, 5)
- if len(suggestions) > 0 {
- return s.snippetSuggestions(qn, suggestions), nil
- }
- return errResult(fmt.Sprintf("node not found: %s", qn)), nil
- }
-
- return s.buildSnippetResponse(match, includeNeighbors, nil)
-}
-
-// buildSnippetResponse reads source and builds the enriched JSON response for a resolved match.
-func (s *Server) buildSnippetResponse(match *snippetMatch, includeNeighbors bool, alternatives []map[string]string) (*mcp.CallToolResult, error) {
- node := match.node
- foundProject := match.project
-
- if node.FilePath == "" {
- return errResult("node has no file path"), nil
- }
- if node.StartLine == 0 || node.EndLine == 0 {
- return errResult("node has no line range"), nil
- }
-
- // Get the store for the found project to look up root path
- st, stErr := s.router.ForProject(foundProject)
- if stErr != nil {
- return errResult(fmt.Sprintf("store: %v", stErr)), nil
- }
-
- proj, _ := st.GetProject(foundProject)
- if proj == nil {
- return errResult(fmt.Sprintf("project not found: %s", foundProject)), nil
- }
-
- absPath := filepath.Join(proj.RootPath, node.FilePath)
-
- // Read the source file and extract lines
- source, readErr := readLines(absPath, node.StartLine, node.EndLine)
- if readErr != nil {
- return errResult(fmt.Sprintf("read file: %v", readErr)), nil
- }
-
- // Build enriched response
- responseData := map[string]any{
- "qualified_name": node.QualifiedName,
- "name": node.Name,
- "label": node.Label,
- "file_path": absPath,
- "start_line": node.StartLine,
- "end_line": node.EndLine,
- "source": source,
- }
-
- // Add all non-empty node properties
- for k, v := range node.Properties {
- if v != nil {
- responseData[k] = v
- }
- }
-
- // Show match_method for non-exact resolutions
- if match.method != "exact" {
- responseData["match_method"] = match.method
- }
-
- // Add caller/callee counts
- inDegree, outDegree := st.NodeDegree(node.ID)
- responseData["callers"] = inDegree
- responseData["callees"] = outDegree
-
- // Opt-in: include neighbor names
- if includeNeighbors {
- callerNames, calleeNames := st.NodeNeighborNames(node.ID, 10)
- if len(callerNames) > 0 {
- responseData["caller_names"] = callerNames
- }
- if len(calleeNames) > 0 {
- responseData["callee_names"] = calleeNames
- }
- }
-
- // Include alternatives when auto-resolved
- if alternatives != nil {
- responseData["alternatives"] = alternatives
- }
-
- return jsonResult(responseData), nil
-}
-
-// autoResolveBest picks the best candidate from a small set (<=2).
-// Heuristic: highest total degree (in+out across all edge types), preferring non-test files.
-func (s *Server) autoResolveBest(candidates []*store.Node, projectFilter string) *snippetMatch {
- filter := s.resolveProjectName(projectFilter)
- st, err := s.router.ForProject(filter)
- if err != nil {
- return nil
- }
- projects, _ := st.ListProjects()
- if len(projects) == 0 {
- return nil
- }
- projName := projects[0].Name
-
- type scored struct {
- node *store.Node
- degree int
- isTest bool
- }
-
- scored_ := make([]scored, len(candidates))
- for i, c := range candidates {
- in, out := st.NodeDegree(c.ID)
- isTest := strings.Contains(c.FilePath, "_test")
- scored_[i] = scored{node: c, degree: in + out, isTest: isTest}
- }
-
- best := scored_[0]
- for _, s := range scored_[1:] {
- // Prefer non-test over test
- if best.isTest && !s.isTest {
- best = s
- continue
- }
- if !best.isTest && s.isTest {
- continue
- }
- // Higher degree wins
- if s.degree > best.degree {
- best = s
- continue
- }
- // Tiebreaker: alphabetical QN
- if s.degree == best.degree && s.node.QualifiedName < best.node.QualifiedName {
- best = s
- }
- }
-
- slog.Info("snippet.auto_resolved", "input", candidates[0].Name, "picked", best.node.QualifiedName, "candidates", len(candidates))
- return &snippetMatch{node: best.node, project: projName, method: "auto_best"}
-}
-
-// resolveSnippetNode implements a 4-tier lookup:
-//
-// Tier 1: Exact QN match
-// Tier 2: QN suffix match (dot-boundary)
-// Tier 3: Short name match
-// Tier 4: (caller handles fuzzy via findSimilarNodes)
-//
-// Returns (match, nil, nil) on unique hit, (nil, candidates, nil) on ambiguous,
-// (nil, nil, nil) when nothing found, or (nil, nil, err) on infrastructure error.
-func (s *Server) resolveSnippetNode(input, projectFilter string) (*snippetMatch, []*store.Node, error) {
- filter := s.sessionProject
- if projectFilter != "" {
- if projectFilter == "*" || projectFilter == "all" {
- return nil, nil, fmt.Errorf("cross-project queries are not supported; use list_projects to find a specific project name, or omit the project parameter to use the current session project")
- }
- filter = projectFilter
- }
- if filter == "" {
- return nil, nil, fmt.Errorf("no project specified and no session project detected")
- }
- if !s.router.HasProject(filter) {
- return nil, nil, fmt.Errorf("project %q not found; use list_projects to see available projects", filter)
- }
-
- st, err := s.router.ForProject(filter)
- if err != nil {
- return nil, nil, err
- }
- projects, _ := st.ListProjects()
- if len(projects) == 0 {
- return nil, nil, fmt.Errorf("no projects in store")
- }
- projName := projects[0].Name
-
- // Tier 1: Exact QN match
- node, findErr := st.FindNodeByQN(projName, input)
- if findErr == nil && node != nil {
- return &snippetMatch{node: node, project: projName, method: "exact"}, nil, nil
- }
-
- // Tier 2: QN suffix match (dot-boundary)
- suffixMatches, err := st.FindNodesByQNSuffix(projName, input)
- if err == nil && len(suffixMatches) == 1 {
- return &snippetMatch{node: suffixMatches[0], project: projName, method: "suffix"}, nil, nil
- }
-
- // Tier 3: Short name match
- nameMatches, err := st.FindNodesByName(projName, input)
- if err == nil && len(nameMatches) == 1 {
- return &snippetMatch{node: nameMatches[0], project: projName, method: "name"}, nil, nil
- }
-
- // Collect all candidates for suggestions (deduped)
- candidates := dedupNodes(suffixMatches, nameMatches)
- if len(candidates) > 0 {
- return nil, candidates, nil
- }
-
- // Nothing found at any tier
- return nil, nil, nil
-}
-
-// snippetSuggestions returns a structured suggestion response for ambiguous or not-found lookups.
-func (s *Server) snippetSuggestions(input string, nodes []*store.Node) *mcp.CallToolResult {
- suggList := make([]map[string]string, 0, len(nodes))
- for _, n := range nodes {
- suggList = append(suggList, map[string]string{
- "qualified_name": n.QualifiedName,
- "name": n.Name,
- "label": n.Label,
- "file_path": n.FilePath,
- })
- }
- return jsonResult(map[string]any{
- "status": "ambiguous",
- "message": fmt.Sprintf("%d matches found for %q — use a qualified_name from the suggestions to disambiguate", len(nodes), input),
- "suggestions": suggList,
- })
-}
-
-// dedupNodes merges multiple node slices, deduplicating by node ID.
-func dedupNodes(slices ...[]*store.Node) []*store.Node {
- seen := make(map[int64]bool)
- var result []*store.Node
- for _, s := range slices {
- for _, n := range s {
- if n != nil && !seen[n.ID] {
- seen[n.ID] = true
- result = append(result, n)
- }
- }
- }
- return result
-}
-
-// readLines reads specific lines from a file, returning them with line numbers.
-func readLines(path string, startLine, endLine int) (string, error) {
- f, err := os.Open(path)
- if err != nil {
- return "", fmt.Errorf("open: %w", err)
- }
- defer f.Close()
-
- var sb strings.Builder
- scanner := bufio.NewScanner(f)
- lineNum := 0
- for scanner.Scan() {
- lineNum++
- if lineNum > endLine {
- break
- }
- if lineNum >= startLine {
- fmt.Fprintf(&sb, "%4d | %s\n", lineNum, scanner.Text())
- }
- }
- if err := scanner.Err(); err != nil {
- return "", fmt.Errorf("scan: %w", err)
- }
-
- if sb.Len() == 0 {
- return "", fmt.Errorf("no lines found in range %d-%d (file has %d lines)", startLine, endLine, lineNum)
- }
-
- return sb.String(), nil
-}
diff --git a/internal/tools/snippet_test.go b/internal/tools/snippet_test.go
deleted file mode 100644
index 9252e7c88..000000000
--- a/internal/tools/snippet_test.go
+++ /dev/null
@@ -1,490 +0,0 @@
-package tools
-
-import (
- "context"
- "encoding/json"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-// testSnippetServer creates a Server with an in-memory-like store backed by a temp dir,
-// pre-populated with a project, nodes, and edges.
-func testSnippetServer(t *testing.T) *Server {
- t.Helper()
-
- tmpDir := t.TempDir()
- routerDir := filepath.Join(tmpDir, "db")
- projRoot := filepath.Join(tmpDir, "project")
-
- if err := os.MkdirAll(projRoot, 0o750); err != nil {
- t.Fatal(err)
- }
-
- // Write a sample source file
- srcContent := `package main
-
-func HandleRequest() error {
- return nil
-}
-
-func ProcessOrder(id int) {
- // process
-}
-
-func Run() {
- // server
-}
-`
- if err := os.WriteFile(filepath.Join(projRoot, "main.go"), []byte(srcContent), 0o600); err != nil {
- t.Fatal(err)
- }
-
- router, err := store.NewRouterWithDir(routerDir)
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(router.CloseAll)
-
- projName := "test-project"
- st, err := router.ForProject(projName)
- if err != nil {
- t.Fatal(err)
- }
- if err := st.UpsertProject(projName, projRoot); err != nil {
- t.Fatal(err)
- }
-
- // Create nodes
- idHR, _ := st.UpsertNode(&store.Node{
- Project: projName,
- Label: "Function",
- Name: "HandleRequest",
- QualifiedName: "test-project.cmd.server.main.HandleRequest",
- FilePath: "main.go",
- StartLine: 3,
- EndLine: 5,
- Properties: map[string]any{
- "signature": "func HandleRequest() error",
- "return_type": "error",
- "is_exported": true,
- },
- })
- idPO, _ := st.UpsertNode(&store.Node{
- Project: projName,
- Label: "Function",
- Name: "ProcessOrder",
- QualifiedName: "test-project.cmd.server.main.ProcessOrder",
- FilePath: "main.go",
- StartLine: 7,
- EndLine: 9,
- Properties: map[string]any{"signature": "func ProcessOrder(id int)"},
- })
- idRun1, _ := st.UpsertNode(&store.Node{
- Project: projName,
- Label: "Function",
- Name: "Run",
- QualifiedName: "test-project.cmd.server.Run",
- FilePath: "main.go",
- StartLine: 11,
- EndLine: 13,
- })
- idRun2, _ := st.UpsertNode(&store.Node{
- Project: projName,
- Label: "Function",
- Name: "Run",
- QualifiedName: "test-project.cmd.worker.Run",
- FilePath: "main.go",
- StartLine: 11,
- EndLine: 13,
- })
-
- // Create edges: HandleRequest -> ProcessOrder, HandleRequest -> Run1
- _, _ = st.InsertEdge(&store.Edge{Project: projName, SourceID: idHR, TargetID: idPO, Type: "CALLS"})
- _, _ = st.InsertEdge(&store.Edge{Project: projName, SourceID: idHR, TargetID: idRun1, Type: "CALLS"})
- _ = idRun2 // used to create ambiguity for "Run"
-
- srv := &Server{
- router: router,
- handlers: make(map[string]mcp.ToolHandler),
- sessionProject: projName,
- }
-
- return srv
-}
-
-func callSnippetRaw(t *testing.T, srv *Server, qn string) *mcp.CallToolResult {
- t.Helper()
- args := map[string]any{"qualified_name": qn}
- rawArgs, _ := json.Marshal(args)
-
- req := &mcp.CallToolRequest{
- Params: &mcp.CallToolParamsRaw{
- Name: "get_code_snippet",
- Arguments: rawArgs,
- },
- }
-
- result, err := srv.handleGetCodeSnippet(context.TODO(), req)
- if err != nil {
- t.Fatalf("handleGetCodeSnippet error: %v", err)
- }
- return result
-}
-
-func callSnippet(t *testing.T, srv *Server, qn string) map[string]any {
- t.Helper()
- return callSnippetWithOpts(t, srv, map[string]any{"qualified_name": qn})
-}
-
-func callSnippetWithOpts(t *testing.T, srv *Server, args map[string]any) map[string]any {
- t.Helper()
- // Remove empty project to match old behavior
- if p, ok := args["project"]; ok && p == "" {
- delete(args, "project")
- }
- rawArgs, _ := json.Marshal(args)
-
- req := &mcp.CallToolRequest{
- Params: &mcp.CallToolParamsRaw{
- Name: "get_code_snippet",
- Arguments: rawArgs,
- },
- }
-
- result, err := srv.handleGetCodeSnippet(context.TODO(), req)
- if err != nil {
- t.Fatalf("handleGetCodeSnippet error: %v", err)
- }
- if len(result.Content) == 0 {
- t.Fatal("empty result content")
- }
- tc, ok := result.Content[0].(*mcp.TextContent)
- if !ok {
- t.Fatalf("expected TextContent, got %T", result.Content[0])
- }
- var data map[string]any
- if err := json.Unmarshal([]byte(tc.Text), &data); err != nil {
- t.Fatalf("unmarshal result: %v (text: %s)", err, tc.Text)
- }
- return data
-}
-
-func TestSnippet_ExactQN(t *testing.T) {
- srv := testSnippetServer(t)
- data := callSnippet(t, srv, "test-project.cmd.server.main.HandleRequest")
-
- if data["name"] != "HandleRequest" {
- t.Errorf("expected name=HandleRequest, got %v", data["name"])
- }
- if data["source"] == nil || data["source"] == "" {
- t.Error("expected non-empty source")
- }
- // Exact match should not have match_method
- if _, ok := data["match_method"]; ok {
- t.Errorf("exact match should not have match_method, got %v", data["match_method"])
- }
- // Should have enriched properties
- if data["signature"] != "func HandleRequest() error" {
- t.Errorf("expected signature, got %v", data["signature"])
- }
- if data["return_type"] != "error" {
- t.Errorf("expected return_type=error, got %v", data["return_type"])
- }
- // Should have caller/callee counts
- if data["callers"] == nil {
- t.Error("expected callers field")
- }
- if data["callees"] == nil {
- t.Error("expected callees field")
- }
- // HandleRequest has 0 callers and 2 callees
- if data["callers"] != float64(0) {
- t.Errorf("expected 0 callers, got %v", data["callers"])
- }
- if data["callees"] != float64(2) {
- t.Errorf("expected 2 callees, got %v", data["callees"])
- }
-}
-
-func TestSnippet_QNSuffix(t *testing.T) {
- srv := testSnippetServer(t)
- data := callSnippet(t, srv, "main.HandleRequest")
-
- if data["name"] != "HandleRequest" {
- t.Errorf("expected name=HandleRequest, got %v", data["name"])
- }
- if data["match_method"] != "suffix" {
- t.Errorf("expected match_method=suffix, got %v", data["match_method"])
- }
- if data["source"] == nil || data["source"] == "" {
- t.Error("expected non-empty source")
- }
-}
-
-func TestSnippet_UniqueShortName(t *testing.T) {
- srv := testSnippetServer(t)
- // "ProcessOrder" is unique across both suffix and name tiers
- data := callSnippet(t, srv, "ProcessOrder")
-
- if data["name"] != "ProcessOrder" {
- t.Errorf("expected name=ProcessOrder, got %v", data["name"])
- }
- // ProcessOrder QN ends with ".ProcessOrder" — suffix tier matches first (1 result)
- if data["match_method"] != "suffix" {
- t.Errorf("expected match_method=suffix, got %v", data["match_method"])
- }
- if data["source"] == nil || data["source"] == "" {
- t.Error("expected non-empty source")
- }
-}
-
-func TestSnippet_NameTier(t *testing.T) {
- // To test name-tier specifically, we need a node whose short name is unique
- // but whose QN doesn't end with ".ShortName" (so suffix tier misses).
- // This is hard to construct since QNs always end with the name.
- // Instead, verify that short names resolve correctly when suffix tier returns 1.
- srv := testSnippetServer(t)
- data := callSnippet(t, srv, "HandleRequest")
-
- if data["name"] != "HandleRequest" {
- t.Errorf("expected name=HandleRequest, got %v", data["name"])
- }
- // Suffix tier finds it (QN ends with ".HandleRequest"), which is correct behavior
- if data["match_method"] != "suffix" {
- t.Errorf("expected match_method=suffix, got %v", data["match_method"])
- }
-}
-
-func TestSnippet_AmbiguousShortName(t *testing.T) {
- srv := testSnippetServer(t)
- data := callSnippet(t, srv, "Run")
-
- // Should return suggestions, not source code
- if data["source"] != nil {
- t.Error("ambiguous lookup should not return source code")
- }
- // Should use "status"/"message" instead of "error"
- if data["status"] != "ambiguous" {
- t.Fatalf("expected status=ambiguous, got %v", data["status"])
- }
- if data["message"] == nil {
- t.Fatal("expected message field for ambiguous match")
- }
- // Must NOT have "error" key
- if _, hasError := data["error"]; hasError {
- t.Error("ambiguous response must not contain 'error' key")
- }
- suggestions, ok := data["suggestions"].([]any)
- if !ok {
- t.Fatalf("expected suggestions array, got %T", data["suggestions"])
- }
- if len(suggestions) < 2 {
- t.Errorf("expected at least 2 suggestions, got %d", len(suggestions))
- }
- // Verify suggestions have qualified_name
- for _, s := range suggestions {
- sMap, ok := s.(map[string]any)
- if !ok {
- t.Fatalf("expected suggestion map, got %T", s)
- }
- if sMap["qualified_name"] == nil || sMap["qualified_name"] == "" {
- t.Error("suggestion missing qualified_name")
- }
- }
-}
-
-func TestSnippet_NotFound(t *testing.T) {
- srv := testSnippetServer(t)
- result := callSnippetRaw(t, srv, "CompletelyNonexistentFunctionXYZ123")
-
- // Should be an error result (plain text or JSON with suggestions)
- if !result.IsError {
- // If not IsError, check it has suggestions
- tc, ok := result.Content[0].(*mcp.TextContent)
- if !ok {
- t.Fatal("expected TextContent")
- }
- var data map[string]any
- if err := json.Unmarshal([]byte(tc.Text), &data); err == nil {
- if data["suggestions"] == nil && data["status"] == nil {
- t.Error("expected status or suggestions for non-existent function")
- }
- }
- return
- }
- // Plain error result is fine for truly not-found names
-}
-
-func TestSnippet_FuzzySuggestions(t *testing.T) {
- srv := testSnippetServer(t)
- // "Handle" should fuzzy-match "HandleRequest" via findSimilarNodes
- data := callSnippet(t, srv, "Handle")
-
- // Should return suggestions (fuzzy match to HandleRequest)
- if suggestions, ok := data["suggestions"].([]any); ok {
- found := false
- for _, s := range suggestions {
- sMap, ok := s.(map[string]any)
- if !ok {
- t.Fatalf("expected suggestion map, got %T", s)
- }
- if sMap["name"] == "HandleRequest" {
- found = true
- }
- }
- if !found {
- t.Error("expected HandleRequest in fuzzy suggestions")
- }
- }
- // If no suggestions, it should at least have a status
- if data["suggestions"] == nil && data["status"] == nil && data["source"] == nil {
- t.Error("expected either suggestions, status, or source")
- }
-}
-
-func TestSnippet_EnrichedProperties(t *testing.T) {
- srv := testSnippetServer(t)
- data := callSnippet(t, srv, "test-project.cmd.server.main.HandleRequest")
-
- // Verify all enriched properties are present
- if data["signature"] == nil {
- t.Error("expected signature property")
- }
- if data["return_type"] == nil {
- t.Error("expected return_type property")
- }
- if data["is_exported"] != true {
- t.Errorf("expected is_exported=true, got %v", data["is_exported"])
- }
-}
-
-func TestSnippet_FuzzyLastSegment(t *testing.T) {
- srv := testSnippetServer(t)
- // "auth.handlers.HandleRequest" — full dotted string won't match anything,
- // but last segment "HandleRequest" should fuzzy-match
- data := callSnippet(t, srv, "auth.handlers.HandleRequest")
-
- // Should return suggestions via last-segment extraction
- if data["status"] != "ambiguous" && data["source"] == nil {
- // It could be a direct match via suffix or fuzzy
- if data["suggestions"] == nil {
- t.Error("expected suggestions for dotted input with last-segment fallback")
- }
- }
- // If it returned suggestions, verify HandleRequest is among them
- if suggestions, ok := data["suggestions"].([]any); ok {
- found := false
- for _, s := range suggestions {
- sMap, ok := s.(map[string]any)
- if !ok {
- t.Fatalf("expected suggestion map, got %T", s)
- }
- if sMap["name"] == "HandleRequest" {
- found = true
- }
- }
- if !found {
- t.Error("expected HandleRequest in last-segment suggestions")
- }
- }
-}
-
-func TestSnippet_AutoResolve_Default(t *testing.T) {
- srv := testSnippetServer(t)
- // "Run" is ambiguous (2 candidates). Without auto_resolve, should return suggestions.
- data := callSnippet(t, srv, "Run")
-
- if data["status"] != "ambiguous" {
- t.Errorf("expected status=ambiguous without auto_resolve, got %v", data["status"])
- }
- if data["source"] != nil {
- t.Error("should not return source without auto_resolve")
- }
-}
-
-func TestSnippet_AutoResolve_Enabled(t *testing.T) {
- srv := testSnippetServer(t)
- // "Run" is ambiguous (2 candidates). With auto_resolve=true, should pick best.
- data := callSnippetWithOpts(t, srv, map[string]any{
- "qualified_name": "Run",
- "auto_resolve": true,
- })
-
- if data["source"] == nil || data["source"] == "" {
- t.Fatal("expected source with auto_resolve=true")
- }
- if data["match_method"] != "auto_best" {
- t.Errorf("expected match_method=auto_best, got %v", data["match_method"])
- }
- // Should have alternatives
- alternatives, ok := data["alternatives"].([]any)
- if !ok {
- t.Fatalf("expected alternatives array, got %T", data["alternatives"])
- }
- if len(alternatives) != 1 {
- t.Errorf("expected 1 alternative, got %d", len(alternatives))
- }
- // The picked one should be cmd.server.Run (has 1 inbound CALLS edge = higher degree)
- if data["qualified_name"] != "test-project.cmd.server.Run" {
- t.Errorf("expected auto_resolve to pick server.Run (higher degree), got %v", data["qualified_name"])
- }
-}
-
-func TestSnippet_IncludeNeighbors_Default(t *testing.T) {
- srv := testSnippetServer(t)
- data := callSnippet(t, srv, "test-project.cmd.server.main.HandleRequest")
-
- // Without include_neighbors, should NOT have caller_names/callee_names
- if data["caller_names"] != nil {
- t.Error("should not have caller_names without include_neighbors")
- }
- if data["callee_names"] != nil {
- t.Error("should not have callee_names without include_neighbors")
- }
- // But should still have counts
- if data["callers"] == nil || data["callees"] == nil {
- t.Error("expected callers/callees counts")
- }
-}
-
-func TestSnippet_IncludeNeighbors_Enabled(t *testing.T) {
- srv := testSnippetServer(t)
- data := callSnippetWithOpts(t, srv, map[string]any{
- "qualified_name": "test-project.cmd.server.main.HandleRequest",
- "include_neighbors": true,
- })
-
- if data["source"] == nil || data["source"] == "" {
- t.Fatal("expected source")
- }
- // HandleRequest has 0 callers and 2 callees (ProcessOrder, Run)
- if data["caller_names"] != nil {
- t.Errorf("expected nil caller_names (0 callers), got %v", data["caller_names"])
- }
- calleeNames, ok := data["callee_names"].([]any)
- if !ok {
- t.Fatalf("expected callee_names array, got %T (%v)", data["callee_names"], data["callee_names"])
- }
- if len(calleeNames) != 2 {
- t.Errorf("expected 2 callee names, got %d", len(calleeNames))
- }
- // Verify the names are present (sorted alphabetically by SQL ORDER BY)
- names := make(map[string]bool)
- for _, n := range calleeNames {
- s, ok := n.(string)
- if !ok {
- t.Fatalf("expected string callee name, got %T", n)
- }
- names[s] = true
- }
- if !names["ProcessOrder"] {
- t.Error("expected ProcessOrder in callee_names")
- }
- if !names["Run"] {
- t.Error("expected Run in callee_names")
- }
-}
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
deleted file mode 100644
index 5f1fcfda3..000000000
--- a/internal/tools/tools.go
+++ /dev/null
@@ -1,935 +0,0 @@
-package tools
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/pipeline"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/DeusData/codebase-memory-mcp/internal/watcher"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-// Version is the current release version, set from main.version via SetVersion().
-// Defaults to "dev" for local builds.
-var Version = "dev"
-
-// SetVersion sets the package version from the build-injected main.version.
-func SetVersion(v string) { Version = v }
-
-// releaseURL is the GitHub API endpoint for latest release. Package-level var for test injection.
-var releaseURL = "https://api.github.com/repos/DeusData/codebase-memory-mcp/releases/latest"
-
-// Server wraps the MCP server with tool handlers.
-type Server struct {
- mcp *mcp.Server
- router *store.StoreRouter
- config *store.ConfigStore
- watcher *watcher.Watcher
- ctx context.Context // server lifetime context — cancelled on shutdown
- indexMu sync.Mutex
- handlers map[string]mcp.ToolHandler
-
- // Session-aware fields (set once via sync.Once, then immutable)
- sessionOnce sync.Once
- sessionRoot string // absolute path from client
- sessionProject string // derived from sessionRoot via ProjectNameFromPath
- indexStatus atomic.Value
- indexStartedAt atomic.Value // time.Time — when current/last index started
- updateNotice atomic.Value // string — set once by checkForUpdate, cleared after first injection
- updateOnce sync.Once // ensures checkForUpdate runs at most once per session
-}
-
-// ServerOption configures a Server.
-type ServerOption func(*Server)
-
-// WithConfig attaches a ConfigStore for reading runtime settings.
-func WithConfig(c *store.ConfigStore) ServerOption {
- return func(s *Server) { s.config = c }
-}
-
-// NewServer creates a new MCP server with all tools registered.
-func NewServer(r *store.StoreRouter, opts ...ServerOption) *Server {
- srv := &Server{
- router: r,
- handlers: make(map[string]mcp.ToolHandler),
- }
- for _, opt := range opts {
- opt(srv)
- }
-
- srv.mcp = mcp.NewServer(
- &mcp.Implementation{
- Name: "codebase-memory-mcp",
- Version: Version,
- },
- &mcp.ServerOptions{
- InitializedHandler: srv.onInitialized,
- RootsListChangedHandler: srv.onRootsChanged,
- },
- )
-
- srv.registerTools()
- srv.watcher = watcher.New(r, srv.syncProject)
- return srv
-}
-
-// StartWatcher launches the background file-change polling goroutine.
-// It stores ctx for use by startAutoIndex and stops when ctx is cancelled.
-func (s *Server) StartWatcher(ctx context.Context) {
- s.ctx = ctx
- go s.watcher.Run(ctx)
-}
-
-// syncProject is called by the watcher when file changes are detected.
-// Uses TryLock to skip if an index operation is already in progress.
-func (s *Server) syncProject(ctx context.Context, projectName, rootPath string) error {
- if !s.indexMu.TryLock() {
- slog.Debug("watcher.skip", "path", rootPath, "reason", "index_in_progress")
- return nil
- }
- defer s.indexMu.Unlock()
- st, err := s.router.ForProject(projectName)
- if err != nil {
- return fmt.Errorf("store for %s: %w", projectName, err)
- }
- p := pipeline.New(ctx, st, rootPath, discover.ModeFull)
- return p.Run()
-}
-
-// MCPServer returns the underlying MCP server.
-func (s *Server) MCPServer() *mcp.Server {
- return s.mcp
-}
-
-// Router returns the underlying StoreRouter for direct access (e.g. CLI mode).
-func (s *Server) Router() *store.StoreRouter {
- return s.router
-}
-
-// SessionProject returns the auto-detected session project name (may be empty).
-func (s *Server) SessionProject() string {
- return s.sessionProject
-}
-
-// SetSessionRoot sets the session root path directly (for CLI mode).
-func (s *Server) SetSessionRoot(rootPath string) {
- go s.updateOnce.Do(s.checkForUpdate)
- s.sessionOnce.Do(func() {
- s.sessionRoot = rootPath
- if rootPath != "" {
- s.sessionProject = pipeline.ProjectNameFromPath(rootPath)
- }
- })
-}
-
-// --- Session detection ---
-
-// onInitialized is called when the client sends notifications/initialized.
-func (s *Server) onInitialized(ctx context.Context, req *mcp.InitializedRequest) {
- go s.updateOnce.Do(s.checkForUpdate)
- s.sessionOnce.Do(func() {
- s.sessionRoot = s.detectSessionRoot(ctx, req.Session)
- if s.sessionRoot != "" {
- s.sessionProject = pipeline.ProjectNameFromPath(s.sessionRoot)
- s.startAutoIndex()
- }
- })
-}
-
-// onRootsChanged re-detects session root if not yet set.
-func (s *Server) onRootsChanged(ctx context.Context, req *mcp.RootsListChangedRequest) {
- go s.updateOnce.Do(s.checkForUpdate)
- s.sessionOnce.Do(func() {
- s.sessionRoot = s.detectSessionRoot(ctx, req.Session)
- if s.sessionRoot != "" {
- s.sessionProject = pipeline.ProjectNameFromPath(s.sessionRoot)
- s.startAutoIndex()
- }
- })
-}
-
-// detectSessionRoot tries multiple fallback strategies to find the project root.
-func (s *Server) detectSessionRoot(ctx context.Context, session *mcp.ServerSession) string {
- // 1. Try MCP roots protocol
- if session != nil {
- result, err := session.ListRoots(ctx, nil)
- if err == nil && len(result.Roots) > 0 {
- uri := result.Roots[0].URI
- if path, ok := parseFileURI(uri); ok {
- slog.Info("session.root.from_roots", "path", path)
- return path
- }
- }
- }
-
- // 2. Fall back to process working directory
- if cwd, err := os.Getwd(); err == nil && cwd != "/" && cwd != os.Getenv("HOME") {
- slog.Info("session.root.from_cwd", "path", cwd)
- return cwd
- }
-
- // 3. Fall back to single indexed project from DB
- projects, err := s.router.ListProjects()
- if err == nil && len(projects) == 1 && projects[0].RootPath != "" {
- slog.Info("session.root.from_db", "path", projects[0].RootPath)
- return projects[0].RootPath
- }
-
- slog.Info("session.root.none", "reason", "no_roots_no_cwd_no_single_project")
- return ""
-}
-
-// parseFileURI extracts a filesystem path from a file:// URI.
-func parseFileURI(uri string) (string, bool) {
- u, err := url.Parse(uri)
- if err != nil || u.Scheme != "file" {
- return "", false
- }
- path := u.Path
- // On Windows, file:///C:/path parses to /C:/path — strip leading / before drive letter
- if len(path) >= 3 && path[0] == '/' && path[2] == ':' {
- path = path[1:]
- }
- return filepath.FromSlash(path), true
-}
-
-// defaultAutoIndexLimit is the maximum number of source files that auto-index
-// will process for a never-before-indexed project. Override with config key
-// "auto_index_limit". Projects above this limit require explicit index_repository.
-const defaultAutoIndexLimit = 50000
-
-// startAutoIndex triggers background indexing for the session project.
-// Respects config: auto_index must be true (default: false).
-// For never-indexed projects: only auto-indexes if file count <= auto_index_limit.
-// For previously-indexed projects: always re-indexes (incremental, fast).
-func (s *Server) startAutoIndex() {
- hasDB := s.router.HasProject(s.sessionProject)
-
- // Auto-index for new projects requires explicit opt-in via config.
- // Previously-indexed projects always get incremental re-index (cheap).
- if !hasDB {
- autoIndex := false
- fileLimit := defaultAutoIndexLimit
- if s.config != nil {
- autoIndex = s.config.GetBool(store.ConfigAutoIndex, false)
- fileLimit = s.config.GetInt(store.ConfigAutoIndexLimit, defaultAutoIndexLimit)
- }
-
- if !autoIndex {
- slog.Info("autoindex.skip",
- "reason", "auto_index_disabled",
- "hint", "run: codebase-memory-mcp config set auto_index true",
- )
- return
- }
-
- // Check file count before committing to index.
- // Prevents OOM when the server starts in a large monorepo.
- files, err := discover.Discover(s.ctx, s.sessionRoot, nil)
- if err != nil {
- slog.Warn("autoindex.discover.err", "err", err)
- return
- }
- if len(files) > fileLimit {
- slog.Warn("autoindex.skip",
- "reason", "too_many_files",
- "files", len(files),
- "limit", fileLimit,
- "hint", "call index_repository explicitly or increase auto_index_limit",
- )
- return
- }
- s.indexStatus.Store("indexing")
- } else {
- s.indexStatus.Store("ready")
- }
-
- go func() {
- if !s.indexMu.TryLock() {
- slog.Debug("autoindex.skip", "reason", "index_in_progress")
- return
- }
- defer s.indexMu.Unlock()
-
- s.indexStartedAt.Store(time.Now())
- if !hasDB {
- s.indexStatus.Store("indexing")
- }
-
- st, err := s.router.ForProject(s.sessionProject)
- if err != nil {
- slog.Warn("autoindex.store.err", "err", err)
- return
- }
- p := pipeline.New(s.ctx, st, s.sessionRoot, discover.ModeFull)
- if err := p.Run(); err != nil {
- slog.Warn("autoindex.err", "err", err)
- return
- }
- s.indexStatus.Store("ready")
- s.watcher.Watch(s.sessionProject, s.sessionRoot)
- slog.Info("autoindex.done", "project", s.sessionProject)
- }()
-}
-
-// --- Store routing ---
-
-// resolveStore returns the Store for the given project, or the session project if empty.
-func (s *Server) resolveStore(project string) (*store.Store, error) {
- if project == "*" || project == "all" {
- return nil, fmt.Errorf("cross-project queries are not supported; use list_projects to find a specific project name, or omit the project parameter to use the current session project")
- }
- if project == "" {
- project = s.sessionProject
- }
- if project == "" {
- return nil, fmt.Errorf("no project specified and no session project detected; pass project parameter")
- }
- if !s.router.HasProject(project) {
- return nil, fmt.Errorf("project %q not found; use list_projects to see available projects", project)
- }
- // Touch watcher so cross-project queries keep that project fresh.
- if project != s.sessionProject {
- s.watcher.TouchProject(project)
- }
- return s.router.ForProject(project)
-}
-
-// resolveProjectName returns the effective project name for routing.
-func (s *Server) resolveProjectName(project string) string {
- if project == "" {
- return s.sessionProject
- }
- return project
-}
-
-// addIndexStatus adds the index_status field to response data if indexing is in progress.
-func (s *Server) addIndexStatus(data map[string]any) {
- status, _ := s.indexStatus.Load().(string)
- if status == "indexing" {
- data["index_status"] = "indexing"
- }
-}
-
-// addUpdateNotice prepends an update notice to the first tool response, then clears itself.
-func (s *Server) addUpdateNotice(result *mcp.CallToolResult) {
- if notice, ok := s.updateNotice.Load().(string); ok && notice != "" {
- result.Content = append([]mcp.Content{&mcp.TextContent{Text: notice}}, result.Content...)
- s.updateNotice.Store("")
- }
-}
-
-// checkForUpdate fetches the latest GitHub release and stores a notice if newer.
-func (s *Server) checkForUpdate() {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
-
- req, err := http.NewRequestWithContext(ctx, "GET", releaseURL, http.NoBody)
- if err != nil {
- slog.Warn("update check: request create failed", "err", err)
- return
- }
- req.Header.Set("Accept", "application/vnd.github+json")
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- slog.Warn("update check: http failed", "err", err)
- return
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != 200 {
- slog.Warn("update check: bad status", "status", resp.StatusCode)
- return
- }
-
- body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
- if err != nil {
- slog.Warn("update check: body read failed", "err", err)
- return
- }
-
- var release struct {
- TagName string `json:"tag_name"`
- }
- if err := json.Unmarshal(body, &release); err != nil {
- slog.Warn("update check: json parse failed", "err", err)
- return
- }
-
- latest := strings.TrimPrefix(release.TagName, "v")
- if latest == "" || latest == Version {
- slog.Debug("update check: current", "version", Version, "latest", latest)
- return
- }
- if compareVersions(latest, Version) > 0 {
- notice := fmt.Sprintf(
- "⚡ Update available: v%s → v%s — run: codebase-memory-mcp update",
- Version, latest)
- s.updateNotice.Store(notice)
- slog.Info("update available", "current", Version, "latest", latest)
- }
-}
-
-// compareVersions compares two semver strings (e.g. "0.2.1" vs "0.2.0").
-// Returns >0 if a > b, <0 if a < b, 0 if equal.
-func compareVersions(a, b string) int {
- aParts := strings.Split(a, ".")
- bParts := strings.Split(b, ".")
- for i := 0; i < len(aParts) && i < len(bParts); i++ {
- ai, _ := strconv.Atoi(aParts[i])
- bi, _ := strconv.Atoi(bParts[i])
- if ai != bi {
- return ai - bi
- }
- }
- return len(aParts) - len(bParts)
-}
-
-// --- Tool registration ---
-
-func (s *Server) addTool(tool *mcp.Tool, handler mcp.ToolHandler) {
- s.mcp.AddTool(tool, handler)
- s.handlers[tool.Name] = handler
-}
-
-// CallTool invokes a tool handler directly by name, bypassing MCP transport.
-func (s *Server) CallTool(ctx context.Context, name string, argsJSON json.RawMessage) (*mcp.CallToolResult, error) {
- handler, ok := s.handlers[name]
- if !ok {
- return nil, fmt.Errorf("unknown tool: %s", name)
- }
- if len(argsJSON) == 0 {
- argsJSON = json.RawMessage(`{}`)
- }
- req := &mcp.CallToolRequest{
- Params: &mcp.CallToolParamsRaw{
- Name: name,
- Arguments: argsJSON,
- },
- }
- return handler(ctx, req)
-}
-
-// ToolNames returns all registered tool names in sorted order.
-func (s *Server) ToolNames() []string {
- names := make([]string, 0, len(s.handlers))
- for name := range s.handlers {
- names = append(names, name)
- }
- sort.Strings(names)
- return names
-}
-
-func (s *Server) registerTools() {
- s.registerGraphTools()
- s.registerProjectTools()
- s.registerTraceTools()
- s.registerDetectChanges()
- s.registerArchitectureTools()
-}
-
-func (s *Server) registerArchitectureTools() {
- s.addTool(&mcp.Tool{
- Name: "get_architecture",
- Description: "Get codebase architecture overview. Returns structural analysis computed from the code graph. Call with aspects=['all'] for full orientation or select specific aspects for targeted queries. Available aspects: languages (language breakdown), packages (top packages with fan-in/out), entry_points (main/init functions), routes (HTTP endpoints with handlers), hotspots (most-called functions), boundaries (cross-package call volumes), services (cross-service HTTP/async links), layers (package-level layer classification — heuristic), clusters (community detection via Louvain algorithm on CALLS + HTTP_CALLS + ASYNC_CALLS — reveals hidden functional modules across packages and services), file_tree (condensed directory structure), adr (stored Architecture Decision Record — use manage_adr to create/update). Recommended: call this first when exploring an unfamiliar codebase.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "aspects": {
- "type": "array",
- "items": {"type": "string", "enum": ["all", "languages", "packages", "entry_points", "routes", "hotspots", "boundaries", "services", "layers", "clusters", "file_tree", "adr"]},
- "description": "Which architecture aspects to return. Default: ['all']. Use specific aspects to reduce output: ['languages', 'packages'] for quick orientation, ['hotspots', 'boundaries'] for dependency analysis, ['clusters'] for community detection across CALLS/HTTP/ASYNC edges."
- },
- "project": {
- "type": "string",
- "description": "Project to analyze. Defaults to session project."
- }
- }
- }`),
- }, s.handleGetArchitecture)
-
- s.addTool(&mcp.Tool{
- Name: "manage_adr",
- Description: "Manage the Architecture Decision Record (ADR) for a project. CRUD operations for a persistent, section-based architectural summary. Modes: get (retrieve full ADR or specific sections via include filter), store (create or fully replace — all 6 sections required), update (patch specific sections — only canonical keys accepted, unmentioned sections preserved), delete (remove ADR). Fixed sections in canonical order: PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY. Max 8000 chars total. Validation: store rejects content missing any section; update rejects non-canonical keys. Use include=['STACK','PATTERNS'] with get to fetch only needed sections (saves tokens). PLAN ALIGNMENT: Before finalizing any implementation plan, fetch the ADR and validate the plan against it — check ARCHITECTURE for structural fit, PATTERNS for convention compliance, STACK for technology alignment, PHILOSOPHY for principle adherence. Flag conflicts before proceeding. For creating/replacing: explore the codebase first using get_architecture and graph tools, then enter plan mode to draft the ADR collaboratively with the user. Store only after user approval.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "mode": {
- "type": "string",
- "enum": ["get", "store", "update", "delete"],
- "description": "Operation: 'get' retrieves ADR, 'store' creates/replaces (all 6 sections required), 'update' patches sections (canonical keys only), 'delete' removes."
- },
- "project": {
- "type": "string",
- "description": "Project name. Defaults to session project."
- },
- "content": {
- "type": "string",
- "description": "Full ADR markdown (required for mode='store'). Must contain all 6 ## SECTION headers: PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY. Missing sections will be rejected."
- },
- "sections": {
- "type": "object",
- "additionalProperties": {"type": "string"},
- "description": "Section updates (required for mode='update'). Keys must be canonical section names (PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY). Non-canonical keys are rejected. Values are new content. Unmentioned sections preserved."
- },
- "include": {
- "type": "array",
- "items": {"type": "string", "enum": ["PURPOSE", "STACK", "ARCHITECTURE", "PATTERNS", "TRADEOFFS", "PHILOSOPHY"]},
- "description": "Section filter for mode='get'. Returns only the listed sections instead of the full ADR. Example: ['STACK', 'PATTERNS'] returns ~800 chars instead of ~8000. Omit to get all sections."
- }
- },
- "required": ["mode"]
- }`),
- }, s.handleManageADR)
-}
-
-// registerGraphTools registers tools for graph querying, searching, and tracing.
-func (s *Server) registerGraphTools() {
- s.registerIndexAndTraceTool()
- s.registerSchemaAndSnippetTools()
- s.registerSearchTools()
- s.registerQueryTool()
-}
-
-func (s *Server) registerIndexAndTraceTool() {
- s.addTool(&mcp.Tool{
- Name: "index_repository",
- Description: "Index a repository into the code graph. Parses source files, extracts functions/classes/modules, resolves call relationships (CALLS), read references (USAGE), interface implementations (IMPLEMENTS + OVERRIDE), HTTP/async cross-service links, and git history change coupling (FILE_CHANGES_WITH). Supports incremental reindex via content hashing. Auto-sync keeps the graph fresh after initial indexing. If repo_path is omitted, uses the auto-detected session project root. Use mode='fast' for large repos (>50K files) — skips generated code, test fixtures, large files (>512KB), and non-source files for 30-50% faster indexing at the cost of some coverage.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "repo_path": {
- "type": "string",
- "description": "Absolute path to the repository to index. If omitted, uses the auto-detected session project root."
- },
- "mode": {
- "type": "string",
- "enum": ["full", "fast"],
- "description": "Indexing mode. 'full' (default): parse all supported files. 'fast': aggressive filtering — skips generated code, test fixtures, docs, large files (>512KB), and non-source assets for faster indexing of large repos."
- }
- }
- }`),
- }, s.handleIndexRepository)
-
- s.addTool(&mcp.Tool{
- Name: "trace_call_path",
- Description: "Trace the call path of a function (who calls it, what it calls). Requires exact function name — use search_graph first to find the exact name. Follow up with get_code_snippet to read the actual source code. Returns hop-by-hop callees/callers with edge types (CALLS, HTTP_CALLS, ASYNC_CALLS, USAGE, OVERRIDE). If the function is not found, returns suggestions of similar names — use the qualified_name from suggestions in a retry. Use depth=1 first, increase only if needed. Use direction='both' for full cross-service context — HTTP_CALLS edges from other services appear as inbound edges, so direction='outbound' alone misses cross-service callers. Best practice: search_graph(name_pattern='.*Order.*') → trace_call_path(function_name='processOrder') → get_code_snippet(qualified_name='...')",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "function_name": {
- "type": "string",
- "description": "Name of the function to trace (e.g. 'ProcessOrder')"
- },
- "depth": {
- "type": "integer",
- "description": "Maximum BFS depth (1-5, default 3)"
- },
- "direction": {
- "type": "string",
- "description": "Traversal direction: 'outbound' (what it calls), 'inbound' (what calls it), or 'both'",
- "enum": ["outbound", "inbound", "both"]
- },
- "risk_labels": {
- "type": "boolean",
- "description": "Add risk classification (CRITICAL/HIGH/MEDIUM/LOW) based on hop depth. Hop 1=CRITICAL, 2=HIGH, 3=MEDIUM, 4+=LOW. Includes impact_summary with counts. Default false."
- },
- "min_confidence": {
- "type": "number",
- "description": "Minimum confidence threshold (0.0-1.0) for CALLS edges. Filters out low-confidence fuzzy matches. Bands: high (>=0.7), medium (>=0.45), speculative (<0.45). Default 0 (no filter)."
- },
- "project": {
- "type": "string",
- "description": "Project to trace in. Defaults to session project."
- }
- },
- "required": ["function_name"]
- }`),
- }, s.handleTraceCallPath)
-}
-
-func (s *Server) registerSchemaAndSnippetTools() {
- s.addTool(&mcp.Tool{
- Name: "get_graph_schema",
- Description: "Return the schema of the indexed code graph: node label counts, edge type counts, relationship patterns (e.g. Function-CALLS->Function), and sample function/class names. Use to understand what's in the graph before querying.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "project": {
- "type": "string",
- "description": "Project to get schema for. Defaults to session project."
- }
- }
- }`),
- }, s.handleGetGraphSchema)
-
- s.addTool(&mcp.Tool{
- Name: "get_code_snippet",
- Description: "Retrieve source code for a function/class by name with rich metadata. Accepts exact qualified name ('myproject.cmd.server.main.HandleRequest'), partial QN suffix ('main.HandleRequest'), or short name ('HandleRequest'). Returns source code, signature, return type, complexity, decorators, docstring, and caller/callee counts. Returns suggestions with status='ambiguous' when multiple matches found (no 'error' key in disambiguation responses). Use auto_resolve=true to let the tool pick the best match from <=2 candidates (returns alternatives for correction). Use include_neighbors=true to get caller/callee names alongside counts.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "qualified_name": {
- "type": "string",
- "description": "Name or qualified name of the function/class. Exact QN for precision, short name for discovery. Returns suggestions if ambiguous."
- },
- "project": {
- "type": "string",
- "description": "Project to search in. Defaults to session project."
- },
- "auto_resolve": {
- "type": "boolean",
- "description": "When true and <=2 ambiguous candidates exist, auto-pick the best match (highest degree, prefer non-test). Returns source with match_method='auto_best' and alternatives list. Default: false."
- },
- "include_neighbors": {
- "type": "boolean",
- "description": "When true, include caller_names and callee_names arrays (up to 10 each) alongside the counts. Default: false."
- }
- },
- "required": ["qualified_name"]
- }`),
- }, s.handleGetCodeSnippet)
-}
-
-func (s *Server) registerSearchTools() {
- s.addTool(&mcp.Tool{
- Name: "search_graph",
- Description: "Search the code knowledge graph for functions, classes, modules, routes, and other code elements. Search is case-insensitive by default (set case_sensitive=true for exact case). Best practice: use regex alternatives for broad matching — include abbreviations ('handler|hdlr|ctrl'), word forms ('sponsor|sponsoring|sponsored'), and synonyms ('delete|remove|drop'). One broad regex replaces multiple narrow searches. Returns nodes matching the criteria with their connectivity (in/out degree). Results are sorted by relevance by default (exact match first, prefix match second, then by connectivity). Community nodes are excluded by default. Pass exclude_labels: [] to include them. Best practice: Chain with trace_call_path and get_code_snippet for complete answers. Example workflow: search_graph(name_pattern='.*Order.*') → trace_call_path(function_name='processOrder') → get_code_snippet(qualified_name='...'). Returns 10 results per page (use offset to paginate, has_more indicates more pages). name_pattern and qn_pattern support full Go regex — one precise regex replaces multiple literal searches. See parameter descriptions for patterns. For dead code: use relationship='CALLS', direction='inbound', max_degree=0, exclude_entry_points=true. For fan-out: use relationship='CALLS', direction='outbound', min_degree=N. Route nodes: properties.handler contains the actual handler function name. Prefer this over query_graph for counting — no row cap. IMPORTANT: The 'relationship' filter counts how many edges of that type each node has (degree filtering) — it does NOT return the actual edges. To list cross-service HTTP_CALLS or ASYNC_CALLS edges with their properties, use query_graph with Cypher instead. Relationship types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "project": {
- "type": "string",
- "description": "Project to search in. Defaults to session project."
- },
- "label": {
- "type": "string",
- "description": "Node label filter: Function, Class, Module, Method, Interface, Enum, Type, File, Package, Folder, Route"
- },
- "name_pattern": {
- "type": "string",
- "description": "Regex pattern matched against the short node name. Case-insensitive by default. Supports full Go regex: '.*Handler$' (suffix), 'get|set|delete' (alternatives — no backslash before pipe), '^on[A-Z]' (prefix+char class). Best practice: include word variations in alternatives — 'auth|authenticate|authorization' (word forms), 'handler|hdlr|ctrl' (abbreviations), 'create|new|init' (synonyms). One regex with | replaces multiple separate searches."
- },
- "qn_pattern": {
- "type": "string",
- "description": "Regex pattern matched against the qualified name (full module path). Case-insensitive by default. Use to scope searches to directories/modules: '.*services\\.order\\..*' (order service), '.*tests\\..*' (test files only), '.*controller.*\\.handle.*' (handler methods in controllers). Combine with name_pattern for precise cross-cutting queries."
- },
- "file_pattern": {
- "type": "string",
- "description": "Glob pattern for file path within the project. Use to filter by directory ('**/services/**'), file extension ('*.py', '*.yaml'), or filename ('**/Makefile'). Essential for shared-repo projects where multiple languages coexist — e.g., use '*.html' to find only HTML files in a JavaScript project."
- },
- "relationship": {
- "type": "string",
- "description": "Filter by relationship type: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE, IMPLEMENTS"
- },
- "direction": {
- "type": "string",
- "description": "Edge direction for degree filters: 'inbound', 'outbound', or 'any'",
- "enum": ["inbound", "outbound", "any"]
- },
- "min_degree": {
- "type": "integer",
- "description": "Minimum edge count (e.g. 10 for high fan-out functions)"
- },
- "max_degree": {
- "type": "integer",
- "description": "Maximum edge count (e.g. 0 for dead code detection)"
- },
- "exclude_entry_points": {
- "type": "boolean",
- "description": "Exclude entry points (route handlers, main(), framework-registered functions) from results. Use with max_degree=0 for accurate dead code detection."
- },
- "limit": {
- "type": "integer",
- "description": "Max results per page (default: 10). Use small limits and paginate with offset — response includes has_more flag."
- },
- "offset": {
- "type": "integer",
- "description": "Skip N results for pagination (default: 0). Check has_more in response to know if more pages exist."
- },
- "include_connected": {
- "type": "boolean",
- "description": "Include connected node names in results (default: false). Expensive — only enable when you need to see neighbor names."
- },
- "exclude_labels": {
- "type": "array",
- "items": {"type": "string"},
- "description": "Labels to exclude from results. Community nodes are excluded by default — pass [] to include them."
- },
- "sort_by": {
- "type": "string",
- "enum": ["relevance", "name", "degree"],
- "description": "Sort order. Default: relevance (exact match first, prefix match second, then by connectivity)"
- },
- "case_sensitive": {
- "type": "boolean",
- "description": "Match patterns case-sensitively. Default: false (case-insensitive). Set true for exact case matching."
- }
- }
- }`),
- }, s.handleSearchGraph)
-
- s.addTool(&mcp.Tool{
- Name: "search_code",
- Description: "Search for text in source code files (like grep, scoped to indexed project). Search is case-insensitive by default (set case_sensitive=true for exact case). With regex=true, use alternatives for broad matching: 'TODO|FIXME|HACK|WORKAROUND' (issue markers), 'sponsor|sponsoring|sponsored' (word forms), 'import|require|include' (cross-language patterns). Returns matching lines with file path, line number, and context. Returns 10 matches per page — use offset to paginate, has_more indicates more pages. Use for: string literals, error messages, TODO comments, config values, import statements. Prefer search_graph for finding functions/classes by name — search_code is for text content that isn't in the graph.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "pattern": {
- "type": "string",
- "description": "Text to search for. Case-insensitive by default. Literal string match unless regex=true. With regex=true: Go regex syntax (no backslash before pipe). Best practice: use alternatives for word form variance — 'deprecat|obsolete|legacy' catches 'deprecated', 'deprecating', 'obsolete', etc. A partial stem with alternatives is more effective than an exact word."
- },
- "file_pattern": {
- "type": "string",
- "description": "Glob pattern to filter files (e.g. '*.go', '*.py', '*.toml'). Use to focus search on specific file types or directories."
- },
- "regex": {
- "type": "boolean",
- "description": "Treat pattern as a regular expression (default: false)"
- },
- "max_results": {
- "type": "integer",
- "description": "Max matches per page (default: 10). Response includes has_more flag for pagination."
- },
- "offset": {
- "type": "integer",
- "description": "Skip N matches for pagination (default: 0). Check has_more in response."
- },
- "case_sensitive": {
- "type": "boolean",
- "description": "Match case-sensitively. Default: false (case-insensitive). Set true for exact case matching."
- },
- "project": {
- "type": "string",
- "description": "Project to search in. Defaults to session project."
- }
- },
- "required": ["pattern"]
- }`),
- }, s.handleSearchCode)
-}
-
-func (s *Server) registerQueryTool() {
- s.addTool(&mcp.Tool{
- Name: "query_graph",
- Description: "Execute a Cypher-like graph query. String matching in WHERE is case-sensitive by default. For case-insensitive regex: use (?i) flag — WHERE f.name =~ '(?i)handler'. CONTAINS and STARTS WITH are always case-sensitive — use =~ with (?i) for case-insensitive substring matching: WHERE f.name =~ '(?i).*order.*'. Best practice: use regex alternatives for word form variance — WHERE f.name =~ '(?i)sponsor|sponsoring|sponsored'. Tip: prefer search_graph for simple name searches (case-insensitive by default) — use query_graph only when you need Cypher's relationship patterns or edge properties. Default row cap is 200 — use max_rows parameter to increase (up to 10000) for COUNT/aggregation queries on large codebases. Best for: relationship patterns, filtered joins, path queries, and edge property filtering. Supports WHERE on edge properties: r.url_path CONTAINS 'orders', r.confidence >= 0.6, r.method = 'POST', r.confidence_band = 'high', r.validated_by_trace = true, r.coupling_score >= 0.5. This is the correct tool for listing cross-service edges — use MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence, r.confidence_band to see HTTP links with URLs and confidence scores (bands: high>=0.7, medium>=0.45, speculative>=0.25), or MATCH (a)-[r:ASYNC_CALLS]->(b) for async dispatch edges. For change coupling: MATCH (a)-[r:FILE_CHANGES_WITH]->(b) RETURN a.name, b.name, r.coupling_score, r.co_change_count. For interface method overrides: MATCH (s)-[r:OVERRIDE]->(i) to find struct methods implementing interface methods. For read references (callbacks, variable assignments): MATCH (a)-[r:USAGE]->(b). Always use LIMIT. Edge types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "Cypher query, e.g. MATCH (f:Function)-[:CALLS]->(g:Function) WHERE f.name = 'main' RETURN g.name, g.qualified_name LIMIT 20"
- },
- "project": {
- "type": "string",
- "description": "Project to query. Defaults to session project."
- },
- "max_rows": {
- "type": "integer",
- "description": "Maximum result rows (default 200, max 10000). Overrides the internal row cap. Use higher values for COUNT/aggregation queries on large codebases."
- }
- },
- "required": ["query"]
- }`),
- }, s.handleQueryGraph)
-}
-
-// registerProjectTools registers tools for project management.
-func (s *Server) registerProjectTools() {
- s.addTool(&mcp.Tool{
- Name: "list_projects",
- Description: "List all indexed projects with their indexed_at timestamp, root path, and node/edge counts.",
- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
- }, s.handleListProjects)
-
- s.addTool(&mcp.Tool{
- Name: "delete_project",
- Description: "Delete an indexed project and all its graph data (nodes, edges, file hashes). Removes the project's .db file. This action is irreversible.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "project_name": {
- "type": "string",
- "description": "Name of the project to delete"
- }
- },
- "required": ["project_name"]
- }`),
- }, s.handleDeleteProject)
-
- s.addTool(&mcp.Tool{
- Name: "index_status",
- Description: "Check the indexing status of a project. Returns whether the project is indexed, currently indexing, or not found. Shows last indexed timestamp, node/edge counts, and whether the index is initial or incremental. Use this to check if the graph is ready for queries.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "project": {
- "type": "string",
- "description": "Project name to check. Defaults to the auto-detected session project."
- }
- }
- }`),
- }, s.handleIndexStatus)
-}
-
-// --- Helpers ---
-
-// jsonResult marshals data to JSON and returns as tool result.
-func jsonResult(data any) *mcp.CallToolResult {
- b, err := json.MarshalIndent(data, "", " ")
- if err != nil {
- return errResult("json marshal err=" + err.Error())
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: string(b)},
- },
- }
-}
-
-// errResult returns a tool result indicating an error.
-func errResult(msg string) *mcp.CallToolResult {
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: msg},
- },
- IsError: true,
- }
-}
-
-// parseArgs unmarshals the raw JSON arguments into a map.
-func parseArgs(req *mcp.CallToolRequest) (map[string]any, error) {
- if len(req.Params.Arguments) == 0 {
- return map[string]any{}, nil
- }
- var m map[string]any
- if err := json.Unmarshal(req.Params.Arguments, &m); err != nil {
- return nil, fmt.Errorf("invalid arguments: %w", err)
- }
- return m, nil
-}
-
-// getStringArg extracts a string argument from parsed args.
-func getStringArg(args map[string]any, key string) string {
- v, ok := args[key]
- if !ok {
- return ""
- }
- str, ok := v.(string)
- if !ok {
- return ""
- }
- return str
-}
-
-// getIntArg extracts an integer argument with a default value.
-func getIntArg(args map[string]any, key string, defaultVal int) int {
- v, ok := args[key]
- if !ok {
- return defaultVal
- }
- f, ok := v.(float64) // JSON numbers decode as float64
- if !ok {
- return defaultVal
- }
- return int(f)
-}
-
-// getMapStringArg extracts a map[string]string argument from parsed args.
-func getMapStringArg(args map[string]any, key string) map[string]string {
- v, ok := args[key]
- if !ok {
- return nil
- }
- m, ok := v.(map[string]any)
- if !ok {
- return nil
- }
- result := make(map[string]string, len(m))
- for k, val := range m {
- if s, ok := val.(string); ok {
- result[k] = s
- }
- }
- return result
-}
-
-// getBoolArg extracts a boolean argument from parsed args.
-// getFloatArg extracts a float64 argument with a default value.
-func getFloatArg(args map[string]any, key string, defaultVal float64) float64 {
- v, ok := args[key]
- if !ok {
- return defaultVal
- }
- f, ok := v.(float64)
- if !ok {
- return defaultVal
- }
- return f
-}
-
-func getBoolArg(args map[string]any, key string) bool {
- v, ok := args[key]
- if !ok {
- return false
- }
- b, ok := v.(bool)
- if !ok {
- return false
- }
- return b
-}
-
-// findNodeAcrossProjects searches for a node by simple name in the specified project.
-// Falls back to the session project if no filter is given.
-func (s *Server) findNodeAcrossProjects(name string, projectFilter ...string) (*store.Node, string, error) {
- filter := s.sessionProject
- if len(projectFilter) > 0 && projectFilter[0] != "" {
- if projectFilter[0] == "*" || projectFilter[0] == "all" {
- return nil, "", fmt.Errorf("cross-project queries are not supported; use list_projects to find a specific project name, or omit the project parameter to use the current session project")
- }
- filter = projectFilter[0]
- }
- if filter == "" {
- return nil, "", fmt.Errorf("no project specified and no session project detected")
- }
- if !s.router.HasProject(filter) {
- return nil, "", fmt.Errorf("project %q not found; use list_projects to see available projects", filter)
- }
- // Touch watcher so cross-project queries keep that project fresh.
- if filter != s.sessionProject {
- s.watcher.TouchProject(filter)
- }
-
- st, err := s.router.ForProject(filter)
- if err != nil {
- return nil, "", err
- }
- projects, _ := st.ListProjects()
- for _, p := range projects {
- nodes, findErr := st.FindNodesByName(p.Name, name)
- if findErr != nil {
- continue
- }
- if len(nodes) > 0 {
- return nodes[0], p.Name, nil
- }
- }
- return nil, "", fmt.Errorf("node not found: %s", name)
-}
diff --git a/internal/tools/tools_test.go b/internal/tools/tools_test.go
deleted file mode 100644
index b9e1a3aa9..000000000
--- a/internal/tools/tools_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package tools
-
-import (
- "runtime"
- "testing"
-)
-
-func TestParseFileURI(t *testing.T) {
- tests := []struct {
- uri string
- wantPath string
- wantOK bool
- }{
- // Unix paths
- {"file:///home/user/project", "/home/user/project", true},
- {"file:///tmp/test", "/tmp/test", true},
-
- // Windows paths — url.Parse returns /C:/path, must strip leading /
- {"file:///C:/Users/project", "C:/Users/project", true},
- {"file:///D:/Projects/myapp", "D:/Projects/myapp", true},
-
- // Non-file schemes
- {"https://example.com", "", false},
- {"", "", false},
-
- // Edge cases
- {"file:///", "/", true},
- }
-
- for _, tt := range tests {
- t.Run(tt.uri, func(t *testing.T) {
- got, ok := parseFileURI(tt.uri)
- if ok != tt.wantOK {
- t.Fatalf("parseFileURI(%q) ok=%v, want %v", tt.uri, ok, tt.wantOK)
- }
- if !ok {
- return
- }
-
- want := tt.wantPath
- // On Windows, filepath.FromSlash converts / to \
- if runtime.GOOS == "windows" {
- // paths will use backslashes
- want = windowsPath(want)
- }
-
- if got != want {
- t.Errorf("parseFileURI(%q) = %q, want %q", tt.uri, got, want)
- }
- })
- }
-}
-
-// windowsPath converts forward slashes to backslashes for Windows comparison.
-func windowsPath(p string) string {
- result := make([]byte, len(p))
- for i := 0; i < len(p); i++ {
- if p[i] == '/' {
- result[i] = '\\'
- } else {
- result[i] = p[i]
- }
- }
- return string(result)
-}
diff --git a/internal/tools/trace.go b/internal/tools/trace.go
deleted file mode 100644
index 8633dc717..000000000
--- a/internal/tools/trace.go
+++ /dev/null
@@ -1,307 +0,0 @@
-package tools
-
-import (
- "context"
- "fmt"
- "regexp"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- funcName := getStringArg(args, "function_name")
- if funcName == "" {
- return errResult("function_name is required"), nil
- }
-
- depth := getIntArg(args, "depth", 3)
- if depth < 1 {
- depth = 1
- }
- if depth > 5 {
- depth = 5
- }
-
- direction := getStringArg(args, "direction")
- if direction == "" {
- direction = "outbound"
- }
-
- riskLabels := getBoolArg(args, "risk_labels")
- minConfidence := getFloatArg(args, "min_confidence", 0)
-
- project := getStringArg(args, "project")
- effectiveProject := s.resolveProjectName(project)
-
- // Find the function node
- rootNode, foundProject, findErr := s.findNodeAcrossProjects(funcName, effectiveProject)
- if findErr != nil && !strings.HasPrefix(findErr.Error(), "node not found") {
- return errResult(findErr.Error()), nil
- }
- if rootNode == nil {
- // Fuzzy fallback: search for similar names and return structured suggestions
- suggestions := s.findSimilarNodes(funcName, effectiveProject, 5)
- if len(suggestions) > 0 {
- suggList := make([]map[string]string, len(suggestions))
- for i, n := range suggestions {
- suggList[i] = map[string]string{
- "name": n.Name,
- "qualified_name": n.QualifiedName,
- "label": n.Label,
- }
- }
- return jsonResult(map[string]any{
- "status": "not_found",
- "message": fmt.Sprintf("function not found: %s — use a name from the suggestions below", funcName),
- "suggestions": suggList,
- }), nil
- }
- return errResult(fmt.Sprintf("function not found: %s", funcName)), nil
- }
-
- // Get the store for the found project
- st, err := s.router.ForProject(foundProject)
- if err != nil {
- return errResult(fmt.Sprintf("store: %v", err)), nil
- }
-
- edgeTypes := []string{"CALLS", "HTTP_CALLS", "ASYNC_CALLS"}
-
- allVisited, allEdges, bfsErr := runTraceBFS(st, rootNode.ID, direction, edgeTypes, depth, minConfidence)
- if bfsErr != nil {
- return errResult(fmt.Sprintf("bfs err: %v", bfsErr)), nil
- }
-
- if riskLabels {
- allVisited = store.DeduplicateHops(allVisited)
- }
-
- var hops []hopEntry
- if riskLabels {
- hops = buildHopsWithRisk(allVisited)
- } else {
- hops = buildHops(allVisited)
- }
-
- responseData := buildTraceResponse(st, rootNode, foundProject, hops, allVisited, allEdges)
- if riskLabels {
- responseData["impact_summary"] = store.BuildImpactSummary(allVisited, allEdges)
- }
- responseData["module"] = s.getModuleInfo(st, rootNode, foundProject)
- s.addIndexStatus(responseData)
-
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result, nil
-}
-
-func runTraceBFS(st *store.Store, rootID int64, direction string, edgeTypes []string, depth int, minConfidence float64) ([]*store.NodeHop, []store.EdgeInfo, error) {
- if direction == "both" {
- var allVisited []*store.NodeHop
- var allEdges []store.EdgeInfo
- outResult, outErr := st.BFS(rootID, "outbound", edgeTypes, depth, 200)
- if outErr == nil {
- allVisited = append(allVisited, outResult.Visited...)
- allEdges = append(allEdges, outResult.Edges...)
- }
- inResult, inErr := st.BFS(rootID, "inbound", edgeTypes, depth, 200)
- if inErr == nil {
- allVisited = append(allVisited, inResult.Visited...)
- allEdges = append(allEdges, inResult.Edges...)
- }
- if minConfidence > 0 {
- allEdges = filterEdgesByConfidence(allEdges, minConfidence)
- }
- return allVisited, allEdges, nil
- }
- result, err := st.BFS(rootID, direction, edgeTypes, depth, 200)
- if err != nil {
- return nil, nil, err
- }
- edges := result.Edges
- if minConfidence > 0 {
- edges = filterEdgesByConfidence(edges, minConfidence)
- }
- return result.Visited, edges, nil
-}
-
-// filterEdgesByConfidence removes edges below the threshold.
-// Edges with confidence=0 (no confidence set, e.g. HTTP_CALLS) are kept.
-func filterEdgesByConfidence(edges []store.EdgeInfo, minConfidence float64) []store.EdgeInfo {
- filtered := make([]store.EdgeInfo, 0, len(edges))
- for _, e := range edges {
- if e.Confidence == 0 || e.Confidence >= minConfidence {
- filtered = append(filtered, e)
- }
- }
- return filtered
-}
-
-func buildTraceResponse(st *store.Store, rootNode *store.Node, project string, hops []hopEntry, visited []*store.NodeHop, edges []store.EdgeInfo) map[string]any {
- proj, _ := st.GetProject(project)
- indexedAt := ""
- if proj != nil {
- indexedAt = proj.IndexedAt
- }
- return map[string]any{
- "root": buildNodeInfo(rootNode),
- "hops": hops,
- "edges": buildEdgeList(edges),
- "indexed_at": indexedAt,
- "total_results": len(visited),
- }
-}
-
-func buildNodeInfo(n *store.Node) map[string]any {
- info := map[string]any{
- "name": n.Name,
- "qualified_name": n.QualifiedName,
- "label": n.Label,
- "file_path": n.FilePath,
- "start_line": n.StartLine,
- "end_line": n.EndLine,
- }
- if sig, ok := n.Properties["signature"]; ok {
- info["signature"] = sig
- }
- if rt, ok := n.Properties["return_type"]; ok {
- info["return_type"] = rt
- }
- return info
-}
-
-func (s *Server) getModuleInfo(st *store.Store, funcNode *store.Node, project string) map[string]any {
- if funcNode.FilePath == "" {
- return map[string]any{}
- }
-
- modules, err := st.FindNodesByLabel(project, "Module")
- if err != nil {
- return map[string]any{}
- }
-
- for _, m := range modules {
- if m.FilePath == funcNode.FilePath {
- info := map[string]any{"name": m.Name}
- if constants, ok := m.Properties["constants"]; ok {
- info["constants"] = constants
- }
- return info
- }
- }
- return map[string]any{}
-}
-
-type hopEntry struct {
- Hop int `json:"hop"`
- Nodes []map[string]any `json:"nodes"`
-}
-
-func buildHops(visited []*store.NodeHop) []hopEntry {
- hopMap := map[int][]map[string]any{}
- for _, nh := range visited {
- info := map[string]any{
- "name": nh.Node.Name,
- "qualified_name": nh.Node.QualifiedName,
- "label": nh.Node.Label,
- }
- if sig, ok := nh.Node.Properties["signature"]; ok {
- info["signature"] = sig
- }
- hopMap[nh.Hop] = append(hopMap[nh.Hop], info)
- }
-
- var hops []hopEntry
- for h := 1; h <= len(hopMap); h++ {
- if nodes, ok := hopMap[h]; ok {
- hops = append(hops, hopEntry{Hop: h, Nodes: nodes})
- }
- }
- return hops
-}
-
-func buildHopsWithRisk(visited []*store.NodeHop) []hopEntry {
- hopMap := map[int][]map[string]any{}
- for _, nh := range visited {
- info := map[string]any{
- "name": nh.Node.Name,
- "qualified_name": nh.Node.QualifiedName,
- "label": nh.Node.Label,
- "risk": string(store.HopToRisk(nh.Hop)),
- "hop": nh.Hop,
- }
- if sig, ok := nh.Node.Properties["signature"]; ok {
- info["signature"] = sig
- }
- hopMap[nh.Hop] = append(hopMap[nh.Hop], info)
- }
-
- var hops []hopEntry
- for h := 1; h <= len(hopMap); h++ {
- if nodes, ok := hopMap[h]; ok {
- hops = append(hops, hopEntry{Hop: h, Nodes: nodes})
- }
- }
- return hops
-}
-
-// findSimilarNodes searches for nodes whose name contains the input string (case-insensitive).
-func (s *Server) findSimilarNodes(name, project string, limit int) []*store.Node {
- effectiveProject := s.resolveProjectName(project)
- if effectiveProject == "" {
- return nil
- }
- if !s.router.HasProject(effectiveProject) {
- return nil
- }
- st, err := s.router.ForProject(effectiveProject)
- if err != nil {
- return nil
- }
- // Get actual project name from DB
- projName := effectiveProject
- projects, _ := st.ListProjects()
- if len(projects) > 0 {
- projName = projects[0].Name
- }
- params := &store.SearchParams{
- Project: projName,
- NamePattern: regexp.QuoteMeta(name),
- Limit: limit,
- MinDegree: -1,
- MaxDegree: -1,
- ExcludeLabels: []string{"Community"},
- }
- out, searchErr := st.Search(params)
- if searchErr != nil {
- return nil
- }
- nodes := make([]*store.Node, len(out.Results))
- for i, r := range out.Results {
- nodes[i] = r.Node
- }
- return nodes
-}
-
-func buildEdgeList(edges []store.EdgeInfo) []map[string]any {
- result := make([]map[string]any, 0, len(edges))
- for _, e := range edges {
- entry := map[string]any{
- "from": e.FromName,
- "to": e.ToName,
- "type": e.Type,
- }
- if e.Confidence > 0 {
- entry["confidence"] = e.Confidence
- }
- result = append(result, entry)
- }
- return result
-}
diff --git a/internal/tools/traces.go b/internal/tools/traces.go
deleted file mode 100644
index d48936ee1..000000000
--- a/internal/tools/traces.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package tools
-
-import (
- "context"
- "encoding/json"
-
- "github.com/DeusData/codebase-memory-mcp/internal/traces"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func (s *Server) registerTraceTools() {
- s.addTool(&mcp.Tool{
- Name: "ingest_traces",
- Description: "Ingest OpenTelemetry JSON traces (OTLP format) to validate and enrich HTTP_CALLS edges. Matches HTTP spans to existing edges by URL path, boosts confidence by +0.15 (capped at 1.0), and sets validated_by_trace=true, trace_call_count, and p99_latency_ns on matched edges. Use after index_repository to confirm static analysis predictions with runtime data. Export traces via: otel-cli or collector with OTLP JSON exporter.",
- InputSchema: json.RawMessage(`{
- "type": "object",
- "properties": {
- "project": {
- "type": "string",
- "description": "Name of the indexed project"
- },
- "file_path": {
- "type": "string",
- "description": "Path to the OTLP JSON export file"
- }
- },
- "required": ["project", "file_path"]
- }`),
- }, s.handleIngestTraces)
-}
-
-func (s *Server) handleIngestTraces(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- args, err := parseArgs(req)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- project := getStringArg(args, "project")
- filePath := getStringArg(args, "file_path")
-
- if project == "" || filePath == "" {
- return errResult("project and file_path are required"), nil
- }
-
- st, err := s.resolveStore(project)
- if err != nil {
- return errResult("store: " + err.Error()), nil //nolint:nilerr // WHY: MCP handler contract returns tool errors in result, Go error is always nil
- }
-
- result, err := traces.Ingest(st, project, filePath)
- if err != nil {
- return errResult(err.Error()), nil
- }
-
- return jsonResult(result), nil
-}
diff --git a/internal/tools/update_test.go b/internal/tools/update_test.go
deleted file mode 100644
index b079ebd11..000000000
--- a/internal/tools/update_test.go
+++ /dev/null
@@ -1,173 +0,0 @@
-package tools
-
-import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-
- "github.com/modelcontextprotocol/go-sdk/mcp"
-)
-
-func TestCompareVersions(t *testing.T) {
- tests := []struct {
- a, b string
- want int // >0, 0, or <0
- }{
- {"0.2.1", "0.2.0", 1},
- {"0.2.0", "0.2.0", 0},
- {"0.1.9", "0.2.0", -1},
- {"0.10.0", "0.2.0", 1}, // numeric, not string comparison
- {"1.0.0", "0.99.99", 1},
- {"0.0.1", "0.0.2", -1},
- }
- for _, tt := range tests {
- t.Run(fmt.Sprintf("%s_vs_%s", tt.a, tt.b), func(t *testing.T) {
- got := compareVersions(tt.a, tt.b)
- switch {
- case tt.want > 0 && got <= 0:
- t.Fatalf("compareVersions(%q, %q) = %d, want > 0", tt.a, tt.b, got)
- case tt.want < 0 && got >= 0:
- t.Fatalf("compareVersions(%q, %q) = %d, want < 0", tt.a, tt.b, got)
- case tt.want == 0 && got != 0:
- t.Fatalf("compareVersions(%q, %q) = %d, want 0", tt.a, tt.b, got)
- }
- })
- }
-}
-
-func withTestVersion(t *testing.T, v string) {
- t.Helper()
- old := Version
- Version = v
- t.Cleanup(func() { Version = old })
-}
-
-func TestCheckForUpdate_NewerAvailable(t *testing.T) {
- withTestVersion(t, "1.0.0")
-
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, `{"tag_name": "v99.0.0"}`)
- }))
- defer ts.Close()
-
- old := releaseURL
- releaseURL = ts.URL
- defer func() { releaseURL = old }()
-
- srv := &Server{}
- srv.checkForUpdate()
-
- notice, _ := srv.updateNotice.Load().(string)
- if notice == "" {
- t.Fatal("expected update notice to be set")
- }
- if !strings.Contains(notice, "v99.0.0") {
- t.Fatalf("notice should mention v99.0.0, got: %s", notice)
- }
- if !strings.Contains(notice, "codebase-memory-mcp update") {
- t.Fatalf("notice should contain update command, got: %s", notice)
- }
-}
-
-func TestCheckForUpdate_AlreadyCurrent(t *testing.T) {
- withTestVersion(t, "1.0.0")
-
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, `{"tag_name": "v%s"}`, Version)
- }))
- defer ts.Close()
-
- old := releaseURL
- releaseURL = ts.URL
- defer func() { releaseURL = old }()
-
- srv := &Server{}
- srv.checkForUpdate()
-
- notice, _ := srv.updateNotice.Load().(string)
- if notice != "" {
- t.Fatalf("expected empty notice for current version, got: %s", notice)
- }
-}
-
-func TestCheckForUpdate_OlderAvailable(t *testing.T) {
- withTestVersion(t, "1.0.0")
-
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, `{"tag_name": "v0.0.1"}`)
- }))
- defer ts.Close()
-
- old := releaseURL
- releaseURL = ts.URL
- defer func() { releaseURL = old }()
-
- srv := &Server{}
- srv.checkForUpdate()
-
- notice, _ := srv.updateNotice.Load().(string)
- if notice != "" {
- t.Fatalf("expected empty notice for older version, got: %s", notice)
- }
-}
-
-func TestCheckForUpdate_ServerError(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(500)
- }))
- defer ts.Close()
-
- old := releaseURL
- releaseURL = ts.URL
- defer func() { releaseURL = old }()
-
- srv := &Server{}
- srv.checkForUpdate() // should not panic
-
- notice, _ := srv.updateNotice.Load().(string)
- if notice != "" {
- t.Fatalf("expected empty notice on server error, got: %s", notice)
- }
-}
-
-func TestCheckForUpdate_MalformedJSON(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, `not json at all!!!`)
- }))
- defer ts.Close()
-
- old := releaseURL
- releaseURL = ts.URL
- defer func() { releaseURL = old }()
-
- srv := &Server{}
- srv.checkForUpdate() // should not panic
-
- notice, _ := srv.updateNotice.Load().(string)
- if notice != "" {
- t.Fatalf("expected empty notice on malformed JSON, got: %s", notice)
- }
-}
-
-func TestAddUpdateNotice_ShowsOnce(t *testing.T) {
- srv := &Server{}
- srv.updateNotice.Store("v0.2.0 → v0.3.0 available")
-
- first := &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "{}"}}}
- srv.addUpdateNotice(first)
- if len(first.Content) != 2 {
- t.Fatalf("expected 2 content blocks, got %d", len(first.Content))
- }
- tc, ok := first.Content[0].(*mcp.TextContent)
- if !ok || tc.Text != "v0.2.0 → v0.3.0 available" {
- t.Fatalf("expected notice as first content block, got %v", first.Content[0])
- }
-
- second := &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "{}"}}}
- srv.addUpdateNotice(second)
- if len(second.Content) != 1 {
- t.Fatal("expected update notice to be absent in second call (show-once)")
- }
-}
diff --git a/internal/traces/traces.go b/internal/traces/traces.go
deleted file mode 100644
index 9dadfc9aa..000000000
--- a/internal/traces/traces.go
+++ /dev/null
@@ -1,265 +0,0 @@
-package traces
-
-import (
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "sort"
- "strings"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// OTLPExport represents the top-level structure of an OTLP JSON export.
-type OTLPExport struct {
- ResourceSpans []ResourceSpan `json:"resourceSpans"`
-}
-
-// ResourceSpan contains spans from a single service/resource.
-type ResourceSpan struct {
- Resource Resource `json:"resource"`
- ScopeSpans []ScopeSpan `json:"scopeSpans"`
-}
-
-// Resource describes the service that produced the spans.
-type Resource struct {
- Attributes []Attribute `json:"attributes"`
-}
-
-// ScopeSpan groups spans by instrumentation scope.
-type ScopeSpan struct {
- Spans []Span `json:"spans"`
-}
-
-// Span represents a single trace span.
-type Span struct {
- TraceID string `json:"traceId"`
- SpanID string `json:"spanId"`
- ParentSpanID string `json:"parentSpanId"`
- Name string `json:"name"`
- Kind int `json:"kind"` // 1=internal, 2=server, 3=client
- StartTime string `json:"startTimeUnixNano"`
- EndTime string `json:"endTimeUnixNano"`
- Attributes []Attribute `json:"attributes"`
- Status SpanStatus `json:"status"`
-}
-
-// SpanStatus represents the status of a span.
-type SpanStatus struct {
- Code int `json:"code"` // 0=unset, 1=ok, 2=error
-}
-
-// Attribute is a key-value pair in OTLP format.
-type Attribute struct {
- Key string `json:"key"`
- Value AttributeValue `json:"value"`
-}
-
-// AttributeValue holds the typed value.
-type AttributeValue struct {
- StringValue string `json:"stringValue,omitempty"`
- IntValue string `json:"intValue,omitempty"`
-}
-
-// HTTPSpanInfo holds extracted HTTP info from a span.
-type HTTPSpanInfo struct {
- ServiceName string
- Method string
- Path string
- StatusCode string
- SpanKind int
- DurationNs int64
-}
-
-// IngestResult summarizes what the trace ingestion accomplished.
-type IngestResult struct {
- SpansProcessed int `json:"spans_processed"`
- EdgesValidated int `json:"edges_validated"`
- EdgesEnriched int `json:"edges_enriched"`
-}
-
-// Ingest reads an OTLP JSON file and uses the spans to validate/enrich HTTP_CALLS edges.
-func Ingest(s *store.Store, project, filePath string) (*IngestResult, error) {
- data, err := os.ReadFile(filePath)
- if err != nil {
- return nil, fmt.Errorf("read trace file: %w", err)
- }
-
- var export OTLPExport
- if err := json.Unmarshal(data, &export); err != nil {
- return nil, fmt.Errorf("parse OTLP JSON: %w", err)
- }
-
- result := &IngestResult{}
-
- var httpSpans []HTTPSpanInfo
- for _, rs := range export.ResourceSpans {
- serviceName := extractServiceName(rs.Resource)
- for _, ss := range rs.ScopeSpans {
- for i := range ss.Spans {
- info := extractHTTPInfo(&ss.Spans[i], serviceName)
- if info != nil {
- httpSpans = append(httpSpans, *info)
- result.SpansProcessed++
- }
- }
- }
- }
-
- slog.Info("traces.ingest", "http_spans", len(httpSpans))
-
- matchSpansToEdges(s, project, httpSpans, result)
-
- return result, nil
-}
-
-// extractServiceName gets service.name from resource attributes.
-func extractServiceName(r Resource) string {
- for _, attr := range r.Attributes {
- if attr.Key == "service.name" {
- return attr.Value.StringValue
- }
- }
- return ""
-}
-
-// extractHTTPInfo extracts HTTP method/path from span attributes.
-func extractHTTPInfo(span *Span, serviceName string) *HTTPSpanInfo {
- info := &HTTPSpanInfo{
- ServiceName: serviceName,
- SpanKind: span.Kind,
- }
-
- hasHTTP := false
- for _, attr := range span.Attributes {
- switch attr.Key {
- case "http.method", "http.request.method":
- info.Method = attr.Value.StringValue
- hasHTTP = true
- case "http.route", "http.target", "url.path":
- info.Path = attr.Value.StringValue
- hasHTTP = true
- case "http.status_code":
- info.StatusCode = attr.Value.StringValue
- case "url.full":
- if path := extractPathFromURL(attr.Value.StringValue); path != "" {
- info.Path = path
- hasHTTP = true
- }
- }
- }
-
- if !hasHTTP || info.Path == "" {
- return nil
- }
-
- info.DurationNs = parseDuration(span.StartTime, span.EndTime)
- return info
-}
-
-// extractPathFromURL extracts the path component from a full URL string.
-func extractPathFromURL(fullURL string) string {
- slashes := 0
- idx := 0
- for i, c := range fullURL {
- if c == '/' {
- slashes++
- if slashes == 3 {
- idx = i
- break
- }
- }
- }
- if idx > 0 {
- path := fullURL[idx:]
- if qIdx := strings.Index(path, "?"); qIdx >= 0 {
- path = path[:qIdx]
- }
- return path
- }
- return ""
-}
-
-// parseDuration parses nanosecond timestamps and returns duration.
-func parseDuration(startNano, endNano string) int64 {
- var start, end int64
- _, _ = fmt.Sscanf(startNano, "%d", &start)
- _, _ = fmt.Sscanf(endNano, "%d", &end)
- if end > start {
- return end - start
- }
- return 0
-}
-
-// matchSpansToEdges matches HTTP spans to existing graph edges.
-func matchSpansToEdges(s *store.Store, project string, spans []HTTPSpanInfo, result *IngestResult) {
- edges, err := s.FindEdgesByType(project, "HTTP_CALLS")
- if err != nil {
- slog.Warn("traces.edges.err", "err", err)
- return
- }
-
- edgeByPath := make(map[string]*store.Edge)
- for _, e := range edges {
- if urlPath, ok := e.Properties["url_path"].(string); ok {
- normalized := strings.ToLower(strings.TrimRight(urlPath, "/"))
- edgeByPath[normalized] = e
- }
- }
-
- pathFrequency := make(map[string]int)
- pathLatencies := make(map[string][]int64)
-
- for _, span := range spans {
- normalized := strings.ToLower(strings.TrimRight(span.Path, "/"))
- pathFrequency[normalized]++
- if span.DurationNs > 0 {
- pathLatencies[normalized] = append(pathLatencies[normalized], span.DurationNs)
- }
- }
-
- for path, edge := range edgeByPath {
- freq, ok := pathFrequency[path]
- if !ok {
- continue
- }
-
- result.EdgesValidated++
-
- props := edge.Properties
- if props == nil {
- props = make(map[string]any)
- }
- props["validated_by_trace"] = true
- props["trace_call_count"] = freq
-
- if conf, ok := props["confidence"].(float64); ok && conf < 0.9 {
- props["confidence"] = min(conf+0.15, 1.0)
- props["confidence_band"] = "high"
- }
-
- if latencies, ok := pathLatencies[path]; ok && len(latencies) > 0 {
- props["p99_latency_ns"] = calculateP99(latencies)
- result.EdgesEnriched++
- }
-
- edge.Properties = props
- _, _ = s.InsertEdge(edge)
- }
-}
-
-// calculateP99 returns the 99th percentile value.
-func calculateP99(values []int64) int64 {
- if len(values) == 0 {
- return 0
- }
- sorted := make([]int64, len(values))
- copy(sorted, values)
- sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
- idx := int(float64(len(sorted)) * 0.99)
- if idx >= len(sorted) {
- idx = len(sorted) - 1
- }
- return sorted[idx]
-}
diff --git a/internal/traces/traces_test.go b/internal/traces/traces_test.go
deleted file mode 100644
index 32f46c04f..000000000
--- a/internal/traces/traces_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package traces
-
-import (
- "os"
- "path/filepath"
- "testing"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-func TestExtractServiceName(t *testing.T) {
- r := Resource{
- Attributes: []Attribute{
- {Key: "service.name", Value: AttributeValue{StringValue: "order-service"}},
- },
- }
- if got := extractServiceName(r); got != "order-service" {
- t.Errorf("expected order-service, got %s", got)
- }
-}
-
-func TestExtractHTTPInfo(t *testing.T) {
- span := Span{
- Kind: 2,
- Attributes: []Attribute{
- {Key: "http.method", Value: AttributeValue{StringValue: "GET"}},
- {Key: "http.route", Value: AttributeValue{StringValue: "/api/orders"}},
- {Key: "http.status_code", Value: AttributeValue{StringValue: "200"}},
- },
- StartTime: "1000000000",
- EndTime: "1050000000",
- }
- info := extractHTTPInfo(&span, "svc")
- if info == nil {
- t.Fatal("expected HTTPSpanInfo")
- }
- if info.Method != "GET" {
- t.Errorf("expected GET, got %s", info.Method)
- }
- if info.Path != "/api/orders" {
- t.Errorf("expected /api/orders, got %s", info.Path)
- }
- if info.DurationNs != 50000000 {
- t.Errorf("expected 50000000ns, got %d", info.DurationNs)
- }
-}
-
-func TestExtractHTTPInfoNonHTTPSpan(t *testing.T) {
- span := Span{
- Kind: 1,
- Attributes: []Attribute{
- {Key: "db.system", Value: AttributeValue{StringValue: "postgresql"}},
- },
- }
- info := extractHTTPInfo(&span, "svc")
- if info != nil {
- t.Error("expected nil for non-HTTP span")
- }
-}
-
-func TestExtractPathFromURL(t *testing.T) {
- tests := []struct {
- url string
- want string
- }{
- {"https://example.com/api/orders", "/api/orders"},
- {"http://localhost:8080/health?check=true", "/health"},
- {"not-a-url", ""},
- }
- for _, tt := range tests {
- if got := extractPathFromURL(tt.url); got != tt.want {
- t.Errorf("extractPathFromURL(%q) = %q, want %q", tt.url, got, tt.want)
- }
- }
-}
-
-func TestIngestOTLPJSON(t *testing.T) {
- s, err := store.OpenMemory()
- if err != nil {
- t.Fatal(err)
- }
- defer s.Close()
-
- project := "test-proj"
- _ = s.UpsertProject(project, "/tmp/test")
-
- srcID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "caller",
- QualifiedName: "svcA.caller",
- })
- tgtID, _ := s.UpsertNode(&store.Node{
- Project: project, Label: "Function", Name: "handler",
- QualifiedName: "svcB.handler",
- })
- _, _ = s.InsertEdge(&store.Edge{
- Project: project, SourceID: srcID, TargetID: tgtID,
- Type: "HTTP_CALLS",
- Properties: map[string]any{
- "url_path": "/api/orders",
- "confidence": 0.5,
- "confidence_band": "medium",
- },
- })
-
- fixture := `{
- "resourceSpans": [{
- "resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "order-service"}}]},
- "scopeSpans": [{
- "spans": [{
- "traceId": "abc123",
- "spanId": "def456",
- "name": "GET /api/orders",
- "kind": 2,
- "startTimeUnixNano": "1000000000",
- "endTimeUnixNano": "1050000000",
- "attributes": [
- {"key": "http.method", "value": {"stringValue": "GET"}},
- {"key": "http.route", "value": {"stringValue": "/api/orders"}}
- ],
- "status": {"code": 1}
- }]
- }]
- }]
- }`
-
- tmpFile := filepath.Join(t.TempDir(), "traces.json")
- if err := os.WriteFile(tmpFile, []byte(fixture), 0o600); err != nil {
- t.Fatal(err)
- }
-
- result, err := Ingest(s, project, tmpFile)
- if err != nil {
- t.Fatal(err)
- }
-
- if result.SpansProcessed != 1 {
- t.Errorf("expected 1 span, got %d", result.SpansProcessed)
- }
- if result.EdgesValidated != 1 {
- t.Errorf("expected 1 validated, got %d", result.EdgesValidated)
- }
-
- // Check edge was enriched
- edges, _ := s.FindEdgesByType(project, "HTTP_CALLS")
- if len(edges) != 1 {
- t.Fatalf("expected 1 edge, got %d", len(edges))
- }
- e := edges[0]
- if v, ok := e.Properties["validated_by_trace"].(bool); !ok || !v {
- t.Error("expected validated_by_trace=true")
- }
- if conf, ok := e.Properties["confidence"].(float64); !ok || conf < 0.6 {
- t.Errorf("expected boosted confidence >= 0.6, got %v", e.Properties["confidence"])
- }
-}
-
-func TestCalculateP99(t *testing.T) {
- values := []int64{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
- p99 := calculateP99(values)
- if p99 != 100 {
- t.Errorf("expected 100, got %d", p99)
- }
-
- single := []int64{42}
- if got := calculateP99(single); got != 42 {
- t.Errorf("expected 42, got %d", got)
- }
-}
diff --git a/internal/watcher/main_test.go b/internal/watcher/main_test.go
deleted file mode 100644
index 70eab86d6..000000000
--- a/internal/watcher/main_test.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package watcher
-
-import (
- "testing"
-
- "go.uber.org/goleak"
-)
-
-func TestMain(m *testing.M) {
- goleak.VerifyTestMain(m,
- // HTTP transport dial goroutines from version checker
- goleak.IgnoreTopFunction("net/http.(*Transport).dialConnFor"),
- goleak.IgnoreTopFunction("internal/poll.runtime_pollWait"),
- )
-}
diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.go
deleted file mode 100644
index cfb9c63c5..000000000
--- a/internal/watcher/watcher.go
+++ /dev/null
@@ -1,628 +0,0 @@
-package watcher
-
-import (
- "bytes"
- "context"
- "io/fs"
- "log/slog"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-
- "github.com/fsnotify/fsnotify"
-
- "github.com/DeusData/codebase-memory-mcp/internal/discover"
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// watchStrategy determines how the watcher detects file changes for a project.
-type watchStrategy int
-
-const (
- strategyAuto watchStrategy = iota // auto-detect at first poll
- strategyGit // git status + HEAD tracking
- strategyFSNotify // fsnotify event-driven
- strategyDirMtime // directory mtime polling (fallback)
-)
-
-func (s watchStrategy) String() string {
- switch s {
- case strategyGit:
- return "git"
- case strategyFSNotify:
- return "fsnotify"
- case strategyDirMtime:
- return "dirmtime"
- default:
- return "auto"
- }
-}
-
-const (
- baseInterval = 5 * time.Second
- maxInterval = 60 * time.Second
- fullSnapshotInterval = 5 // polls between forced full snapshots
-)
-
-type fileSnapshot struct {
- modTime time.Time
- size int64
-}
-
-type projectState struct {
- snapshot map[string]fileSnapshot
- pollsSinceFull int
- interval time.Duration
- nextPoll time.Time
-
- // Strategy (set during baseline, may downgrade at runtime).
- strategy watchStrategy
-
- // Git strategy state.
- lastGitHead string
-
- // FSNotify strategy state.
- fsWatcher *fsnotify.Watcher
- fsChanged atomic.Bool
- fsCancel context.CancelFunc
- fsDone chan struct{} // closed when drainFSEvents exits
-
- // Dir-mtime strategy state.
- dirMtimes map[string]time.Time
-}
-
-// close releases per-project resources (fsnotify watcher, goroutines).
-func (ps *projectState) close() {
- if ps.fsCancel != nil {
- ps.fsCancel()
- }
- if ps.fsWatcher != nil {
- ps.fsWatcher.Close()
- }
- if ps.fsDone != nil {
- <-ps.fsDone // wait for drain goroutine to exit
- }
- ps.fsCancel = nil
- ps.fsWatcher = nil
- ps.fsDone = nil
-}
-
-// IndexFunc is the callback signature for triggering a re-index.
-type IndexFunc func(ctx context.Context, projectName, rootPath string) error
-
-// watchEntry tracks a project in the explicit watch list.
-type watchEntry struct {
- rootPath string
- touchedAt time.Time
-}
-
-// Watcher polls indexed projects for file changes and triggers re-indexing.
-// Change detection uses a 3-tier strategy per project:
-//
-// 1. Git — git status + HEAD tracking (for git repos)
-// 2. FSNotify — event-driven via OS file notifications (for non-git dirs)
-// 3. Dir-mtime — directory mtime polling (fallback if fsnotify setup fails)
-type Watcher struct {
- router *store.StoreRouter
- indexFn IndexFunc
- projects map[string]*projectState
- ctx context.Context
-
- // Explicit watch list — only watched projects get polled.
- mu sync.Mutex
- watchList map[string]watchEntry
-
- // testStrategy overrides auto-detection when non-zero (for tests).
- testStrategy watchStrategy
-}
-
-// New creates a Watcher. indexFn is called when file changes are detected.
-func New(r *store.StoreRouter, indexFn IndexFunc) *Watcher {
- return &Watcher{
- router: r,
- indexFn: indexFn,
- projects: make(map[string]*projectState),
- watchList: make(map[string]watchEntry),
- ctx: context.Background(),
- }
-}
-
-// Watch adds a project to the watch list. Called after successful index.
-func (w *Watcher) Watch(name, rootPath string) {
- w.mu.Lock()
- defer w.mu.Unlock()
- w.watchList[name] = watchEntry{rootPath: rootPath, touchedAt: time.Now()}
- slog.Debug("watcher.watch", "project", name, "path", rootPath)
-}
-
-// Unwatch removes a project from the watch list. Called on delete.
-func (w *Watcher) Unwatch(name string) {
- w.mu.Lock()
- defer w.mu.Unlock()
- delete(w.watchList, name)
- slog.Debug("watcher.unwatch", "project", name)
-}
-
-// TouchProject refreshes a project's timestamp in the watch list.
-// If the project isn't watched yet, adds it (looks up rootPath from DB).
-func (w *Watcher) TouchProject(name string) {
- w.mu.Lock()
- defer w.mu.Unlock()
- if e, ok := w.watchList[name]; ok {
- e.touchedAt = time.Now()
- w.watchList[name] = e
- return
- }
- // Not yet watched — look up rootPath from DB.
- st, release, err := w.router.AcquireStore(name)
- if err != nil {
- return
- }
- proj, projErr := st.GetProject(name)
- release()
- if projErr != nil || proj == nil || proj.RootPath == "" {
- return
- }
- w.watchList[name] = watchEntry{rootPath: proj.RootPath, touchedAt: time.Now()}
- slog.Debug("watcher.touch_add", "project", name, "path", proj.RootPath)
-}
-
-// Run blocks until ctx is cancelled. Ticks at baseInterval, polling each
-// project only when its adaptive interval has elapsed.
-func (w *Watcher) Run(ctx context.Context) {
- w.ctx = ctx
- ticker := time.NewTicker(baseInterval)
- defer ticker.Stop()
- defer w.closeAll()
-
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- w.pollAll()
- }
- }
-}
-
-// closeAll releases resources for all tracked projects.
-func (w *Watcher) closeAll() {
- for _, state := range w.projects {
- state.close()
- }
-}
-
-// pollAll iterates the explicit watch list and polls each project that is due.
-// Prunes watcher state for unwatched projects.
-func (w *Watcher) pollAll() {
- w.mu.Lock()
- // Copy watch list under lock to avoid holding lock during poll.
- entries := make(map[string]watchEntry, len(w.watchList))
- for k, v := range w.watchList {
- entries[k] = v
- }
- w.mu.Unlock()
-
- // Prune projectState for unwatched projects.
- for name, state := range w.projects {
- if _, ok := entries[name]; !ok {
- slog.Info("watcher.prune", "project", name)
- state.close()
- delete(w.projects, name)
- }
- }
-
- now := time.Now()
- for name, entry := range entries {
- state, exists := w.projects[name]
- if exists && now.Before(state.nextPoll) {
- continue
- }
-
- st, release, stErr := w.router.AcquireStore(name)
- if stErr != nil {
- continue
- }
- proj, projErr := st.GetProject(name)
- release()
- if projErr != nil || proj == nil {
- continue
- }
-
- // Use rootPath from watch list (most current).
- if entry.rootPath != "" {
- proj.RootPath = entry.rootPath
- }
-
- if !exists {
- state = &projectState{}
- w.projects[name] = state
- }
-
- w.pollProject(proj, state)
- }
-}
-
-// --- Strategy probing ---
-
-// probeStrategy determines the best change detection strategy for a project.
-// Order: git → fsnotify → dirmtime.
-func (w *Watcher) probeStrategy(ctx context.Context, rootPath string) watchStrategy {
- if w.testStrategy != strategyAuto {
- return w.testStrategy
- }
- if isGitRepo(ctx, rootPath) {
- return strategyGit
- }
- // FSNotify is the intent; actual setup may fail → falls back in initBaseline.
- return strategyFSNotify
-}
-
-// --- Core poll logic ---
-
-func (w *Watcher) pollProject(proj *store.Project, state *projectState) {
- if _, err := os.Stat(proj.RootPath); err != nil {
- slog.Warn("watcher.root_gone", "project", proj.Name, "path", proj.RootPath)
- state.nextPoll = time.Now().Add(maxInterval)
- return
- }
-
- // First poll — capture baseline and select strategy.
- if state.snapshot == nil {
- w.initBaseline(proj, state)
- return
- }
-
- state.pollsSinceFull++
-
- // Check sentinel based on strategy.
- changed, strategyFailed := w.checkSentinel(proj, state)
-
- if strategyFailed {
- w.downgradeStrategy(proj, state)
- changed, _ = w.checkSentinel(proj, state)
- }
-
- // Git sentinel catches everything — no forced full snapshot needed.
- // FSNotify + dir-mtime may miss in-place edits, so force periodically.
- forceFull := state.strategy != strategyGit && state.pollsSinceFull >= fullSnapshotInterval
-
- if !changed && !forceFull {
- state.nextPoll = time.Now().Add(state.interval)
- return
- }
-
- w.fullSnapshotAndIndex(proj, state)
-}
-
-func (w *Watcher) initBaseline(proj *store.Project, state *projectState) {
- snap, err := captureSnapshot(w.ctx, proj.RootPath)
- if err != nil {
- slog.Warn("watcher.snapshot", "project", proj.Name, "err", err)
- state.nextPoll = time.Now().Add(baseInterval)
- return
- }
-
- state.snapshot = snap
- state.pollsSinceFull = 0
- state.interval = pollInterval(len(snap))
- state.nextPoll = time.Now().Add(state.interval)
-
- // Select and initialize strategy.
- state.strategy = w.probeStrategy(w.ctx, proj.RootPath)
-
- switch state.strategy {
- case strategyGit:
- head, _ := gitHead(w.ctx, proj.RootPath)
- state.lastGitHead = head
- slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "git", "files", len(snap))
-
- case strategyFSNotify:
- if err := w.initFSNotify(state, proj.RootPath); err != nil {
- slog.Debug("watcher.fsnotify.fallback", "project", proj.Name, "err", err)
- state.strategy = strategyDirMtime
- state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)
- slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "dirmtime", "files", len(snap), "dirs", len(state.dirMtimes))
- } else {
- slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "fsnotify", "files", len(snap))
- }
-
- case strategyDirMtime:
- state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)
- slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "dirmtime", "files", len(snap), "dirs", len(state.dirMtimes))
- }
-}
-
-// checkSentinel returns (changed, strategyFailed).
-func (w *Watcher) checkSentinel(proj *store.Project, state *projectState) (changed, strategyFailed bool) {
- switch state.strategy {
- case strategyGit:
- changed, newHead, err := gitSentinel(w.ctx, proj.RootPath, state.lastGitHead)
- if err != nil {
- slog.Warn("watcher.git.err", "project", proj.Name, "err", err)
- return false, true
- }
- state.lastGitHead = newHead
- return changed, false
-
- case strategyFSNotify:
- return state.fsChanged.CompareAndSwap(true, false), false
-
- case strategyDirMtime:
- dirMtimes, _ := checkDirMtimes(w.ctx, proj.RootPath)
- changed := !dirMtimesEqual(state.dirMtimes, dirMtimes)
- state.dirMtimes = dirMtimes
- return changed, false
-
- default:
- return false, true
- }
-}
-
-// downgradeStrategy moves to the next fallback tier.
-func (w *Watcher) downgradeStrategy(proj *store.Project, state *projectState) {
- old := state.strategy
- switch old {
- case strategyGit:
- // Try fsnotify, then dir-mtime.
- state.strategy = strategyFSNotify
- if err := w.initFSNotify(state, proj.RootPath); err != nil {
- state.strategy = strategyDirMtime
- state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)
- }
- case strategyFSNotify:
- state.close()
- state.strategy = strategyDirMtime
- state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)
- default:
- return // already at bottom tier
- }
- slog.Info("watcher.strategy.downgrade", "project", proj.Name, "from", old.String(), "to", state.strategy.String())
-}
-
-func (w *Watcher) fullSnapshotAndIndex(proj *store.Project, state *projectState) {
- snap, err := captureSnapshot(w.ctx, proj.RootPath)
- if err != nil {
- slog.Warn("watcher.snapshot", "project", proj.Name, "err", err)
- state.nextPoll = time.Now().Add(state.interval)
- return
- }
-
- interval := pollInterval(len(snap))
- state.pollsSinceFull = 0
-
- if snapshotsEqual(state.snapshot, snap) {
- state.interval = interval
- state.nextPoll = time.Now().Add(interval)
- return
- }
-
- slog.Info("watcher.changed", "project", proj.Name, "strategy", state.strategy.String(), "files", len(snap))
- if err := w.indexFn(w.ctx, proj.Name, proj.RootPath); err != nil {
- slog.Warn("watcher.index", "project", proj.Name, "err", err)
- state.nextPoll = time.Now().Add(interval)
- return
- }
-
- state.snapshot = snap
- state.interval = pollInterval(len(snap))
- state.nextPoll = time.Now().Add(state.interval)
-
- // Update git HEAD after successful index.
- if state.strategy == strategyGit {
- if head, err := gitHead(w.ctx, proj.RootPath); err == nil {
- state.lastGitHead = head
- }
- }
-}
-
-// --- Git sentinel ---
-
-// isGitRepo checks if rootPath is inside a git repository.
-func isGitRepo(ctx context.Context, rootPath string) bool {
- ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
- defer cancel()
- cmd := exec.CommandContext(ctx, "git", "-C", rootPath, "rev-parse", "--git-dir")
- cmd.Stdout = nil
- cmd.Stderr = nil
- return cmd.Run() == nil
-}
-
-// gitHead returns the current HEAD commit hash.
-func gitHead(ctx context.Context, rootPath string) (string, error) {
- ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
- cmd := exec.CommandContext(ctx, "git", "-C", rootPath, "rev-parse", "HEAD")
- out, err := cmd.Output()
- if err != nil {
- return "", err
- }
- return strings.TrimSpace(string(out)), nil
-}
-
-// gitSentinel checks for working tree changes or HEAD movement since lastHead.
-func gitSentinel(ctx context.Context, rootPath, lastHead string) (changed bool, newHead string, err error) {
- ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- head, err := gitHead(ctx, rootPath)
- if err != nil {
- return false, "", err
- }
- if lastHead != "" && head != lastHead {
- return true, head, nil // HEAD moved (commit, checkout, pull)
- }
-
- // Check working tree.
- cmd := exec.CommandContext(ctx, "git", "--no-optional-locks", "-C", rootPath,
- "status", "--porcelain", "--untracked-files=normal")
- out, err := cmd.Output()
- if err != nil {
- return false, head, err
- }
- return len(bytes.TrimSpace(out)) > 0, head, nil
-}
-
-// --- FSNotify sentinel ---
-
-// initFSNotify sets up an fsnotify watcher for all directories under rootPath.
-// Starts a drain goroutine that sets state.fsChanged on events.
-func (w *Watcher) initFSNotify(state *projectState, rootPath string) error {
- fsw, err := fsnotify.NewWatcher()
- if err != nil {
- return err
- }
-
- walkErr := filepath.WalkDir(rootPath, func(path string, d fs.DirEntry, walkDirErr error) error {
- if walkDirErr != nil {
- return walkDirErr
- }
- if !d.IsDir() {
- return nil
- }
- name := d.Name()
- if name == ".git" || name == "node_modules" || name == "__pycache__" || name == ".venv" || name == "vendor" {
- return filepath.SkipDir
- }
- if addErr := fsw.Add(path); addErr != nil {
- return addErr // FD limit or other OS error → fall back
- }
- return nil
- })
- if walkErr != nil {
- fsw.Close()
- return walkErr
- }
-
- ctx, cancel := context.WithCancel(w.ctx)
- done := make(chan struct{})
- state.fsWatcher = fsw
- state.fsCancel = cancel
- state.fsDone = done
- go drainFSEvents(ctx, fsw, &state.fsChanged, done)
- return nil
-}
-
-// drainFSEvents reads fsnotify events and sets the changed flag.
-// Exits when ctx is cancelled or the watcher is closed.
-func drainFSEvents(ctx context.Context, fsw *fsnotify.Watcher, changed *atomic.Bool, done chan struct{}) {
- defer close(done)
- for {
- select {
- case <-ctx.Done():
- return
- case ev, ok := <-fsw.Events:
- if !ok {
- return
- }
- changed.Store(true)
- // Watch newly created directories for future events.
- if ev.Has(fsnotify.Create) {
- if info, err := os.Stat(ev.Name); err == nil && info.IsDir() {
- _ = fsw.Add(ev.Name)
- }
- }
- case _, ok := <-fsw.Errors:
- if !ok {
- return
- }
- }
- }
-}
-
-// --- Dir-mtime sentinel ---
-
-// checkDirMtimes walks only directories under rootPath and records their mtimes.
-// Cost: ~200 syscalls for a project with 200 dirs (vs 10K+ for full file walk).
-func checkDirMtimes(ctx context.Context, rootPath string) (map[string]time.Time, error) {
- mtimes := make(map[string]time.Time, 256)
- err := filepath.WalkDir(rootPath, func(path string, d fs.DirEntry, walkDirErr error) error {
- if walkDirErr != nil {
- return walkDirErr
- }
- if ctx.Err() != nil {
- return ctx.Err()
- }
- if !d.IsDir() {
- return nil
- }
- name := d.Name()
- if name == ".git" || name == "node_modules" || name == "__pycache__" || name == ".venv" || name == "vendor" {
- return filepath.SkipDir
- }
- info, statErr := d.Info()
- if statErr != nil {
- return statErr
- }
- mtimes[path] = info.ModTime()
- return nil
- })
- return mtimes, err
-}
-
-// dirMtimesEqual returns true if two dir mtime maps are identical.
-func dirMtimesEqual(a, b map[string]time.Time) bool {
- if len(a) != len(b) {
- return false
- }
- for path, aTime := range a {
- if bTime, ok := b[path]; !ok || !aTime.Equal(bTime) {
- return false
- }
- }
- return true
-}
-
-// --- Snapshot functions ---
-
-// captureSnapshot walks the file tree using discover.Discover and captures
-// mtime+size for each file.
-func captureSnapshot(ctx context.Context, rootPath string) (map[string]fileSnapshot, error) {
- files, err := discover.Discover(ctx, rootPath, nil)
- if err != nil {
- return nil, err
- }
- snap := make(map[string]fileSnapshot, len(files))
- for _, f := range files {
- info, statErr := os.Stat(f.Path)
- if statErr != nil {
- continue
- }
- snap[f.RelPath] = fileSnapshot{
- modTime: info.ModTime(),
- size: info.Size(),
- }
- }
- return snap, nil
-}
-
-// snapshotsEqual returns true if two snapshots have identical files with same mtime+size.
-func snapshotsEqual(a, b map[string]fileSnapshot) bool {
- if len(a) != len(b) {
- return false
- }
- for path, aSnap := range a {
- bSnap, ok := b[path]
- if !ok {
- return false
- }
- if !aSnap.modTime.Equal(bSnap.modTime) || aSnap.size != bSnap.size {
- return false
- }
- }
- return true
-}
-
-// pollInterval computes the adaptive interval from file count.
-// 5s base + 1s per 500 files, capped at 60s.
-func pollInterval(fileCount int) time.Duration {
- ms := 5000 + (fileCount/500)*1000
- if ms > 60000 {
- ms = 60000
- }
- return time.Duration(ms) * time.Millisecond
-}
diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.go
deleted file mode 100644
index a105f0aac..000000000
--- a/internal/watcher/watcher_test.go
+++ /dev/null
@@ -1,1150 +0,0 @@
-package watcher
-
-import (
- "context"
- "os"
- "os/exec"
- "path/filepath"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/DeusData/codebase-memory-mcp/internal/store"
-)
-
-// --- Test helpers ---
-
-// mustWriteFile is a test helper that writes a file and fails the test on error.
-func mustWriteFile(t *testing.T, path string, data []byte) {
- t.Helper()
- if err := os.WriteFile(path, data, 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-// mustMkdirAll is a test helper that creates directories and fails the test on error.
-func mustMkdirAll(t *testing.T, path string) {
- t.Helper()
- if err := os.MkdirAll(path, 0o755); err != nil {
- t.Fatal(err)
- }
-}
-
-// newTestRouter creates a StoreRouter backed by a temp directory with a project registered.
-func newTestRouter(t *testing.T, projectName, rootPath string) *store.StoreRouter {
- t.Helper()
- dbDir := t.TempDir()
- r, err := store.NewRouterWithDir(dbDir)
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(r.CloseAll)
- if projectName != "" {
- st, err := r.ForProject(projectName)
- if err != nil {
- t.Fatal(err)
- }
- if err := st.UpsertProject(projectName, rootPath); err != nil {
- t.Fatal(err)
- }
- }
- return r
-}
-
-func gitAvailable() bool {
- _, err := exec.LookPath("git")
- return err == nil
-}
-
-// initGitRepo initializes a git repo in dir with an initial commit.
-func initGitRepo(t *testing.T, dir string) {
- t.Helper()
- gitRun(t, dir, "init")
- gitRun(t, dir, "config", "user.email", "[email protected]")
- gitRun(t, dir, "config", "user.name", "test")
-}
-
-// gitCommitAll stages all files and commits.
-func gitCommitAll(t *testing.T, dir, msg string) {
- t.Helper()
- gitRun(t, dir, "add", "-A")
- gitRun(t, dir, "commit", "-m", msg)
-}
-
-func gitRun(t *testing.T, dir string, args ...string) {
- t.Helper()
- cmd := exec.CommandContext(context.Background(), "git", args...)
- cmd.Dir = dir
- cmd.Env = append(os.Environ(),
- "GIT_AUTHOR_NAME=test",
- "GIT_COMMITTER_NAME=test",
- )
- if out, err := cmd.CombinedOutput(); err != nil {
- t.Fatalf("git %v: %v\n%s", args, err, out)
- }
-}
-
-func newWatcherWithStrategy(r *store.StoreRouter, indexFn IndexFunc, strategy watchStrategy) *Watcher {
- w := New(r, indexFn)
- w.testStrategy = strategy
- return w
-}
-
-// resetPollTimers allows immediate re-polling.
-func resetPollTimers(w *Watcher) {
- for _, state := range w.projects {
- state.nextPoll = time.Time{}
- }
-}
-
-// --- Snapshot unit tests ---
-
-func TestSnapshotsEqual(t *testing.T) {
- now := time.Now()
-
- a := map[string]fileSnapshot{
- "main.go": {modTime: now, size: 100},
- "util.go": {modTime: now, size: 200},
- }
- b := map[string]fileSnapshot{
- "main.go": {modTime: now, size: 100},
- "util.go": {modTime: now, size: 200},
- }
- if !snapshotsEqual(a, b) {
- t.Error("identical snapshots should be equal")
- }
-
- // Different size
- c := map[string]fileSnapshot{
- "main.go": {modTime: now, size: 101},
- "util.go": {modTime: now, size: 200},
- }
- if snapshotsEqual(a, c) {
- t.Error("different size should not be equal")
- }
-
- // Different mtime
- d := map[string]fileSnapshot{
- "main.go": {modTime: now.Add(time.Second), size: 100},
- "util.go": {modTime: now, size: 200},
- }
- if snapshotsEqual(a, d) {
- t.Error("different mtime should not be equal")
- }
-
- // Missing file
- e := map[string]fileSnapshot{
- "main.go": {modTime: now, size: 100},
- }
- if snapshotsEqual(a, e) {
- t.Error("different file count should not be equal")
- }
-
- // Extra file
- f := map[string]fileSnapshot{
- "main.go": {modTime: now, size: 100},
- "util.go": {modTime: now, size: 200},
- "new.go": {modTime: now, size: 50},
- }
- if snapshotsEqual(a, f) {
- t.Error("extra file should not be equal")
- }
-
- // Both empty
- if !snapshotsEqual(map[string]fileSnapshot{}, map[string]fileSnapshot{}) {
- t.Error("both empty should be equal")
- }
-}
-
-func TestPollInterval(t *testing.T) {
- tests := []struct {
- files int
- expected time.Duration
- }{
- {0, 5 * time.Second},
- {70, 5 * time.Second},
- {499, 5 * time.Second},
- {500, 6 * time.Second},
- {2000, 9 * time.Second},
- {5000, 15 * time.Second},
- {10000, 25 * time.Second},
- {50000, 60 * time.Second},
- {100000, 60 * time.Second},
- }
- for _, tt := range tests {
- got := pollInterval(tt.files)
- if got != tt.expected {
- t.Errorf("pollInterval(%d) = %v, want %v", tt.files, got, tt.expected)
- }
- }
-}
-
-func TestCaptureSnapshot(t *testing.T) {
- tmpDir := t.TempDir()
- if err := os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- snap, err := captureSnapshot(context.Background(), tmpDir)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(snap) != 1 {
- t.Fatalf("expected 1 file, got %d", len(snap))
- }
-
- s, ok := snap["main.go"]
- if !ok {
- t.Fatal("expected main.go in snapshot")
- }
- if s.size == 0 {
- t.Error("expected non-zero size")
- }
- if s.modTime.IsZero() {
- t.Error("expected non-zero modtime")
- }
-}
-
-func TestCaptureSnapshotDetectsChanges(t *testing.T) {
- tmpDir := t.TempDir()
- goFile := filepath.Join(tmpDir, "main.go")
- if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- snap1, err := captureSnapshot(context.Background(), tmpDir)
- if err != nil {
- t.Fatal(err)
- }
-
- // Ensure mtime advances (some filesystems have 1s granularity)
- time.Sleep(10 * time.Millisecond)
- now := time.Now().Add(time.Second)
- if err := os.Chtimes(goFile, now, now); err != nil {
- t.Fatal(err)
- }
-
- snap2, err := captureSnapshot(context.Background(), tmpDir)
- if err != nil {
- t.Fatal(err)
- }
-
- if snapshotsEqual(snap1, snap2) {
- t.Error("snapshots should differ after mtime change")
- }
-}
-
-// --- Strategy selection tests ---
-
-func TestStrategyString(t *testing.T) {
- tests := []struct {
- s watchStrategy
- want string
- }{
- {strategyAuto, "auto"},
- {strategyGit, "git"},
- {strategyFSNotify, "fsnotify"},
- {strategyDirMtime, "dirmtime"},
- }
- for _, tt := range tests {
- if got := tt.s.String(); got != tt.want {
- t.Errorf("%d.String() = %q, want %q", tt.s, got, tt.want)
- }
- }
-}
-
-func TestProbeStrategyGit(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
- tmpDir := t.TempDir()
- initGitRepo(t, tmpDir)
-
- w := &Watcher{ctx: context.Background()}
- got := w.probeStrategy(context.Background(), tmpDir)
- if got != strategyGit {
- t.Errorf("expected strategyGit for git repo, got %v", got)
- }
-}
-
-func TestProbeStrategyNonGit(t *testing.T) {
- tmpDir := t.TempDir()
-
- w := &Watcher{ctx: context.Background()}
- got := w.probeStrategy(context.Background(), tmpDir)
- // Non-git dir should probe fsnotify (intent — actual setup may fail).
- if got != strategyFSNotify {
- t.Errorf("expected strategyFSNotify for non-git dir, got %v", got)
- }
-}
-
-func TestProbeStrategyOverride(t *testing.T) {
- tmpDir := t.TempDir()
-
- w := &Watcher{ctx: context.Background(), testStrategy: strategyDirMtime}
- got := w.probeStrategy(context.Background(), tmpDir)
- if got != strategyDirMtime {
- t.Errorf("expected strategyDirMtime with override, got %v", got)
- }
-}
-
-// --- Git sentinel unit tests ---
-
-func TestIsGitRepo(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
-
- t.Run("git_repo", func(t *testing.T) {
- dir := t.TempDir()
- initGitRepo(t, dir)
- if !isGitRepo(context.Background(), dir) {
- t.Error("expected true for git repo")
- }
- })
-
- t.Run("non_git", func(t *testing.T) {
- dir := t.TempDir()
- if isGitRepo(context.Background(), dir) {
- t.Error("expected false for non-git dir")
- }
- })
-}
-
-func TestGitSentinelClean(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
- dir := t.TempDir()
- initGitRepo(t, dir)
- mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n"))
- gitCommitAll(t, dir, "init")
-
- head, err := gitHead(context.Background(), dir)
- if err != nil {
- t.Fatal(err)
- }
-
- changed, newHead, err := gitSentinel(context.Background(), dir, head)
- if err != nil {
- t.Fatal(err)
- }
- if changed {
- t.Error("clean repo should not report changes")
- }
- if newHead != head {
- t.Error("HEAD should not change on clean repo")
- }
-}
-
-func TestGitSentinelDetectsEdit(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
- dir := t.TempDir()
- initGitRepo(t, dir)
- goFile := filepath.Join(dir, "main.go")
- mustWriteFile(t, goFile, []byte("package main\n"))
- gitCommitAll(t, dir, "init")
-
- head, _ := gitHead(context.Background(), dir)
-
- // Modify tracked file.
- mustWriteFile(t, goFile, []byte("package main\n\nfunc main() {}\n"))
-
- changed, _, err := gitSentinel(context.Background(), dir, head)
- if err != nil {
- t.Fatal(err)
- }
- if !changed {
- t.Error("modified tracked file should be detected")
- }
-}
-
-func TestGitSentinelDetectsNewFile(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
- dir := t.TempDir()
- initGitRepo(t, dir)
- mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n"))
- gitCommitAll(t, dir, "init")
-
- head, _ := gitHead(context.Background(), dir)
-
- // Add untracked file.
- mustWriteFile(t, filepath.Join(dir, "util.go"), []byte("package main\n"))
-
- changed, _, err := gitSentinel(context.Background(), dir, head)
- if err != nil {
- t.Fatal(err)
- }
- if !changed {
- t.Error("new untracked file should be detected")
- }
-}
-
-func TestGitSentinelDetectsCommit(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
- dir := t.TempDir()
- initGitRepo(t, dir)
- mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n"))
- gitCommitAll(t, dir, "init")
-
- headBefore, _ := gitHead(context.Background(), dir)
-
- // Make a commit.
- mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n\nfunc main() {}\n"))
- gitCommitAll(t, dir, "add main")
-
- changed, newHead, err := gitSentinel(context.Background(), dir, headBefore)
- if err != nil {
- t.Fatal(err)
- }
- if !changed {
- t.Error("commit should be detected via HEAD change")
- }
- if newHead == headBefore {
- t.Error("HEAD should differ after commit")
- }
-}
-
-// --- FSNotify sentinel tests ---
-
-func TestFSNotifyDetectsFileCreate(t *testing.T) {
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
-
- state := &projectState{}
- w := &Watcher{ctx: context.Background()}
-
- if err := w.initFSNotify(state, tmpDir); err != nil {
- t.Skipf("fsnotify not available: %v", err)
- }
- t.Cleanup(state.close)
-
- // Create a new file — should trigger an event.
- mustWriteFile(t, filepath.Join(tmpDir, "new.go"), []byte("package main\n"))
-
- // Wait for the event with timeout.
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if state.fsChanged.Load() {
- return // success
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Error("fsnotify did not detect file creation within 2s")
-}
-
-func TestFSNotifyDetectsFileDelete(t *testing.T) {
- tmpDir := t.TempDir()
- delFile := filepath.Join(tmpDir, "todelete.go")
- mustWriteFile(t, delFile, []byte("package main\n"))
-
- state := &projectState{}
- w := &Watcher{ctx: context.Background()}
-
- if err := w.initFSNotify(state, tmpDir); err != nil {
- t.Skipf("fsnotify not available: %v", err)
- }
- t.Cleanup(state.close)
-
- os.Remove(delFile)
-
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if state.fsChanged.Load() {
- return
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Error("fsnotify did not detect file deletion within 2s")
-}
-
-func TestFSNotifyWatchesNewSubdir(t *testing.T) {
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
-
- state := &projectState{}
- w := &Watcher{ctx: context.Background()}
-
- if err := w.initFSNotify(state, tmpDir); err != nil {
- t.Skipf("fsnotify not available: %v", err)
- }
- t.Cleanup(state.close)
-
- // Create a new subdirectory — drain goroutine should auto-add a watch for it.
- subDir := filepath.Join(tmpDir, "pkg")
- mustMkdirAll(t, subDir)
-
- // Wait for the dir creation event.
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if state.fsChanged.Load() {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
-
- // Reset flag and create a file in the new subdir.
- state.fsChanged.Store(false)
- time.Sleep(50 * time.Millisecond) // let the Add() complete
- mustWriteFile(t, filepath.Join(subDir, "lib.go"), []byte("package pkg\n"))
-
- deadline = time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if state.fsChanged.Load() {
- return
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Error("fsnotify did not detect file creation in new subdirectory within 2s")
-}
-
-func TestFSNotifyCleanup(t *testing.T) {
- tmpDir := t.TempDir()
-
- state := &projectState{}
- w := &Watcher{ctx: context.Background()}
-
- if err := w.initFSNotify(state, tmpDir); err != nil {
- t.Skipf("fsnotify not available: %v", err)
- }
-
- // Verify resources exist.
- if state.fsWatcher == nil || state.fsDone == nil || state.fsCancel == nil {
- t.Fatal("fsnotify resources not initialized")
- }
-
- // Close and verify goroutine exits.
- state.close()
-
- if state.fsWatcher != nil || state.fsDone != nil || state.fsCancel != nil {
- t.Error("close() did not nil out resources")
- }
-}
-
-func TestFSNotifyNoEventMeansNoChange(t *testing.T) {
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
-
- state := &projectState{}
- w := &Watcher{ctx: context.Background()}
-
- if err := w.initFSNotify(state, tmpDir); err != nil {
- t.Skipf("fsnotify not available: %v", err)
- }
- t.Cleanup(state.close)
-
- // No file changes — flag should remain false.
- time.Sleep(50 * time.Millisecond)
- if state.fsChanged.Load() {
- t.Error("expected no change without file operations")
- }
-}
-
-// --- Dir-mtime sentinel tests ---
-
-func TestDirMtimesEqual(t *testing.T) {
- now := time.Now()
- a := map[string]time.Time{"/a": now, "/b": now}
- b := map[string]time.Time{"/a": now, "/b": now}
- if !dirMtimesEqual(a, b) {
- t.Error("identical maps should be equal")
- }
-
- c := map[string]time.Time{"/a": now.Add(time.Second), "/b": now}
- if dirMtimesEqual(a, c) {
- t.Error("different mtime should not be equal")
- }
-
- d := map[string]time.Time{"/a": now}
- if dirMtimesEqual(a, d) {
- t.Error("different size should not be equal")
- }
-}
-
-// --- Full watcher flow tests (dir-mtime strategy) ---
-
-func TestWatcherTriggersOnChange(t *testing.T) {
- tmpDir := t.TempDir()
- goFile := filepath.Join(tmpDir, "main.go")
- if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- indexFn := func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }
-
- w := newWatcherWithStrategy(r, indexFn, strategyDirMtime)
- t.Cleanup(w.closeAll)
-
- // Add to watch list (required for pollAll to see it).
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // First poll — baseline capture, no index
- w.pollAll()
- if indexCount.Load() != 0 {
- t.Errorf("first poll should not trigger index, got %d", indexCount.Load())
- }
-
- // Poll again without changes — no index
- resetPollTimers(w)
- w.pollAll()
- if indexCount.Load() != 0 {
- t.Errorf("no-change poll should not trigger index, got %d", indexCount.Load())
- }
-
- // Modify the file
- futureTime := time.Now().Add(time.Second)
- if err := os.Chtimes(goFile, futureTime, futureTime); err != nil {
- t.Fatal(err)
- }
-
- // Force full snapshot (file mtime change doesn't affect dir mtime)
- for _, state := range w.projects {
- state.nextPoll = time.Time{}
- state.pollsSinceFull = fullSnapshotInterval
- }
- w.pollAll()
- if indexCount.Load() != 1 {
- t.Errorf("changed file should trigger index, got %d", indexCount.Load())
- }
-}
-
-func TestWatcherNewFileTriggersIndex_DirMtime(t *testing.T) {
- tmpDir := t.TempDir()
- goFile := filepath.Join(tmpDir, "main.go")
- if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }, strategyDirMtime)
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // Baseline
- w.pollAll()
-
- // Add a new file (changes parent dir mtime)
- if err := os.WriteFile(filepath.Join(tmpDir, "util.go"), []byte("package main\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- resetPollTimers(w)
- w.pollAll()
- if indexCount.Load() != 1 {
- t.Errorf("new file should trigger index, got %d", indexCount.Load())
- }
-}
-
-// --- Full watcher flow tests (git strategy) ---
-
-func TestWatcherGitDetectsEdit(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
-
- tmpDir := t.TempDir()
- goFile := filepath.Join(tmpDir, "main.go")
- mustWriteFile(t, goFile, []byte("package main\n"))
- initGitRepo(t, tmpDir)
- gitCommitAll(t, tmpDir, "init")
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }, strategyGit)
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // Baseline
- w.pollAll()
- if indexCount.Load() != 0 {
- t.Fatalf("baseline should not trigger index, got %d", indexCount.Load())
- }
-
- // Modify tracked file.
- mustWriteFile(t, goFile, []byte("package main\n\nfunc main() {}\n"))
-
- resetPollTimers(w)
- w.pollAll()
- if indexCount.Load() != 1 {
- t.Errorf("git strategy should detect edit, got index_count=%d", indexCount.Load())
- }
-}
-
-func TestWatcherGitDetectsCommit(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
-
- tmpDir := t.TempDir()
- goFile := filepath.Join(tmpDir, "main.go")
- mustWriteFile(t, goFile, []byte("package main\n"))
- initGitRepo(t, tmpDir)
- gitCommitAll(t, tmpDir, "init")
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }, strategyGit)
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // Baseline
- w.pollAll()
-
- // Make a commit (modifies HEAD but working tree is clean after).
- mustWriteFile(t, goFile, []byte("package main\n\nfunc main() {}\n"))
- gitCommitAll(t, tmpDir, "add main func")
-
- resetPollTimers(w)
- w.pollAll()
- if indexCount.Load() != 1 {
- t.Errorf("git strategy should detect commit via HEAD change, got %d", indexCount.Load())
- }
-}
-
-func TestWatcherGitNoChanges(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
-
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
- initGitRepo(t, tmpDir)
- gitCommitAll(t, tmpDir, "init")
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }, strategyGit)
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // Baseline
- w.pollAll()
-
- // Poll again without changes — no index. Git strategy does NOT force full snapshot.
- resetPollTimers(w)
- w.pollAll()
- if indexCount.Load() != 0 {
- t.Errorf("clean git repo should not trigger index, got %d", indexCount.Load())
- }
-
- // Even after many polls, no forced full snapshot (git is authoritative).
- for i := 0; i < fullSnapshotInterval+2; i++ {
- resetPollTimers(w)
- w.pollAll()
- }
- if indexCount.Load() != 0 {
- t.Errorf("git strategy should never force full snapshot, got %d", indexCount.Load())
- }
-}
-
-// --- Full watcher flow tests (fsnotify strategy) ---
-
-func TestWatcherFSNotifyDetectsNewFile(t *testing.T) {
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }, strategyFSNotify)
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // Baseline (sets up fsnotify watcher).
- w.pollAll()
- projName := filepath.Base(tmpDir)
- state := w.projects[projName]
- if state == nil {
- t.Fatal("project state not created")
- }
- if state.strategy != strategyFSNotify && state.strategy != strategyDirMtime {
- t.Fatalf("unexpected strategy: %v", state.strategy)
- }
- if state.strategy == strategyDirMtime {
- t.Skip("fsnotify not available, fell back to dirmtime")
- }
-
- // Create a new file.
- mustWriteFile(t, filepath.Join(tmpDir, "util.go"), []byte("package main\n"))
-
- // Wait for fsnotify event.
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if state.fsChanged.Load() {
- break
- }
- time.Sleep(10 * time.Millisecond)
- }
-
- resetPollTimers(w)
- w.pollAll()
- if indexCount.Load() != 1 {
- t.Errorf("fsnotify strategy should detect new file, got %d", indexCount.Load())
- }
-}
-
-// --- Fallback / degradation tests ---
-
-func TestStrategyDowngradeGitToDirMtime(t *testing.T) {
- if !gitAvailable() {
- t.Skip("git not available")
- }
-
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
- initGitRepo(t, tmpDir)
- gitCommitAll(t, tmpDir, "init")
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := New(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- })
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // Baseline — should auto-detect git strategy.
- w.pollAll()
- projName := filepath.Base(tmpDir)
- state := w.projects[projName]
- if state == nil {
- t.Fatal("project state not created")
- }
- if state.strategy != strategyGit {
- t.Fatalf("expected strategyGit, got %v", state.strategy)
- }
-
- // Remove .git directory — git commands will fail.
- os.RemoveAll(filepath.Join(tmpDir, ".git"))
-
- // Modify a file so the full snapshot comparison triggers.
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n\nfunc main() {}\n"))
-
- resetPollTimers(w)
- w.pollAll()
-
- // Strategy should have downgraded (git failed → fsnotify or dirmtime).
- if state.strategy == strategyGit {
- t.Error("strategy should have downgraded from git after .git removal")
- }
-}
-
-func TestFSNotifyFallbackToDirMtime(t *testing.T) {
- // When fsnotify is the selected strategy but initFSNotify fails,
- // baseline should fall back to dirmtime.
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- var indexCount atomic.Int32
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- }, strategyFSNotify)
- t.Cleanup(w.closeAll)
- w.Watch(filepath.Base(tmpDir), tmpDir)
-
- // initBaseline will try fsnotify. Even if it succeeds, verify the flow works.
- // If fsnotify fails on this platform, it falls back to dirmtime.
- w.pollAll()
-
- projName := filepath.Base(tmpDir)
- state := w.projects[projName]
- if state == nil {
- t.Fatal("project state not created")
- }
-
- // Either fsnotify or dirmtime is acceptable.
- if state.strategy != strategyFSNotify && state.strategy != strategyDirMtime {
- t.Errorf("expected fsnotify or dirmtime, got %v", state.strategy)
- }
-
- // Regardless of strategy, adding a file and forcing full snapshot should work.
- mustWriteFile(t, filepath.Join(tmpDir, "new.go"), []byte("package main\n"))
- for _, s := range w.projects {
- s.nextPoll = time.Time{}
- s.pollsSinceFull = fullSnapshotInterval
- }
- w.pollAll()
- if indexCount.Load() != 1 {
- t.Errorf("should detect change with fallback strategy, got %d", indexCount.Load())
- }
-}
-
-// --- Lifecycle tests ---
-
-func TestWatcherCancellation(t *testing.T) {
- dbDir := t.TempDir()
- r, err := store.NewRouterWithDir(dbDir)
- if err != nil {
- t.Fatal(err)
- }
- defer r.CloseAll()
-
- w := New(r, func(_ context.Context, _, _ string) error { return nil })
-
- ctx, cancel := context.WithCancel(context.Background())
-
- done := make(chan struct{})
- go func() {
- w.Run(ctx)
- close(done)
- }()
-
- cancel()
-
- select {
- case <-done:
- // OK — goroutine exited cleanly
- case <-time.After(3 * time.Second):
- t.Fatal("watcher did not stop after context cancellation")
- }
-}
-
-func TestWatcherSkipsMissingRoot(t *testing.T) {
- r := newTestRouter(t, "ghost", "/nonexistent/path")
-
- var indexCount atomic.Int32
- w := New(r, func(_ context.Context, _, _ string) error {
- indexCount.Add(1)
- return nil
- })
- t.Cleanup(w.closeAll)
- w.Watch("ghost", "/nonexistent/path")
-
- w.pollAll()
- if indexCount.Load() != 0 {
- t.Errorf("should not index missing root, got %d", indexCount.Load())
- }
-}
-
-func TestWatcherPrunesDeletedProjects(t *testing.T) {
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
-
- r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)
-
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- return nil
- }, strategyDirMtime)
- t.Cleanup(w.closeAll)
-
- projName := filepath.Base(tmpDir)
- w.Watch(projName, tmpDir)
-
- // Baseline
- w.pollAll()
- if _, ok := w.projects[projName]; !ok {
- t.Fatal("project should exist after baseline")
- }
-
- // Delete the project and unwatch.
- if err := r.DeleteProject(projName); err != nil {
- t.Fatal(err)
- }
- w.Unwatch(projName)
-
- w.pollAll()
-
- if _, ok := w.projects[projName]; ok {
- t.Error("pruned project should not exist in watcher state")
- }
-}
-
-// --- Watch list unit tests ---
-
-func TestWatchAddsProject(t *testing.T) {
- r := newTestRouter(t, "", "")
- w := New(r, func(_ context.Context, _, _ string) error { return nil })
-
- w.Watch("foo", "/tmp/foo")
-
- w.mu.Lock()
- defer w.mu.Unlock()
- e, ok := w.watchList["foo"]
- if !ok {
- t.Fatal("Watch should add entry to watchList")
- }
- if e.rootPath != "/tmp/foo" {
- t.Errorf("rootPath = %q, want /tmp/foo", e.rootPath)
- }
- if e.touchedAt.IsZero() {
- t.Error("touchedAt should be set")
- }
-}
-
-func TestUnwatchRemovesProject(t *testing.T) {
- r := newTestRouter(t, "", "")
- w := New(r, func(_ context.Context, _, _ string) error { return nil })
-
- w.Watch("foo", "/tmp/foo")
- w.Unwatch("foo")
-
- w.mu.Lock()
- defer w.mu.Unlock()
- if _, ok := w.watchList["foo"]; ok {
- t.Error("Unwatch should remove entry from watchList")
- }
-}
-
-func TestTouchProjectUpdatesTimestamp(t *testing.T) {
- r := newTestRouter(t, "", "")
- w := New(r, func(_ context.Context, _, _ string) error { return nil })
-
- w.Watch("foo", "/tmp/foo")
-
- w.mu.Lock()
- before := w.watchList["foo"].touchedAt
- w.mu.Unlock()
-
- time.Sleep(5 * time.Millisecond)
- w.TouchProject("foo")
-
- w.mu.Lock()
- after := w.watchList["foo"].touchedAt
- w.mu.Unlock()
-
- if !after.After(before) {
- t.Error("TouchProject should update touchedAt")
- }
-}
-
-func TestTouchProjectAddsUnwatched(t *testing.T) {
- tmpDir := t.TempDir()
- projName := filepath.Base(tmpDir)
-
- r := newTestRouter(t, projName, tmpDir)
- w := New(r, func(_ context.Context, _, _ string) error { return nil })
-
- // Not in watch list yet — TouchProject should look up from DB and add.
- w.TouchProject(projName)
-
- w.mu.Lock()
- defer w.mu.Unlock()
- e, ok := w.watchList[projName]
- if !ok {
- t.Fatal("TouchProject should add unwatched project from DB")
- }
- if e.rootPath != tmpDir {
- t.Errorf("rootPath = %q, want %q", e.rootPath, tmpDir)
- }
-}
-
-func TestPollAllOnlyWatched(t *testing.T) {
- tmpDirA := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDirA, "main.go"), []byte("package main\n"))
- nameA := filepath.Base(tmpDirA)
-
- tmpDirB := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDirB, "main.go"), []byte("package main\n"))
- nameB := filepath.Base(tmpDirB)
-
- // Register both in DB.
- dbDir := t.TempDir()
- r, err := store.NewRouterWithDir(dbDir)
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(r.CloseAll)
- stA, err2 := r.ForProject(nameA)
- if err2 != nil {
- t.Fatal(err2)
- }
- if err2 = stA.UpsertProject(nameA, tmpDirA); err2 != nil {
- t.Fatal(err2)
- }
- stB, err2 := r.ForProject(nameB)
- if err2 != nil {
- t.Fatal(err2)
- }
- if err2 = stB.UpsertProject(nameB, tmpDirB); err2 != nil {
- t.Fatal(err2)
- }
-
- polled := make(map[string]bool)
- w := newWatcherWithStrategy(r, func(_ context.Context, name, _ string) error {
- polled[name] = true
- return nil
- }, strategyDirMtime)
- t.Cleanup(w.closeAll)
-
- // Only watch A.
- w.Watch(nameA, tmpDirA)
-
- // Baseline
- w.pollAll()
-
- // Verify only A has state.
- if _, ok := w.projects[nameA]; !ok {
- t.Error("project A should have state after poll")
- }
- if _, ok := w.projects[nameB]; ok {
- t.Error("project B should NOT have state (not watched)")
- }
-}
-
-func TestPollAllPrunesUnwatched(t *testing.T) {
- tmpDir := t.TempDir()
- mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))
- projName := filepath.Base(tmpDir)
-
- r := newTestRouter(t, projName, tmpDir)
- w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {
- return nil
- }, strategyDirMtime)
- t.Cleanup(w.closeAll)
-
- w.Watch(projName, tmpDir)
-
- // Baseline — creates projectState.
- w.pollAll()
- if _, ok := w.projects[projName]; !ok {
- t.Fatal("project should exist after baseline")
- }
-
- // Unwatch, then poll — state should be pruned.
- w.Unwatch(projName)
- w.pollAll()
-
- if _, ok := w.projects[projName]; ok {
- t.Error("unwatched project should be pruned from projects map")
- }
-}
diff --git a/scripts/gen-go-stdlib.go b/scripts/gen-go-stdlib.go
deleted file mode 100644
index 292a36f8b..000000000
--- a/scripts/gen-go-stdlib.go
+++ /dev/null
@@ -1,357 +0,0 @@
-// gen-go-stdlib.go generates C source data for Go stdlib type information.
-// It parses GOROOT/src/ packages and emits static arrays that can be compiled
-// into the codebase-memory-mcp binary, providing stdlib type information
-// without requiring a Go toolchain at indexing time.
-//
-// Usage: go run scripts/gen-go-stdlib.go > internal/cbm/lsp/generated/go_stdlib_data.c
-//
-//go:build ignore
-
-package main
-
-import (
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "os"
- "path/filepath"
- "runtime"
- "sort"
- "strings"
-)
-
-// Packages to include (top-level stdlib packages used most commonly).
-var targetPackages = []string{
- "bufio", "bytes", "context", "crypto", "database/sql",
- "encoding", "encoding/json", "encoding/xml", "errors",
- "fmt", "hash", "io", "io/fs", "log", "log/slog",
- "math", "mime", "net", "net/http", "net/url",
- "os", "os/exec", "path", "path/filepath", "regexp",
- "sort", "strconv", "strings", "sync", "sync/atomic",
- "testing", "text/template", "time", "unicode",
-}
-
-type funcInfo struct {
- Name string
- PkgPath string
- Receiver string // empty for functions, "TypeName" for methods
- ParamTypes []string
- ReturnTypes []string
-}
-
-type typeInfo struct {
- Name string
- PkgPath string
- Fields []fieldInfo
- Methods []string // method names
- IsInterface bool
-}
-
-type fieldInfo struct {
- Name string
- Type string
-}
-
-func main() {
- goroot := runtime.GOROOT()
- if goroot == "" {
- fmt.Fprintf(os.Stderr, "GOROOT not set\n")
- os.Exit(1)
- }
-
- var allFuncs []funcInfo
- var allTypes []typeInfo
-
- for _, pkg := range targetPackages {
- pkgDir := filepath.Join(goroot, "src", pkg)
- fset := token.NewFileSet()
- pkgs, err := parser.ParseDir(fset, pkgDir, func(fi os.FileInfo) bool {
- return !strings.HasSuffix(fi.Name(), "_test.go")
- }, 0)
- if err != nil {
- fmt.Fprintf(os.Stderr, "skip %s: %v\n", pkg, err)
- continue
- }
-
- for _, p := range pkgs {
- funcs, types := extractPackage(pkg, p)
- allFuncs = append(allFuncs, funcs...)
- allTypes = append(allTypes, types...)
- }
- }
-
- // Sort for deterministic output
- sort.Slice(allFuncs, func(i, j int) bool {
- return allFuncs[i].PkgPath+"."+allFuncs[i].Name < allFuncs[j].PkgPath+"."+allFuncs[j].Name
- })
- sort.Slice(allTypes, func(i, j int) bool {
- return allTypes[i].PkgPath+"."+allTypes[i].Name < allTypes[j].PkgPath+"."+allTypes[j].Name
- })
-
- emitC(allFuncs, allTypes)
-}
-
-func extractPackage(pkgPath string, pkg *ast.Package) ([]funcInfo, []typeInfo) {
- var funcs []funcInfo
- var types []typeInfo
- methodsByType := make(map[string][]string)
-
- for _, f := range pkg.Files {
- for _, decl := range f.Decls {
- switch d := decl.(type) {
- case *ast.FuncDecl:
- if !d.Name.IsExported() {
- continue
- }
- fi := funcInfo{
- Name: d.Name.Name,
- PkgPath: pkgPath,
- }
- if d.Recv != nil && len(d.Recv.List) > 0 {
- fi.Receiver = typeExprToString(d.Recv.List[0].Type)
- methodsByType[fi.Receiver] = append(methodsByType[fi.Receiver], fi.Name)
- }
- if d.Type.Params != nil {
- for _, p := range d.Type.Params.List {
- typeStr := typeExprToString(p.Type)
- n := len(p.Names)
- if n == 0 { n = 1 }
- for range n {
- fi.ParamTypes = append(fi.ParamTypes, typeStr)
- }
- }
- }
- if d.Type.Results != nil {
- for _, r := range d.Type.Results.List {
- typeStr := typeExprToString(r.Type)
- n := len(r.Names)
- if n == 0 { n = 1 }
- for range n {
- fi.ReturnTypes = append(fi.ReturnTypes, typeStr)
- }
- }
- }
- funcs = append(funcs, fi)
-
- case *ast.GenDecl:
- if d.Tok != token.TYPE {
- continue
- }
- for _, spec := range d.Specs {
- ts := spec.(*ast.TypeSpec)
- if !ts.Name.IsExported() {
- continue
- }
- ti := typeInfo{
- Name: ts.Name.Name,
- PkgPath: pkgPath,
- }
- switch t := ts.Type.(type) {
- case *ast.StructType:
- if t.Fields != nil {
- for _, f := range t.Fields.List {
- typeStr := typeExprToString(f.Type)
- if len(f.Names) == 0 {
- // Embedded field
- ti.Fields = append(ti.Fields, fieldInfo{Name: typeStr, Type: typeStr})
- } else {
- for _, name := range f.Names {
- if name.IsExported() {
- ti.Fields = append(ti.Fields, fieldInfo{Name: name.Name, Type: typeStr})
- }
- }
- }
- }
- }
- case *ast.InterfaceType:
- ti.IsInterface = true
- if t.Methods != nil {
- for _, m := range t.Methods.List {
- for _, name := range m.Names {
- if name.IsExported() {
- ti.Methods = append(ti.Methods, name.Name)
- }
- }
- }
- }
- }
- types = append(types, ti)
- }
- }
- }
- }
-
- // Attach methods to types
- for i := range types {
- if methods, ok := methodsByType[types[i].Name]; ok {
- types[i].Methods = append(types[i].Methods, methods...)
- }
- if methods, ok := methodsByType["*"+types[i].Name]; ok {
- types[i].Methods = append(types[i].Methods, methods...)
- }
- }
-
- return funcs, types
-}
-
-func typeExprToString(expr ast.Expr) string {
- switch t := expr.(type) {
- case *ast.Ident:
- return t.Name
- case *ast.StarExpr:
- return "*" + typeExprToString(t.X)
- case *ast.ArrayType:
- return "[]" + typeExprToString(t.Elt)
- case *ast.MapType:
- return "map[" + typeExprToString(t.Key) + "]" + typeExprToString(t.Value)
- case *ast.SelectorExpr:
- return typeExprToString(t.X) + "." + t.Sel.Name
- case *ast.InterfaceType:
- return "interface{}"
- case *ast.ChanType:
- return "chan " + typeExprToString(t.Value)
- case *ast.FuncType:
- return "func()"
- case *ast.Ellipsis:
- return "..." + typeExprToString(t.Elt)
- default:
- return "any"
- }
-}
-
-func emitC(funcs []funcInfo, types []typeInfo) {
- fmt.Println("// AUTO-GENERATED by scripts/gen-go-stdlib.go — DO NOT EDIT")
- fmt.Println("// Go stdlib type information for LSP type resolver.")
- fmt.Println("")
- fmt.Println("#include \"../type_rep.h\"")
- fmt.Println("#include \"../type_registry.h\"")
- fmt.Println("#include <string.h>")
- fmt.Println("")
-
- // Emit string literals
- fmt.Printf("// %d functions, %d types from %d packages\n\n", len(funcs), len(types), len(targetPackages))
-
- // Emit function registration helper
- fmt.Println("void cbm_go_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {")
- fmt.Println(" CBMRegisteredFunc rf;")
- fmt.Println(" CBMRegisteredType rt;")
- fmt.Println("")
-
- // Emit static method_names arrays for interfaces
- for _, t := range types {
- if !t.IsInterface || len(t.Methods) == 0 {
- continue
- }
- // Deduplicate and sort method names
- seen := make(map[string]bool)
- var methods []string
- for _, m := range t.Methods {
- if !seen[m] {
- seen[m] = true
- methods = append(methods, m)
- }
- }
- sort.Strings(methods)
- varName := strings.ReplaceAll(t.PkgPath, "/", "_") + "_" + t.Name + "_methods"
- fmt.Printf(" static const char* %s[] = {", varName)
- for _, m := range methods {
- fmt.Printf("%s, ", cStr(m))
- }
- fmt.Printf("NULL};\n")
- }
- fmt.Println()
-
- // Register types
- for _, t := range types {
- qn := cStr(t.PkgPath + "." + t.Name)
- fmt.Printf(" // Type: %s.%s\n", t.PkgPath, t.Name)
- fmt.Printf(" memset(&rt, 0, sizeof(rt));\n")
- fmt.Printf(" rt.qualified_name = %s;\n", qn)
- fmt.Printf(" rt.short_name = %s;\n", cStr(t.Name))
- if t.IsInterface {
- fmt.Printf(" rt.is_interface = true;\n")
- // Attach method_names if this interface has methods
- if len(t.Methods) > 0 {
- varName := strings.ReplaceAll(t.PkgPath, "/", "_") + "_" + t.Name + "_methods"
- fmt.Printf(" rt.method_names = %s;\n", varName)
- }
- }
- fmt.Printf(" cbm_registry_add_type(reg, rt);\n\n")
- }
-
- // Register functions
- for _, f := range funcs {
- qn := f.PkgPath + "." + f.Name
- if f.Receiver != "" {
- recv := strings.TrimPrefix(f.Receiver, "*")
- qn = f.PkgPath + "." + recv + "." + f.Name
- }
- fmt.Printf(" // %s\n", qn)
- fmt.Printf(" memset(&rf, 0, sizeof(rf));\n")
- fmt.Printf(" rf.qualified_name = %s;\n", cStr(qn))
- fmt.Printf(" rf.short_name = %s;\n", cStr(f.Name))
- if f.Receiver != "" {
- recv := strings.TrimPrefix(f.Receiver, "*")
- fmt.Printf(" rf.receiver_type = %s;\n", cStr(f.PkgPath+"."+recv))
- }
-
- // Build return type (simplified: single return type as named)
- if len(f.ReturnTypes) > 0 {
- // Use a simple FUNC type with return types
- fmt.Printf(" {\n")
- fmt.Printf(" const CBMType* ret[%d];\n", len(f.ReturnTypes)+1)
- for i, rt := range f.ReturnTypes {
- if isBuiltinType(rt) {
- fmt.Printf(" ret[%d] = cbm_type_builtin(arena, %s);\n", i, cStr(rt))
- } else if strings.HasPrefix(rt, "*") {
- inner := strings.TrimPrefix(rt, "*")
- if isBuiltinType(inner) {
- fmt.Printf(" ret[%d] = cbm_type_pointer(arena, cbm_type_builtin(arena, %s));\n", i, cStr(inner))
- } else {
- fmt.Printf(" ret[%d] = cbm_type_pointer(arena, cbm_type_named(arena, %s));\n", i, cStr(resolveStdlibType(f.PkgPath, inner)))
- }
- } else if strings.HasPrefix(rt, "[]") {
- inner := strings.TrimPrefix(rt, "[]")
- if isBuiltinType(inner) {
- fmt.Printf(" ret[%d] = cbm_type_slice(arena, cbm_type_builtin(arena, %s));\n", i, cStr(inner))
- } else {
- fmt.Printf(" ret[%d] = cbm_type_slice(arena, cbm_type_named(arena, %s));\n", i, cStr(resolveStdlibType(f.PkgPath, inner)))
- }
- } else {
- fmt.Printf(" ret[%d] = cbm_type_named(arena, %s);\n", i, cStr(resolveStdlibType(f.PkgPath, rt)))
- }
- }
- fmt.Printf(" ret[%d] = NULL;\n", len(f.ReturnTypes))
- fmt.Printf(" rf.signature = cbm_type_func(arena, NULL, NULL, ret);\n")
- fmt.Printf(" }\n")
- }
- fmt.Printf(" cbm_registry_add_func(reg, rf);\n\n")
- }
-
- fmt.Println("}")
-}
-
-func isBuiltinType(t string) bool {
- switch t {
- case "int", "int8", "int16", "int32", "int64",
- "uint", "uint8", "uint16", "uint32", "uint64",
- "float32", "float64", "string", "bool", "byte", "rune",
- "error", "any", "uintptr", "complex64", "complex128":
- return true
- }
- return false
-}
-
-func resolveStdlibType(currentPkg, typeName string) string {
- if strings.Contains(typeName, ".") {
- return typeName // already qualified
- }
- return currentPkg + "." + typeName
-}
-
-func cStr(s string) string {
- s = strings.ReplaceAll(s, "\\", "\\\\")
- s = strings.ReplaceAll(s, "\"", "\\\"")
- return "\"" + s + "\""
-}
diff --git a/scripts/hooks/pre-commit b/scripts/hooks/pre-commit
index e2f1b58d5..9129092b9 100755
--- a/scripts/hooks/pre-commit
+++ b/scripts/hooks/pre-commit
@@ -1,21 +1,42 @@
#!/usr/bin/env bash
set -euo pipefail
-# Pre-commit hook: mirrors the GitHub Actions lint + test jobs.
-# Same commands as .github/workflows/release.yml
+# Pre-commit hook: C linting + tests.
+# Mirrors the lint targets in Makefile.cbm.
#
# Setup (once after clone):
# git config core.hooksPath scripts/hooks
-# --- Lint ---
-if ! command -v golangci-lint &>/dev/null; then
- echo "pre-commit: golangci-lint not found, skipping lint check"
- echo " install: go install github.com/golangci/golangci-lint/v2/cmd/[email protected]"
+LLVM_BIN="$(brew --prefix llvm 2>/dev/null)/bin"
+
+# Resolve tool paths (Homebrew LLVM is keg-only on macOS)
+CLANG_TIDY="${LLVM_BIN}/clang-tidy"
+CLANG_FORMAT="${LLVM_BIN}/clang-format"
+[ -x "$CLANG_TIDY" ] || CLANG_TIDY="clang-tidy"
+[ -x "$CLANG_FORMAT" ] || CLANG_FORMAT="clang-format"
+
+# --- clang-format (blocking — fastest, check first) ---
+echo "pre-commit: checking formatting..."
+make -f Makefile.cbm lint-format CLANG_FORMAT="$CLANG_FORMAT"
+
+# --- cppcheck (blocking) ---
+if command -v cppcheck &>/dev/null; then
+ echo "pre-commit: running cppcheck..."
+ make -f Makefile.cbm lint-cppcheck
+else
+ echo "pre-commit: cppcheck not found, skipping"
+ echo " install: brew install cppcheck"
+fi
+
+# --- clang-tidy (blocking) ---
+if command -v "$CLANG_TIDY" &>/dev/null; then
+ echo "pre-commit: running clang-tidy..."
+ make -f Makefile.cbm lint-tidy CLANG_TIDY="$CLANG_TIDY"
else
- echo "pre-commit: running golangci-lint..."
- golangci-lint run --timeout=5m ./...
+ echo "pre-commit: clang-tidy not found, skipping"
+ echo " install: brew install llvm"
fi
-# --- Tests ---
-echo "pre-commit: running tests..."
-go test ./... -timeout=5m
+# --- Build + Tests (blocking) ---
+echo "pre-commit: building and running tests..."
+make -f Makefile.cbm test
diff --git a/testdata/smoke/helper.go b/testdata/smoke/helper.go
deleted file mode 100644
index fd976b22c..000000000
--- a/testdata/smoke/helper.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package smoke
-
-import "strings"
-
-// FormatOutput formats a string for output.
-func FormatOutput(s string) string {
- return strings.TrimSpace(s)
-}
diff --git a/testdata/smoke/main.go b/testdata/smoke/main.go
deleted file mode 100644
index bfc3bd4d0..000000000
--- a/testdata/smoke/main.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package smoke
-
-import "fmt"
-
-// DataStore holds processed data.
-type DataStore struct {
- Items []string
-}
-
-// ProcessData processes input and stores results.
-func ProcessData(input string) *DataStore {
- formatted := FormatOutput(input)
- ds := &DataStore{Items: []string{formatted}}
- return ds
-}
-
-// Summary returns a summary of stored items.
-func (ds *DataStore) Summary() string {
- return fmt.Sprintf("items=%d", len(ds.Items))
-}