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.

Release v0.3.1: detect_changes, risk scoring, editor support, SDK upgrade

Martin Vogeldc506b4bd02b
diff --git a/README.md b/README.md
index 0eabdc028..d557dc059 100644
--- a/README.md
+++ b/README.md
@@ -4,12 +4,14 @@
Single Go binary. No Docker, no external databases, no API keys. One command to install, 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, Codex CLI, or any MCP-compatible client. Also includes a **CLI mode** for direct tool invocation from the shell — no MCP client needed.
+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 14 MCP tools for use with Claude Code, Codex CLI, Cursor, Windsurf, or any MCP-compatible client. Also includes a **CLI mode** for direct tool invocation from the shell — no MCP client needed.
## Features
- **35 languages**: Python, Go, JavaScript, TypeScript, TSX, Rust, Java, C++, C#, C, PHP, Lua, Scala, Kotlin, Ruby, Bash, Zig, Elixir, Haskell, OCaml, Objective-C, Swift, Dart, Perl, Groovy, Erlang, R, HTML, CSS, SCSS, YAML, TOML, HCL, SQL, Dockerfile
-- **One-command install**: `codebase-memory-mcp install` auto-detects Claude Code and Codex CLI, registers the MCP server, and installs task-specific skills
+- **Git diff impact mapping**: `detect_changes` maps uncommitted changes to affected graph symbols + blast radius with risk classification (CRITICAL/HIGH/MEDIUM/LOW)
+- **Risk-classified tracing**: `trace_call_path` with `risk_labels=true` adds impact classification to every node in the call chain
+- **One-command install**: `codebase-memory-mcp install` auto-detects Claude Code, Codex CLI, Cursor, and Windsurf, registers the MCP server, and installs task-specific skills
- **Self-update**: `codebase-memory-mcp update` downloads the latest release, verifies checksums, and atomically swaps the binary
- **Task-specific skills**: 4 skills (exploring, tracing, quality, reference) that prescribe exact tool sequences — Claude Code automatically uses graph tools instead of defaulting to grep
- **Fast**: Sub-millisecond graph queries, incremental reindex 4x faster than full scan, optimized SQLite with LIKE pre-filtering for regex searches
@@ -84,7 +86,7 @@ Benchmarked on Apple M3 Pro, macOS Darwin 25.3.0:
4. **Restart** Claude Code / Codex CLI
5. Say **"Index this project"** — done.
-The `install` command auto-detects Claude Code and Codex CLI, registers the MCP server, installs 4 task-specific skills, and ensures the binary is on your PATH. Use `--dry-run` to preview without making changes.
+The `install` command auto-detects Claude Code, Codex CLI, Cursor, and Windsurf, registers the MCP server, installs 4 task-specific skills, and ensures the binary is on your PATH. Use `--dry-run` to preview without making changes.
### Keeping Up to Date
@@ -237,7 +239,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 12 tools.
+Restart Claude Code after adding the config. Verify with `/mcp` — you should see `codebase-memory-mcp` listed with 14 tools.
</details>
@@ -330,7 +332,8 @@ The CLI uses the same SQLite database as the MCP server (`~/.cache/codebase-memo
| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `search_graph` | `label`, `name_pattern`, `project`, `file_pattern`, `relationship`, `direction`, `min_degree`, `max_degree`, `exclude_entry_points`, `limit` (default 100), `offset` | Structured search with filters. Use `project` to scope to a single repo when multiple are indexed. Supports pagination via `limit`/`offset` — response includes `has_more` and `total`. |
-| `trace_call_path` | `function_name` (required), `direction` (inbound/outbound/both), `depth` (1-5, default 3) | BFS traversal from/to a function (exact name match). Returns call chains with signatures, constants, and edge types. Capped at 200 nodes. |
+| `trace_call_path` | `function_name` (required), `direction` (inbound/outbound/both), `depth` (1-5, default 3), `risk_labels` (boolean) | BFS traversal from/to a function (exact name match). Returns call chains with signatures, constants, and edge types. Capped at 200 nodes. With `risk_labels=true`, adds CRITICAL/HIGH/MEDIUM/LOW classification and `impact_summary`. |
+| `detect_changes` | `scope` (unstaged/staged/all/branch), `base_branch`, `depth` (1-5, default 3) | Map git diff to affected graph symbols + blast radius. Returns changed files, changed symbols, and impacted callers with risk classification. Requires git in PATH. |
| `query_graph` | `query` (required) | Execute Cypher-like graph queries (read-only). See [Supported Cypher Subset](#supported-cypher-subset) for what's supported. |
| `get_graph_schema` | — | Node/edge counts, relationship patterns, sample names. Run this first to understand what's in the graph. |
| `get_code_snippet` | `qualified_name` (required) | Read source code for a function by its qualified name (reads from disk). See [Qualified Names](#qualified-names) for the format. |
@@ -371,6 +374,20 @@ trace_call_path(function_name="ProcessOrder", depth=3, direction="outbound")
trace_call_path(function_name="ProcessOrder", depth=2, direction="inbound")
```
+### Risk-classified impact analysis
+
+```
+trace_call_path(function_name="ProcessOrder", direction="inbound", depth=3, risk_labels=true)
+```
+
+### Detect changes (git diff impact)
+
+```
+detect_changes()
+detect_changes(scope="staged")
+detect_changes(scope="branch", base_branch="main", depth=3)
+```
+
### Dead code detection
```
@@ -577,6 +594,7 @@ make install # go install
| `trace_call_path` returns 0 results | Exact name match — no fuzzy matching | Use `search_graph(name_pattern=".*PartialName.*")` to discover the exact function name first. |
| Queries return results from wrong project | Multiple projects indexed, no filter | Add `project="your-project-name"` to `search_graph`. Use `list_projects` to see indexed project names. |
| Graph is missing recently added files | Auto-sync hasn't caught up yet, or project was never indexed | Wait a few seconds for auto-sync, or run `index_repository` manually. Auto-sync polls at 1–60s intervals depending on repo size. |
+| `detect_changes` fails with "git not found" | git not installed or not on PATH | Install git. Required at runtime only for `detect_changes`. |
| Binary not found after install | `~/.local/bin` not on PATH | Add to your shell profile: `export PATH="$HOME/.local/bin:$PATH"` |
| Cypher query fails with parse error | Unsupported Cypher feature | See [Supported Cypher Subset](#supported-cypher-subset). `WITH`, `COLLECT`, `OPTIONAL MATCH` are not supported. |
@@ -606,7 +624,7 @@ internal/
httplink/ Cross-service HTTP route/call-site matching
cypher/ Cypher query lexer, parser, planner, executor
selfupdate/ GitHub release checking, version comparison, asset download
- tools/ MCP tool handlers (12 tools) + CLI dispatch
+ tools/ MCP tool handlers (14 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/assets/skills/codebase-memory-reference/SKILL.md b/cmd/codebase-memory-mcp/assets/skills/codebase-memory-reference/SKILL.md
index 547d4a556..97dbfd621 100644
--- a/cmd/codebase-memory-mcp/assets/skills/codebase-memory-reference/SKILL.md
+++ b/cmd/codebase-memory-mcp/assets/skills/codebase-memory-reference/SKILL.md
@@ -9,7 +9,7 @@ description: >
# Codebase Memory MCP — Tool Reference
-## Tools (12 total)
+## Tools (14 total)
| Tool | Purpose |
|------|---------|
@@ -19,12 +19,14 @@ description: >
| `delete_project` | Remove a project from the graph |
| `search_graph` | Structured search with filters (name, label, degree, file pattern) |
| `search_code` | Grep-like text search within indexed project files |
-| `trace_call_path` | BFS call chain traversal (exact name match required) |
+| `trace_call_path` | BFS call chain traversal (exact name match required). Supports `risk_labels=true` for impact classification. |
+| `detect_changes` | Map git diff to affected symbols + blast radius with risk scoring |
| `query_graph` | Cypher-like graph queries (200-row cap) |
| `get_graph_schema` | Node/edge counts, relationship patterns |
| `get_code_snippet` | Read source code by qualified name |
| `read_file` | Read any file from indexed project |
| `list_directory` | List files/directories with glob filter |
+| `ingest_traces` | Ingest OpenTelemetry traces to validate HTTP_CALLS edges |
## Edge Types
@@ -90,6 +92,46 @@ MATCH (a)-[r:FILE_CHANGES_WITH]->(b) WHERE r.coupling_score >= 0.5 RETURN a.name
MATCH (f:Function)-[:CALLS]->(g:Function) WHERE g.name = 'ProcessOrder' RETURN f.name LIMIT 20
```
+## Regex-Powered Search (No Full-Text Index Needed)
+
+`search_graph` and `search_code` support full Go regex, making full-text search indexes unnecessary. Regex patterns provide precise, composable queries that cover all common discovery scenarios:
+
+### search_graph — name_pattern / qn_pattern
+
+| Pattern | Matches | Use case |
+|---------|---------|----------|
+| `.*Handler$` | names ending in Handler | Find all handlers |
+| `(?i)auth` | case-insensitive "auth" | Find auth-related symbols |
+| `get\|fetch\|load` | any of three words | Find data-loading functions |
+| `^on[A-Z]` | names starting with on + uppercase | Find event handlers |
+| `.*Service.*Impl` | Service...Impl pattern | Find service implementations |
+| `^(Get\|Set\|Delete)` | CRUD prefixes | Find CRUD operations |
+| `.*_test$` | names ending in _test | Find test functions |
+| `.*\\.controllers\\..*` | qn_pattern for directory scoping | Scope to controllers dir |
+
+### search_code — regex=true
+
+| Pattern | Matches | Use case |
+|---------|---------|----------|
+| `TODO\|FIXME\|HACK` | multi-pattern scan | Find tech debt markers |
+| `(?i)password\|secret\|token` | case-insensitive secrets | Security scan |
+| `func\\s+Test` | Go test functions | Find test entry points |
+| `api[._/]v[0-9]` | API version references | Find versioned API usage |
+| `import.*from ['"]@` | scoped npm imports | Find package imports |
+
+### Combining Filters for Surgical Queries
+
+```
+# Find unused auth handlers
+search_graph(name_pattern="(?i).*auth.*handler.*", max_degree=0, exclude_entry_points=true)
+
+# Find high fan-out functions in the services directory
+search_graph(qn_pattern=".*\\.services\\..*", min_degree=10, relationship="CALLS", direction="outbound")
+
+# Find all route handlers matching a URL pattern
+search_code(pattern="(?i)(POST|PUT).*\\/api\\/v[0-9]\\/orders", regex=true)
+```
+
## Critical Pitfalls
1. **`search_graph(relationship="HTTP_CALLS")` does NOT return edges** — it filters nodes by degree. Use `query_graph` with Cypher to see actual edges.
@@ -107,4 +149,6 @@ MATCH (f:Function)-[:CALLS]->(g:Function) WHERE g.name = 'ProcessOrder' RETURN f
| Find by name pattern | `search_graph(name_pattern="...")` |
| Dead code | `search_graph(max_degree=0, exclude_entry_points=true)` |
| Cross-service edges | `query_graph` with Cypher |
+| Impact of local changes | `detect_changes()` |
+| Risk-classified trace | `trace_call_path(risk_labels=true)` |
| Text search | `search_code` or Grep |
diff --git a/cmd/codebase-memory-mcp/assets/skills/codebase-memory-tracing/SKILL.md b/cmd/codebase-memory-mcp/assets/skills/codebase-memory-tracing/SKILL.md
index 8b71065f0..bc14abe72 100644
--- a/cmd/codebase-memory-mcp/assets/skills/codebase-memory-tracing/SKILL.md
+++ b/cmd/codebase-memory-mcp/assets/skills/codebase-memory-tracing/SKILL.md
@@ -16,12 +16,18 @@ Use graph tools to trace function call relationships. One `trace_call_path` call
### Step 1: Discover the exact function name
-`trace_call_path` requires an **exact** name match. If you don't know the exact name, discover it first:
+`trace_call_path` requires an **exact** name match. If you don't know the exact name, discover it first with regex:
```
search_graph(name_pattern=".*Order.*", label="Function")
```
+Use full regex for precise discovery — no full-text search needed:
+- `(?i)order` — case-insensitive
+- `^(Get|Set|Delete)Order` — CRUD variants
+- `.*Order.*Handler$` — handlers only
+- `qn_pattern=".*services\\.order\\..*"` — scope to order service directory
+
This returns matching functions with their qualified names and file locations.
### Step 2: Trace callers (who calls this function?)
@@ -88,9 +94,32 @@ query_graph(query="MATCH (s)-[r:OVERRIDE]->(i) WHERE i.name = 'Read' RETURN s.na
query_graph(query="MATCH (a)-[r:USAGE]->(b) WHERE b.name = 'ProcessOrder' RETURN a.name, a.file_path LIMIT 20")
```
+## Risk-Classified Impact Analysis
+
+Add `risk_labels=true` to get risk classification on each node:
+
+```
+trace_call_path(function_name="ProcessOrder", direction="inbound", depth=3, risk_labels=true)
+```
+
+Returns nodes with `risk` (CRITICAL/HIGH/MEDIUM/LOW) based on hop depth, plus an `impact_summary` with counts. Risk mapping: hop 1=CRITICAL, 2=HIGH, 3=MEDIUM, 4+=LOW.
+
+## Detect Changes (Git Diff Impact)
+
+Map uncommitted changes to affected symbols and their blast radius:
+
+```
+detect_changes()
+detect_changes(scope="staged")
+detect_changes(scope="branch", base_branch="main")
+```
+
+Returns changed files, changed symbols, and impacted callers with risk classification. Scopes: `unstaged`, `staged`, `all` (default), `branch`.
+
## Key Tips
- Start with `depth=1` for quick answers, increase only if needed (max 5).
- Edge types in trace results: `CALLS` (direct), `HTTP_CALLS` (cross-service), `ASYNC_CALLS` (async dispatch), `USAGE` (read reference), `OVERRIDE` (interface implementation).
- `search_graph(relationship="HTTP_CALLS")` filters nodes by degree — it does NOT return edges. Use `query_graph` with Cypher to see actual edges with properties.
- Results are capped at 200 nodes per trace.
+- `detect_changes` requires git in PATH.
diff --git a/cmd/codebase-memory-mcp/install.go b/cmd/codebase-memory-mcp/install.go
index 6aa7851f8..ec3e79df9 100644
--- a/cmd/codebase-memory-mcp/install.go
+++ b/cmd/codebase-memory-mcp/install.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "encoding/json"
"fmt"
"os"
"os/exec"
@@ -61,7 +62,15 @@ func runInstall(args []string) int {
fmt.Println("[Codex CLI] not found — skipping")
}
- fmt.Println("\nDone. Restart Claude Code / Codex to activate.")
+ fmt.Println()
+
+ // Cursor
+ installEditorMCP(binaryPath, cursorConfigPath(), "Cursor", cfg)
+
+ // Windsurf
+ installEditorMCP(binaryPath, windsurfConfigPath(), "Windsurf", cfg)
+
+ fmt.Println("\nDone. Restart Claude Code / Codex / Cursor / Windsurf to activate.")
return 0
}
@@ -91,6 +100,12 @@ func runUninstall(args []string) int {
removeCodexInstructions(cfg)
}
+ // Cursor
+ removeEditorMCP(cursorConfigPath(), "Cursor", cfg)
+
+ // Windsurf
+ removeEditorMCP(windsurfConfigPath(), "Windsurf", cfg)
+
fmt.Println("\nDone. Binary and databases were NOT removed.")
return 0
}
@@ -462,3 +477,123 @@ func execCLI(path string, args ...string) error {
cmd.Stderr = os.Stderr
return cmd.Run()
}
+
+// --- Editor MCP config (Cursor, Windsurf) ---
+
+const mcpServerKey = "codebase-memory-mcp"
+
+// cursorConfigPath returns the Cursor MCP config path.
+func cursorConfigPath() string {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ return filepath.Join(home, ".cursor", "mcp.json")
+}
+
+// windsurfConfigPath returns the Windsurf MCP config path.
+func windsurfConfigPath() string {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ return filepath.Join(home, ".codeium", "windsurf", "mcp_config.json")
+}
+
+// installEditorMCP upserts our MCP server entry in an editor's JSON config file.
+func installEditorMCP(binaryPath, configPath, editorName string, cfg installConfig) {
+ if configPath == "" {
+ return
+ }
+
+ fmt.Printf("[%s] MCP config: %s\n", editorName, configPath)
+
+ if cfg.dryRun {
+ fmt.Printf(" [dry-run] Would upsert %s in %s\n", mcpServerKey, configPath)
+ return
+ }
+
+ // Read existing config or start fresh
+ root := make(map[string]any)
+ if data, err := os.ReadFile(configPath); err == nil {
+ if jsonErr := json.Unmarshal(data, &root); jsonErr != nil {
+ // File exists but is invalid JSON — back up and overwrite
+ fmt.Printf(" ⚠ Invalid JSON in %s, overwriting\n", configPath)
+ root = make(map[string]any)
+ }
+ }
+
+ // Ensure mcpServers map exists
+ servers, ok := root["mcpServers"].(map[string]any)
+ if !ok {
+ servers = make(map[string]any)
+ }
+
+ // Upsert our server entry
+ servers[mcpServerKey] = map[string]any{
+ "command": binaryPath,
+ }
+ root["mcpServers"] = servers
+
+ // Write back
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
+ fmt.Printf(" ⚠ mkdir %s: %v\n", filepath.Dir(configPath), err)
+ return
+ }
+ out, err := json.MarshalIndent(root, "", " ")
+ if err != nil {
+ fmt.Printf(" ⚠ marshal JSON: %v\n", err)
+ return
+ }
+ if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
+ fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
+ return
+ }
+ fmt.Printf(" ✓ MCP server registered in %s\n", configPath)
+}
+
+// removeEditorMCP removes our MCP server entry from an editor's JSON config file.
+func removeEditorMCP(configPath, editorName string, cfg installConfig) {
+ if configPath == "" {
+ return
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ return // no config file, nothing to remove
+ }
+
+ var root map[string]any
+ if err := json.Unmarshal(data, &root); err != nil {
+ return
+ }
+
+ servers, ok := root["mcpServers"].(map[string]any)
+ if !ok {
+ return
+ }
+ if _, exists := servers[mcpServerKey]; !exists {
+ return
+ }
+
+ fmt.Printf("[%s] MCP config: %s\n", editorName, configPath)
+
+ if cfg.dryRun {
+ fmt.Printf(" [dry-run] Would remove %s from %s\n", mcpServerKey, configPath)
+ return
+ }
+
+ delete(servers, mcpServerKey)
+ root["mcpServers"] = servers
+
+ out, err := json.MarshalIndent(root, "", " ")
+ if err != nil {
+ fmt.Printf(" ⚠ marshal JSON: %v\n", err)
+ return
+ }
+ if err := os.WriteFile(configPath, append(out, '\n'), 0o600); err != nil {
+ fmt.Printf(" ⚠ write %s: %v\n", configPath, err)
+ return
+ }
+ fmt.Printf(" ✓ Removed %s from %s\n", mcpServerKey, configPath)
+}
diff --git a/cmd/codebase-memory-mcp/install_test.go b/cmd/codebase-memory-mcp/install_test.go
index 0b9b6b445..8f764280a 100644
--- a/cmd/codebase-memory-mcp/install_test.go
+++ b/cmd/codebase-memory-mcp/install_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "encoding/json"
"os"
"path/filepath"
"runtime"
@@ -295,9 +296,9 @@ func TestSkillFilesContent(t *testing.T) {
expectations := map[string][]string{
"codebase-memory-exploring": {"explore the codebase", "search_graph", "get_graph_schema"},
- "codebase-memory-tracing": {"who calls this function", "trace_call_path", "direction"},
+ "codebase-memory-tracing": {"who calls this function", "trace_call_path", "direction", "risk_labels", "detect_changes"},
"codebase-memory-quality": {"find dead code", "max_degree=0", "exclude_entry_points"},
- "codebase-memory-reference": {"edge types", "query_graph", "Cypher"},
+ "codebase-memory-reference": {"edge types", "query_graph", "Cypher", "detect_changes", "14 total"},
}
for name, expectedPhrases := range expectations {
@@ -313,6 +314,132 @@ func TestSkillFilesContent(t *testing.T) {
}
}
+func TestEditorMCPInstall(t *testing.T) {
+ home := t.TempDir()
+ setTestHome(t, home)
+
+ configPath := filepath.Join(home, ".cursor", "mcp.json")
+ binaryPath := "/usr/local/bin/codebase-memory-mcp"
+
+ // First install — creates file from scratch
+ installEditorMCP(binaryPath, configPath, "Cursor", installConfig{})
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ var root map[string]any
+ if err := json.Unmarshal(data, &root); err != nil {
+ t.Fatalf("unmarshal config: %v", err)
+ }
+ servers, ok := root["mcpServers"].(map[string]any)
+ if !ok {
+ t.Fatal("expected mcpServers key")
+ }
+ entry, ok := servers["codebase-memory-mcp"].(map[string]any)
+ if !ok {
+ t.Fatal("expected codebase-memory-mcp entry")
+ }
+ if cmd, _ := entry["command"].(string); cmd != binaryPath {
+ t.Fatalf("expected command %q, got %q", binaryPath, cmd)
+ }
+}
+
+func TestEditorMCPInstallIdempotent(t *testing.T) {
+ home := t.TempDir()
+ setTestHome(t, home)
+
+ configPath := filepath.Join(home, ".cursor", "mcp.json")
+ binaryPath := "/usr/local/bin/codebase-memory-mcp"
+
+ // Install twice — second install should preserve valid JSON
+ installEditorMCP(binaryPath, configPath, "Cursor", installConfig{})
+ installEditorMCP(binaryPath, configPath, "Cursor", installConfig{})
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ var root map[string]any
+ if err := json.Unmarshal(data, &root); err != nil {
+ t.Fatalf("double install produced invalid JSON: %v", err)
+ }
+ servers, ok := root["mcpServers"].(map[string]any)
+ if !ok {
+ t.Fatal("mcpServers is not a map")
+ }
+ if len(servers) != 1 {
+ t.Fatalf("expected 1 server, got %d", len(servers))
+ }
+}
+
+func TestEditorMCPPreservesOtherServers(t *testing.T) {
+ home := t.TempDir()
+ setTestHome(t, home)
+
+ configPath := filepath.Join(home, ".cursor", "mcp.json")
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o750); err != nil {
+ t.Fatal(err)
+ }
+
+ // Write config with an existing server
+ existing := `{"mcpServers": {"other-server": {"command": "/usr/bin/other"}}}`
+ if err := os.WriteFile(configPath, []byte(existing), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ installEditorMCP("/usr/local/bin/codebase-memory-mcp", configPath, "Cursor", installConfig{})
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var root map[string]any
+ if err := json.Unmarshal(data, &root); err != nil {
+ t.Fatal(err)
+ }
+ servers, ok := root["mcpServers"].(map[string]any)
+ if !ok {
+ t.Fatal("mcpServers is not a map")
+ }
+ if len(servers) != 2 {
+ t.Fatalf("expected 2 servers, got %d", len(servers))
+ }
+ if _, ok = servers["other-server"]; !ok {
+ t.Fatal("other-server was removed")
+ }
+ if _, ok := servers["codebase-memory-mcp"]; !ok {
+ t.Fatal("codebase-memory-mcp not added")
+ }
+}
+
+func TestEditorMCPUninstall(t *testing.T) {
+ home := t.TempDir()
+ setTestHome(t, home)
+
+ configPath := filepath.Join(home, ".cursor", "mcp.json")
+
+ // Install then uninstall
+ installEditorMCP("/usr/local/bin/codebase-memory-mcp", configPath, "Cursor", installConfig{})
+ removeEditorMCP(configPath, "Cursor", installConfig{})
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var root map[string]any
+ if err := json.Unmarshal(data, &root); err != nil {
+ t.Fatal(err)
+ }
+ servers, ok := root["mcpServers"].(map[string]any)
+ if !ok {
+ t.Fatal("mcpServers is not a map")
+ }
+ if _, exists := servers["codebase-memory-mcp"]; exists {
+ t.Fatal("codebase-memory-mcp should be removed after uninstall")
+ }
+}
+
func TestRemoveOldMonolithicSkill(t *testing.T) {
home := t.TempDir()
setTestHome(t, home)
diff --git a/cmd/codebase-memory-mcp/main.go b/cmd/codebase-memory-mcp/main.go
index eeec3253b..cfa581688 100644
--- a/cmd/codebase-memory-mcp/main.go
+++ b/cmd/codebase-memory-mcp/main.go
@@ -182,6 +182,8 @@ func printSummary(toolName, text, dbPath string) {
printIngestSummary(data, dbPath)
case "index_status":
printIndexStatusSummary(data)
+ case "detect_changes":
+ printDetectChangesSummary(data)
default:
// Fallback: pretty-print the JSON
printRawJSON(text)
@@ -486,6 +488,36 @@ func printIndexStatusSummary(data map[string]any) {
}
}
+func printDetectChangesSummary(data map[string]any) {
+ summary, _ := data["summary"].(map[string]any)
+ changedFiles := jsonInt(summary["changed_files"])
+ changedSymbols := jsonInt(summary["changed_symbols"])
+ total := jsonInt(summary["total"])
+ critical := jsonInt(summary["critical"])
+ high := jsonInt(summary["high"])
+ medium := jsonInt(summary["medium"])
+ low := jsonInt(summary["low"])
+
+ fmt.Printf("Changes: %d file(s), %d symbol(s) modified\n", changedFiles, changedSymbols)
+ fmt.Printf("Impact: %d affected symbol(s)\n", total)
+ if total > 0 {
+ fmt.Printf(" CRITICAL: %d HIGH: %d MEDIUM: %d LOW: %d\n", critical, high, medium, low)
+ }
+
+ impacted, _ := data["impacted_symbols"].([]any)
+ for _, is := range impacted {
+ m, ok := is.(map[string]any)
+ if !ok {
+ continue
+ }
+ risk, _ := m["risk"].(string)
+ name, _ := m["name"].(string)
+ label, _ := m["label"].(string)
+ changedBy, _ := m["changed_by"].(string)
+ fmt.Printf(" [%s] [%s] %s (via %s)\n", risk, label, name, changedBy)
+ }
+}
+
// jsonInt extracts an integer from a JSON-decoded value (float64 or int).
func jsonInt(v any) int {
switch n := v.(type) {
diff --git a/go.mod b/go.mod
index 4e4e8ab1c..66173bf94 100644
--- a/go.mod
+++ b/go.mod
@@ -8,7 +8,7 @@ require (
github.com/alex-pinkus/tree-sitter-swift v0.0.0
github.com/camdencheek/tree-sitter-dockerfile v0.0.0
github.com/mattn/go-sqlite3 v1.14.34
- github.com/modelcontextprotocol/go-sdk v1.3.1
+ github.com/modelcontextprotocol/go-sdk v1.4.0
github.com/murtaza64/tree-sitter-groovy v0.0.0
github.com/r-lib/tree-sitter-r v0.0.0
github.com/tree-sitter-grammars/tree-sitter-hcl v1.2.0
@@ -41,7 +41,7 @@ require (
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
+ golang.org/x/sync v0.19.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -53,9 +53,9 @@ require (
github.com/segmentio/encoding v0.5.3 // indirect
github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
- golang.org/x/oauth2 v0.30.0 // indirect
- golang.org/x/sys v0.37.0 // indirect
- golang.org/x/tools v0.38.0 // indirect
+ golang.org/x/oauth2 v0.34.0 // indirect
+ golang.org/x/sys v0.40.0 // indirect
+ golang.org/x/tools v0.41.0 // indirect
)
replace github.com/tree-sitter/go-tree-sitter => github.com/DeusData/go-tree-sitter v0.26.0-deusdata.1
diff --git a/go.sum b/go.sum
index 8ff691fc1..ee61c8e3b 100644
--- a/go.sum
+++ b/go.sum
@@ -24,6 +24,7 @@ github.com/elixir-lang/tree-sitter-elixir v0.3.4 h1:M0Wc3XXEJyGpVELOzxqhV069bBsR
github.com/elixir-lang/tree-sitter-elixir v0.3.4/go.mod h1:wNBVf64kzvhSbZ8ojVtBF1jRiqGY0lsuK5Kx/60s6Z0=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
+github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
@@ -36,6 +37,8 @@ github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp
github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modelcontextprotocol/go-sdk v1.3.1 h1:TfqtNKOIWN4Z1oqmPAiWDC2Jq7K9OdJaooe0teoXASI=
github.com/modelcontextprotocol/go-sdk v1.3.1/go.mod h1:DgVX498dMD8UJlseK1S5i1T4tFz2fkBk4xogC3D15nw=
+github.com/modelcontextprotocol/go-sdk v1.4.0 h1:u0kr8lbJc1oBcawK7Df+/ajNMpIDFE41OEPxdeTLOn8=
+github.com/modelcontextprotocol/go-sdk v1.4.0/go.mod h1:Nxc2n+n/GdCebUaqCOhTetptS17SXXNu9IfNTaLDi1E=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
@@ -106,12 +109,20 @@ 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/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
+golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
+golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
+golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
+golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 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=
diff --git a/internal/pipeline/gitdiff.go b/internal/pipeline/gitdiff.go
new file mode 100644
index 000000000..d54644e70
--- /dev/null
+++ b/internal/pipeline/gitdiff.go
@@ -0,0 +1,225 @@
+package pipeline
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "log/slog"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// DiffScope controls which changes to include.
+type DiffScope string
+
+const (
+ DiffUnstaged DiffScope = "unstaged"
+ DiffStaged DiffScope = "staged"
+ DiffAll DiffScope = "all"
+ DiffBranch DiffScope = "branch"
+)
+
+// ChangedFile represents a file with a status from git diff --name-status.
+type ChangedFile struct {
+ Status string // M, A, D, R (modified, added, deleted, renamed)
+ Path string
+ OldPath string // non-empty only for renames
+}
+
+// ChangedHunk represents a changed region within a file.
+type ChangedHunk struct {
+ Path string
+ StartLine int
+ EndLine int
+}
+
+// ParseGitDiffFiles runs git diff --name-status and returns changed files.
+func ParseGitDiffFiles(repoPath string, scope DiffScope, baseBranch string) ([]ChangedFile, error) {
+ args := buildDiffArgs(scope, baseBranch)
+ args = append(args, "--name-status")
+ return parseDiffNameStatus(repoPath, args)
+}
+
+// ParseGitDiffHunks runs git diff --unified=0 and extracts changed line ranges.
+func ParseGitDiffHunks(repoPath string, scope DiffScope, baseBranch string) ([]ChangedHunk, error) {
+ args := buildDiffArgs(scope, baseBranch)
+ args = append(args, "--unified=0")
+ return parseDiffHunks(repoPath, args)
+}
+
+func buildDiffArgs(scope DiffScope, baseBranch string) []string {
+ base := []string{"diff"}
+ switch scope {
+ case DiffStaged:
+ return append(base, "--cached")
+ case DiffAll:
+ return append(base, "HEAD")
+ case DiffBranch:
+ if baseBranch == "" {
+ baseBranch = "main"
+ }
+ return append(base, baseBranch+"...HEAD")
+ default: // unstaged
+ return base
+ }
+}
+
+func parseDiffNameStatus(repoPath string, args []string) ([]ChangedFile, error) {
+ output, err := runGit(repoPath, args)
+ if err != nil {
+ return nil, err
+ }
+ return ParseNameStatusOutput(output), nil
+}
+
+// ParseNameStatusOutput parses the raw output of git diff --name-status.
+func ParseNameStatusOutput(output string) []ChangedFile {
+ var files []ChangedFile
+ scanner := bufio.NewScanner(strings.NewReader(output))
+ for scanner.Scan() {
+ line := scanner.Text()
+ if line == "" {
+ continue
+ }
+ parts := strings.Split(line, "\t")
+ if len(parts) < 2 {
+ continue
+ }
+ status := parts[0]
+ path := parts[1]
+
+ cf := ChangedFile{Path: path}
+
+ // Handle renames: R100\told\tnew
+ if strings.HasPrefix(status, "R") {
+ cf.Status = "R"
+ cf.OldPath = path
+ if len(parts) >= 3 {
+ cf.Path = parts[2]
+ }
+ } else {
+ cf.Status = status[:1] // first char: M, A, D, etc.
+ }
+
+ if !isTrackableFile(cf.Path) {
+ continue
+ }
+ files = append(files, cf)
+ }
+ return files
+}
+
+func parseDiffHunks(repoPath string, args []string) ([]ChangedHunk, error) {
+ output, err := runGit(repoPath, args)
+ if err != nil {
+ return nil, err
+ }
+ return ParseHunksOutput(output), nil
+}
+
+// ParseHunksOutput parses the raw output of git diff --unified=0.
+func ParseHunksOutput(output string) []ChangedHunk {
+ var hunks []ChangedHunk
+ var currentFile string
+
+ scanner := bufio.NewScanner(strings.NewReader(output))
+ for scanner.Scan() {
+ line := scanner.Text()
+
+ // Track current file from +++ header
+ if strings.HasPrefix(line, "+++ b/") {
+ currentFile = strings.TrimPrefix(line, "+++ b/")
+ continue
+ }
+
+ // Skip binary files
+ if strings.HasPrefix(line, "Binary files") {
+ continue
+ }
+
+ // Parse @@ hunk headers: @@ -old,count +new,count @@
+ if strings.HasPrefix(line, "@@") && currentFile != "" {
+ hunk := parseHunkHeader(line, currentFile)
+ if hunk != nil && isTrackableFile(currentFile) {
+ hunks = append(hunks, *hunk)
+ }
+ }
+ }
+ return hunks
+}
+
+// parseHunkHeader extracts the new-file line range from a @@ header.
+// Format: @@ -old_start[,old_count] +new_start[,new_count] @@
+func parseHunkHeader(line, file string) *ChangedHunk {
+ // Find the +start,count part
+ plusIdx := strings.Index(line, "+")
+ if plusIdx < 0 {
+ return nil
+ }
+ // Find the end @@
+ endIdx := strings.Index(line[plusIdx:], " @@")
+ if endIdx < 0 {
+ endIdx = len(line) - plusIdx
+ }
+ rangeStr := line[plusIdx+1 : plusIdx+endIdx]
+
+ start, count := parseRange(rangeStr)
+ if start == 0 {
+ return nil
+ }
+ end := start + count - 1
+ if end < start {
+ end = start
+ }
+
+ return &ChangedHunk{
+ Path: file,
+ StartLine: start,
+ EndLine: end,
+ }
+}
+
+// parseRange parses "start,count" or "start" into (start, count).
+func parseRange(s string) (start, count int) {
+ parts := strings.SplitN(s, ",", 2)
+ start, err := strconv.Atoi(parts[0])
+ if err != nil {
+ return 0, 0
+ }
+ count = 1
+ if len(parts) == 2 {
+ count, err = strconv.Atoi(parts[1])
+ if err != nil {
+ count = 1
+ }
+ }
+ return start, count
+}
+
+// runGit executes a git command and returns stdout. Returns a clear error if git is not found.
+func runGit(repoPath string, args []string) (string, error) {
+ gitPath, err := exec.LookPath("git")
+ if err != nil {
+ return "", fmt.Errorf("git not found in PATH: install git to use detect_changes")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, gitPath, args...)
+ cmd.Dir = repoPath
+
+ output, err := cmd.Output()
+ if err != nil {
+ // git diff returns exit code 1 when there are differences in some modes
+ // but we still want the output
+ if exitErr, ok := err.(*exec.ExitError); ok {
+ slog.Debug("git.exit", "code", exitErr.ExitCode(), "args", args)
+ return string(output), nil
+ }
+ return "", fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
+ }
+ return string(output), nil
+}
diff --git a/internal/pipeline/gitdiff_test.go b/internal/pipeline/gitdiff_test.go
new file mode 100644
index 000000000..0aee95d8f
--- /dev/null
+++ b/internal/pipeline/gitdiff_test.go
@@ -0,0 +1,182 @@
+package pipeline
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestParseNameStatusOutput(t *testing.T) {
+ input := "M\tinternal/store/nodes.go\nA\tnew_file.go\nD\told_file.go\nR100\tsrc/old.go\tsrc/new.go\n"
+
+ files := ParseNameStatusOutput(input)
+
+ if len(files) != 4 {
+ t.Fatalf("expected 4 files, got %d", len(files))
+ }
+
+ tests := []struct {
+ idx int
+ status string
+ path string
+ oldPath string
+ }{
+ {0, "M", "internal/store/nodes.go", ""},
+ {1, "A", "new_file.go", ""},
+ {2, "D", "old_file.go", ""},
+ {3, "R", "src/new.go", "src/old.go"},
+ }
+
+ for _, tt := range tests {
+ f := files[tt.idx]
+ if f.Status != tt.status {
+ t.Errorf("[%d] status = %q, want %q", tt.idx, f.Status, tt.status)
+ }
+ if f.Path != tt.path {
+ t.Errorf("[%d] path = %q, want %q", tt.idx, f.Path, tt.path)
+ }
+ if f.OldPath != tt.oldPath {
+ t.Errorf("[%d] oldPath = %q, want %q", tt.idx, f.OldPath, tt.oldPath)
+ }
+ }
+}
+
+func TestParseNameStatusOutput_FiltersUntrackable(t *testing.T) {
+ input := "M\tpackage-lock.json\nM\tsrc/main.go\nM\tvendor/lib.go\n"
+ files := ParseNameStatusOutput(input)
+
+ if len(files) != 1 {
+ t.Fatalf("expected 1 trackable file, got %d", len(files))
+ }
+ if files[0].Path != "src/main.go" {
+ t.Errorf("expected src/main.go, got %s", files[0].Path)
+ }
+}
+
+func TestParseHunksOutput(t *testing.T) {
+ input := `diff --git a/main.go b/main.go
+index abc1234..def5678 100644
+--- a/main.go
++++ b/main.go
+@@ -10,3 +10,5 @@ func main() {
++ newLine1()
++ newLine2()
+@@ -50,0 +52,2 @@ func helper() {
++ another()
++ line()
+diff --git a/binary.png b/binary.png
+Binary files a/binary.png and b/binary.png differ
+diff --git a/utils.go b/utils.go
+--- a/utils.go
++++ b/utils.go
+@@ -1 +1 @@ package utils
+-old
++new
+`
+
+ hunks := ParseHunksOutput(input)
+
+ if len(hunks) != 3 {
+ t.Fatalf("expected 3 hunks, got %d", len(hunks))
+ }
+
+ // First hunk: main.go @@ -10,3 +10,5 @@
+ if hunks[0].Path != "main.go" {
+ t.Errorf("hunk 0 path = %q", hunks[0].Path)
+ }
+ if hunks[0].StartLine != 10 || hunks[0].EndLine != 14 {
+ t.Errorf("hunk 0 range = %d-%d, want 10-14", hunks[0].StartLine, hunks[0].EndLine)
+ }
+
+ // Second hunk: main.go @@ -50,0 +52,2 @@
+ if hunks[1].Path != "main.go" {
+ t.Errorf("hunk 1 path = %q", hunks[1].Path)
+ }
+ if hunks[1].StartLine != 52 || hunks[1].EndLine != 53 {
+ t.Errorf("hunk 1 range = %d-%d, want 52-53", hunks[1].StartLine, hunks[1].EndLine)
+ }
+
+ // Third hunk: utils.go @@ -1 +1 @@
+ if hunks[2].Path != "utils.go" {
+ t.Errorf("hunk 2 path = %q", hunks[2].Path)
+ }
+ if hunks[2].StartLine != 1 || hunks[2].EndLine != 1 {
+ t.Errorf("hunk 2 range = %d-%d, want 1-1", hunks[2].StartLine, hunks[2].EndLine)
+ }
+}
+
+func TestParseHunksOutput_NoNewlineMarker(t *testing.T) {
+ input := `diff --git a/file.go b/file.go
+--- a/file.go
++++ b/file.go
+@@ -5,2 +5,3 @@ func foo() {
++ bar()
+\ No newline at end of file
+`
+ hunks := ParseHunksOutput(input)
+ if len(hunks) != 1 {
+ t.Fatalf("expected 1 hunk, got %d", len(hunks))
+ }
+ if hunks[0].StartLine != 5 || hunks[0].EndLine != 7 {
+ t.Errorf("range = %d-%d, want 5-7", hunks[0].StartLine, hunks[0].EndLine)
+ }
+}
+
+func TestParseRange(t *testing.T) {
+ tests := []struct {
+ input string
+ wantStart int
+ wantCount int
+ }{
+ {"10,5", 10, 5},
+ {"10", 10, 1},
+ {"52,2", 52, 2},
+ {"1,0", 1, 0},
+ }
+ for _, tt := range tests {
+ start, count := parseRange(tt.input)
+ if start != tt.wantStart || count != tt.wantCount {
+ t.Errorf("parseRange(%q) = (%d, %d), want (%d, %d)", tt.input, start, count, tt.wantStart, tt.wantCount)
+ }
+ }
+}
+
+func TestParseHunksOutput_ModeChange(t *testing.T) {
+ input := `diff --git a/script.sh b/script.sh
+old mode 100644
+new mode 100755
+`
+ hunks := ParseHunksOutput(input)
+ if len(hunks) != 0 {
+ t.Fatalf("expected 0 hunks for mode-only change, got %d", len(hunks))
+ }
+}
+
+func TestGitNotFound(t *testing.T) {
+ // Override PATH to ensure git can't be found
+ t.Setenv("PATH", t.TempDir())
+
+ _, err := runGit(t.TempDir(), []string{"status"})
+ if err == nil {
+ t.Fatal("expected error when git is not found")
+ }
+ if !strings.Contains(err.Error(), "git not found in PATH") {
+ t.Errorf("expected 'git not found in PATH' error, got: %v", err)
+ }
+}
+
+func TestParseHunksOutput_Deletion(t *testing.T) {
+ // Deletion hunks have +start,0 — should still produce a valid hunk at start line
+ input := `diff --git a/file.go b/file.go
+--- a/file.go
++++ b/file.go
+@@ -10,3 +10,0 @@ func foo() {
+`
+ hunks := ParseHunksOutput(input)
+ if len(hunks) != 1 {
+ t.Fatalf("expected 1 hunk, got %d", len(hunks))
+ }
+ // count=0, so endLine = start + 0 - 1 = 9, but we clamp to start
+ if hunks[0].StartLine != 10 {
+ t.Errorf("start = %d, want 10", hunks[0].StartLine)
+ }
+}
diff --git a/internal/store/impact.go b/internal/store/impact.go
new file mode 100644
index 000000000..4ac29ea02
--- /dev/null
+++ b/internal/store/impact.go
@@ -0,0 +1,76 @@
+package store
+
+// RiskLevel classifies impact based on BFS hop depth.
+type RiskLevel string
+
+const (
+ RiskCritical RiskLevel = "CRITICAL"
+ RiskHigh RiskLevel = "HIGH"
+ RiskMedium RiskLevel = "MEDIUM"
+ RiskLow RiskLevel = "LOW"
+)
+
+// HopToRisk maps a BFS hop depth to a risk level.
+func HopToRisk(hop int) RiskLevel {
+ switch hop {
+ case 1:
+ return RiskCritical
+ case 2:
+ return RiskHigh
+ case 3:
+ return RiskMedium
+ default:
+ return RiskLow
+ }
+}
+
+// ImpactSummary aggregates risk counts from a BFS traversal.
+type ImpactSummary struct {
+ Critical int `json:"critical"`
+ High int `json:"high"`
+ Medium int `json:"medium"`
+ Low int `json:"low"`
+ Total int `json:"total"`
+ HasCrossService bool `json:"has_cross_service"`
+}
+
+// BuildImpactSummary computes risk distribution from deduplicated node hops.
+func BuildImpactSummary(hops []*NodeHop, edges []EdgeInfo) ImpactSummary {
+ var s ImpactSummary
+ for _, nh := range hops {
+ switch HopToRisk(nh.Hop) {
+ case RiskCritical:
+ s.Critical++
+ case RiskHigh:
+ s.High++
+ case RiskMedium:
+ s.Medium++
+ case RiskLow:
+ s.Low++
+ }
+ s.Total++
+ }
+ for _, e := range edges {
+ if e.Type == "HTTP_CALLS" || e.Type == "ASYNC_CALLS" {
+ s.HasCrossService = true
+ break
+ }
+ }
+ return s
+}
+
+// DeduplicateHops removes duplicate nodes from BFS results, keeping the
+// minimum hop (highest risk) for each node.
+func DeduplicateHops(hops []*NodeHop) []*NodeHop {
+ best := make(map[int64]*NodeHop)
+ for _, nh := range hops {
+ if existing, ok := best[nh.Node.ID]; !ok || nh.Hop < existing.Hop {
+ best[nh.Node.ID] = nh
+ }
+ }
+ result := make([]*NodeHop, 0, len(best))
+ for _, nh := range best {
+ result = append(result, nh)
+ }
+ return result
+}
diff --git a/internal/store/impact_test.go b/internal/store/impact_test.go
new file mode 100644
index 000000000..3ecbd3d2c
--- /dev/null
+++ b/internal/store/impact_test.go
@@ -0,0 +1,108 @@
+package store
+
+import (
+ "sort"
+ "testing"
+)
+
+func TestHopToRisk(t *testing.T) {
+ tests := []struct {
+ hop int
+ want RiskLevel
+ }{
+ {1, RiskCritical},
+ {2, RiskHigh},
+ {3, RiskMedium},
+ {4, RiskLow},
+ {5, RiskLow},
+ {10, RiskLow},
+ }
+ for _, tt := range tests {
+ got := HopToRisk(tt.hop)
+ if got != tt.want {
+ t.Errorf("HopToRisk(%d) = %s, want %s", tt.hop, got, tt.want)
+ }
+ }
+}
+
+func TestBuildImpactSummary(t *testing.T) {
+ hops := []*NodeHop{
+ {Node: &Node{ID: 1}, Hop: 1},
+ {Node: &Node{ID: 2}, Hop: 1},
+ {Node: &Node{ID: 3}, Hop: 2},
+ {Node: &Node{ID: 4}, Hop: 3},
+ {Node: &Node{ID: 5}, Hop: 4},
+ }
+ edges := []EdgeInfo{
+ {FromName: "A", ToName: "B", Type: "CALLS"},
+ }
+
+ s := BuildImpactSummary(hops, edges)
+
+ if s.Critical != 2 {
+ t.Errorf("critical = %d, want 2", s.Critical)
+ }
+ if s.High != 1 {
+ t.Errorf("high = %d, want 1", s.High)
+ }
+ if s.Medium != 1 {
+ t.Errorf("medium = %d, want 1", s.Medium)
+ }
+ if s.Low != 1 {
+ t.Errorf("low = %d, want 1", s.Low)
+ }
+ if s.Total != 5 {
+ t.Errorf("total = %d, want 5", s.Total)
+ }
+ if s.HasCrossService {
+ t.Error("expected has_cross_service=false")
+ }
+}
+
+func TestCrossServiceDetection(t *testing.T) {
+ hops := []*NodeHop{{Node: &Node{ID: 1}, Hop: 1}}
+ edges := []EdgeInfo{
+ {FromName: "A", ToName: "B", Type: "HTTP_CALLS"},
+ }
+ s := BuildImpactSummary(hops, edges)
+ if !s.HasCrossService {
+ t.Error("expected has_cross_service=true for HTTP_CALLS")
+ }
+
+ edges2 := []EdgeInfo{
+ {FromName: "A", ToName: "B", Type: "ASYNC_CALLS"},
+ }
+ s2 := BuildImpactSummary(hops, edges2)
+ if !s2.HasCrossService {
+ t.Error("expected has_cross_service=true for ASYNC_CALLS")
+ }
+}
+
+func TestDeduplicateHops(t *testing.T) {
+ hops := []*NodeHop{
+ {Node: &Node{ID: 1, Name: "A"}, Hop: 2},
+ {Node: &Node{ID: 1, Name: "A"}, Hop: 3}, // duplicate at higher hop
+ {Node: &Node{ID: 2, Name: "B"}, Hop: 1},
+ {Node: &Node{ID: 3, Name: "C"}, Hop: 3},
+ }
+
+ result := DeduplicateHops(hops)
+
+ // Sort for deterministic comparison
+ sort.Slice(result, func(i, j int) bool {
+ return result[i].Node.ID < result[j].Node.ID
+ })
+
+ if len(result) != 3 {
+ t.Fatalf("expected 3 nodes, got %d", len(result))
+ }
+ if result[0].Node.ID != 1 || result[0].Hop != 2 {
+ t.Errorf("node 1: expected hop=2, got hop=%d", result[0].Hop)
+ }
+ if result[1].Node.ID != 2 || result[1].Hop != 1 {
+ t.Errorf("node 2: expected hop=1, got hop=%d", result[1].Hop)
+ }
+ if result[2].Node.ID != 3 || result[2].Hop != 3 {
+ t.Errorf("node 3: expected hop=3, got hop=%d", result[2].Hop)
+ }
+}
diff --git a/internal/store/nodes.go b/internal/store/nodes.go
index d9c5ffde1..5550af1fa 100644
--- a/internal/store/nodes.go
+++ b/internal/store/nodes.go
@@ -154,6 +154,21 @@ func (s *Store) FindNodesByIDs(ids []int64) (map[int64]*Node, error) {
return result, nil
}
+// FindNodesByFileOverlap returns nodes whose line range overlaps [startLine, endLine].
+// The fileSuffix is matched with LIKE '%' || ? against the file_path column to handle
+// relative/absolute path differences.
+func (s *Store) FindNodesByFileOverlap(project, fileSuffix string, startLine, endLine int) ([]*Node, error) {
+ rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
+ FROM nodes WHERE project=? AND file_path LIKE '%' || ? AND start_line <= ? AND end_line >= ?
+ AND label NOT IN ('Project', 'Package', 'Folder', 'File', 'Module')`,
+ project, fileSuffix, endLine, startLine)
+ if err != nil {
+ return nil, fmt.Errorf("find by file overlap: %w", err)
+ }
+ defer rows.Close()
+ return scanNodes(rows)
+}
+
// AllNodes returns all nodes for a project.
func (s *Store) AllNodes(project string) ([]*Node, error) {
rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index 7b5c1293a..da2da94d9 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -844,3 +844,143 @@ func TestSearchExcludeLabels(t *testing.T) {
}
}
}
+
+func TestFindNodesByFileOverlap(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Create nodes with different line ranges in the same file
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "funcA", QualifiedName: "test.main.funcA", FilePath: "main.go", StartLine: 1, EndLine: 10})
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "funcB", QualifiedName: "test.main.funcB", FilePath: "main.go", StartLine: 12, EndLine: 25})
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "funcC", QualifiedName: "test.main.funcC", FilePath: "other.go", StartLine: 1, EndLine: 50})
+ // Module node should be excluded from overlap results
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Module", Name: "main", QualifiedName: "test.main", FilePath: "main.go", StartLine: 1, EndLine: 100})
+
+ // Overlap with funcA (lines 5-8)
+ nodes, err := s.FindNodesByFileOverlap("test", "main.go", 5, 8)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 1 || nodes[0].Name != "funcA" {
+ t.Errorf("expected funcA, got %d nodes", len(nodes))
+ }
+
+ // Overlap spanning funcA and funcB (lines 8-15)
+ nodes, err = s.FindNodesByFileOverlap("test", "main.go", 8, 15)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 2 {
+ t.Errorf("expected 2 nodes (funcA + funcB), got %d", len(nodes))
+ }
+
+ // No overlap (lines 26-30)
+ nodes, err = s.FindNodesByFileOverlap("test", "main.go", 26, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 0 {
+ t.Errorf("expected 0 nodes, got %d", len(nodes))
+ }
+
+ // Different file
+ nodes, err = s.FindNodesByFileOverlap("test", "other.go", 1, 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 1 || nodes[0].Name != "funcC" {
+ t.Errorf("expected funcC, got %d nodes", len(nodes))
+ }
+}
+
+func TestBFSWithRiskLabels(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Build chain: A -> B -> C -> D
+ idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
+ idB, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
+ idC, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "C", QualifiedName: "test.C"})
+ idD, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "D", QualifiedName: "test.D"})
+
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idB, TargetID: idC, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idC, TargetID: idD, Type: "CALLS"})
+
+ // BFS from A outbound, depth=3
+ result, err := s.BFS(idA, "outbound", []string{"CALLS"}, 3, 200)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Deduplicate (needed for risk labels)
+ deduped := DeduplicateHops(result.Visited)
+ if len(deduped) != 3 {
+ t.Fatalf("expected 3 visited nodes (B,C,D), got %d", len(deduped))
+ }
+
+ // Verify risk labels
+ riskByName := make(map[string]RiskLevel)
+ for _, nh := range deduped {
+ riskByName[nh.Node.Name] = HopToRisk(nh.Hop)
+ }
+ if riskByName["B"] != RiskCritical {
+ t.Errorf("B: expected CRITICAL, got %s", riskByName["B"])
+ }
+ if riskByName["C"] != RiskHigh {
+ t.Errorf("C: expected HIGH, got %s", riskByName["C"])
+ }
+ if riskByName["D"] != RiskMedium {
+ t.Errorf("D: expected MEDIUM, got %s", riskByName["D"])
+ }
+
+ // Build summary
+ summary := BuildImpactSummary(deduped, result.Edges)
+ if summary.Critical != 1 || summary.High != 1 || summary.Medium != 1 {
+ t.Errorf("summary: critical=%d high=%d medium=%d, want 1/1/1", summary.Critical, summary.High, summary.Medium)
+ }
+ if summary.Total != 3 {
+ t.Errorf("total=%d, want 3", summary.Total)
+ }
+}
+
+func TestBFSWithCrossServiceEdges(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+
+ idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
+ idB, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
+
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "HTTP_CALLS"})
+
+ result, err := s.BFS(idA, "outbound", []string{"CALLS", "HTTP_CALLS"}, 1, 200)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ summary := BuildImpactSummary(result.Visited, result.Edges)
+ if !summary.HasCrossService {
+ t.Error("expected has_cross_service=true for HTTP_CALLS edge")
+ }
+}
diff --git a/internal/tools/detect_changes.go b/internal/tools/detect_changes.go
new file mode 100644
index 000000000..7780233fb
--- /dev/null
+++ b/internal/tools/detect_changes.go
@@ -0,0 +1,363 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "sort"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/pipeline"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+func (s *Server) registerDetectChanges() {
+ s.addTool(&mcp.Tool{
+ Name: "detect_changes",
+ Description: "Detect uncommitted or branch changes and map them to affected graph symbols + blast radius. Runs git diff, maps changed hunks to functions/classes in the graph, then traces inbound callers with risk classification (CRITICAL/HIGH/MEDIUM/LOW). Requires git in PATH. Risk is topology-based: hop 1=CRITICAL (direct callers), 2=HIGH, 3=MEDIUM, 4+=LOW.",
+ InputSchema: json.RawMessage(`{
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "description": "Which changes to analyze: 'unstaged' (working tree), 'staged' (git add), 'all' (HEAD, default), 'branch' (compare with base_branch)",
+ "enum": ["unstaged", "staged", "all", "branch"]
+ },
+ "base_branch": {
+ "type": "string",
+ "description": "Base branch for scope=branch comparison (default: main)"
+ },
+ "depth": {
+ "type": "integer",
+ "description": "Maximum BFS depth for impact tracing (1-5, default 3)"
+ },
+ "project": {
+ "type": "string",
+ "description": "Project to analyze. Defaults to session project."
+ }
+ }
+ }`),
+ }, s.handleDetectChanges)
+}
+
+func (s *Server) handleDetectChanges(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ args, err := parseArgs(req)
+ if err != nil {
+ return errResult(err.Error()), nil
+ }
+
+ scopeStr := getStringArg(args, "scope")
+ if scopeStr == "" {
+ scopeStr = "all"
+ }
+ scope := pipeline.DiffScope(scopeStr)
+
+ baseBranch := getStringArg(args, "base_branch")
+ depth := getIntArg(args, "depth", 3)
+ if depth < 1 {
+ depth = 1
+ }
+ if depth > 5 {
+ depth = 5
+ }
+
+ project := getStringArg(args, "project")
+ effectiveProject := s.resolveProjectName(project)
+
+ st, repoPath, projName, resolveErr := s.resolveDetectRepo(effectiveProject)
+ if resolveErr != nil {
+ return resolveErr, nil
+ }
+
+ // Parse changed files
+ changedFiles, err := pipeline.ParseGitDiffFiles(repoPath, scope, baseBranch)
+ if err != nil {
+ return errResult(fmt.Sprintf("git diff: %v", err)), nil
+ }
+
+ if len(changedFiles) == 0 {
+ return s.emptyDetectResponse(), nil
+ }
+
+ // Parse hunks for line-level mapping
+ hunks, err := pipeline.ParseGitDiffHunks(repoPath, scope, baseBranch)
+ if err != nil {
+ slog.Warn("detect_changes.hunks.err", "err", err)
+ }
+
+ changedSymbols := mapChangesToSymbols(st, projName, changedFiles, hunks)
+ impactedSymbols, allEdges := traceImpact(st, changedSymbols, depth)
+ summary := buildDetectSummary(changedFiles, changedSymbols, impactedSymbols, allEdges)
+
+ responseData := map[string]any{
+ "changed_files": buildFileList(changedFiles),
+ "changed_symbols": buildSymbolList(changedSymbols),
+ "impacted_symbols": buildImpactList(impactedSymbols),
+ "summary": summary,
+ }
+ s.addIndexStatus(responseData)
+
+ result := jsonResult(responseData)
+ s.addUpdateNotice(result)
+ return result, nil
+}
+
+// resolveDetectRepo resolves the store, repo path, and project name for detect_changes.
+func (s *Server) resolveDetectRepo(effectiveProject string) (st *store.Store, repoPath, projName string, toolErr *mcp.CallToolResult) {
+ var err error
+ st, err = s.resolveStore(effectiveProject)
+ if err != nil {
+ return nil, "", "", errResult(err.Error())
+ }
+
+ projects, _ := st.ListProjects()
+ if len(projects) == 0 {
+ return nil, "", "", errResult("no projects indexed")
+ }
+ projName = projects[0].Name
+ proj, err := st.GetProject(projName)
+ if err != nil {
+ return nil, "", "", errResult(fmt.Sprintf("project %q: %v", effectiveProject, err))
+ }
+ if proj == nil {
+ return nil, "", "", errResult(fmt.Sprintf("project %q not found", effectiveProject))
+ }
+ if proj.RootPath == "" {
+ return nil, "", "", errResult("project has no root_path — reindex with repo_path")
+ }
+ return st, proj.RootPath, projName, nil
+}
+
+func (s *Server) emptyDetectResponse() *mcp.CallToolResult {
+ responseData := map[string]any{
+ "changed_files": []any{},
+ "changed_symbols": []any{},
+ "impacted_symbols": []any{},
+ "summary": map[string]any{
+ "changed_files": 0,
+ "changed_symbols": 0,
+ "critical": 0,
+ "high": 0,
+ "medium": 0,
+ "low": 0,
+ "total": 0,
+ "has_cross_service": false,
+ },
+ }
+ s.addIndexStatus(responseData)
+ result := jsonResult(responseData)
+ s.addUpdateNotice(result)
+ return result
+}
+
+func buildFileList(files []pipeline.ChangedFile) []map[string]any {
+ result := make([]map[string]any, len(files))
+ for i, f := range files {
+ entry := map[string]any{"status": f.Status, "path": f.Path}
+ if f.OldPath != "" {
+ entry["old_path"] = f.OldPath
+ }
+ result[i] = entry
+ }
+ return result
+}
+
+func buildSymbolList(symbols []*store.Node) []map[string]any {
+ result := make([]map[string]any, len(symbols))
+ for i, n := range symbols {
+ result[i] = map[string]any{
+ "name": n.Name,
+ "qualified_name": n.QualifiedName,
+ "label": n.Label,
+ "file_path": n.FilePath,
+ "start_line": n.StartLine,
+ "end_line": n.EndLine,
+ }
+ }
+ return result
+}
+
+func buildImpactList(impacted []impactedSymbol) []map[string]any {
+ result := make([]map[string]any, len(impacted))
+ for i, is := range impacted {
+ result[i] = map[string]any{
+ "name": is.Node.Name,
+ "qualified_name": is.Node.QualifiedName,
+ "label": is.Node.Label,
+ "file_path": is.Node.FilePath,
+ "risk": string(store.HopToRisk(is.Hop)),
+ "hop": is.Hop,
+ "changed_by": is.ChangedBy,
+ }
+ }
+ return result
+}
+
+// impactedSymbol extends NodeHop with the symbol that caused the impact.
+type impactedSymbol struct {
+ Node *store.Node
+ Hop int
+ ChangedBy string // name of the changed symbol that led to this impact
+}
+
+// mapChangesToSymbols finds graph nodes affected by the changed hunks.
+func mapChangesToSymbols(st *store.Store, project string, files []pipeline.ChangedFile, hunks []pipeline.ChangedHunk) []*store.Node {
+ seen := make(map[int64]bool)
+ var result []*store.Node
+
+ hunksByFile := make(map[string][]pipeline.ChangedHunk)
+ for _, h := range hunks {
+ hunksByFile[h.Path] = append(hunksByFile[h.Path], h)
+ }
+
+ for _, f := range files {
+ if f.Status == "D" {
+ continue
+ }
+ nodes := resolveFileSymbols(st, project, f.Path, hunksByFile[f.Path])
+ for _, n := range nodes {
+ if !seen[n.ID] {
+ seen[n.ID] = true
+ result = append(result, n)
+ }
+ }
+ }
+
+ if len(result) == 0 && len(files) > 0 {
+ logZeroSymbolsDiag(files)
+ }
+
+ return result
+}
+
+// resolveFileSymbols finds symbols for a single file, using hunk-level overlap when available.
+func resolveFileSymbols(st *store.Store, project, path string, hunks []pipeline.ChangedHunk) []*store.Node {
+ if len(hunks) > 0 {
+ return resolveByHunks(st, project, path, hunks)
+ }
+ return resolveByFile(st, project, path)
+}
+
+func resolveByHunks(st *store.Store, project, path string, hunks []pipeline.ChangedHunk) []*store.Node {
+ var result []*store.Node
+ for _, h := range hunks {
+ nodes, err := st.FindNodesByFileOverlap(project, path, h.StartLine, h.EndLine)
+ if err != nil {
+ slog.Debug("detect_changes.overlap.err", "path", path, "err", err)
+ continue
+ }
+ result = append(result, nodes...)
+ }
+ return result
+}
+
+func resolveByFile(st *store.Store, project, path string) []*store.Node {
+ nodes, err := st.FindNodesByFile(project, path)
+ if err != nil {
+ slog.Debug("detect_changes.file.err", "path", path, "err", err)
+ return nil
+ }
+ if len(nodes) == 0 {
+ nodes, err = st.FindNodesByFileOverlap(project, path, 0, 999999)
+ if err != nil {
+ return nil
+ }
+ }
+ return nodes
+}
+
+func logZeroSymbolsDiag(files []pipeline.ChangedFile) {
+ paths := make([]string, 0, 3)
+ for i, f := range files {
+ if i >= 3 {
+ break
+ }
+ paths = append(paths, f.Path)
+ }
+ slog.Warn("detect_changes.zero_symbols", "diff_paths", paths)
+}
+
+// traceImpact runs inbound BFS from each changed symbol and deduplicates results.
+func traceImpact(st *store.Store, changedSymbols []*store.Node, depth int) ([]impactedSymbol, []store.EdgeInfo) {
+ edgeTypes := []string{"CALLS", "HTTP_CALLS", "ASYNC_CALLS"}
+ bestHop := make(map[int64]*impactedSymbol)
+ changedIDs := make(map[int64]bool)
+ var allEdges []store.EdgeInfo
+
+ for _, sym := range changedSymbols {
+ changedIDs[sym.ID] = true
+ }
+
+ for _, sym := range changedSymbols {
+ result, err := st.BFS(sym.ID, "inbound", edgeTypes, depth, 200)
+ if err != nil {
+ slog.Debug("detect_changes.bfs.err", "sym", sym.Name, "err", err)
+ continue
+ }
+
+ for _, nh := range result.Visited {
+ if changedIDs[nh.Node.ID] {
+ continue // skip the changed symbols themselves
+ }
+ existing, ok := bestHop[nh.Node.ID]
+ if !ok || nh.Hop < existing.Hop {
+ bestHop[nh.Node.ID] = &impactedSymbol{
+ Node: nh.Node,
+ Hop: nh.Hop,
+ ChangedBy: sym.Name,
+ }
+ }
+ }
+ allEdges = append(allEdges, result.Edges...)
+ }
+
+ // Sort by risk (hop ascending)
+ sorted := make([]impactedSymbol, 0, len(bestHop))
+ for _, is := range bestHop {
+ sorted = append(sorted, *is)
+ }
+ sort.Slice(sorted, func(i, j int) bool {
+ if sorted[i].Hop != sorted[j].Hop {
+ return sorted[i].Hop < sorted[j].Hop
+ }
+ return sorted[i].Node.Name < sorted[j].Node.Name
+ })
+
+ return sorted, allEdges
+}
+
+func buildDetectSummary(files []pipeline.ChangedFile, symbols []*store.Node, impacted []impactedSymbol, edges []store.EdgeInfo) map[string]any {
+ var critical, high, medium, low int
+ for _, is := range impacted {
+ switch store.HopToRisk(is.Hop) {
+ case store.RiskCritical:
+ critical++
+ case store.RiskHigh:
+ high++
+ case store.RiskMedium:
+ medium++
+ case store.RiskLow:
+ low++
+ }
+ }
+
+ hasCrossService := false
+ for _, e := range edges {
+ if e.Type == "HTTP_CALLS" || e.Type == "ASYNC_CALLS" {
+ hasCrossService = true
+ break
+ }
+ }
+
+ return map[string]any{
+ "changed_files": len(files),
+ "changed_symbols": len(symbols),
+ "critical": critical,
+ "high": high,
+ "medium": medium,
+ "low": low,
+ "total": len(impacted),
+ "has_cross_service": hasCrossService,
+ }
+}
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
index d0c104c90..02db97d3e 100644
--- a/internal/tools/tools.go
+++ b/internal/tools/tools.go
@@ -23,7 +23,7 @@ import (
)
// Version is the current release version, referenced by MCP handshake and update checker.
-const Version = "0.2.1-dev"
+const Version = "0.3.1"
// releaseURL is the GitHub API endpoint for latest release. Package-level var for test injection.
var releaseURL = "https://api.github.com/repos/DeusData/codebase-memory-mcp/releases/latest"
@@ -369,6 +369,7 @@ func (s *Server) registerTools() {
s.registerFileTools()
s.registerProjectTools()
s.registerTraceTools()
+ s.registerDetectChanges()
}
// registerGraphTools registers tools for graph querying, searching, and tracing.
@@ -413,6 +414,10 @@ func (s *Server) registerIndexAndTraceTool() {
"description": "Traversal direction: 'outbound' (what it calls), 'inbound' (what calls it), or 'both'",
"enum": ["outbound", "inbound", "both"]
},
+ "risk_labels": {
+ "type": "boolean",
+ "description": "Add risk classification (CRITICAL/HIGH/MEDIUM/LOW) based on hop depth. Hop 1=CRITICAL, 2=HIGH, 3=MEDIUM, 4+=LOW. Includes impact_summary with counts. Default false."
+ },
"project": {
"type": "string",
"description": "Project to trace in. Defaults to session project."
@@ -461,7 +466,7 @@ func (s *Server) registerSchemaAndSnippetTools() {
func (s *Server) registerSearchTools() {
s.addTool(&mcp.Tool{
Name: "search_graph",
- Description: "Search the code knowledge graph for functions, classes, modules, routes, and other code elements. Returns nodes matching the criteria with their connectivity (in/out degree). Results are sorted by relevance by default (exact match first, prefix match second, then by connectivity). Community nodes are excluded by default. Pass exclude_labels: [] to include them. Best practice: Chain with trace_call_path and get_code_snippet for complete answers. Example workflow: search_graph(name_pattern='.*Order.*') → trace_call_path(function_name='processOrder') → get_code_snippet(qualified_name='...'). Returns 10 results per page (use offset to paginate, has_more indicates more pages). For dead code: use relationship='CALLS', direction='inbound', max_degree=0, exclude_entry_points=true. For fan-out: use relationship='CALLS', direction='outbound', min_degree=N. Route nodes: properties.handler contains the actual handler function name. Prefer this over query_graph for counting — no row cap. IMPORTANT: The 'relationship' filter counts how many edges of that type each node has (degree filtering) — it does NOT return the actual edges. To list cross-service HTTP_CALLS or ASYNC_CALLS edges with their properties, use query_graph with Cypher instead. Relationship types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",
+ Description: "Search the code knowledge graph for functions, classes, modules, routes, and other code elements. Returns nodes matching the criteria with their connectivity (in/out degree). Results are sorted by relevance by default (exact match first, prefix match second, then by connectivity). Community nodes are excluded by default. Pass exclude_labels: [] to include them. Best practice: Chain with trace_call_path and get_code_snippet for complete answers. Example workflow: search_graph(name_pattern='.*Order.*') → trace_call_path(function_name='processOrder') → get_code_snippet(qualified_name='...'). Returns 10 results per page (use offset to paginate, has_more indicates more pages). name_pattern and qn_pattern support full Go regex — one precise regex replaces multiple literal searches. See parameter descriptions for patterns. For dead code: use relationship='CALLS', direction='inbound', max_degree=0, exclude_entry_points=true. For fan-out: use relationship='CALLS', direction='outbound', min_degree=N. Route nodes: properties.handler contains the actual handler function name. Prefer this over query_graph for counting — no row cap. IMPORTANT: The 'relationship' filter counts how many edges of that type each node has (degree filtering) — it does NOT return the actual edges. To list cross-service HTTP_CALLS or ASYNC_CALLS edges with their properties, use query_graph with Cypher instead. Relationship types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",
InputSchema: json.RawMessage(`{
"type": "object",
"properties": {
@@ -475,11 +480,11 @@ func (s *Server) registerSearchTools() {
},
"name_pattern": {
"type": "string",
- "description": "Regex pattern matched against the short node name only (e.g. '.*Handler', 'Send.*'). Does NOT match against file paths or qualified names."
+ "description": "Regex pattern matched against the short node name only. Supports full Go regex: '.*Handler$' (suffix), '(?i)auth' (case-insensitive), 'get|set|delete' (alternatives), '^on[A-Z]' (prefix+char class). Does NOT match against file paths or qualified names — use qn_pattern for path scoping."
},
"qn_pattern": {
"type": "string",
- "description": "Regex pattern matched against the qualified name (includes module path, e.g. '.*tests\\.conftest\\..*', '.*services\\.order\\..*'). Use this to scope searches to specific directories or modules."
+ "description": "Regex pattern matched against the qualified name (full module path). Use to scope searches to directories/modules: '.*services\\.order\\..*' (order service), '.*tests\\..*' (test files only), '(?i).*controller.*\\.handle.*' (handler methods in controllers). Combine with name_pattern for precise cross-cutting queries."
},
"file_pattern": {
"type": "string",
@@ -534,13 +539,13 @@ func (s *Server) registerSearchTools() {
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.",
+ Description: "Search for text in source code files (like grep, scoped to indexed project). Returns matching lines with file path, line number, and context. Returns 10 matches per page — use offset to paginate, has_more indicates more pages. Use for: string literals, error messages, TODO comments, config values, import statements. With regex=true, supports full Go regex — see pattern parameter for examples. Prefer search_graph for finding functions/classes by name — search_code is for text content that isn't in the graph.",
InputSchema: json.RawMessage(`{
"type": "object",
"properties": {
"pattern": {
"type": "string",
- "description": "Text to search for (literal string, or regex if regex=true)"
+ "description": "Text to search for. Literal string by default; with regex=true supports full Go regex (e.g. 'err != nil', 'TODO|FIXME', '(?i)deprecated')"
},
"file_pattern": {
"type": "string",
diff --git a/internal/tools/trace.go b/internal/tools/trace.go
index 8f67f6fda..72789c2f7 100644
--- a/internal/tools/trace.go
+++ b/internal/tools/trace.go
@@ -34,6 +34,8 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest
direction = "outbound"
}
+ riskLabels := getBoolArg(args, "risk_labels")
+
project := getStringArg(args, "project")
effectiveProject := s.resolveProjectName(project)
@@ -70,62 +72,70 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest
edgeTypes := []string{"CALLS", "HTTP_CALLS", "ASYNC_CALLS"}
- // Build root info
- root := buildNodeInfo(rootNode)
+ allVisited, allEdges, bfsErr := runTraceBFS(st, rootNode.ID, direction, edgeTypes, depth)
+ if bfsErr != nil {
+ return errResult(fmt.Sprintf("bfs err: %v", bfsErr)), nil
+ }
- // Get module info
- moduleInfo := s.getModuleInfo(st, rootNode, foundProject)
+ if riskLabels {
+ allVisited = store.DeduplicateHops(allVisited)
+ }
- // Run BFS
- var allVisited []*store.NodeHop
- var allEdges []store.EdgeInfo
+ var hops []hopEntry
+ if riskLabels {
+ hops = buildHopsWithRisk(allVisited)
+ } else {
+ hops = buildHops(allVisited)
+ }
+ responseData := buildTraceResponse(st, rootNode, foundProject, hops, allVisited, allEdges)
+ if riskLabels {
+ responseData["impact_summary"] = store.BuildImpactSummary(allVisited, allEdges)
+ }
+ responseData["module"] = s.getModuleInfo(st, rootNode, foundProject)
+ s.addIndexStatus(responseData)
+
+ result := jsonResult(responseData)
+ s.addUpdateNotice(result)
+ return result, nil
+}
+
+func runTraceBFS(st *store.Store, rootID int64, direction string, edgeTypes []string, depth int) ([]*store.NodeHop, []store.EdgeInfo, error) {
if direction == "both" {
- outResult, outErr := st.BFS(rootNode.ID, "outbound", edgeTypes, depth, 200)
+ var allVisited []*store.NodeHop
+ var allEdges []store.EdgeInfo
+ outResult, outErr := st.BFS(rootID, "outbound", edgeTypes, depth, 200)
if outErr == nil {
allVisited = append(allVisited, outResult.Visited...)
allEdges = append(allEdges, outResult.Edges...)
}
- inResult, inErr := st.BFS(rootNode.ID, "inbound", edgeTypes, depth, 200)
+ inResult, inErr := st.BFS(rootID, "inbound", edgeTypes, depth, 200)
if inErr == nil {
allVisited = append(allVisited, inResult.Visited...)
allEdges = append(allEdges, inResult.Edges...)
}
- } else {
- result, bfsErr := st.BFS(rootNode.ID, direction, edgeTypes, depth, 200)
- if bfsErr != nil {
- return errResult(fmt.Sprintf("bfs err: %v", bfsErr)), nil
- }
- allVisited = result.Visited
- allEdges = result.Edges
+ return allVisited, allEdges, nil
}
+ result, err := st.BFS(rootID, direction, edgeTypes, depth, 200)
+ if err != nil {
+ return nil, nil, err
+ }
+ return result.Visited, result.Edges, nil
+}
- // Group visited nodes by hop
- hops := buildHops(allVisited)
-
- // Build edge list
- edges := buildEdgeList(allEdges)
-
- // Get indexed_at from project
- proj, _ := st.GetProject(foundProject)
+func buildTraceResponse(st *store.Store, rootNode *store.Node, project string, hops []hopEntry, visited []*store.NodeHop, edges []store.EdgeInfo) map[string]any {
+ proj, _ := st.GetProject(project)
indexedAt := ""
if proj != nil {
indexedAt = proj.IndexedAt
}
-
- responseData := map[string]any{
- "root": root,
- "module": moduleInfo,
+ return map[string]any{
+ "root": buildNodeInfo(rootNode),
"hops": hops,
- "edges": edges,
+ "edges": buildEdgeList(edges),
"indexed_at": indexedAt,
- "total_results": len(allVisited),
+ "total_results": len(visited),
}
- s.addIndexStatus(responseData)
-
- result := jsonResult(responseData)
- s.addUpdateNotice(result)
- return result, nil
}
func buildNodeInfo(n *store.Node) map[string]any {
@@ -196,6 +206,31 @@ func buildHops(visited []*store.NodeHop) []hopEntry {
return hops
}
+func buildHopsWithRisk(visited []*store.NodeHop) []hopEntry {
+ hopMap := map[int][]map[string]any{}
+ for _, nh := range visited {
+ info := map[string]any{
+ "name": nh.Node.Name,
+ "qualified_name": nh.Node.QualifiedName,
+ "label": nh.Node.Label,
+ "risk": string(store.HopToRisk(nh.Hop)),
+ "hop": nh.Hop,
+ }
+ if sig, ok := nh.Node.Properties["signature"]; ok {
+ info["signature"] = sig
+ }
+ hopMap[nh.Hop] = append(hopMap[nh.Hop], info)
+ }
+
+ var hops []hopEntry
+ for h := 1; h <= len(hopMap); h++ {
+ if nodes, ok := hopMap[h]; ok {
+ hops = append(hops, hopEntry{Hop: h, Nodes: nodes})
+ }
+ }
+ return hops
+}
+
// findSimilarNodes searches for nodes whose name contains the input string (case-insensitive).
func (s *Server) findSimilarNodes(name, project string, limit int) []*store.Node {
effectiveProject := s.resolveProjectName(project)