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.

v0.1.4: CLI mode, query performance optimizations, Go 1.26

Martin Vogelf932e87b6e8e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 96308dcdc..1cd07cac2 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -19,7 +19,7 @@ jobs:
- uses: actions/setup-go@v5
with:
- go-version: "1.23"
+ go-version: "1.26"
- uses: golangci/golangci-lint-action@v6
with:
@@ -48,7 +48,7 @@ jobs:
- uses: actions/setup-go@v5
with:
- go-version: "1.23"
+ go-version: "1.26"
- name: Run tests
run: go test ./...
@@ -75,7 +75,7 @@ jobs:
- uses: actions/setup-go@v5
with:
- go-version: "1.23"
+ go-version: "1.26"
- uses: msys2/setup-msys2@v2
with:
diff --git a/README.md b/README.md
index ce18c79fd..10730dcf1 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,15 @@
# codebase-memory-mcp
-An MCP server that remembers your codebase structure. Indexes source code into a queryable knowledge graph — functions, classes, call chains, cross-service HTTP links — all stored in embedded SQLite. Single Go binary, no Docker, no external databases.
+**Stop paying 100x more tokens for code exploration.** This MCP server indexes your codebase into a persistent knowledge graph that survives session restarts and context compaction. One graph query returns what would take dozens of grep/Glob calls — precise structural results in ~500 tokens vs ~80K tokens for file-by-file exploration.
-Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/), extracts functions, classes, modules, call relationships, and cross-service HTTP links. Exposes the graph through 11 MCP tools for use with Claude Code or any MCP-compatible client.
+Single Go binary. No Docker, no external databases, no API keys. Download, configure, say *"Index this project"* — done.
+
+Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/), extracts functions, classes, modules, call relationships, and cross-service HTTP links. Exposes the graph through 12 MCP tools for use with Claude Code or any MCP-compatible client. Also includes a **CLI mode** for direct tool invocation from the shell — no MCP client needed.
## Features
- **12 languages**: Python, Go, JavaScript, TypeScript, TSX, Rust, Java, C++, C#, PHP, Lua, Scala
+- **Fast**: Sub-millisecond graph queries, incremental reindex 4x faster than full scan, optimized SQLite with LIKE pre-filtering for regex searches
- **Call graph**: Resolves function calls across files and packages (import-aware, type-inferred)
- **Cross-service HTTP linking**: Discovers REST routes (FastAPI, Gin, Express) and matches them to HTTP call sites with confidence scoring
- **Auto-sync**: Background polling detects file changes and triggers incremental re-indexing automatically — no manual reindex needed after the initial index
@@ -15,6 +18,7 @@ Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/
- **Dead code detection**: Finds functions with zero callers, excluding entry points (route handlers, `main()`, framework-decorated functions)
- **Route nodes**: REST endpoints are first-class graph entities, queryable by path/method
- **JSON config scanning**: Extracts URLs from config/payload JSON files for cross-service linking
+- **CLI mode**: Invoke any tool directly from the shell — `codebase-memory-mcp cli search_graph '{"name_pattern": ".*Handler.*"}'`
- **Single binary, zero infrastructure**: SQLite WAL mode, persists to `~/.cache/codebase-memory-mcp/`
## How It Works
@@ -46,6 +50,21 @@ Claude Code formats and explains the results.
**Token efficiency**: Compared to having an AI agent grep through your codebase file by file, graph queries return precise results in a single tool call. In benchmarks on a multi-service project (2,348 nodes, 3,853 edges), five structural queries consumed ~3,400 tokens via codebase-memory-mcp versus ~412,000 tokens via file-by-file exploration — a **99.2% reduction**.
+## Performance
+
+Benchmarked on a multi-service project (~37K nodes, ~35K edges) with Go 1.26 on Apple Silicon:
+
+| Operation | Time | Notes |
+|-----------|------|-------|
+| Fresh index (full codebase) | ~6.3s | 37K nodes, 35K edges |
+| Incremental reindex | ~1.2s | Content-hash skip for unchanged files |
+| Cypher query (relationship traversal) | <1ms | Up to 600x faster than v0.1.3 for pattern queries |
+| Name search (regex) | <10ms | SQL LIKE pre-filtering narrows before Go regex |
+| Dead code detection | ~150ms | Full graph scan with degree filtering |
+| Trace call path (3 hops) | <10ms | BFS traversal with batch degree counting |
+
+**Token efficiency**: Five structural queries consumed ~3,400 tokens via codebase-memory-mcp versus ~412,000 tokens via file-by-file grep exploration — a **99.2% reduction**.
+
## Installation
### Just Want to Get Started?
@@ -117,7 +136,7 @@ Claude Code will clone, build, and configure it automatically.
| Requirement | Version | Check | Install |
|-------------|---------|-------|---------|
-| **Go** | 1.23+ | `go version` | [go.dev/dl](https://go.dev/dl/) |
+| **Go** | 1.26+ | `go version` | [go.dev/dl](https://go.dev/dl/) |
| **C compiler** | gcc or clang | `gcc --version` or `clang --version` | See below |
| **Git** | any | `git --version` | Pre-installed on most systems |
@@ -160,7 +179,7 @@ On **Windows with WSL** (credit: [@Flipper1994](https://github.com/Flipper1994))
```bash
# Inside WSL (Ubuntu)
sudo apt update && sudo apt install build-essential
-# Install Go 1.23+ from https://go.dev/dl/
+# Install Go 1.26+ from https://go.dev/dl/
git clone https://github.com/DeusData/codebase-memory-mcp.git
cd codebase-memory-mcp
CGO_ENABLED=1 go build -buildvcs=false -o ~/.local/bin/codebase-memory-mcp ./cmd/codebase-memory-mcp/
@@ -195,7 +214,7 @@ Add the MCP server to your project's `.mcp.json` (per-project, recommended) or `
}
```
-Restart Claude Code after adding the config. Verify with `/mcp` — you should see `codebase-memory-mcp` listed with 11 tools.
+Restart Claude Code after adding the config. Verify with `/mcp` — you should see `codebase-memory-mcp` listed with 12 tools.
### First Use
@@ -217,6 +236,60 @@ After the initial `index_repository` call, the graph **stays fresh automatically
You can still call `index_repository` manually at any time to force an immediate reindex (e.g. after a large `git pull`).
+## CLI Mode
+
+Every MCP tool can be invoked directly from the command line — no MCP client needed. Useful for testing, scripting, CI pipelines, and quick one-off queries.
+
+```bash
+codebase-memory-mcp cli <tool_name> [json_args]
+```
+
+By default, the CLI prints a **human-friendly summary**. Use `--raw` for full JSON output (same format the MCP server returns).
+
+### Examples
+
+```bash
+# Index a repository
+codebase-memory-mcp cli index_repository '{"repo_path": "/path/to/repo"}'
+# → Indexed "repo": 1017 nodes, 2574 edges
+# → db: ~/.cache/codebase-memory-mcp/codebase-memory.db
+
+# List indexed projects
+codebase-memory-mcp cli list_projects
+# → 2 project(s) indexed:
+# → my-api 1017 nodes, 2574 edges (indexed 2026-02-26T18:10:24Z)
+# → my-frontend 450 nodes, 312 edges (indexed 2026-02-26T17:34:06Z)
+
+# Search for functions
+codebase-memory-mcp cli search_graph '{"name_pattern": ".*Handler.*", "label": "Function"}'
+# → 5 result(s) found
+# → [Function] HandleRequest cmd/server/main.go:42
+
+# Trace call paths
+codebase-memory-mcp cli trace_call_path '{"function_name": "Search", "direction": "both"}'
+# → Trace from "Search": 8 node(s), 8 edge(s), 2 hop(s)
+
+# Run Cypher queries
+codebase-memory-mcp cli query_graph '{"query": "MATCH (f:Function) RETURN f.name LIMIT 5"}'
+# → 5 row(s) returned [f.name]
+# → main
+# → HandleRequest
+
+# View graph schema
+codebase-memory-mcp cli get_graph_schema
+
+# No args needed for tools without required parameters
+codebase-memory-mcp cli list_projects
+
+# Full JSON output for scripting
+codebase-memory-mcp cli --raw search_graph '{"label": "Function", "limit": 100}' | jq '.results[].name'
+
+# List available tools
+codebase-memory-mcp cli --help
+```
+
+The CLI uses the same SQLite database as the MCP server (`~/.cache/codebase-memory-mcp/codebase-memory.db`). No watcher is started in CLI mode — each invocation is a single-shot operation.
+
## MCP Tools
### Indexing
@@ -501,7 +574,7 @@ make install # go install
## Architecture
```
-cmd/codebase-memory-mcp/ Entry point (MCP stdio server)
+cmd/codebase-memory-mcp/ Entry point (MCP stdio server + CLI mode)
internal/
store/ SQLite graph storage (nodes, edges, traversal, search)
lang/ Language specs (12 languages, tree-sitter node types)
@@ -509,7 +582,7 @@ internal/
pipeline/ 4-pass indexing (structure -> definitions -> calls -> HTTP links)
httplink/ Cross-service HTTP route/call-site matching
cypher/ Cypher query lexer, parser, planner, executor
- tools/ MCP tool handlers (11 tools)
+ tools/ MCP tool handlers (12 tools) + CLI dispatch
watcher/ Background auto-sync (mtime+size polling, adaptive intervals)
discover/ File discovery with .cgrignore support
fqn/ Qualified name computation
diff --git a/cmd/codebase-memory-mcp/main.go b/cmd/codebase-memory-mcp/main.go
index c0ef38bf2..120e14355 100644
--- a/cmd/codebase-memory-mcp/main.go
+++ b/cmd/codebase-memory-mcp/main.go
@@ -2,9 +2,11 @@ package main
import (
"context"
+ "encoding/json"
"fmt"
"log"
"os"
+ "strings"
"github.com/DeusData/codebase-memory-mcp/internal/store"
"github.com/DeusData/codebase-memory-mcp/internal/tools"
@@ -18,6 +20,11 @@ func main() {
fmt.Println("codebase-memory-mcp", version)
os.Exit(0)
}
+
+ if len(os.Args) >= 3 && os.Args[1] == "cli" {
+ os.Exit(runCLI(os.Args[2:]))
+ }
+
s, err := store.Open("codebase-memory")
if err != nil {
log.Fatalf("store open err=%v", err)
@@ -35,3 +42,397 @@ func main() {
log.Fatalf("server err=%v", runErr)
}
}
+
+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)
+ }
+ }
+
+ if len(positional) == 0 || positional[0] == "--help" || positional[0] == "-h" {
+ s, err := store.Open("codebase-memory")
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "error: %v\n", err)
+ return 1
+ }
+ srv := tools.NewServer(s)
+ s.Close()
+ 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]
+
+ s, err := store.Open("codebase-memory")
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "error: %v\n", err)
+ return 1
+ }
+ defer s.Close()
+
+ srv := tools.NewServer(s)
+
+ 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
+ printSummary(toolName, text, s.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)
+ 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: %s\n", dbPath)
+ return
+ }
+ fmt.Printf("%d project(s) indexed:\n", len(arr))
+ for _, item := range arr {
+ if m, ok := item.(map[string]any); ok {
+ name, _ := m["name"].(string)
+ nodes := jsonInt(m["nodes"])
+ edges := jsonInt(m["edges"])
+ indexedAt, _ := m["indexed_at"].(string)
+ rootPath, _ := m["root_path"].(string)
+ fmt.Printf(" %-30s %d nodes, %d edges (indexed %s)\n", name, nodes, edges, indexedAt)
+ if rootPath != "" {
+ fmt.Printf(" %-30s %s\n", "", rootPath)
+ }
+ }
+ }
+ fmt.Printf("\n db: %s\n", dbPath)
+ 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 {
+ if m, ok := r.(map[string]any); ok {
+ name, _ := m["name"].(string)
+ label, _ := m["label"].(string)
+ filePath, _ := m["file_path"].(string)
+ startLine := jsonInt(m["start_line"])
+ fmt.Printf(" [%s] %s", label, name)
+ if filePath != "" {
+ fmt.Printf(" %s:%d", filePath, startLine)
+ }
+ fmt.Println()
+ }
+ }
+}
+
+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)
+}
+
+// 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/go.mod b/go.mod
index bb5a3301f..f6d7f35a1 100644
--- a/go.mod
+++ b/go.mod
@@ -1,6 +1,6 @@
module github.com/DeusData/codebase-memory-mcp
-go 1.23.0
+go 1.26
require (
github.com/modelcontextprotocol/go-sdk v1.3.1
@@ -15,27 +15,28 @@ require (
github.com/tree-sitter/tree-sitter-rust v0.24.0
github.com/tree-sitter/tree-sitter-scala v0.24.0
github.com/tree-sitter/tree-sitter-typescript v0.23.2
+ github.com/zeebo/xxh3 v1.1.0
+ golang.org/x/sync v0.17.0
gopkg.in/yaml.v3 v3.0.1
- modernc.org/sqlite v1.37.1
+ modernc.org/sqlite v1.46.1
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/google/uuid v1.6.0 // indirect
+ github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-pointer v0.0.1 // indirect
- github.com/ncruces/go-strftime v0.1.9 // indirect
+ github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // 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/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
- golang.org/x/mod v0.25.0 // indirect
+ golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
- golang.org/x/sync v0.15.0 // indirect
- golang.org/x/sys v0.35.0 // indirect
- modernc.org/libc v1.65.7 // indirect
+ golang.org/x/sys v0.37.0 // indirect
+ modernc.org/libc v1.67.6 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)
diff --git a/go.sum b/go.sum
index 4351bca6f..5ca7cd581 100644
--- a/go.sum
+++ b/go.sum
@@ -12,14 +12,18 @@ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17k
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+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/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0=
github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc=
github.com/modelcontextprotocol/go-sdk v1.3.1 h1:TfqtNKOIWN4Z1oqmPAiWDC2Jq7K9OdJaooe0teoXASI=
github.com/modelcontextprotocol/go-sdk v1.3.1/go.mod h1:DgVX498dMD8UJlseK1S5i1T4tFz2fkBk4xogC3D15nw=
-github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
-github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
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/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
@@ -64,33 +68,41 @@ github.com/tree-sitter/tree-sitter-typescript v0.23.2 h1:/Odvphn18PniVixb9e97X0D
github.com/tree-sitter/tree-sitter-typescript v0.23.2/go.mod h1:zjzMXT/Ulffel2xfOcAkQQkiAkmgnbtPGlFQw/5X4xA=
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=
-golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
-golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
-golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
-golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
+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=
+golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
+golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
+golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
+golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
-golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
-golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
+golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
-golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
-golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
-golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
+golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
+golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
+golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/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=
-modernc.org/cc/v4 v4.26.1 h1:+X5NtzVBn0KgsBCBe+xkDC7twLb/jNVj9FPgiwSQO3s=
-modernc.org/cc/v4 v4.26.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
-modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU=
-modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE=
-modernc.org/fileutil v1.3.1 h1:8vq5fe7jdtEvoCf3Zf9Nm0Q05sH6kGx0Op2CPx1wTC8=
-modernc.org/fileutil v1.3.1/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
+modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
+modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
+modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
+modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM=
+modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
+modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
-modernc.org/libc v1.65.7 h1:Ia9Z4yzZtWNtUIuiPuQ7Qf7kxYrxP1/jeHZzG8bFu00=
-modernc.org/libc v1.65.7/go.mod h1:011EQibzzio/VX3ygj1qGFt5kMjP0lHb0qCW5/D/pQU=
+modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
+modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
+modernc.org/libc v1.67.6 h1:eVOQvpModVLKOdT+LvBPjdQqfrZq+pC39BygcT+E7OI=
+modernc.org/libc v1.67.6/go.mod h1:JAhxUVlolfYDErnwiqaLvUqc8nfb2r6S6slAgZOnaiE=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
@@ -99,8 +111,8 @@ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
-modernc.org/sqlite v1.37.1 h1:EgHJK/FPoqC+q2YBXg7fUmES37pCHFc97sI7zSayBEs=
-modernc.org/sqlite v1.37.1/go.mod h1:XwdRtsE1MpiBcL54+MbKcaDvcuej+IYSMfLN6gSKV8g=
+modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
+modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
diff --git a/internal/cypher/executor.go b/internal/cypher/executor.go
index 71d9d075b..0b9b37f25 100644
--- a/internal/cypher/executor.go
+++ b/internal/cypher/executor.go
@@ -85,6 +85,21 @@ func (e *Executor) executeStepsForProject(project string, steps []PlanStep) ([]b
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) {
@@ -95,6 +110,8 @@ func (e *Executor) executeStepsForProject(project string, steps []PlanStep) ([]b
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 {
@@ -121,6 +138,129 @@ func (e *Executor) executeStepsForProject(project string, steps []PlanStep) ([]b
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)
+
+ args = append(args, maxResultRows*2)
+
+ rows, err := e.Store.DB().Query(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",
diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go
index da8f3cced..b3f2dd515 100644
--- a/internal/pipeline/pipeline.go
+++ b/internal/pipeline/pipeline.go
@@ -1,7 +1,6 @@
package pipeline
import (
- "crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
@@ -10,9 +9,12 @@ import (
"os"
"path/filepath"
"regexp"
+ "runtime"
"strings"
tree_sitter "github.com/tree-sitter/go-tree-sitter"
+ "github.com/zeebo/xxh3"
+ "golang.org/x/sync/errgroup"
"github.com/DeusData/codebase-memory-mcp/internal/discover"
"github.com/DeusData/codebase-memory-mcp/internal/fqn"
@@ -66,15 +68,24 @@ func (p *Pipeline) Run() error {
}
slog.Info("pipeline.discovered", "files", len(files))
+ wroteData := false
if err := p.Store.WithTransaction(func(txStore *store.Store) error {
origStore := p.Store
p.Store = txStore
defer func() { p.Store = origStore }()
- return p.runPasses(files)
+ var passErr error
+ wroteData, passErr = p.runPasses(files)
+ return passErr
}); err != nil {
return err
}
+ // Only checkpoint + optimize when actual data was written.
+ // No-op incremental reindexes skip this to avoid ANALYZE overhead.
+ if wroteData {
+ p.Store.Checkpoint()
+ }
+
nc, _ := p.Store.CountNodes(p.ProjectName)
ec, _ := p.Store.CountEdges(p.ProjectName)
slog.Info("pipeline.done", "nodes", nc, "edges", ec)
@@ -82,9 +93,10 @@ func (p *Pipeline) Run() error {
}
// runPasses executes all indexing passes (called within a transaction).
-func (p *Pipeline) runPasses(files []discover.FileInfo) error {
+// Returns (wroteData, error) — wroteData is true if nodes/edges were written.
+func (p *Pipeline) runPasses(files []discover.FileInfo) (bool, error) {
if err := p.Store.UpsertProject(p.ProjectName, p.RepoPath); err != nil {
- return fmt.Errorf("upsert project: %w", err)
+ return false, fmt.Errorf("upsert project: %w", err)
}
// Classify files as changed/unchanged using stored hashes
@@ -93,11 +105,18 @@ func (p *Pipeline) runPasses(files []discover.FileInfo) error {
// If all files are changed (first index or no hashes), do full pass
isFullIndex := len(unchanged) == 0
if isFullIndex {
- return p.runFullPasses(files)
+ return true, p.runFullPasses(files)
}
slog.Info("incremental.classify", "changed", len(changed), "unchanged", len(unchanged), "total", len(files))
- return p.runIncrementalPasses(files, changed, unchanged)
+
+ // Fast path: nothing changed → skip all heavy passes
+ if len(changed) == 0 {
+ slog.Info("incremental.noop", "reason", "no_changes")
+ return false, nil
+ }
+
+ return true, p.runIncrementalPasses(files, changed, unchanged)
}
// runFullPasses runs the complete pipeline (no incremental optimization).
@@ -182,19 +201,42 @@ func (p *Pipeline) runIncrementalPasses(
}
// classifyFiles splits files into changed and unchanged based on stored hashes.
+// File hashing is parallelized across CPU cores.
func (p *Pipeline) classifyFiles(files []discover.FileInfo) (changed, unchanged []discover.FileInfo) {
storedHashes, err := p.Store.GetFileHashes(p.ProjectName)
if err != nil || len(storedHashes) == 0 {
return files, nil // no hashes → full index
}
- for _, f := range files {
- currentHash, hashErr := fileHash(f.Path)
- if hashErr != nil {
+ type hashResult struct {
+ Hash string
+ 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)
+ results[i] = hashResult{Hash: hash, Err: hashErr}
+ return nil
+ })
+ }
+ _ = g.Wait()
+
+ for i, f := range files {
+ r := results[i]
+ if r.Err != nil {
changed = append(changed, f)
continue
}
- if stored, ok := storedHashes[f.RelPath]; ok && stored == currentHash {
+ if stored, ok := storedHashes[f.RelPath]; ok && stored == r.Hash {
unchanged = append(unchanged, f)
} else {
changed = append(changed, f)
@@ -315,12 +357,40 @@ func (p *Pipeline) cleanupASTCache() {
}
func (p *Pipeline) updateFileHashes(files []discover.FileInfo) {
- for _, f := range files {
- hash, hashErr := fileHash(f.Path)
- if hashErr == nil {
- _ = p.Store.UpsertFileHash(p.ProjectName, f.RelPath, hash)
+ type hashResult struct {
+ Hash string
+ 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)
+ results[i] = hashResult{Hash: hash, Err: hashErr}
+ 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,
+ })
}
}
+ _ = p.Store.UpsertFileHashBatch(batch)
}
// mergeFiles returns the union of two file slices (deduped by RelPath).
@@ -473,10 +543,33 @@ func (p *Pipeline) dirQN(relDir string) string {
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
+ Tree *tree_sitter.Tree
+ Source []byte
+ Nodes []*store.Node
+ PendingEdges []pendingEdge
+ ImportMap map[string]string
+ Err error
+}
+
// passDefinitions parses each file and extracts function/class/method/module nodes.
+// Uses parallel parsing (Stage 1) followed by sequential batch DB writes (Stage 2).
func (p *Pipeline) passDefinitions(files []discover.FileInfo) {
slog.Info("pass2.definitions")
+ // Separate JSON files (processed sequentially, they're fast and few)
+ var parseableFiles []discover.FileInfo
for _, f := range files {
if f.Language == lang.JSON {
if err := p.processJSONFile(f); err != nil {
@@ -484,76 +577,143 @@ func (p *Pipeline) passDefinitions(files []discover.FileInfo) {
}
continue
}
- if err := p.processFileDefinitions(f); err != nil {
- slog.Warn("pass2.file.err", "path", f.RelPath, "err", err)
- // Continue with other files
+ parseableFiles = append(parseableFiles, f)
+ }
+
+ if len(parseableFiles) == 0 {
+ return
+ }
+
+ // Stage 1: Parallel parse (CPU-bound, no DB, no shared state)
+ results := make([]*parseResult, len(parseableFiles))
+ numWorkers := runtime.NumCPU()
+ if numWorkers > len(parseableFiles) {
+ numWorkers = len(parseableFiles)
+ }
+
+ g := new(errgroup.Group)
+ g.SetLimit(numWorkers)
+ for i, f := range parseableFiles {
+ g.Go(func() error {
+ results[i] = parseFileAST(p.ProjectName, f)
+ return nil
+ })
+ }
+ _ = g.Wait()
+
+ // Stage 2: Sequential cache population + batch DB writes
+ var allNodes []*store.Node
+ var allPendingEdges []pendingEdge
+
+ for _, r := range results {
+ if r == nil || r.Err != nil {
+ if r != nil && r.Err != nil {
+ slog.Warn("pass2.file.err", "path", r.File.RelPath, "err", r.Err)
+ }
+ continue
+ }
+ // Populate AST cache (sequential, map writes)
+ p.astCache[r.File.RelPath] = &cachedAST{
+ Tree: r.Tree,
+ Source: r.Source,
+ Language: r.File.Language,
+ }
+ // Store import map
+ moduleQN := fqn.ModuleQN(p.ProjectName, r.File.RelPath)
+ if len(r.ImportMap) > 0 {
+ p.importMaps[moduleQN] = r.ImportMap
}
+ allNodes = append(allNodes, r.Nodes...)
+ allPendingEdges = append(allPendingEdges, r.PendingEdges...)
+ }
+
+ // Batch insert all nodes
+ idMap, err := p.Store.UpsertNodeBatch(allNodes)
+ if err != nil {
+ slog.Warn("pass2.batch_upsert.err", "err", err)
+ return
+ }
+
+ // Resolve pending edges to real edges using the ID map
+ 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)
}
}
-func (p *Pipeline) processFileDefinitions(f discover.FileInfo) error {
+// parseFileAST is a pure function that reads a file, parses its AST,
+// and extracts all nodes and edges as data. No DB access, no shared state mutation.
+func parseFileAST(projectName string, f discover.FileInfo) *parseResult {
+ result := &parseResult{File: f}
+
source, err := os.ReadFile(f.Path)
if err != nil {
- return err
+ result.Err = err
+ return result
}
tree, err := parser.Parse(f.Language, source)
if err != nil {
- return err
+ result.Err = err
+ return result
}
- // Cache for pass 3
- p.astCache[f.RelPath] = &cachedAST{
- Tree: tree,
- Source: source,
- Language: f.Language,
- }
+ result.Tree = tree
+ result.Source = source
- moduleQN := fqn.ModuleQN(p.ProjectName, f.RelPath)
+ moduleQN := fqn.ModuleQN(projectName, f.RelPath)
spec := lang.ForLanguage(f.Language)
if spec == nil {
- return nil
+ return result
}
- // Create Module node
- moduleID, err := p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
+ // Module node
+ moduleNode := &store.Node{
+ Project: projectName,
Label: "Module",
Name: filepath.Base(f.RelPath),
QualifiedName: moduleQN,
FilePath: f.RelPath,
- })
- if err != nil {
- return err
}
+ result.Nodes = append(result.Nodes, moduleNode)
// Extract definitions by walking the AST
root := tree.RootNode()
funcTypes := toSet(spec.FunctionNodeTypes)
classTypes := toSet(spec.ClassNodeTypes)
- // Track raw constants for display + resolved constants for HTTP linking
var constants []string
parser.Walk(root, func(node *tree_sitter.Node) bool {
kind := node.Kind()
- // Functions / methods
if funcTypes[kind] {
- p.extractFunction(node, source, f, moduleID)
- return false // don't recurse into function body
+ extractFunctionDef(node, source, f, projectName, moduleQN, result)
+ return false
}
- // Classes / types / interfaces
if classTypes[kind] {
- p.extractClass(node, source, f, moduleID, spec)
- return false // don't recurse; extractClass handles methods internally
+ extractClassDef(node, source, f, projectName, moduleQN, spec, result)
+ return false
}
- // Module-level constants (top-level assignments, const declarations)
if isConstantNode(node, f.Language) {
c := extractConstant(node, source)
- if c != "" && len(c) > 1 { // skip single-char constants
+ if c != "" && len(c) > 1 {
constants = append(constants, c)
}
}
@@ -561,11 +721,9 @@ func (p *Pipeline) processFileDefinitions(f discover.FileInfo) error {
return true
})
- // Resolve interpolated/concatenated strings via AST-based constant propagation.
- // This resolves e.g. f"{BASE_URL}/path" → "https://example.com/path" in RAM only.
+ // Resolve interpolated/concatenated strings
resolved := resolveModuleStrings(root, source, f.Language)
- // Merge resolved values into constants (deduplicated)
seen := make(map[string]bool, len(constants))
for _, c := range constants {
seen[c] = true
@@ -581,30 +739,21 @@ func (p *Pipeline) processFileDefinitions(f discover.FileInfo) error {
}
}
- // Update module with constants
+ // Update module node with constants (replace the initial module node)
if len(constants) > 0 {
- _, _ = 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},
- })
+ moduleNode.Properties = map[string]any{"constants": constants}
}
- // Parse imports for this file and store the import map
- importMap := parseImports(root, source, f.Language, p.ProjectName, f.RelPath)
- if len(importMap) > 0 {
- p.importMaps[moduleQN] = importMap
- }
+ // Parse imports
+ result.ImportMap = parseImports(root, source, f.Language, projectName, f.RelPath)
- return nil
+ return result
}
-func (p *Pipeline) extractFunction(
+// extractFunctionDef extracts a function/method node and DEFINES edge as data (no DB).
+func extractFunctionDef(
node *tree_sitter.Node, source []byte, f discover.FileInfo,
- moduleID int64,
+ projectName, moduleQN string, result *parseResult,
) {
nameNode := node.ChildByFieldName("name")
if nameNode == nil {
@@ -615,19 +764,16 @@ func (p *Pipeline) extractFunction(
return
}
- funcQN := fqn.Compute(p.ProjectName, f.RelPath, name)
+ funcQN := fqn.Compute(projectName, f.RelPath, name)
- // Determine if it's a method (has receiver — Go) or top-level function
label := "Function"
props := map[string]any{}
- // Extract signature
paramsNode := node.ChildByFieldName("parameters")
if paramsNode != nil {
props["signature"] = parser.NodeText(paramsNode, source)
}
- // Extract return type (field name varies by language)
for _, field := range []string{"result", "return_type", "type"} {
rtNode := node.ChildByFieldName(field)
if rtNode != nil {
@@ -636,17 +782,14 @@ func (p *Pipeline) extractFunction(
}
}
- // Go receiver -> this is a Method
recvNode := node.ChildByFieldName("receiver")
if recvNode != nil {
props["receiver"] = parser.NodeText(recvNode, source)
label = "Method"
}
- // Is exported? (Go: starts with uppercase, Python: no underscore prefix)
props["is_exported"] = isExported(name, f.Language)
- // Extract decorators (Python)
if f.Language == lang.Python {
decorators := extractDecorators(node, source)
if len(decorators) > 0 {
@@ -657,7 +800,6 @@ func (p *Pipeline) extractFunction(
}
}
- // Mark main() functions as entry points
if name == "main" {
props["is_entry_point"] = true
}
@@ -665,8 +807,8 @@ func (p *Pipeline) extractFunction(
startLine := safeRowToLine(node.StartPosition().Row)
endLine := safeRowToLine(node.EndPosition().Row)
- funcID, err := p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
+ result.Nodes = append(result.Nodes, &store.Node{
+ Project: projectName,
Label: label,
Name: name,
QualifiedName: funcQN,
@@ -675,26 +817,22 @@ func (p *Pipeline) extractFunction(
EndLine: endLine,
Properties: props,
})
- if err != nil {
- return
- }
- // Create DEFINES edge from Module
edgeType := "DEFINES"
if label == "Method" {
edgeType = "DEFINES_METHOD"
}
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: moduleID,
- TargetID: funcID,
+ result.PendingEdges = append(result.PendingEdges, pendingEdge{
+ SourceQN: moduleQN,
+ TargetQN: funcQN,
Type: edgeType,
})
}
-func (p *Pipeline) extractClass(
+// extractClassDef extracts a class/type node and its methods as data (no DB).
+func extractClassDef(
node *tree_sitter.Node, source []byte, f discover.FileInfo,
- moduleID int64, spec *lang.LanguageSpec,
+ projectName, moduleQN string, spec *lang.LanguageSpec, result *parseResult,
) {
nameNode := node.ChildByFieldName("name")
if nameNode == nil {
@@ -705,12 +843,9 @@ func (p *Pipeline) extractClass(
return
}
- classQN := fqn.Compute(p.ProjectName, f.RelPath, name)
-
- // Determine specific label
+ classQN := fqn.Compute(projectName, f.RelPath, name)
label := classLabelForKind(node.Kind())
- // Go type_spec: determine actual type from child (interface vs struct)
if node.Kind() == "type_spec" {
if typeNode := node.ChildByFieldName("type"); typeNode != nil {
switch typeNode.Kind() {
@@ -725,8 +860,8 @@ func (p *Pipeline) extractClass(
startLine := safeRowToLine(node.StartPosition().Row)
endLine := safeRowToLine(node.EndPosition().Row)
- classID, err := p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
+ result.Nodes = append(result.Nodes, &store.Node{
+ Project: projectName,
Label: label,
Name: name,
QualifiedName: classQN,
@@ -735,26 +870,21 @@ func (p *Pipeline) extractClass(
EndLine: endLine,
Properties: map[string]any{"is_exported": isExported(name, f.Language)},
})
- if err != nil {
- return
- }
- // DEFINES edge from Module
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: moduleID,
- TargetID: classID,
+ result.PendingEdges = append(result.PendingEdges, pendingEdge{
+ SourceQN: moduleQN,
+ TargetQN: classQN,
Type: "DEFINES",
})
// Extract methods inside the class
- p.extractClassMethods(node, source, f, classQN, classID, spec)
+ extractClassMethodDefs(node, source, f, projectName, classQN, spec, result)
}
-// extractClassMethods walks a class AST node and creates Method nodes for each method found.
-func (p *Pipeline) extractClassMethods(
+// extractClassMethodDefs walks a class AST node and extracts Method nodes (no DB).
+func extractClassMethodDefs(
classNode *tree_sitter.Node, source []byte, f discover.FileInfo,
- classQN string, classID int64, spec *lang.LanguageSpec,
+ projectName, classQN string, spec *lang.LanguageSpec, result *parseResult,
) {
funcTypes := toSet(spec.FunctionNodeTypes)
parser.Walk(classNode, func(child *tree_sitter.Node) bool {
@@ -793,8 +923,8 @@ func (p *Pipeline) extractClassMethods(
mStartLine := safeRowToLine(child.StartPosition().Row)
mEndLine := safeRowToLine(child.EndPosition().Row)
- methodID, upsertErr := p.Store.UpsertNode(&store.Node{
- Project: p.ProjectName,
+ result.Nodes = append(result.Nodes, &store.Node{
+ Project: projectName,
Label: "Method",
Name: methodName,
QualifiedName: methodQN,
@@ -803,14 +933,11 @@ func (p *Pipeline) extractClassMethods(
EndLine: mEndLine,
Properties: props,
})
- if upsertErr == nil {
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: classID,
- TargetID: methodID,
- Type: "DEFINES_METHOD",
- })
- }
+ result.PendingEdges = append(result.PendingEdges, pendingEdge{
+ SourceQN: classQN,
+ TargetQN: methodQN,
+ Type: "DEFINES_METHOD",
+ })
return false
})
}
@@ -831,32 +958,75 @@ func (p *Pipeline) buildRegistry() {
slog.Info("registry.built", "entries", p.registry.Size())
}
+// 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.
+// Uses parallel per-file resolution (Stage 1) followed by batch DB writes (Stage 2).
func (p *Pipeline) passCalls() {
slog.Info("pass3.calls")
+ // Collect files to process
+ type fileEntry struct {
+ relPath string
+ cached *cachedAST
+ }
+ var files []fileEntry
for relPath, cached := range p.astCache {
- spec := lang.ForLanguage(cached.Language)
- if spec == nil {
- continue
+ if lang.ForLanguage(cached.Language) != nil {
+ files = append(files, fileEntry{relPath, cached})
}
- p.processFileCalls(relPath, cached, spec)
}
+
+ if len(files) == 0 {
+ return
+ }
+
+ // Stage 1: Parallel per-file call resolution
+ 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.resolveFileCalls(fe.relPath, fe.cached)
+ return nil
+ })
+ }
+ _ = g.Wait()
+
+ // Stage 2: Batch QN→ID resolution + batch edge insert
+ p.flushResolvedEdges(results)
}
-func (p *Pipeline) processFileCalls(relPath string, cached *cachedAST, spec *lang.LanguageSpec) {
+// resolveFileCalls resolves all call targets in a single file. Returns resolved edges as QN pairs.
+// Thread-safe: reads from registry (RLock), importMaps (read-only), and AST cache (read-only).
+func (p *Pipeline) resolveFileCalls(relPath string, cached *cachedAST) []resolvedEdge {
+ spec := lang.ForLanguage(cached.Language)
+ if spec == nil {
+ return nil
+ }
+
callTypes := toSet(spec.CallNodeTypes)
moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
-
root := cached.Tree.RootNode()
-
- // Get import map for this module
importMap := p.importMaps[moduleQN]
// Infer variable types for method dispatch
typeMap := inferTypes(root, cached.Source, cached.Language, p.registry, moduleQN, importMap)
- // Walk to find calls and resolve them
+ var edges []resolvedEdge
+
parser.Walk(root, func(node *tree_sitter.Node) bool {
if !callTypes[node.Kind()] {
return true
@@ -873,43 +1043,108 @@ func (p *Pipeline) processFileCalls(relPath string, cached *cachedAST, spec *lan
}
// Python self.method() resolution
- if p.resolvePythonSelfCall(node, cached, calleeName, callerQN, relPath) {
- return false
+ if cached.Language == lang.Python && strings.HasPrefix(calleeName, "self.") {
+ classQN := findEnclosingClassQN(node, cached.Source, p.ProjectName, relPath)
+ if classQN != "" {
+ candidate := classQN + "." + calleeName[5:]
+ if p.registry.Exists(candidate) {
+ edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: candidate, Type: "CALLS"})
+ return false
+ }
+ }
}
- // Go receiver scoping — extend type map with receiver variable
+ // Go receiver scoping
localTypeMap := p.extendTypeMapWithReceiver(node, cached, typeMap, spec, moduleQN, importMap)
targetQN := p.resolveCallWithTypes(calleeName, moduleQN, importMap, localTypeMap)
if targetQN == "" {
- // Strategy 5: Fuzzy name-only fallback
if fuzzyQN, ok := p.registry.FuzzyResolve(calleeName, moduleQN); ok {
- p.createFuzzyCallEdge(callerQN, fuzzyQN)
+ edges = append(edges, resolvedEdge{
+ CallerQN: callerQN,
+ TargetQN: fuzzyQN,
+ Type: "CALLS",
+ Properties: map[string]any{"resolution_mode": "fuzzy"},
+ })
}
return false
}
- p.createCallEdge(callerQN, targetQN)
+ edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: targetQN, Type: "CALLS"})
return false
})
+
+ return edges
}
-// resolvePythonSelfCall handles Python self.method() resolution via enclosing class scope.
-// Returns true if the call was resolved.
-func (p *Pipeline) resolvePythonSelfCall(node *tree_sitter.Node, cached *cachedAST, calleeName, callerQN, relPath string) bool {
- if cached.Language != lang.Python || !strings.HasPrefix(calleeName, "self.") {
- return false
+// processFileCalls is the legacy sequential entry point for incremental re-indexing.
+// It resolves calls for a single file and writes edges to DB immediately.
+func (p *Pipeline) processFileCalls(relPath string, cached *cachedAST, spec *lang.LanguageSpec) {
+ edges := p.resolveFileCalls(relPath, cached)
+ 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,
+ })
+ }
}
- classQN := findEnclosingClassQN(node, cached.Source, p.ProjectName, relPath)
- if classQN == "" {
- return false
+}
+
+// flushResolvedEdges converts QN-based resolved edges to ID-based edges and batch-inserts them.
+func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {
+ // Collect all unique QNs
+ qnSet := make(map[string]struct{})
+ totalEdges := 0
+ for _, fileEdges := range results {
+ for _, re := range fileEdges {
+ qnSet[re.CallerQN] = struct{}{}
+ qnSet[re.TargetQN] = struct{}{}
+ totalEdges++
+ }
}
- candidate := classQN + "." + calleeName[5:]
- if n, _ := p.Store.FindNodeByQN(p.ProjectName, candidate); n != nil {
- p.createCallEdge(callerQN, candidate)
- return true
+
+ 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
+ }
+
+ // Build edges
+ 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: p.ProjectName,
+ SourceID: srcID,
+ TargetID: tgtID,
+ Type: re.Type,
+ Properties: re.Properties,
+ })
+ }
+ }
+ }
+
+ if err := p.Store.InsertEdgeBatch(edges); err != nil {
+ slog.Warn("pass3.batch_edges.err", "err", err)
}
- return false
}
// extendTypeMapWithReceiver augments the type map with the Go receiver variable
@@ -942,39 +1177,6 @@ func (p *Pipeline) extendTypeMapWithReceiver(
return localTypeMap
}
-// createCallEdge creates a CALLS edge between caller and target by QN.
-func (p *Pipeline) createCallEdge(callerQN, targetQN string) {
- callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, callerQN)
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
- if callerNode != nil && targetNode != nil {
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: callerNode.ID,
- TargetID: targetNode.ID,
- Type: "CALLS",
- })
- }
-}
-
-// createFuzzyCallEdge creates a CALLS edge with resolution_mode="fuzzy" property,
-// indicating the callee was resolved via text-based name matching rather than
-// structural analysis (imports, same-module, etc.).
-func (p *Pipeline) createFuzzyCallEdge(callerQN, targetQN string) {
- callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, callerQN)
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
- if callerNode != nil && targetNode != nil {
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: callerNode.ID,
- TargetID: targetNode.ID,
- Type: "CALLS",
- Properties: map[string]any{
- "resolution_mode": "fuzzy",
- },
- })
- }
-}
-
// resolveCallWithTypes resolves a callee name using the registry, import maps,
// and type inference for method dispatch.
func (p *Pipeline) resolveCallWithTypes(
@@ -991,7 +1193,7 @@ func (p *Pipeline) resolveCallWithTypes(
// Check if the object has a known type from type inference
if classQN, ok := typeMap[objName]; ok {
candidate := classQN + "." + methodName
- if node, _ := p.Store.FindNodeByQN(p.ProjectName, candidate); node != nil {
+ if p.registry.Exists(candidate) {
return candidate
}
}
@@ -1486,7 +1688,7 @@ func fileHash(path string) (string, error) {
return "", err
}
defer f.Close()
- h := sha256.New()
+ h := xxh3.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
diff --git a/internal/pipeline/resolver.go b/internal/pipeline/resolver.go
index fddbca7dd..338ea6f16 100644
--- a/internal/pipeline/resolver.go
+++ b/internal/pipeline/resolver.go
@@ -183,6 +183,15 @@ func (r *FunctionRegistry) FuzzyResolve(calleeName, moduleQN string) (string, bo
return "", false
}
+// 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()
diff --git a/internal/pipeline/resolver_test.go b/internal/pipeline/resolver_test.go
index a6db06c9d..8b3f2f624 100644
--- a/internal/pipeline/resolver_test.go
+++ b/internal/pipeline/resolver_test.go
@@ -80,3 +80,22 @@ func TestFuzzyResolve_NoMatchForBareName(t *testing.T) {
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")
+ }
+}
diff --git a/internal/pipeline/usages.go b/internal/pipeline/usages.go
index 2e5195f27..49e1fef04 100644
--- a/internal/pipeline/usages.go
+++ b/internal/pipeline/usages.go
@@ -2,8 +2,10 @@ package pipeline
import (
"log/slog"
+ "runtime"
tree_sitter "github.com/tree-sitter/go-tree-sitter"
+ "golang.org/x/sync/errgroup"
"github.com/DeusData/codebase-memory-mcp/internal/discover"
"github.com/DeusData/codebase-memory-mcp/internal/fqn"
@@ -14,19 +16,50 @@ import (
// passUsages walks ASTs and creates USAGE edges for identifier references
// that are NOT inside call expressions (those are already CALLS edges).
-// This distinguishes read references (passed as callbacks, stored in variables,
-// used in type annotations) from function invocations.
+// Uses parallel per-file resolution (Stage 1) followed by batch DB writes (Stage 2).
func (p *Pipeline) passUsages() {
slog.Info("pass3b.usages")
- count := 0
+
+ type fileEntry struct {
+ relPath string
+ cached *cachedAST
+ }
+ var files []fileEntry
for relPath, cached := range p.astCache {
- spec := lang.ForLanguage(cached.Language)
- if spec == nil {
- continue
+ if lang.ForLanguage(cached.Language) != nil {
+ files = append(files, fileEntry{relPath, cached})
}
- count += p.processFileUsages(relPath, cached, spec)
}
- slog.Info("pass3b.usages.done", "edges", count)
+
+ if len(files) == 0 {
+ return
+ }
+
+ // Stage 1: Parallel per-file usage resolution
+ 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.resolveFileUsages(fe.relPath, fe.cached)
+ 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).
@@ -38,11 +71,21 @@ func (p *Pipeline) passUsagesForFiles(files []discover.FileInfo) {
if !ok {
continue
}
- spec := lang.ForLanguage(cached.Language)
- if spec == nil {
- continue
+ edges := p.resolveFileUsages(f.RelPath, cached)
+ // 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++
+ }
}
- count += p.processFileUsages(f.RelPath, cached, spec)
}
slog.Info("pass3b.usages.incremental.done", "edges", count)
}
@@ -84,9 +127,15 @@ func importNodeTypes(spec *lang.LanguageSpec) map[string]bool {
return combined
}
-// processFileUsages walks a file's AST to find identifier references that
-// are not call expressions and creates USAGE edges for resolved references.
-func (p *Pipeline) processFileUsages(relPath string, cached *cachedAST, spec *lang.LanguageSpec) int {
+// resolveFileUsages walks a file's AST to find identifier references that
+// are not call expressions and resolves them to USAGE edges.
+// Thread-safe: reads from registry (RLock) and importMaps (read-only).
+func (p *Pipeline) resolveFileUsages(relPath string, cached *cachedAST) []resolvedEdge {
+ spec := lang.ForLanguage(cached.Language)
+ if spec == nil {
+ return nil
+ }
+
refTypes := toSet(referenceNodeTypes(cached.Language))
callTypes := toSet(spec.CallNodeTypes)
importTypes := importNodeTypes(spec)
@@ -94,17 +143,15 @@ func (p *Pipeline) processFileUsages(relPath string, cached *cachedAST, spec *la
importMap := p.importMaps[moduleQN]
root := cached.Tree.RootNode()
- count := 0
+ var edges []resolvedEdge
parser.Walk(root, func(node *tree_sitter.Node) bool {
kind := node.Kind()
- // Skip call expression subtrees — those are handled by passCalls
if callTypes[kind] {
return false
}
- // Skip import statement subtrees
if importTypes[kind] {
return false
}
@@ -113,7 +160,6 @@ func (p *Pipeline) processFileUsages(relPath string, cached *cachedAST, spec *la
return true
}
- // Skip if this identifier is inside a function/class definition name
if isDefinitionName(node) {
return false
}
@@ -123,38 +169,24 @@ func (p *Pipeline) processFileUsages(relPath string, cached *cachedAST, spec *la
return false
}
- // Find enclosing function for the "caller" side of the USAGE edge
callerQN := findEnclosingFunction(node, cached.Source, p.ProjectName, relPath, spec)
if callerQN == "" {
callerQN = moduleQN
}
- // Try to resolve the reference against the registry
targetQN := p.registry.Resolve(refName, moduleQN, importMap)
if targetQN == "" {
return false
}
- // Don't create USAGE edge to self
if targetQN == callerQN {
return false
}
- // Create the USAGE edge
- callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, callerQN)
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
- if callerNode != nil && targetNode != nil {
- _, _ = p.Store.InsertEdge(&store.Edge{
- Project: p.ProjectName,
- SourceID: callerNode.ID,
- TargetID: targetNode.ID,
- Type: "USAGE",
- })
- count++
- }
+ edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: targetQN, Type: "USAGE"})
return false
})
- return count
+ return edges
}
// isDefinitionName returns true if the node is the name child of a function,
diff --git a/internal/store/edges.go b/internal/store/edges.go
index 53c7a7c88..eb9860a60 100644
--- a/internal/store/edges.go
+++ b/internal/store/edges.go
@@ -3,6 +3,7 @@ package store
import (
"database/sql"
"fmt"
+ "strings"
)
// InsertEdge inserts an edge (dedup by source_id, target_id, type).
@@ -119,6 +120,47 @@ func (s *Store) FindEdgesByURLPath(project, pathSubstring string) ([]*Edge, erro
return scanEdges(rows)
}
+// edgesBatchSize is the max rows per batch INSERT for edges (5 cols × 150 = 750 vars < 999).
+const edgesBatchSize = 150
+
+// 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=excluded.properties`)
+
+ if _, err := s.q.Exec(sb.String(), args...); err != nil {
+ return fmt.Errorf("insert edge batch: %w", err)
+ }
+ return nil
+}
+
func scanEdges(rows *sql.Rows) ([]*Edge, error) {
var result []*Edge
for rows.Next() {
diff --git a/internal/store/nodes.go b/internal/store/nodes.go
index 11d948c56..5cd35e8c3 100644
--- a/internal/store/nodes.go
+++ b/internal/store/nodes.go
@@ -3,6 +3,7 @@ package store
import (
"database/sql"
"fmt"
+ "strings"
)
// UpsertNode inserts or replaces a node (dedup by qualified_name).
@@ -145,3 +146,122 @@ func scanNodes(rows *sql.Rows) ([]*Node, error) {
}
return result, rows.Err()
}
+
+// nodesBatchSize is the max rows per batch INSERT for nodes (8 cols × 100 = 800 vars < 999).
+const nodesBatchSize = 100
+
+// 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, ","))
+
+ rows, err := s.q.Query(query, args...)
+ if err != nil {
+ return fmt.Errorf("resolve node IDs: %w", err)
+ }
+ for rows.Next() {
+ var id int64
+ var qn string
+ if err := rows.Scan(&id, &qn); err != nil {
+ rows.Close()
+ return err
+ }
+ idMap[qn] = id
+ }
+ rows.Close()
+ if err := 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
index 2394aaaa5..6abf6b4d7 100644
--- a/internal/store/projects.go
+++ b/internal/store/projects.go
@@ -1,6 +1,9 @@
package store
-import "fmt"
+import (
+ "fmt"
+ "strings"
+)
// Project represents an indexed project.
type Project struct {
@@ -105,6 +108,47 @@ func (s *Store) ListFilesForProject(project string) ([]string, error) {
return result, rows.Err()
}
+// fileHashBatchSize is the max rows per batch INSERT for file hashes (3 cols × 200 = 600 vars < 999).
+const fileHashBatchSize = 200
+
+// 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) VALUES `)
+
+ args := make([]any, 0, len(batch)*3)
+ for i, h := range batch {
+ if i > 0 {
+ sb.WriteByte(',')
+ }
+ sb.WriteString("(?,?,?)")
+ args = append(args, h.Project, h.RelPath, h.SHA256)
+ }
+ sb.WriteString(` ON CONFLICT(project, rel_path) DO UPDATE SET sha256=excluded.sha256`)
+
+ 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)
diff --git a/internal/store/schema.go b/internal/store/schema.go
index 6785fc667..a77a8253c 100644
--- a/internal/store/schema.go
+++ b/internal/store/schema.go
@@ -1,6 +1,9 @@
package store
-import "fmt"
+import (
+ "fmt"
+ "sort"
+)
// SchemaInfo contains graph schema statistics.
type SchemaInfo struct {
@@ -62,32 +65,66 @@ func (s *Store) GetSchema(project string) (*SchemaInfo, error) {
return nil, err
}
- // Relationship patterns: (src_label)-[type]->(tgt_label) with counts
- rows3, err := s.q.Query(`
- SELECT sn.label, e.type, tn.label, COUNT(*) as cnt
- FROM edges e
- JOIN nodes sn ON e.source_id = sn.id
- JOIN nodes tn ON e.target_id = tn.id
- WHERE e.project=?
- GROUP BY sn.label, e.type, tn.label
- ORDER BY cnt DESC
- LIMIT 25`, project)
+ // Relationship patterns: build id→label map, then scan edges and aggregate in Go.
+ // This replaces a 3-way JOIN (O(edges × 2 lookups)) with two sequential scans.
+ idLabel := make(map[int64]string, 4096)
+ rows3, err := s.q.Query("SELECT id, label FROM nodes WHERE project=?", project)
if err != nil {
- return nil, fmt.Errorf("schema patterns: %w", err)
+ return nil, fmt.Errorf("schema id-label: %w", err)
}
- defer rows3.Close()
for rows3.Next() {
- var src, rel, tgt string
- var cnt int
- if err := rows3.Scan(&src, &rel, &tgt, &cnt); err != nil {
+ var id int64
+ var label string
+ if err := rows3.Scan(&id, &label); err != nil {
+ rows3.Close()
return nil, err
}
- info.RelationshipPatterns = append(info.RelationshipPatterns, fmt.Sprintf("(:%s)-[:%s]->(:%s) [%dx]", src, rel, tgt, cnt))
+ idLabel[id] = label
}
+ rows3.Close()
if err := rows3.Err(); err != nil {
return nil, err
}
+ type patternKey struct{ src, rel, tgt string }
+ patternCounts := make(map[patternKey]int)
+ rows3b, err := s.q.Query("SELECT source_id, target_id, type FROM edges WHERE project=?", project)
+ if err != nil {
+ return nil, fmt.Errorf("schema edge scan: %w", err)
+ }
+ for rows3b.Next() {
+ var srcID, tgtID int64
+ var edgeType string
+ if err := rows3b.Scan(&srcID, &tgtID, &edgeType); err != nil {
+ rows3b.Close()
+ return nil, err
+ }
+ pk := patternKey{src: idLabel[srcID], rel: edgeType, tgt: idLabel[tgtID]}
+ patternCounts[pk]++
+ }
+ rows3b.Close()
+ if err := rows3b.Err(); err != nil {
+ return nil, err
+ }
+
+ // Sort by count descending, take top 25
+ 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]
+ }
+ for _, e := range entries {
+ info.RelationshipPatterns = append(info.RelationshipPatterns,
+ fmt.Sprintf("(:%s)-[:%s]->(:%s) [%dx]", e.key.src, e.key.rel, e.key.tgt, e.cnt))
+ }
+
// Sample function names
rows4, err := s.q.Query("SELECT name FROM nodes WHERE project=? AND label='Function' ORDER BY name LIMIT 30", project)
if err != nil {
diff --git a/internal/store/search.go b/internal/store/search.go
index 9fc28e7f3..651d5cc6a 100644
--- a/internal/store/search.go
+++ b/internal/store/search.go
@@ -37,26 +37,6 @@ type SearchOutput struct {
Total int
}
-// countDegrees populates in/out degree counts on a SearchResult.
-func (s *Store) countDegrees(sr *SearchResult, nodeID int64, relationship string) error {
- if relationship != "" {
- if err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE target_id=? AND type=?", nodeID, relationship).Scan(&sr.InDegree); err != nil {
- return fmt.Errorf("count in-degree: %w", err)
- }
- if err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE source_id=? AND type=?", nodeID, relationship).Scan(&sr.OutDegree); err != nil {
- return fmt.Errorf("count out-degree: %w", err)
- }
- } else {
- if err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE target_id=?", nodeID).Scan(&sr.InDegree); err != nil {
- return fmt.Errorf("count in-degree: %w", err)
- }
- if err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE source_id=?", nodeID).Scan(&sr.OutDegree); err != nil {
- return fmt.Errorf("count out-degree: %w", err)
- }
- }
- return nil
-}
-
// loadConnectedNames fetches up to 10 connected node names for display.
func (s *Store) loadConnectedNames(sr *SearchResult, nodeID int64) {
connRows, connErr := s.q.Query(`
@@ -113,19 +93,40 @@ func (s *Store) Search(params *SearchParams) (*SearchOutput, error) {
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.
+ nameHasLikeHints := false
+ if params.NamePattern != "" {
+ hints := extractLikeHints(params.NamePattern)
+ if len(hints) > 0 {
+ nameHasLikeHints = true
+ var likeParts []string
+ for _, hint := range hints {
+ likeVal := "%" + hint + "%"
+ likeParts = append(likeParts, "(n.name LIKE ? OR n.qualified_name LIKE ?)")
+ args = append(args, likeVal, likeVal)
+ }
+ conditions = append(conditions, "("+strings.Join(likeParts, " AND ")+")")
+ }
+ }
+
where := strings.Join(conditions, " AND ")
- // When Go-side filtering is needed (regex, degree), fetch more rows from SQL
- // and apply the user limit after filtering.
+ // When Go-side filtering is needed (regex, degree), we must scan all
+ // qualifying rows since matching nodes may appear at any position.
+ // However, if we pushed LIKE hints into SQL, the result set is already
+ // narrowed and we don't need the full 200K scan for name patterns.
hasDegreeFilter := params.MinDegree >= 0 || params.MaxDegree >= 0
+ needsNameScan := params.NamePattern != "" && !nameHasLikeHints
var sqlLimit int
- if params.NamePattern != "" || hasDegreeFilter {
- sqlLimit = 10000 // fetch enough rows for Go-side filtering
+ if needsNameScan || hasDegreeFilter {
+ sqlLimit = 200000 // must cover full dataset for accurate Go-side filtering
} else {
// Fetch enough for offset + limit
sqlLimit = params.Offset + params.Limit
- if sqlLimit > 100000 {
- sqlLimit = 100000
+ if sqlLimit > 200000 {
+ sqlLimit = 200000
}
}
@@ -212,15 +213,118 @@ func isEntryPoint(n *Node) 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(inArgs, relationship)
+ } else {
+ inQuery = fmt.Sprintf("SELECT target_id, COUNT(*) FROM edges WHERE target_id IN (%s) GROUP BY target_id", inClause)
+ inQueryArgs = inArgs
+ }
+
+ rows, err := s.q.Query(inQuery, inQueryArgs...)
+ if err != nil {
+ return nil, fmt.Errorf("batch count in-degree: %w", err)
+ }
+ for rows.Next() {
+ var id int64
+ var count int
+ if err := rows.Scan(&id, &count); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ dp := result[id]
+ dp.InDegree = count
+ result[id] = dp
+ }
+ rows.Close()
+
+ // Count outbound (source_id)
+ var outQuery string
+ 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
+ }
+
+ rows, err = s.q.Query(outQuery, outQueryArgs...)
+ if err != nil {
+ return nil, fmt.Errorf("batch count out-degree: %w", err)
+ }
+ for rows.Next() {
+ var id int64
+ var count int
+ if err := rows.Scan(&id, &count); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ dp := result[id]
+ dp.OutDegree = count
+ result[id] = dp
+ }
+ rows.Close()
+ }
+
+ return result, nil
+}
+
// 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 {
- sr := &SearchResult{Node: n}
-
- if err := s.countDegrees(sr, n.ID, params.Relationship); err != nil {
- return nil, err
+ dp := degrees[n.ID]
+ sr := &SearchResult{
+ Node: n,
+ InDegree: dp.InDegree,
+ OutDegree: dp.OutDegree,
}
degree := sr.InDegree
@@ -246,6 +350,47 @@ func (s *Store) buildFilteredResults(nodes []*Node, params *SearchParams) ([]*Se
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
+}
+
// filterByNamePattern filters nodes by a regex name pattern.
func filterByNamePattern(nodes []*Node, pattern string) ([]*Node, error) {
re, err := regexp.Compile(pattern)
diff --git a/internal/store/store.go b/internal/store/store.go
index daeb22019..d0be0d304 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -74,10 +74,20 @@ func Open(project string) (*Store, error) {
// OpenPath opens a SQLite database at the given path.
func OpenPath(dbPath string) (*Store, error) {
- db, err := sql.Open("sqlite", dbPath+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(ON)")
+ dsn := dbPath + "?_pragma=journal_mode(WAL)" +
+ "&_pragma=busy_timeout(5000)" +
+ "&_pragma=foreign_keys(ON)" +
+ "&_pragma=synchronous(NORMAL)" +
+ "&_pragma=cache_size(-8192)" +
+ "&_pragma=temp_store(MEMORY)" +
+ "&_pragma=mmap_size(268435456)" // 256 MB mmap for fast reads
+ db, err := sql.Open("sqlite", 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)
s := &Store{db: db, dbPath: dbPath}
s.q = s.db
if err := s.initSchema(); err != nil {
@@ -89,7 +99,10 @@ func OpenPath(dbPath string) (*Store, error) {
// OpenMemory opens an in-memory SQLite database (for testing).
func OpenMemory() (*Store, error) {
- db, err := sql.Open("sqlite", ":memory:?_pragma=foreign_keys(ON)")
+ dsn := ":memory:?_pragma=foreign_keys(ON)" +
+ "&_pragma=synchronous(OFF)" +
+ "&_pragma=temp_store(MEMORY)"
+ db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("open memory db: %w", err)
}
@@ -119,6 +132,14 @@ func (s *Store) WithTransaction(fn func(txStore *Store) error) error {
return tx.Commit()
}
+// Checkpoint forces a WAL checkpoint, moving pages from WAL to the main DB,
+// then runs ANALYZE so the query planner has up-to-date statistics.
+// Cost is absorbed during indexing rather than charged to the first read query.
+func (s *Store) Checkpoint() {
+ _, _ = s.db.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
+ _, _ = s.db.Exec("ANALYZE")
+}
+
// Close closes the database connection.
func (s *Store) Close() error {
return s.db.Close()
@@ -129,6 +150,11 @@ 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 {
schema := `
CREATE TABLE IF NOT EXISTS projects (
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index 28ae7a23c..58fe95999 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -351,6 +351,39 @@ func TestGlobToLike(t *testing.T) {
}
}
+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 {
@@ -425,6 +458,325 @@ func TestFindEdgesByURLPath(t *testing.T) {
}
}
+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().QueryRow("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: 200 + 50)
+ 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),
+ }
+ }
+
+ 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] != h.SHA256 {
+ t.Errorf("hash mismatch for %s: got %s, want %s", h.RelPath, stored[h.RelPath], h.SHA256)
+ }
+ }
+
+ // Update hashes (should not duplicate)
+ for i := range hashes {
+ hashes[i].SHA256 = fmt.Sprintf("updated_%d", i)
+ }
+ 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"] != "updated_0" {
+ t.Errorf("expected updated hash, got %s", stored["file_0.go"])
+ }
+}
+
+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 TestSearchExcludeLabels(t *testing.T) {
s, err := OpenMemory()
if err != nil {
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
index 6dbe20f49..df246d286 100644
--- a/internal/tools/tools.go
+++ b/internal/tools/tools.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
+ "sort"
"sync"
"github.com/DeusData/codebase-memory-mcp/internal/pipeline"
@@ -15,10 +16,11 @@ import (
// Server wraps the MCP server with tool handlers.
type Server struct {
- mcp *mcp.Server
- store *store.Store
- watcher *watcher.Watcher
- indexMu sync.Mutex
+ mcp *mcp.Server
+ store *store.Store
+ watcher *watcher.Watcher
+ indexMu sync.Mutex
+ handlers map[string]mcp.ToolHandler
}
// NewServer creates a new MCP server with all tools registered.
@@ -32,6 +34,7 @@ func NewServer(s *store.Store) *Server {
},
nil,
),
+ handlers: make(map[string]mcp.ToolHandler),
}
srv.registerTools()
srv.watcher = watcher.New(s, srv.syncProject)
@@ -61,6 +64,40 @@ func (s *Server) MCPServer() *mcp.Server {
return s.mcp
}
+// addTool registers a tool in both the MCP server and the local dispatch map.
+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.registerFileTools()
@@ -77,7 +114,7 @@ func (s *Server) registerGraphTools() {
}
func (s *Server) registerIndexAndTraceTool() {
- s.mcp.AddTool(&mcp.Tool{
+ 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.",
InputSchema: json.RawMessage(`{
@@ -91,7 +128,7 @@ func (s *Server) registerIndexAndTraceTool() {
}`),
}, s.handleIndexRepository)
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "trace_call_path",
Description: "Trace call paths from/to a function. Requires EXACT function name — if unsure, call search_graph(name_pattern=...) first to discover the correct name. Returns hop-by-hop callees/callers with edge types (CALLS, HTTP_CALLS, ASYNC_CALLS, USAGE, OVERRIDE). USAGE edges indicate read references (callbacks, variable assignments) rather than invocations. OVERRIDE edges link struct methods to the interface methods they implement. Use depth=1 first, increase only if needed. IMPORTANT: Use direction='both' for full cross-service context — HTTP_CALLS edges from other services appear as inbound edges on backend functions, so direction='outbound' alone misses cross-service callers. For async dispatch (Cloud Tasks, Pub/Sub), find dispatch functions via search_graph(name_pattern='.*CreateTask.*') then trace via CALLS edges. If the function is not found, use search_graph with a name_pattern regex to find similar names before retrying.",
InputSchema: json.RawMessage(`{
@@ -117,13 +154,13 @@ func (s *Server) registerIndexAndTraceTool() {
}
func (s *Server) registerSchemaAndSnippetTools() {
- s.mcp.AddTool(&mcp.Tool{
+ 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"}`),
}, s.handleGetGraphSchema)
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "get_code_snippet",
Description: "Retrieve source code for a function/class by qualified name. Reads directly from disk using the stored file path and line range. Returns the source code with line numbers.",
InputSchema: json.RawMessage(`{
@@ -140,7 +177,7 @@ func (s *Server) registerSchemaAndSnippetTools() {
}
func (s *Server) registerSearchTools() {
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "search_graph",
Description: "Search the code graph for nodes. Returns 10 results per page (use offset to paginate, has_more indicates more pages). 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 (url_path, confidence), use query_graph with Cypher instead: MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence. 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(`{
@@ -204,7 +241,7 @@ func (s *Server) registerSearchTools() {
}`),
}, s.handleSearchGraph)
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "search_code",
Description: "Search for text in source code files (like grep, scoped to indexed project). Returns 10 matches per page — use offset to paginate, has_more indicates more pages. Use for string literals, error messages, TODO comments.",
InputSchema: json.RawMessage(`{
@@ -237,7 +274,7 @@ func (s *Server) registerSearchTools() {
}
func (s *Server) registerQueryTool() {
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "query_graph",
Description: "Execute a Cypher-like graph query. WARNING: 200-row cap applies BEFORE aggregation — COUNT queries on large codebases silently undercount. For fan-out/fan-in counting, use search_graph with min_degree/max_degree instead. 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(`{
@@ -256,7 +293,7 @@ func (s *Server) registerQueryTool() {
// registerFileTools registers tools for file and directory operations.
func (s *Server) registerFileTools() {
// 8. read_file
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "read_file",
Description: "Read any file from the indexed project. Supports line range selection for large files. Use for reading config files (Dockerfile, go.mod, requirements.txt), source code, or any text file.",
InputSchema: json.RawMessage(`{
@@ -280,7 +317,7 @@ func (s *Server) registerFileTools() {
}, s.handleReadFile)
// 9. list_directory
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "list_directory",
Description: "List files and subdirectories in a directory. Supports glob patterns for filtering. Use for exploring project structure.",
InputSchema: json.RawMessage(`{
@@ -302,14 +339,14 @@ func (s *Server) registerFileTools() {
// registerProjectTools registers tools for project management.
func (s *Server) registerProjectTools() {
// 6. list_projects
- s.mcp.AddTool(&mcp.Tool{
+ 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"}`),
}, s.handleListProjects)
// 7. delete_project
- s.mcp.AddTool(&mcp.Tool{
+ s.addTool(&mcp.Tool{
Name: "delete_project",
Description: "Delete an indexed project and all its graph data (nodes, edges, file hashes). This action is irreversible.",
InputSchema: json.RawMessage(`{
diff --git a/internal/tools/traces.go b/internal/tools/traces.go
index b1e8759ae..f427ba8ca 100644
--- a/internal/tools/traces.go
+++ b/internal/tools/traces.go
@@ -9,7 +9,7 @@ import (
)
func (s *Server) registerTraceTools() {
- s.mcp.AddTool(&mcp.Tool{
+ 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(`{
diff --git a/server.json b/server.json
index 0c7615e07..8977eaf36 100644
--- a/server.json
+++ b/server.json
@@ -2,16 +2,16 @@
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "io.github.DeusData/codebase-memory-mcp",
"title": "Codebase Memory",
- "description": "Persistent codebase knowledge graph. Survives session restarts and context compaction.",
+ "description": "Persistent codebase knowledge graph — 12 languages, sub-ms queries, 99% fewer tokens than grep. Survives session restarts and context compaction.",
"repository": {
"url": "https://github.com/DeusData/codebase-memory-mcp",
"source": "github"
},
- "version": "0.1.3",
+ "version": "0.1.4",
"packages": [
{
"registryType": "mcpb",
- "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.3/codebase-memory-mcp-darwin-arm64.tar.gz",
+ "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.4/codebase-memory-mcp-darwin-arm64.tar.gz",
"fileSha256": "7589a880b964abda8dfa735d2946b257752c1ad3f0a093b3146741c15a01af40",
"transport": {
"type": "stdio"
@@ -19,7 +19,7 @@
},
{
"registryType": "mcpb",
- "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.3/codebase-memory-mcp-darwin-amd64.tar.gz",
+ "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.4/codebase-memory-mcp-darwin-amd64.tar.gz",
"fileSha256": "21db2204f9ff76c1e1f879f3eefb4c3943ded9eaaeb7c5aee4dc4c8ac5515185",
"transport": {
"type": "stdio"
@@ -27,7 +27,7 @@
},
{
"registryType": "mcpb",
- "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.3/codebase-memory-mcp-linux-amd64.tar.gz",
+ "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.4/codebase-memory-mcp-linux-amd64.tar.gz",
"fileSha256": "71a3874e9a3999246c0d98def6e9bee1ca88302913ee2330ddbc8cde5774cfee",
"transport": {
"type": "stdio"
@@ -35,7 +35,7 @@
},
{
"registryType": "mcpb",
- "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.3/codebase-memory-mcp-linux-arm64.tar.gz",
+ "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.4/codebase-memory-mcp-linux-arm64.tar.gz",
"fileSha256": "400976941a31b8f68bcff930c24f1399c8df39ff533400e0ce51f83898fcea9c",
"transport": {
"type": "stdio"
@@ -43,7 +43,7 @@
},
{
"registryType": "mcpb",
- "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.3/codebase-memory-mcp-windows-amd64.zip",
+ "identifier": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.1.4/codebase-memory-mcp-windows-amd64.zip",
"fileSha256": "f5de16d05ea26b7d3aa90e0f703e114edeb9d28cc44f0b90bac44141061de4af",
"transport": {
"type": "stdio"