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.

Add auto-sync watcher, fix WithTransaction data race, add infra file indexing

Martin Vogel860e80c88f4f
diff --git a/README.md b/README.md
index baff41ed8..ce18c79fd 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@ Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/
- **12 languages**: Python, Go, JavaScript, TypeScript, TSX, Rust, Java, C++, C#, PHP, Lua, Scala
- **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
- **Incremental reindex**: Content-hash based — only re-parses changed files
- **Cypher-like queries**: `MATCH (f:Function)-[:CALLS]->(g) WHERE f.name = 'main' RETURN g.name`
- **Dead code detection**: Finds functions with zero callers, excluding entry points (route handlers, `main()`, framework-decorated functions)
@@ -206,7 +207,15 @@ Claude Code will call `index_repository` with your project's root path and build
> **Note**: `index_repository` requires a `repo_path` parameter. When you say "Index this project", Claude Code infers the path from its working directory. If indexing fails, pass the path explicitly: `index_repository(repo_path="/absolute/path/to/project")`.
-**When to reindex**: Run `index_repository` again after adding new files, moving functions, or making significant code changes. Incremental reindex is fast — only changed files are re-parsed (content-hash based). Check staleness with `list_projects` which shows `indexed_at` timestamps.
+### Auto-Sync
+
+After the initial `index_repository` call, the graph **stays fresh automatically**. A background watcher polls indexed projects for file changes (mtime + size) and triggers incremental re-indexing when changes are detected. You don't need to manually call `index_repository` again — just edit your code and the graph updates within seconds.
+
+- **Adaptive polling**: The interval scales with repo size (1s for small repos, up to 60s for very large ones)
+- **Non-blocking**: Auto-sync never blocks tool queries — if a manual `index_repository` is in progress, the watcher skips that cycle
+- **Incremental**: Only changed files are re-parsed (content-hash based), so even triggered re-indexes are fast
+
+You can still call `index_repository` manually at any time to force an immediate reindex (e.g. after a large `git pull`).
## MCP Tools
@@ -214,8 +223,8 @@ Claude Code will call `index_repository` with your project's root path and build
| Tool | Key Parameters | Description |
|------|---------------|-------------|
-| `index_repository` | `repo_path` (required) | Index a repository into the graph. Supports incremental reindex via content hashing — only changed files are re-parsed. |
-| `list_projects` | — | List all indexed projects with `indexed_at` timestamps and node/edge counts. Use to check if a reindex is needed. |
+| `index_repository` | `repo_path` (required) | Index a repository into the graph. Only needed once — auto-sync keeps it fresh after that. Supports incremental reindex via content hashing. |
+| `list_projects` | — | List all indexed projects with `indexed_at` timestamps and node/edge counts. |
| `delete_project` | `project_name` (required) | Remove a project and all its graph data. Irreversible. |
### Querying
@@ -414,7 +423,7 @@ Add to `~/.claude/CLAUDE.md`:
When this MCP server is available, **prefer graph tools over grep/Explore for structural code questions**.
Graph queries return precise results in a single tool call (~500 tokens) vs file-by-file exploration (~80K tokens).
-- **Before exploration/planning**: Run `index_repository` to ensure the graph is current
+- **Initial index**: Run `index_repository` once per project — auto-sync keeps it fresh after that
- **"Who calls X?"**: `trace_call_path(function_name="X", direction="inbound")`
- **"What does X call?"**: `trace_call_path(function_name="X", direction="outbound")`
- **Find functions by pattern**: `search_graph(label="Function", name_pattern=".*Pattern.*")`
@@ -436,37 +445,7 @@ Add the same snippet to a specific project's `CLAUDE.md` if you only want it act
### Option C: Claude Code skill file
-Create `~/.claude/skills/codebase-memory.md` for automatic activation when relevant:
-
-```markdown
-# codebase-memory-mcp Skill
-
-## When to use
-- Structural code questions: "who calls X?", "what does X depend on?", "show me the call chain"
-- Dead code analysis: functions with zero callers
-- Cross-service tracing: HTTP call paths between microservices
-- Architecture overview: understanding module boundaries and dependencies
-- Pre-planning: index before designing changes to understand blast radius
-
-## When NOT to use
-- Text search (use grep/Glob instead)
-- Single file reads (use Read tool instead)
-- Syntax/formatting questions (not a graph concern)
-
-## Workflow
-1. **Ensure freshness**: `list_projects` to check `indexed_at`. If stale, `index_repository`.
-2. **Understand schema**: `get_graph_schema` to see what's indexed (node counts, edge types).
-3. **Search**: `search_graph` for filtered queries, `trace_call_path` for call chains.
-4. **Deep dive**: `get_code_snippet` to read source of interesting functions.
-5. **Complex queries**: `query_graph` with Cypher for multi-hop patterns.
-
-## Tips
-- `trace_call_path` with `direction="both"` shows full context (callers + callees)
-- `search_graph` with `file_pattern` scopes results to a service/directory
-- Route nodes (`label="Route"`) let you query REST endpoints as graph entities
-- Edge properties on HTTP_CALLS include `confidence` and `url_path`
-- Reindex after significant code changes (new files, moved functions)
-```
+Copy [`skills/codebase-memory-mcp.md`](skills/codebase-memory-mcp.md) from this repo to `~/.claude/skills/codebase-memory-mcp/SKILL.md` for automatic activation when relevant. This is the most comprehensive option — it includes decision matrices, query pitfalls, and workflow patterns.
## Ignoring Files (`.cgrignore`)
@@ -515,7 +494,7 @@ make install # go install
| `get_code_snippet` returns "node not found" | Wrong qualified name format | Use `search_graph` first to find the exact `qualified_name`, then pass it to `get_code_snippet`. See [Qualified Names](#qualified-names). |
| `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 | Index is stale | Re-run `index_repository`. Incremental reindex only re-parses changed files. |
+| 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. |
| 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. |
@@ -531,6 +510,7 @@ internal/
httplink/ Cross-service HTTP route/call-site matching
cypher/ Cypher query lexer, parser, planner, executor
tools/ MCP tool handlers (11 tools)
+ 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 5adbe2056..c0ef38bf2 100644
--- a/cmd/codebase-memory-mcp/main.go
+++ b/cmd/codebase-memory-mcp/main.go
@@ -25,7 +25,11 @@ func main() {
srv := tools.NewServer(s)
- runErr := srv.MCPServer().Run(context.Background(), &mcp.StdioTransport{})
+ ctx, cancel := context.WithCancel(context.Background())
+ srv.StartWatcher(ctx)
+
+ runErr := srv.MCPServer().Run(ctx, &mcp.StdioTransport{})
+ cancel()
s.Close()
if runErr != nil {
log.Fatalf("server err=%v", runErr)
diff --git a/go.mod b/go.mod
index a2333176a..bb5a3301f 100644
--- a/go.mod
+++ b/go.mod
@@ -15,6 +15,7 @@ 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
+ gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.37.1
)
diff --git a/go.sum b/go.sum
index a8194852e..4351bca6f 100644
--- a/go.sum
+++ b/go.sum
@@ -77,6 +77,8 @@ 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=
+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=
diff --git a/internal/pipeline/infrascan.go b/internal/pipeline/infrascan.go
new file mode 100644
index 000000000..6e4f45d06
--- /dev/null
+++ b/internal/pipeline/infrascan.go
@@ -0,0 +1,496 @@
+package pipeline
+
+import (
+ "bufio"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/discover"
+ "github.com/DeusData/codebase-memory-mcp/internal/fqn"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+// infraFile holds parsed metadata from an infrastructure file.
+type infraFile struct {
+ relPath string
+ infraType string
+ properties map[string]any
+}
+
+// passInfraFiles walks the repo, detects infrastructure files, parses them,
+// and creates File + InfraFile nodes for each.
+func (p *Pipeline) passInfraFiles() {
+ var infras []infraFile
+
+ _ = filepath.Walk(p.RepoPath, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if info.IsDir() {
+ if discover.IGNORE_PATTERNS[info.Name()] {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ for suffix := range discover.IGNORE_SUFFIXES {
+ if strings.HasSuffix(info.Name(), suffix) {
+ return nil
+ }
+ }
+ if info.Size() > 1<<20 {
+ return nil
+ }
+
+ relPath, _ := filepath.Rel(p.RepoPath, path)
+ if relPath == "" {
+ return nil
+ }
+ relPath = filepath.ToSlash(relPath)
+
+ parsed := parseInfraFile(path, relPath, info.Name())
+ infras = append(infras, parsed...)
+ return nil
+ })
+
+ if len(infras) == 0 {
+ return
+ }
+
+ for _, inf := range infras {
+ p.upsertInfraNodes(inf)
+ }
+ slog.Info("pass4.infra", "nodes", len(infras))
+}
+
+// parseInfraFile routes a file to the appropriate parser based on its name.
+func parseInfraFile(absPath, relPath, name string) []infraFile {
+ lower := strings.ToLower(name)
+
+ ext := strings.ToLower(filepath.Ext(name))
+
+ switch {
+ case isDockerfile(lower):
+ return parseDockerfile(absPath, relPath)
+ case isComposeFile(lower):
+ return parseComposeFile(absPath, relPath)
+ case isCloudbuildFile(lower):
+ return parseCloudbuildFile(absPath, relPath)
+ case isEnvFile(lower):
+ return parseDotenvFile(absPath, relPath)
+ case ext == ".tf":
+ return parseTerraformFile(absPath, relPath)
+ case isShellScript(lower, ext):
+ return parseShellScript(absPath, relPath)
+ default:
+ return nil
+ }
+}
+
+// isComposeFile returns true for docker-compose/compose YAML files.
+func isComposeFile(name string) bool {
+ lower := strings.ToLower(name)
+ if strings.HasPrefix(lower, "docker-compose") || lower == "compose.yml" || lower == "compose.yaml" {
+ ext := filepath.Ext(lower)
+ return ext == ".yml" || ext == ".yaml"
+ }
+ return false
+}
+
+// isCloudbuildFile returns true for cloudbuild YAML files.
+func isCloudbuildFile(name string) bool {
+ lower := strings.ToLower(name)
+ if strings.HasPrefix(lower, "cloudbuild") {
+ ext := filepath.Ext(lower)
+ return ext == ".yml" || ext == ".yaml"
+ }
+ return false
+}
+
+// upsertInfraNodes creates a File node (for search_code) and an InfraFile node
+// (for structured graph queries) for each infrastructure file.
+func (p *Pipeline) upsertInfraNodes(inf infraFile) {
+ // File node — enables search_code (which queries label="File")
+ fileQN := fqn.Compute(p.ProjectName, inf.relPath, "") + ".__file__"
+ _, _ = p.Store.UpsertNode(&store.Node{
+ Project: p.ProjectName,
+ Label: "File",
+ Name: filepath.Base(inf.relPath),
+ QualifiedName: fileQN,
+ FilePath: inf.relPath,
+ Properties: map[string]any{"extension": filepath.Ext(inf.relPath)},
+ })
+
+ // InfraFile node — structured metadata queryable via query_graph
+ infraQN := p.infraQN(inf.relPath, inf.properties)
+ _, _ = p.Store.UpsertNode(&store.Node{
+ Project: p.ProjectName,
+ Label: "InfraFile",
+ Name: filepath.Base(inf.relPath),
+ QualifiedName: infraQN,
+ FilePath: inf.relPath,
+ Properties: inf.properties,
+ })
+}
+
+// infraQN builds the qualified name for an InfraFile node.
+// For compose services: project.path.docker-compose::service-name
+// For others: project.path.__infra__
+func (p *Pipeline) infraQN(relPath string, props map[string]any) string {
+ base := fqn.Compute(p.ProjectName, relPath, "")
+
+ // Compose services get a per-service QN suffix
+ if sn, ok := props["service_name"].(string); ok && props["infra_type"] == "compose-service" {
+ return base + "::" + sn
+ }
+ return base + ".__infra__"
+}
+
+// --- Dockerfile parser (regex) ---
+
+var (
+ reFrom = regexp.MustCompile(`(?i)^FROM\s+(\S+)(?:\s+AS\s+(\w+))?`)
+ reExpose = regexp.MustCompile(`(?i)^EXPOSE\s+(.+)`)
+ reEnv = regexp.MustCompile(`(?i)^ENV\s+(\w+)[= ](.+)`)
+ reArg = regexp.MustCompile(`(?i)^ARG\s+(\w+)(?:=(.+))?`)
+ reWorkdir = regexp.MustCompile(`(?i)^WORKDIR\s+(.+)`)
+ reCmd = regexp.MustCompile(`(?i)^CMD\s+(.+)`)
+ reEntrypoint = regexp.MustCompile(`(?i)^ENTRYPOINT\s+(.+)`)
+ reUser = regexp.MustCompile(`(?i)^USER\s+(\w+)`)
+ reHealthcheck = regexp.MustCompile(`(?i)^HEALTHCHECK\s+.*CMD\s+(.+)`)
+)
+
+func parseDockerfile(absPath, relPath string) []infraFile {
+ f, err := os.Open(absPath)
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ var d dockerfileState
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ d.parseLine(line)
+ }
+
+ props := d.toProperties()
+ if len(props) == 0 {
+ return nil
+ }
+ return []infraFile{{relPath: relPath, infraType: "dockerfile", properties: props}}
+}
+
+// dockerfileState accumulates parsed Dockerfile directives.
+type dockerfileState struct {
+ stages []map[string]string
+ ports []string
+ envVars map[string]string
+ args []string
+ workdir string
+ cmd string
+ entry string
+ health string
+ user string
+}
+
+func (d *dockerfileState) parseLine(line string) {
+ d.parseFrom(line)
+ d.parseExpose(line)
+ d.parseEnvArg(line)
+ d.parseDirectives(line)
+}
+
+func (d *dockerfileState) parseFrom(line string) {
+ if m := reFrom.FindStringSubmatch(line); m != nil {
+ stage := map[string]string{"image": m[1]}
+ if m[2] != "" {
+ stage["name"] = m[2]
+ }
+ d.stages = append(d.stages, stage)
+ }
+}
+
+func (d *dockerfileState) parseExpose(line string) {
+ if m := reExpose.FindStringSubmatch(line); m != nil {
+ ports := strings.Fields(m[1])
+ for _, port := range ports {
+ // Strip protocol suffix (e.g. 8080/tcp)
+ port = strings.Split(port, "/")[0]
+ d.ports = append(d.ports, port)
+ }
+ }
+}
+
+func (d *dockerfileState) parseEnvArg(line string) {
+ if m := reEnv.FindStringSubmatch(line); m != nil {
+ key, val := m[1], strings.TrimSpace(m[2])
+ if !isSecretBinding(key, val) {
+ if d.envVars == nil {
+ d.envVars = make(map[string]string)
+ }
+ d.envVars[key] = val
+ }
+ }
+ if m := reArg.FindStringSubmatch(line); m != nil {
+ d.args = append(d.args, m[1])
+ }
+}
+
+func (d *dockerfileState) parseDirectives(line string) {
+ if m := reWorkdir.FindStringSubmatch(line); m != nil {
+ d.workdir = strings.TrimSpace(m[1])
+ }
+ if m := reCmd.FindStringSubmatch(line); m != nil {
+ d.cmd = cleanJSONBrackets(strings.TrimSpace(m[1]))
+ }
+ if m := reEntrypoint.FindStringSubmatch(line); m != nil {
+ d.entry = cleanJSONBrackets(strings.TrimSpace(m[1]))
+ }
+ if m := reUser.FindStringSubmatch(line); m != nil {
+ d.user = m[1]
+ }
+ if m := reHealthcheck.FindStringSubmatch(line); m != nil {
+ d.health = strings.TrimSpace(m[1])
+ }
+}
+
+func (d *dockerfileState) toProperties() map[string]any {
+ if len(d.stages) == 0 {
+ return nil
+ }
+
+ props := map[string]any{
+ "infra_type": "dockerfile",
+ }
+
+ // base_image = last stage's image (final runtime image)
+ lastImage := d.stages[len(d.stages)-1]["image"]
+ props["base_image"] = lastImage
+
+ // base_images = all unique images
+ images := make([]string, 0, len(d.stages))
+ for _, s := range d.stages {
+ images = append(images, s["image"])
+ }
+ props["base_images"] = images
+
+ // stages with name/image
+ props["stages"] = d.stages
+
+ setNonEmpty(props, "exposed_ports", d.ports)
+ setNonEmptyMap(props, "env_vars", d.envVars)
+ setNonEmpty(props, "build_args", d.args)
+ setNonEmptyStr(props, "workdir", d.workdir)
+ setNonEmptyStr(props, "cmd", d.cmd)
+ setNonEmptyStr(props, "entrypoint", d.entry)
+ setNonEmptyStr(props, "healthcheck", d.health)
+ setNonEmptyStr(props, "user", d.user)
+
+ return props
+}
+
+// --- .env file parser ---
+
+var reDotenvLine = regexp.MustCompile(`^([A-Za-z_]\w*)=(.*)$`)
+
+func parseDotenvFile(absPath, relPath string) []infraFile {
+ f, err := os.Open(absPath)
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ envVars := make(map[string]string)
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ if m := reDotenvLine.FindStringSubmatch(line); m != nil {
+ key, val := m[1], strings.Trim(m[2], `"'`)
+ if !isSecretBinding(key, val) {
+ envVars[key] = val
+ }
+ }
+ }
+
+ if len(envVars) == 0 {
+ return nil
+ }
+
+ props := map[string]any{
+ "infra_type": "env",
+ "env_vars": envVars,
+ }
+ return []infraFile{{relPath: relPath, infraType: "env", properties: props}}
+}
+
+// --- Shell script parser ---
+
+// isShellScript returns true for shell script files.
+func isShellScript(name, ext string) bool {
+ _ = name // reserved for future name-based detection
+ return ext == ".sh" || ext == ".bash" || ext == ".zsh"
+}
+
+var (
+ reShebang = regexp.MustCompile(`^#!\s*(.+)`)
+ reExportVar = regexp.MustCompile(`^export\s+(\w+)=(.*)`)
+ reShellVar = regexp.MustCompile(`^(\w+)=["']?([^"'\n]*)["']?`)
+ reSourceFile = regexp.MustCompile(`^(?:source|\.) ["']?(\S+)["']?`)
+ reDockerCmd = regexp.MustCompile(`^(docker(?:-compose)?)\s+(\w+)`)
+)
+
+func parseShellScript(absPath, relPath string) []infraFile {
+ f, err := os.Open(absPath)
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ var st shellState
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ st.parseLine(line)
+ }
+
+ props := st.toProperties()
+ if len(props) <= 1 {
+ return nil
+ }
+ return []infraFile{{relPath: relPath, infraType: "shell", properties: props}}
+}
+
+// shellState accumulates parsed shell script metadata.
+type shellState struct {
+ shebang string
+ envVars map[string]string
+ sources []string
+ dockerCmds []string
+}
+
+func (s *shellState) parseLine(line string) {
+ if line == "" {
+ return
+ }
+
+ // Shebang (first non-empty line starting with #!)
+ if s.shebang == "" {
+ if m := reShebang.FindStringSubmatch(line); m != nil {
+ s.shebang = strings.TrimSpace(m[1])
+ return
+ }
+ }
+
+ // Skip comments
+ if strings.HasPrefix(line, "#") {
+ return
+ }
+
+ s.parseVarsAndCmds(line)
+}
+
+func (s *shellState) parseVarsAndCmds(line string) {
+ // Exported env vars
+ if m := reExportVar.FindStringSubmatch(line); m != nil {
+ s.addEnvVar(m[1], strings.Trim(m[2], `"'`))
+ return
+ }
+
+ // Plain var assignments (only at line start, not inside commands)
+ if m := reShellVar.FindStringSubmatch(line); m != nil && !strings.Contains(line, " ") {
+ s.addEnvVar(m[1], m[2])
+ return
+ }
+
+ // Source/dot includes
+ if m := reSourceFile.FindStringSubmatch(line); m != nil {
+ s.sources = append(s.sources, m[1])
+ return
+ }
+
+ // Docker commands
+ if m := reDockerCmd.FindStringSubmatch(line); m != nil {
+ s.dockerCmds = append(s.dockerCmds, m[1]+" "+m[2])
+ }
+}
+
+func (s *shellState) addEnvVar(key, val string) {
+ if isSecretBinding(key, val) {
+ return
+ }
+ if s.envVars == nil {
+ s.envVars = make(map[string]string)
+ }
+ s.envVars[key] = val
+}
+
+func (s *shellState) toProperties() map[string]any {
+ props := map[string]any{
+ "infra_type": "shell",
+ }
+ setNonEmptyStr(props, "shebang", s.shebang)
+ setNonEmptyMap(props, "env_vars", s.envVars)
+ setNonEmpty(props, "sources", s.sources)
+ setNonEmpty(props, "docker_commands", s.dockerCmds)
+ return props
+}
+
+// --- Property helpers ---
+
+func setNonEmpty(m map[string]any, key string, val []string) {
+ if len(val) > 0 {
+ m[key] = val
+ }
+}
+
+func setNonEmptyMap(m map[string]any, key string, val map[string]string) {
+ if len(val) > 0 {
+ m[key] = val
+ }
+}
+
+func setNonEmptyStr(m map[string]any, key, val string) {
+ if val != "" {
+ m[key] = val
+ }
+}
+
+// cleanJSONBrackets strips JSON array brackets from CMD/ENTRYPOINT values.
+// e.g. ["./app", "--flag"] → ./app --flag
+func cleanJSONBrackets(s string) string {
+ if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
+ inner := s[1 : len(s)-1]
+ inner = strings.ReplaceAll(inner, `"`, "")
+ inner = strings.ReplaceAll(inner, ",", " ")
+ return collapseSpaces(strings.TrimSpace(inner))
+ }
+ return s
+}
+
+// collapseSpaces replaces runs of whitespace with a single space.
+func collapseSpaces(s string) string {
+ var b strings.Builder
+ b.Grow(len(s))
+ inSpace := false
+ for _, r := range s {
+ if r == ' ' || r == '\t' {
+ if !inSpace {
+ b.WriteByte(' ')
+ inSpace = true
+ }
+ } else {
+ b.WriteRune(r)
+ inSpace = false
+ }
+ }
+ return b.String()
+}
diff --git a/internal/pipeline/infrascan_test.go b/internal/pipeline/infrascan_test.go
new file mode 100644
index 000000000..bfaae7913
--- /dev/null
+++ b/internal/pipeline/infrascan_test.go
@@ -0,0 +1,927 @@
+package pipeline
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+// --- Dockerfile parser tests ---
+
+func TestParseDockerfile(t *testing.T) {
+ tests := []struct {
+ name string
+ content string
+ check func(t *testing.T, props map[string]any)
+ }{
+ {
+ name: "multi-stage with all directives",
+ content: `FROM golang:1.23-alpine AS builder
+WORKDIR /app
+ARG SSH_PRIVATE_KEY
+RUN go build -o server .
+
+FROM alpine:3.19
+WORKDIR /usr/app
+ENV PORT=8080
+ENV PYTHONUNBUFFERED=1
+EXPOSE 8080 443
+USER appuser
+CMD ["./server"]
+HEALTHCHECK CMD wget http://localhost:8080/health
+`,
+ check: func(t *testing.T, props map[string]any) {
+ t.Helper()
+ assertEqual(t, props["infra_type"], "dockerfile")
+ assertEqual(t, props["base_image"], "alpine:3.19")
+ assertSliceContains(t, props["base_images"], "golang:1.23-alpine")
+ assertSliceContains(t, props["base_images"], "alpine:3.19")
+ assertSliceContains(t, props["exposed_ports"], "8080")
+ assertSliceContains(t, props["exposed_ports"], "443")
+ assertEqual(t, props["workdir"], "/usr/app")
+ assertEqual(t, props["user"], "appuser")
+ assertEqual(t, props["cmd"], "./server")
+ assertEqual(t, props["healthcheck"], "wget http://localhost:8080/health")
+
+ envVars := requireMapStringString(t, props["env_vars"])
+ assertEqual(t, envVars["PORT"], "8080")
+ assertEqual(t, envVars["PYTHONUNBUFFERED"], "1")
+
+ assertSliceContains(t, props["build_args"], "SSH_PRIVATE_KEY")
+ },
+ },
+ {
+ name: "single stage with entrypoint",
+ content: `FROM python:3.9-slim
+ENTRYPOINT ["python", "main.py"]
+`,
+ check: func(t *testing.T, props map[string]any) {
+ t.Helper()
+ assertEqual(t, props["base_image"], "python:3.9-slim")
+ assertEqual(t, props["entrypoint"], "python main.py")
+
+ stages, ok := props["stages"].([]map[string]string)
+ if !ok {
+ t.Fatal("stages is not []map[string]string")
+ }
+ if len(stages) != 1 {
+ t.Fatalf("stages len: got %d, want 1", len(stages))
+ }
+ },
+ },
+ {
+ name: "secret env vars filtered",
+ content: `FROM node:20
+ENV API_KEY=sk-1234567890abcdef12345
+ENV DATABASE_URL=https://db.example.com
+ENV JWT_SECRET=supersecret
+`,
+ check: func(t *testing.T, props map[string]any) {
+ t.Helper()
+ envVars := requireMapStringString(t, props["env_vars"])
+ if _, ok := envVars["API_KEY"]; ok {
+ t.Error("API_KEY should be filtered as secret value")
+ }
+ if _, ok := envVars["JWT_SECRET"]; ok {
+ t.Error("JWT_SECRET should be filtered as secret key")
+ }
+ assertEqual(t, envVars["DATABASE_URL"], "https://db.example.com")
+ },
+ },
+ {
+ name: "expose with protocol suffix",
+ content: `FROM nginx:latest
+EXPOSE 80/tcp 443/tcp
+`,
+ check: func(t *testing.T, props map[string]any) {
+ t.Helper()
+ assertSliceContains(t, props["exposed_ports"], "80")
+ assertSliceContains(t, props["exposed_ports"], "443")
+ },
+ },
+ {
+ name: "ENV space-separated format",
+ content: `FROM python:3.9
+ENV PYTHONPATH /usr/app
+`,
+ check: func(t *testing.T, props map[string]any) {
+ t.Helper()
+ envVars := requireMapStringString(t, props["env_vars"])
+ assertEqual(t, envVars["PYTHONPATH"], "/usr/app")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ path := writeTempFile(t, "Dockerfile", tt.content)
+ result := parseDockerfile(path, "Dockerfile")
+ if len(result) == 0 {
+ t.Fatal("expected at least one result")
+ }
+ tt.check(t, result[0].properties)
+ })
+ }
+}
+
+func TestParseDockerfileEmpty(t *testing.T) {
+ path := writeTempFile(t, "Dockerfile", "# just a comment\n")
+ result := parseDockerfile(path, "Dockerfile")
+ if len(result) != 0 {
+ t.Errorf("expected empty result for comment-only Dockerfile, got %d", len(result))
+ }
+}
+
+// --- docker-compose parser tests ---
+
+func TestParseComposeFile(t *testing.T) {
+ content := `
+services:
+ auth-service:
+ build:
+ context: ./auth-service
+ ports:
+ - "8080:8080"
+ environment:
+ PORT: "8080"
+ JWT_SECRET: "should-be-filtered"
+ depends_on:
+ - db
+ networks:
+ - backend
+ container_name: my-auth
+ volumes:
+ - ./data:/app/data
+
+ db:
+ image: postgres:15-alpine
+ expose:
+ - "5432"
+ environment:
+ - POSTGRES_DB=mydb
+ - POSTGRES_PASSWORD=secret-should-filter
+`
+
+ path := writeTempFile(t, "docker-compose.yml", content)
+ results := parseComposeFile(path, "docker-compose.yml")
+ if len(results) != 2 {
+ t.Fatalf("expected 2 services, got %d", len(results))
+ }
+
+ // Find auth-service
+ var auth, db *infraFile
+ for i := range results {
+ sn, ok := results[i].properties["service_name"].(string)
+ if !ok {
+ t.Fatal("service_name is not a string")
+ }
+ switch sn {
+ case "auth-service":
+ auth = &results[i]
+ case "db":
+ db = &results[i]
+ }
+ }
+
+ if auth == nil || db == nil {
+ t.Fatal("missing expected services")
+ }
+
+ // auth-service checks
+ assertEqual(t, auth.properties["infra_type"], "compose-service")
+ assertEqual(t, auth.properties["build_context"], "./auth-service")
+ assertSliceContains(t, auth.properties["ports"], "8080:8080")
+ assertEqual(t, auth.properties["container_name"], "my-auth")
+
+ authEnv := requireMapStringString(t, auth.properties["environment"])
+ assertEqual(t, authEnv["PORT"], "8080")
+ if _, ok := authEnv["JWT_SECRET"]; ok {
+ t.Error("JWT_SECRET should be filtered")
+ }
+
+ assertSliceContains(t, auth.properties["depends_on"], "db")
+ assertSliceContains(t, auth.properties["networks"], "backend")
+
+ // db checks
+ assertEqual(t, db.properties["image"], "postgres:15-alpine")
+ assertSliceContains(t, db.properties["expose"], "5432")
+}
+
+func TestParseComposeMapDependsOn(t *testing.T) {
+ content := `
+services:
+ web:
+ image: nginx:latest
+ depends_on:
+ api:
+ condition: service_healthy
+ cache:
+ condition: service_started
+`
+ path := writeTempFile(t, "docker-compose.yml", content)
+ results := parseComposeFile(path, "docker-compose.yml")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 service, got %d", len(results))
+ }
+ deps, ok := results[0].properties["depends_on"].([]string)
+ if !ok {
+ t.Fatal("depends_on is not []string")
+ }
+ if len(deps) != 2 {
+ t.Fatalf("expected 2 deps, got %d", len(deps))
+ }
+}
+
+func TestParseComposeStringBuild(t *testing.T) {
+ content := `
+services:
+ app:
+ build: ./myapp
+`
+ path := writeTempFile(t, "docker-compose.yml", content)
+ results := parseComposeFile(path, "docker-compose.yml")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 service, got %d", len(results))
+ }
+ assertEqual(t, results[0].properties["build_context"], "./myapp")
+}
+
+// --- cloudbuild parser tests ---
+
+func TestParseCloudbuildFile(t *testing.T) {
+ content := `
+substitutions:
+ _SERVICE_NAME: order-processor
+ _REGION: europe-west3
+
+steps:
+ - name: gcr.io/cloud-builders/docker
+ args: ['build', '-t', 'eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME', '.']
+
+ - name: gcr.io/google.com/cloudsdktool/cloud-sdk
+ args:
+ - gcloud
+ - run
+ - deploy
+ - $_SERVICE_NAME
+ - --image=eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME
+ - --region=$_REGION
+ - --cpu=2
+ - --memory=4Gi
+ - --concurrency=1
+ - --max-instances=1
+ - --timeout=3600s
+ - --ingress=internal
+ - --set-env-vars=SOURCE_ENTITY=$_SERVICE_NAME,LOG_LEVEL=INFO
+
+images:
+ - eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME
+`
+
+ path := writeTempFile(t, "cloudbuild.yaml", content)
+ results := parseCloudbuildFile(path, "cloudbuild.yaml")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result, got %d", len(results))
+ }
+
+ props := results[0].properties
+ assertEqual(t, props["infra_type"], "cloudbuild")
+ assertEqual(t, props["service_name"], "order-processor")
+ assertEqual(t, props["deploy_region"], "$_REGION")
+ assertEqual(t, props["deploy_cpu"], "2")
+ assertEqual(t, props["deploy_memory"], "4Gi")
+ assertEqual(t, props["deploy_concurrency"], "1")
+ assertEqual(t, props["deploy_max_instances"], "1")
+ assertEqual(t, props["deploy_timeout"], "3600s")
+ assertEqual(t, props["deploy_ingress"], "internal")
+ assertEqual(t, props["image_registry"], "eu.gcr.io/$PROJECT_ID/$_SERVICE_NAME")
+
+ envVars := requireMapStringString(t, props["deploy_env_vars"])
+ assertEqual(t, envVars["SOURCE_ENTITY"], "$_SERVICE_NAME")
+ assertEqual(t, envVars["LOG_LEVEL"], "INFO")
+}
+
+func TestParseCloudbuildSeparateFlags(t *testing.T) {
+ content := `
+steps:
+ - name: gcr.io/google.com/cloudsdktool/cloud-sdk
+ args:
+ - gcloud
+ - run
+ - deploy
+ - my-service
+ - --region
+ - us-central1
+ - --memory
+ - 1Gi
+`
+ path := writeTempFile(t, "cloudbuild.yaml", content)
+ results := parseCloudbuildFile(path, "cloudbuild.yaml")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result, got %d", len(results))
+ }
+ props := results[0].properties
+ assertEqual(t, props["deploy_region"], "us-central1")
+ assertEqual(t, props["deploy_memory"], "1Gi")
+}
+
+// --- .env file parser tests ---
+
+func TestParseDotenvFile(t *testing.T) {
+ content := `# Database config
+DATABASE_HOST=localhost
+DATABASE_PORT=5432
+DATABASE_NAME=mydb
+API_SECRET=should-not-appear
+PLAIN_VALUE=hello world
+`
+ path := writeTempFile(t, ".env", content)
+ results := parseDotenvFile(path, ".env")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result, got %d", len(results))
+ }
+
+ envVars := requireMapStringString(t, results[0].properties["env_vars"])
+ assertEqual(t, envVars["DATABASE_HOST"], "localhost")
+ assertEqual(t, envVars["DATABASE_PORT"], "5432")
+ assertEqual(t, envVars["PLAIN_VALUE"], "hello world")
+
+ if _, ok := envVars["API_SECRET"]; ok {
+ t.Error("API_SECRET should be filtered")
+ }
+}
+
+func TestParseDotenvQuotedValues(t *testing.T) {
+ content := `KEY1="quoted value"
+KEY2='single quoted'
+`
+ path := writeTempFile(t, ".env", content)
+ results := parseDotenvFile(path, ".env")
+ if len(results) != 1 {
+ t.Fatal("expected 1 result")
+ }
+ envVars := requireMapStringString(t, results[0].properties["env_vars"])
+ assertEqual(t, envVars["KEY1"], "quoted value")
+ assertEqual(t, envVars["KEY2"], "single quoted")
+}
+
+// --- File identification tests ---
+
+func TestIsComposeFile(t *testing.T) {
+ tests := []struct {
+ name string
+ expect bool
+ }{
+ {"docker-compose.yml", true},
+ {"docker-compose.yaml", true},
+ {"docker-compose.prod.yml", true},
+ {"compose.yml", true},
+ {"compose.yaml", true},
+ {"mycompose.yml", false},
+ {"docker-compose.txt", false},
+ {"Dockerfile", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isComposeFile(tt.name); got != tt.expect {
+ t.Errorf("isComposeFile(%q) = %v, want %v", tt.name, got, tt.expect)
+ }
+ })
+ }
+}
+
+func TestIsCloudbuildFile(t *testing.T) {
+ tests := []struct {
+ name string
+ expect bool
+ }{
+ {"cloudbuild.yaml", true},
+ {"cloudbuild.yml", true},
+ {"cloudbuild-prod.yaml", true},
+ {"Cloudbuild.yml", true},
+ {"build.yaml", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isCloudbuildFile(tt.name); got != tt.expect {
+ t.Errorf("isCloudbuildFile(%q) = %v, want %v", tt.name, got, tt.expect)
+ }
+ })
+ }
+}
+
+// --- Terraform parser tests ---
+
+func TestParseTerraformFile(t *testing.T) {
+ content := `
+terraform {
+ required_providers {
+ google = {
+ source = "hashicorp/google"
+ version = "~> 6.35.0"
+ }
+ }
+ backend "gcs" {
+ bucket = "hoepke-tf"
+ prefix = "state"
+ }
+}
+
+variable "project_id" {
+ description = "The GCP project ID"
+ type = string
+ default = "hoepke-cloud"
+}
+
+variable "region" {
+ description = "The region"
+ type = string
+}
+
+resource "google_cloud_run_service" "main" {
+ name = "my-service"
+ location = var.region
+}
+
+resource "google_compute_address" "nat_ip" {
+ name = "nat-ip"
+ region = var.region
+}
+
+output "service_url" {
+ value = google_cloud_run_service.main.status[0].url
+}
+
+data "google_project" "project" {
+}
+
+module "vpc" {
+ source = "./modules/vpc"
+}
+
+locals {
+ env = "prod"
+}
+`
+ path := writeTempFile(t, "main.tf", content)
+ results := parseTerraformFile(path, "opentofu/main.tf")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result, got %d", len(results))
+ }
+
+ props := results[0].properties
+ assertEqual(t, props["infra_type"], "terraform")
+ assertEqual(t, props["backend"], "gcs")
+
+ t.Run("resources", func(t *testing.T) { verifyTFResources(t, props) })
+ t.Run("variables", func(t *testing.T) { verifyTFVariables(t, props) })
+ t.Run("other_blocks", func(t *testing.T) { verifyTFOtherBlocks(t, props) })
+}
+
+func verifyTFResources(t *testing.T, props map[string]any) {
+ t.Helper()
+ resources, ok := props["resources"].([]map[string]string)
+ if !ok {
+ t.Fatal("resources is not []map[string]string")
+ }
+ if len(resources) != 2 {
+ t.Fatalf("expected 2 resources, got %d", len(resources))
+ }
+ foundCloudRun := false
+ for _, r := range resources {
+ if r["type"] == "google_cloud_run_service" && r["name"] == "main" {
+ foundCloudRun = true
+ }
+ }
+ if !foundCloudRun {
+ t.Error("missing google_cloud_run_service.main resource")
+ }
+}
+
+func verifyTFVariables(t *testing.T, props map[string]any) {
+ t.Helper()
+ variables, ok := props["variables"].([]map[string]string)
+ if !ok {
+ t.Fatal("variables is not []map[string]string")
+ }
+ if len(variables) != 2 {
+ t.Fatalf("expected 2 variables, got %d", len(variables))
+ }
+ for _, v := range variables {
+ if v["name"] == "project_id" {
+ assertEqual(t, v["default"], "hoepke-cloud")
+ assertEqual(t, v["type"], "string")
+ assertEqual(t, v["description"], "The GCP project ID")
+ return
+ }
+ }
+ t.Error("missing project_id variable")
+}
+
+func verifyTFOtherBlocks(t *testing.T, props map[string]any) {
+ t.Helper()
+ assertSliceContains(t, props["outputs"], "service_url")
+
+ dataSources, ok := props["data_sources"].([]map[string]string)
+ if !ok {
+ t.Fatal("data_sources is not []map[string]string")
+ }
+ if len(dataSources) != 1 {
+ t.Fatalf("expected 1 data source, got %d", len(dataSources))
+ }
+
+ modules, ok := props["modules"].([]map[string]string)
+ if !ok {
+ t.Fatal("modules is not []map[string]string")
+ }
+ if len(modules) != 1 {
+ t.Fatalf("expected 1 module, got %d", len(modules))
+ }
+ assertEqual(t, modules[0]["name"], "vpc")
+ assertEqual(t, modules[0]["source"], "./modules/vpc")
+
+ if props["has_locals"] != true {
+ t.Error("expected has_locals=true")
+ }
+}
+
+func TestParseTerraformVariablesOnly(t *testing.T) {
+ content := `
+variable "project_id" {
+ description = "The GCP project ID"
+ type = string
+ default = "hoepke-cloud"
+}
+
+variable "secret_key" {
+ description = "A secret"
+ type = string
+ default = "sk-1234567890abcdef12345"
+}
+`
+ path := writeTempFile(t, "variables.tf", content)
+ results := parseTerraformFile(path, "opentofu/variables.tf")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result, got %d", len(results))
+ }
+
+ variables, ok := results[0].properties["variables"].([]map[string]string)
+ if !ok {
+ t.Fatal("variables is not []map[string]string")
+ }
+
+ // Secret default should be filtered
+ for _, v := range variables {
+ if v["name"] == "secret_key" {
+ if _, hasDefault := v["default"]; hasDefault {
+ t.Error("secret_key default should be filtered")
+ }
+ }
+ }
+}
+
+func TestParseTerraformEmpty(t *testing.T) {
+ path := writeTempFile(t, "empty.tf", "# just comments\n")
+ results := parseTerraformFile(path, "empty.tf")
+ if len(results) != 0 {
+ t.Errorf("expected empty result for comment-only .tf, got %d", len(results))
+ }
+}
+
+// --- Shell script parser tests ---
+
+func TestParseShellScript(t *testing.T) {
+ content := `#!/bin/bash
+set -e
+
+# Configuration
+YOUR_CONTAINER_NAME="order-email-extractor-endpoint"
+DOCKERFILE_PATH="/path/to/dockerfile"
+
+export ENVIRONMENT="development"
+export USE_STACKDRIVER="false"
+
+# Shut down existing containers
+./shut-down-docker-container.sh
+
+docker build -t "$YOUR_CONTAINER_NAME" "$DOCKERFILE_PATH"
+docker run -d --name "$YOUR_CONTAINER_NAME" "$YOUR_CONTAINER_NAME"
+docker-compose up -d
+`
+ path := writeTempFile(t, "run.sh", content)
+ results := parseShellScript(path, "scripts/run.sh")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result, got %d", len(results))
+ }
+
+ props := results[0].properties
+ assertEqual(t, props["infra_type"], "shell")
+ assertEqual(t, props["shebang"], "/bin/bash")
+
+ envVars := requireMapStringString(t, props["env_vars"])
+ assertEqual(t, envVars["ENVIRONMENT"], "development")
+ assertEqual(t, envVars["YOUR_CONTAINER_NAME"], "order-email-extractor-endpoint")
+
+ assertSliceContains(t, props["docker_commands"], "docker build")
+ assertSliceContains(t, props["docker_commands"], "docker run")
+ assertSliceContains(t, props["docker_commands"], "docker-compose up")
+}
+
+func TestParseShellScriptWithSource(t *testing.T) {
+ content := `#!/usr/bin/env bash
+source ./config.sh
+. /etc/profile.d/env.sh
+`
+ path := writeTempFile(t, "init.sh", content)
+ results := parseShellScript(path, "init.sh")
+ if len(results) != 1 {
+ t.Fatal("expected 1 result")
+ }
+
+ props := results[0].properties
+ assertEqual(t, props["shebang"], "/usr/bin/env bash")
+ assertSliceContains(t, props["sources"], "./config.sh")
+ assertSliceContains(t, props["sources"], "/etc/profile.d/env.sh")
+}
+
+func TestParseShellScriptSecretFiltered(t *testing.T) {
+ content := `#!/bin/bash
+export API_SECRET="should-not-appear"
+export DATABASE_URL="https://db.example.com"
+`
+ path := writeTempFile(t, "env.sh", content)
+ results := parseShellScript(path, "env.sh")
+ if len(results) != 1 {
+ t.Fatal("expected 1 result")
+ }
+
+ envVars := requireMapStringString(t, results[0].properties["env_vars"])
+ if _, ok := envVars["API_SECRET"]; ok {
+ t.Error("API_SECRET should be filtered")
+ }
+ assertEqual(t, envVars["DATABASE_URL"], "https://db.example.com")
+}
+
+func TestParseShellScriptShebanOnly(t *testing.T) {
+ // A script with only shebang still produces a result (shebang is useful metadata)
+ path := writeTempFile(t, "empty.sh", "#!/bin/bash\n# just comments\n")
+ results := parseShellScript(path, "empty.sh")
+ if len(results) != 1 {
+ t.Fatalf("expected 1 result for shebang-only .sh, got %d", len(results))
+ }
+ assertEqual(t, results[0].properties["shebang"], "/bin/bash")
+}
+
+func TestParseShellScriptTrulyEmpty(t *testing.T) {
+ path := writeTempFile(t, "empty.sh", "# no shebang, just comments\n")
+ results := parseShellScript(path, "empty.sh")
+ if len(results) != 0 {
+ t.Errorf("expected empty result for no-shebang .sh, got %d", len(results))
+ }
+}
+
+func TestIsShellScript(t *testing.T) {
+ tests := []struct {
+ name string
+ ext string
+ expect bool
+ }{
+ {"run.sh", ".sh", true},
+ {"deploy.bash", ".bash", true},
+ {"init.zsh", ".zsh", true},
+ {"main.py", ".py", false},
+ {"Dockerfile", "", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isShellScript(tt.name, tt.ext); got != tt.expect {
+ t.Errorf("isShellScript(%q, %q) = %v, want %v", tt.name, tt.ext, got, tt.expect)
+ }
+ })
+ }
+}
+
+// --- Integration test: passInfraFiles creates nodes ---
+
+func TestPassInfraFilesIntegration(t *testing.T) {
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ // Create a temp repo with infra files
+ tmpDir := t.TempDir()
+ writeFile(t, filepath.Join(tmpDir, "Dockerfile"), `FROM alpine:3.19
+EXPOSE 8080
+`)
+ writeFile(t, filepath.Join(tmpDir, ".env"), `APP_PORT=8080
+`)
+ writeFile(t, filepath.Join(tmpDir, "docker-compose.yml"), `
+services:
+ web:
+ image: nginx:latest
+ ports:
+ - "80:80"
+`)
+
+ p := New(s, tmpDir)
+ err = s.WithTransaction(func(txStore *store.Store) error {
+ p.Store = txStore
+ _ = txStore.UpsertProject(p.ProjectName, tmpDir)
+ p.passInfraFiles()
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Verify InfraFile nodes were created
+ infraNodes, err := s.FindNodesByLabel(p.ProjectName, "InfraFile")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(infraNodes) < 3 {
+ t.Errorf("expected at least 3 InfraFile nodes, got %d", len(infraNodes))
+ }
+
+ // Verify File nodes were also created (for search_code)
+ fileNodes, err := s.FindNodesByLabel(p.ProjectName, "File")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(fileNodes) < 3 {
+ t.Errorf("expected at least 3 File nodes, got %d", len(fileNodes))
+ }
+
+ // Verify no Module nodes were created (InfraFile, not Module)
+ moduleNodes, err := s.FindNodesByLabel(p.ProjectName, "Module")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(moduleNodes) != 0 {
+ t.Errorf("expected 0 Module nodes from infra scan, got %d", len(moduleNodes))
+ }
+
+ // Check InfraFile properties
+ for _, n := range infraNodes {
+ infraType, ok := n.Properties["infra_type"].(string)
+ if !ok {
+ t.Errorf("node %s missing infra_type", n.QualifiedName)
+ continue
+ }
+ switch infraType {
+ case "dockerfile":
+ assertEqual(t, n.Properties["base_image"], "alpine:3.19")
+ case "env":
+ envVars, eOk := n.Properties["env_vars"].(map[string]any)
+ if !eOk {
+ t.Fatal("env_vars is not map[string]any")
+ }
+ assertEqual(t, envVars["APP_PORT"], "8080")
+ case "compose-service":
+ assertEqual(t, n.Properties["service_name"], "web")
+ }
+ }
+}
+
+// TestPassInfraFilesIdempotent verifies that re-running passInfraFiles
+// does not create duplicate nodes (upsert behavior).
+func TestPassInfraFilesIdempotent(t *testing.T) {
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ tmpDir := t.TempDir()
+ writeFile(t, filepath.Join(tmpDir, "Dockerfile"), `FROM alpine:3.19
+EXPOSE 8080
+`)
+
+ p := New(s, tmpDir)
+ err = s.WithTransaction(func(txStore *store.Store) error {
+ p.Store = txStore
+ _ = txStore.UpsertProject(p.ProjectName, tmpDir)
+ p.passInfraFiles()
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ countBefore, _ := s.CountNodes(p.ProjectName)
+
+ // Run again — should delete and recreate (same count)
+ err = s.WithTransaction(func(txStore *store.Store) error {
+ p.Store = txStore
+ _ = txStore.DeleteNodesByLabel(p.ProjectName, "InfraFile")
+ p.passInfraFiles()
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ countAfter, _ := s.CountNodes(p.ProjectName)
+ if countBefore != countAfter {
+ t.Errorf("node count changed: before=%d, after=%d", countBefore, countAfter)
+ }
+}
+
+// --- cleanJSONBrackets tests ---
+
+func TestCleanJSONBrackets(t *testing.T) {
+ tests := []struct {
+ input string
+ want string
+ }{
+ {`["./server"]`, `./server`},
+ {`["python", "main.py"]`, `python main.py`},
+ {`./server`, `./server`},
+ {`["./app", "--flag", "value"]`, `./app --flag value`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got := cleanJSONBrackets(tt.input)
+ if got != tt.want {
+ t.Errorf("cleanJSONBrackets(%q) = %q, want %q", tt.input, got, tt.want)
+ }
+ })
+ }
+}
+
+// --- infraQN tests ---
+
+func TestInfraQN(t *testing.T) {
+ p := &Pipeline{ProjectName: "myproject"}
+
+ // Regular infra file
+ qn := p.infraQN("docker-images/service/Dockerfile", map[string]any{"infra_type": "dockerfile"})
+ if !strings.Contains(qn, ".__infra__") {
+ t.Errorf("expected __infra__ suffix, got %s", qn)
+ }
+
+ // Compose service gets per-service suffix
+ qn = p.infraQN("docker-compose.yml", map[string]any{
+ "infra_type": "compose-service",
+ "service_name": "web",
+ })
+ if !strings.Contains(qn, "::web") {
+ t.Errorf("expected ::web suffix, got %s", qn)
+ }
+}
+
+// --- helpers ---
+
+func writeTempFile(t *testing.T, name, content string) string {
+ t.Helper()
+ dir := t.TempDir()
+ path := filepath.Join(dir, name)
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+// requireMapStringString asserts the value is map[string]string (from parsed props)
+// and returns it. Fails the test if not.
+func requireMapStringString(t *testing.T, v any) map[string]string {
+ t.Helper()
+ m, ok := v.(map[string]string)
+ if !ok {
+ t.Fatalf("expected map[string]string, got %T", v)
+ }
+ return m
+}
+
+func assertEqual(t *testing.T, got, want any) {
+ t.Helper()
+ gotStr, _ := got.(string)
+ wantStr, _ := want.(string)
+ if gotStr != wantStr {
+ t.Errorf("got %v, want %v", got, want)
+ }
+}
+
+func assertSliceContains(t *testing.T, sliceAny any, want string) {
+ t.Helper()
+ switch s := sliceAny.(type) {
+ case []string:
+ for _, v := range s {
+ if v == want {
+ return
+ }
+ }
+ case []any:
+ for _, v := range s {
+ if v == want {
+ return
+ }
+ }
+ }
+ t.Errorf("slice %v does not contain %q", sliceAny, want)
+}
diff --git a/internal/pipeline/infrascan_tf.go b/internal/pipeline/infrascan_tf.go
new file mode 100644
index 000000000..034b129c1
--- /dev/null
+++ b/internal/pipeline/infrascan_tf.go
@@ -0,0 +1,209 @@
+package pipeline
+
+import (
+ "bufio"
+ "os"
+ "regexp"
+ "strings"
+)
+
+// --- Terraform parser (regex, line-oriented with brace tracking) ---
+
+var (
+ reResource = regexp.MustCompile(`^resource\s+"(\S+)"\s+"(\S+)"`)
+ reVariable = regexp.MustCompile(`^variable\s+"(\S+)"`)
+ reOutput = regexp.MustCompile(`^output\s+"(\S+)"`)
+ reProvider = regexp.MustCompile(`^provider\s+"(\S+)"`)
+ reTFModule = regexp.MustCompile(`^module\s+"(\S+)"`)
+ reDataSrc = regexp.MustCompile(`^data\s+"(\S+)"\s+"(\S+)"`)
+ reBackend = regexp.MustCompile(`^\s*backend\s+"(\S+)"`)
+ reTFDefault = regexp.MustCompile(`^\s*default\s*=\s*"?([^"\n]*)"?`)
+ reTFType = regexp.MustCompile(`^\s*type\s*=\s*(\S+)`)
+ reTFSource = regexp.MustCompile(`^\s*source\s*=\s*"([^"]*)"`)
+ reTFDesc = regexp.MustCompile(`^\s*description\s*=\s*"([^"]*)"`)
+ reTFLocals = regexp.MustCompile(`^locals\s*\{`)
+)
+
+// blockKind identifies what type of HCL block we're inside.
+type blockKind int
+
+const (
+ blockNone blockKind = iota
+ blockVariable
+ blockModule
+ blockTerraform
+)
+
+// tfState accumulates parsed Terraform file metadata.
+type tfState struct {
+ resources []map[string]string // [{type, name}]
+ variables []map[string]string // [{name, type, default, description}]
+ outputs []string
+ providers []string
+ modules []map[string]string // [{name, source}]
+ dataSources []map[string]string // [{type, name}]
+ backend string
+ hasLocals bool
+}
+
+func parseTerraformFile(absPath, relPath string) []infraFile {
+ f, err := os.Open(absPath)
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ var st tfState
+ var curBlock blockKind
+ var curBlockData map[string]string
+ braceDepth := 0
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Text()
+ trimmed := strings.TrimSpace(line)
+
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, "//") {
+ continue
+ }
+
+ // Track brace depth
+ braceDepth += strings.Count(trimmed, "{") - strings.Count(trimmed, "}")
+
+ // At top level (depth 0 or entering depth 1), detect block headers
+ if braceDepth <= 1 {
+ if newBlock, data := st.matchBlockHeader(trimmed); newBlock != blockNone {
+ curBlock = newBlock
+ curBlockData = data
+ continue
+ }
+ }
+
+ // Inside a block, extract attributes.
+ // Depth 1 for variable/module attrs, depth 1-2 for terraform (backend is nested).
+ if curBlock != blockNone && braceDepth >= 1 && braceDepth <= 2 {
+ st.extractBlockAttr(trimmed, curBlock, curBlockData)
+ }
+
+ // Block closed — finalize
+ if braceDepth == 0 && curBlock != blockNone {
+ st.finalizeBlock(curBlock, curBlockData)
+ curBlock = blockNone
+ curBlockData = nil
+ }
+ }
+
+ props := st.toProperties()
+ if len(props) <= 1 { // only infra_type, nothing useful
+ return nil
+ }
+ return []infraFile{{relPath: relPath, infraType: "terraform", properties: props}}
+}
+
+// matchBlockHeader checks if the line starts a recognized HCL block.
+// Returns the block kind and a data map to accumulate attributes into.
+func (st *tfState) matchBlockHeader(line string) (kind blockKind, data map[string]string) {
+ if m := reResource.FindStringSubmatch(line); m != nil {
+ st.resources = append(st.resources, map[string]string{"type": m[1], "name": m[2]})
+ return blockNone, nil // no attribute extraction needed
+ }
+ if m := reVariable.FindStringSubmatch(line); m != nil {
+ return blockVariable, map[string]string{"name": m[1]}
+ }
+ if m := reOutput.FindStringSubmatch(line); m != nil {
+ st.outputs = append(st.outputs, m[1])
+ return blockNone, nil
+ }
+ if m := reProvider.FindStringSubmatch(line); m != nil {
+ st.providers = append(st.providers, m[1])
+ return blockNone, nil
+ }
+ if m := reTFModule.FindStringSubmatch(line); m != nil {
+ return blockModule, map[string]string{"name": m[1]}
+ }
+ if m := reDataSrc.FindStringSubmatch(line); m != nil {
+ st.dataSources = append(st.dataSources, map[string]string{"type": m[1], "name": m[2]})
+ return blockNone, nil
+ }
+ if strings.HasPrefix(line, "terraform") && strings.Contains(line, "{") {
+ return blockTerraform, nil
+ }
+ if reTFLocals.MatchString(line) {
+ st.hasLocals = true
+ }
+ return blockNone, nil
+}
+
+// extractBlockAttr extracts key attributes from inside a block.
+func (st *tfState) extractBlockAttr(line string, kind blockKind, data map[string]string) {
+ switch kind {
+ case blockVariable:
+ st.extractVariableAttr(line, data)
+ case blockModule:
+ if m := reTFSource.FindStringSubmatch(line); m != nil {
+ data["source"] = m[1]
+ }
+ case blockTerraform:
+ if m := reBackend.FindStringSubmatch(line); m != nil {
+ st.backend = m[1]
+ }
+ }
+}
+
+func (st *tfState) extractVariableAttr(line string, data map[string]string) {
+ if m := reTFDefault.FindStringSubmatch(line); m != nil {
+ val := strings.TrimSpace(m[1])
+ if !isSecretBinding(data["name"], val) {
+ data["default"] = val
+ }
+ }
+ if m := reTFType.FindStringSubmatch(line); m != nil {
+ data["type"] = m[1]
+ }
+ if m := reTFDesc.FindStringSubmatch(line); m != nil {
+ data["description"] = m[1]
+ }
+}
+
+// finalizeBlock saves the accumulated block data to the state.
+func (st *tfState) finalizeBlock(kind blockKind, data map[string]string) {
+ switch kind {
+ case blockVariable:
+ if data != nil {
+ st.variables = append(st.variables, data)
+ }
+ case blockModule:
+ if data != nil {
+ st.modules = append(st.modules, data)
+ }
+ case blockTerraform:
+ // backend already extracted inline
+ }
+}
+
+func (st *tfState) toProperties() map[string]any {
+ props := map[string]any{
+ "infra_type": "terraform",
+ }
+
+ setNonEmptyMaps(props, "resources", st.resources)
+ setNonEmptyMaps(props, "variables", st.variables)
+ setNonEmpty(props, "outputs", st.outputs)
+ setNonEmpty(props, "providers", st.providers)
+ setNonEmptyMaps(props, "modules", st.modules)
+ setNonEmptyMaps(props, "data_sources", st.dataSources)
+ setNonEmptyStr(props, "backend", st.backend)
+
+ if st.hasLocals {
+ props["has_locals"] = true
+ }
+
+ return props
+}
+
+// setNonEmptyMaps sets a property if the slice of maps is non-empty.
+func setNonEmptyMaps(m map[string]any, key string, val []map[string]string) {
+ if len(val) > 0 {
+ m[key] = val
+ }
+}
diff --git a/internal/pipeline/infrascan_yaml.go b/internal/pipeline/infrascan_yaml.go
new file mode 100644
index 000000000..57ddb6445
--- /dev/null
+++ b/internal/pipeline/infrascan_yaml.go
@@ -0,0 +1,334 @@
+package pipeline
+
+import (
+ "os"
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+// --- docker-compose parser ---
+
+// composeFile represents the top-level structure of a docker-compose file.
+type composeFile struct {
+ Services map[string]composeService `yaml:"services"`
+}
+
+// composeService represents a single service in docker-compose.
+type composeService struct {
+ Build any `yaml:"build"`
+ Image string `yaml:"image"`
+ Ports []string `yaml:"ports"`
+ Expose []string `yaml:"expose"`
+ Environment any `yaml:"environment"`
+ DependsOn any `yaml:"depends_on"`
+ Networks any `yaml:"networks"`
+ ContainerName string `yaml:"container_name"`
+ Volumes []string `yaml:"volumes"`
+ Command any `yaml:"command"`
+ Labels map[string]string `yaml:"labels"`
+}
+
+func parseComposeFile(absPath, relPath string) []infraFile {
+ data, err := os.ReadFile(absPath)
+ if err != nil {
+ return nil
+ }
+
+ var cf composeFile
+ if err := yaml.Unmarshal(data, &cf); err != nil {
+ return nil
+ }
+
+ if len(cf.Services) == 0 {
+ return nil
+ }
+
+ result := make([]infraFile, 0, len(cf.Services))
+ for name := range cf.Services {
+ svc := cf.Services[name]
+ props := buildComposeServiceProps(name, &svc)
+ result = append(result, infraFile{
+ relPath: relPath,
+ infraType: "compose-service",
+ properties: props,
+ })
+ }
+ return result
+}
+
+func buildComposeServiceProps(name string, svc *composeService) map[string]any {
+ props := map[string]any{
+ "infra_type": "compose-service",
+ "service_name": name,
+ }
+
+ setNonEmptyStr(props, "image", svc.Image)
+ setNonEmptyStr(props, "container_name", svc.ContainerName)
+ setBuildContext(props, svc.Build)
+ setNonEmpty(props, "ports", svc.Ports)
+ setNonEmpty(props, "expose", svc.Expose)
+ setNonEmpty(props, "volumes", svc.Volumes)
+
+ envMap := parseComposeEnvironment(svc.Environment)
+ setNonEmptyMap(props, "environment", envMap)
+
+ deps := parseDependsOn(svc.DependsOn)
+ setNonEmpty(props, "depends_on", deps)
+
+ nets := parseNetworks(svc.Networks)
+ setNonEmpty(props, "networks", nets)
+
+ return props
+}
+
+// setBuildContext extracts the build context from various docker-compose formats.
+// build can be a string or a map with "context" key.
+func setBuildContext(props map[string]any, build any) {
+ switch v := build.(type) {
+ case string:
+ setNonEmptyStr(props, "build_context", v)
+ case map[string]any:
+ if ctx, ok := v["context"].(string); ok {
+ setNonEmptyStr(props, "build_context", ctx)
+ }
+ }
+}
+
+// parseComposeEnvironment handles both map and list formats for environment.
+func parseComposeEnvironment(env any) map[string]string {
+ if env == nil {
+ return nil
+ }
+ result := make(map[string]string)
+
+ switch v := env.(type) {
+ case map[string]any:
+ for k, val := range v {
+ if s, ok := val.(string); ok && !isSecretBinding(k, s) {
+ result[k] = s
+ }
+ }
+ case []any:
+ for _, item := range v {
+ s, ok := item.(string)
+ if !ok {
+ continue
+ }
+ parts := strings.SplitN(s, "=", 2)
+ if len(parts) == 2 && !isSecretBinding(parts[0], parts[1]) {
+ result[parts[0]] = parts[1]
+ }
+ }
+ }
+
+ if len(result) == 0 {
+ return nil
+ }
+ return result
+}
+
+// parseDependsOn handles both list and map formats for depends_on.
+func parseDependsOn(dep any) []string {
+ if dep == nil {
+ return nil
+ }
+ switch v := dep.(type) {
+ case []any:
+ var result []string
+ for _, item := range v {
+ if s, ok := item.(string); ok {
+ result = append(result, s)
+ }
+ }
+ return result
+ case map[string]any:
+ var result []string
+ for name := range v {
+ result = append(result, name)
+ }
+ return result
+ }
+ return nil
+}
+
+// parseNetworks handles both list and map formats for networks.
+func parseNetworks(nets any) []string {
+ if nets == nil {
+ return nil
+ }
+ switch v := nets.(type) {
+ case []any:
+ var result []string
+ for _, item := range v {
+ if s, ok := item.(string); ok {
+ result = append(result, s)
+ }
+ }
+ return result
+ case map[string]any:
+ var result []string
+ for name := range v {
+ result = append(result, name)
+ }
+ return result
+ }
+ return nil
+}
+
+// --- cloudbuild parser ---
+
+// cloudbuildFile represents the top-level structure of a Cloud Build YAML.
+type cloudbuildFile struct {
+ Steps []cloudbuildStep `yaml:"steps"`
+ Substitutions map[string]string `yaml:"substitutions"`
+ Images []string `yaml:"images"`
+ Options map[string]any `yaml:"options"`
+}
+
+type cloudbuildStep struct {
+ Name string `yaml:"name"`
+ Args []string `yaml:"args"`
+ Env []string `yaml:"env"`
+}
+
+func parseCloudbuildFile(absPath, relPath string) []infraFile {
+ data, err := os.ReadFile(absPath)
+ if err != nil {
+ return nil
+ }
+
+ var cb cloudbuildFile
+ if err := yaml.Unmarshal(data, &cb); err != nil {
+ return nil
+ }
+
+ props := buildCloudbuildProps(cb)
+ props["infra_type"] = "cloudbuild"
+
+ return []infraFile{{relPath: relPath, infraType: "cloudbuild", properties: props}}
+}
+
+func buildCloudbuildProps(cb cloudbuildFile) map[string]any {
+ props := make(map[string]any)
+
+ if len(cb.Substitutions) > 0 {
+ filtered := filterSecretMap(cb.Substitutions)
+ setNonEmptyMap(props, "substitutions", filtered)
+ if sn, ok := cb.Substitutions["_SERVICE_NAME"]; ok {
+ props["service_name"] = sn
+ }
+ }
+
+ if len(cb.Images) > 0 {
+ props["image_registry"] = cb.Images[0]
+ }
+
+ // Walk steps looking for gcloud run deploy
+ extractDeployFlags(cb.Steps, props)
+
+ return props
+}
+
+// extractDeployFlags scans cloudbuild steps for gcloud run deploy commands
+// and extracts deployment flags.
+func extractDeployFlags(steps []cloudbuildStep, props map[string]any) {
+ for _, step := range steps {
+ if !isDeployStep(step.Args) {
+ continue
+ }
+ parseDeployArgs(step.Args, props)
+ parseDeployEnvVars(step.Args, props)
+ return // only process first deploy step
+ }
+}
+
+// isDeployStep returns true if the args list contains "gcloud run deploy" sequence.
+func isDeployStep(args []string) bool {
+ if len(args) < 3 {
+ return false
+ }
+ // Match "run" + "deploy" anywhere in args (gcloud run deploy ...)
+ for i := 0; i < len(args)-1; i++ {
+ if args[i] == "run" && args[i+1] == "deploy" {
+ return true
+ }
+ }
+ return false
+}
+
+// deployFlagMap maps gcloud run deploy flags to property names.
+var deployFlagMap = map[string]string{
+ "--region": "deploy_region",
+ "--cpu": "deploy_cpu",
+ "--memory": "deploy_memory",
+ "--concurrency": "deploy_concurrency",
+ "--max-instances": "deploy_max_instances",
+ "--timeout": "deploy_timeout",
+ "--ingress": "deploy_ingress",
+ "--image": "image_registry",
+ "--service-account": "deploy_service_account",
+}
+
+func parseDeployArgs(args []string, props map[string]any) {
+ for i, arg := range args {
+ // --flag=value format
+ if idx := strings.Index(arg, "="); idx > 0 {
+ flag := arg[:idx]
+ val := arg[idx+1:]
+ if propName, ok := deployFlagMap[flag]; ok {
+ props[propName] = val
+ }
+ continue
+ }
+ // --flag value format (next arg is value)
+ if propName, ok := deployFlagMap[arg]; ok && i+1 < len(args) {
+ props[propName] = args[i+1]
+ }
+ }
+}
+
+// parseDeployEnvVars extracts --set-env-vars or --update-env-vars from deploy args.
+func parseDeployEnvVars(args []string, props map[string]any) {
+ for i, arg := range args {
+ envStr := extractEnvVarsFlag(arg, args, i)
+ if envStr == "" {
+ continue
+ }
+
+ envMap := make(map[string]string)
+ for _, pair := range strings.Split(envStr, ",") {
+ parts := strings.SplitN(pair, "=", 2)
+ if len(parts) == 2 && !isSecretBinding(parts[0], parts[1]) {
+ envMap[parts[0]] = parts[1]
+ }
+ }
+ setNonEmptyMap(props, "deploy_env_vars", envMap)
+ return
+ }
+}
+
+// extractEnvVarsFlag extracts the env vars string from --set-env-vars or --update-env-vars flags.
+func extractEnvVarsFlag(arg string, args []string, i int) string {
+ switch {
+ case strings.HasPrefix(arg, "--set-env-vars="):
+ return arg[len("--set-env-vars="):]
+ case strings.HasPrefix(arg, "--update-env-vars="):
+ return arg[len("--update-env-vars="):]
+ case (arg == "--set-env-vars" || arg == "--update-env-vars") && i+1 < len(args):
+ return args[i+1]
+ default:
+ return ""
+ }
+}
+
+// filterSecretMap returns a copy of the map with secret key/values removed.
+func filterSecretMap(m map[string]string) map[string]string {
+ filtered := make(map[string]string, len(m))
+ for k, v := range m {
+ if !isSecretBinding(k, v) {
+ filtered[k] = v
+ }
+ }
+ return filtered
+}
diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go
index 45cbd8275..9c38f82ac 100644
--- a/internal/pipeline/pipeline.go
+++ b/internal/pipeline/pipeline.go
@@ -66,7 +66,10 @@ func (p *Pipeline) Run() error {
}
slog.Info("pipeline.discovered", "files", len(files))
- if err := p.Store.WithTransaction(func() error {
+ 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)
}); err != nil {
return err
@@ -1177,12 +1180,16 @@ func (p *Pipeline) passImports() {
// passHTTPLinks runs the HTTP linker to discover cross-service HTTP calls.
func (p *Pipeline) passHTTPLinks() error {
- // Clean up stale Route nodes and HTTP_CALLS/HANDLES/ASYNC_CALLS edges before re-running
+ // Clean up stale Route/InfraFile nodes and HTTP_CALLS/HANDLES/ASYNC_CALLS edges before re-running
_ = p.Store.DeleteNodesByLabel(p.ProjectName, "Route")
+ _ = p.Store.DeleteNodesByLabel(p.ProjectName, "InfraFile")
_ = p.Store.DeleteEdgesByType(p.ProjectName, "HTTP_CALLS")
_ = p.Store.DeleteEdgesByType(p.ProjectName, "HANDLES")
_ = p.Store.DeleteEdgesByType(p.ProjectName, "ASYNC_CALLS")
+ // Index infrastructure files (Dockerfiles, compose, cloudbuild, .env)
+ p.passInfraFiles()
+
// Scan config files for env var URLs and create synthetic Module nodes
envBindings := ScanProjectEnvURLs(p.RepoPath)
if len(envBindings) > 0 {
diff --git a/internal/store/store.go b/internal/store/store.go
index 6b53825ea..51d9a2f6d 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -102,18 +102,16 @@ func OpenMemory() (*Store, error) {
}
// WithTransaction executes fn within a single SQLite transaction.
-// All store methods called inside fn use the transaction automatically.
-func (s *Store) WithTransaction(fn func() error) error {
+// The callback receives a transaction-scoped Store — all store methods called on
+// txStore use the transaction. The receiver's q field is never mutated, so
+// concurrent read-only handlers (using s.q == s.db) are unaffected.
+func (s *Store) WithTransaction(fn func(txStore *Store) error) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
- s.q = tx
- defer func() {
- s.q = s.db
- }()
-
- if err := fn(); err != nil {
+ txStore := &Store{db: s.db, q: tx, dbPath: s.dbPath}
+ if err := fn(txStore); err != nil {
_ = tx.Rollback()
return err
}
diff --git a/internal/tools/index.go b/internal/tools/index.go
index 43ef6b1b2..f5848d4f7 100644
--- a/internal/tools/index.go
+++ b/internal/tools/index.go
@@ -29,6 +29,10 @@ func (s *Server) handleIndexRepository(_ context.Context, req *mcp.CallToolReque
projectName := filepath.Base(absPath)
+ // Lock to prevent concurrent indexing with auto-sync watcher
+ s.indexMu.Lock()
+ defer s.indexMu.Unlock()
+
// Run the indexing pipeline
p := pipeline.New(s.store, absPath)
if err := p.Run(); err != nil {
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
index 8d8350956..d4bf3b610 100644
--- a/internal/tools/tools.go
+++ b/internal/tools/tools.go
@@ -1,17 +1,24 @@
package tools
import (
+ "context"
"encoding/json"
"fmt"
+ "log/slog"
+ "sync"
+ "github.com/DeusData/codebase-memory-mcp/internal/pipeline"
"github.com/DeusData/codebase-memory-mcp/internal/store"
+ "github.com/DeusData/codebase-memory-mcp/internal/watcher"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// Server wraps the MCP server with tool handlers.
type Server struct {
- mcp *mcp.Server
- store *store.Store
+ mcp *mcp.Server
+ store *store.Store
+ watcher *watcher.Watcher
+ indexMu sync.Mutex
}
// NewServer creates a new MCP server with all tools registered.
@@ -21,15 +28,34 @@ func NewServer(s *store.Store) *Server {
mcp: mcp.NewServer(
&mcp.Implementation{
Name: "codebase-memory-mcp",
- Version: "0.1.0",
+ Version: "0.1.1",
},
nil,
),
}
srv.registerTools()
+ srv.watcher = watcher.New(s, srv.syncProject)
return srv
}
+// StartWatcher launches the background file-change polling goroutine.
+// It stops when ctx is cancelled.
+func (s *Server) StartWatcher(ctx context.Context) {
+ go s.watcher.Run(ctx)
+}
+
+// syncProject is called by the watcher when file changes are detected.
+// Uses TryLock to skip if an index operation is already in progress.
+func (s *Server) syncProject(_, rootPath string) error {
+ if !s.indexMu.TryLock() {
+ slog.Debug("watcher.skip", "path", rootPath, "reason", "index_in_progress")
+ return nil
+ }
+ defer s.indexMu.Unlock()
+ p := pipeline.New(s.store, rootPath)
+ return p.Run()
+}
+
// MCPServer returns the underlying MCP server.
func (s *Server) MCPServer() *mcp.Server {
return s.mcp
diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.go
new file mode 100644
index 000000000..7fcec8fe7
--- /dev/null
+++ b/internal/watcher/watcher.go
@@ -0,0 +1,185 @@
+package watcher
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "time"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/discover"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+const (
+ baseInterval = 1 * time.Second
+ maxInterval = 60 * time.Second
+)
+
+type fileSnapshot struct {
+ modTime time.Time
+ size int64
+}
+
+type projectState struct {
+ snapshot map[string]fileSnapshot
+ interval time.Duration
+ nextPoll time.Time
+}
+
+// IndexFunc is the callback signature for triggering a re-index.
+type IndexFunc func(projectName, rootPath string) error
+
+// Watcher polls indexed projects for file changes and triggers re-indexing.
+type Watcher struct {
+ store *store.Store
+ indexFn IndexFunc
+ projects map[string]*projectState
+}
+
+// New creates a Watcher. indexFn is called when file changes are detected.
+func New(s *store.Store, indexFn IndexFunc) *Watcher {
+ return &Watcher{
+ store: s,
+ indexFn: indexFn,
+ projects: make(map[string]*projectState),
+ }
+}
+
+// Run blocks until ctx is cancelled. Ticks at baseInterval, polling each
+// project only when its adaptive interval has elapsed.
+func (w *Watcher) Run(ctx context.Context) {
+ ticker := time.NewTicker(baseInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ w.pollAll()
+ }
+ }
+}
+
+// pollAll lists all indexed projects and polls each that is due.
+func (w *Watcher) pollAll() {
+ projects, err := w.store.ListProjects()
+ if err != nil {
+ slog.Warn("watcher.list_projects", "err", err)
+ return
+ }
+
+ now := time.Now()
+ for _, proj := range projects {
+ state, exists := w.projects[proj.Name]
+ if !exists {
+ // First time seeing this project — capture baseline
+ state = &projectState{}
+ w.projects[proj.Name] = state
+ }
+
+ if exists && now.Before(state.nextPoll) {
+ continue // not due yet
+ }
+
+ w.pollProject(proj, state)
+ }
+}
+
+// pollProject captures a snapshot of the file tree and compares with previous.
+// First poll: captures baseline without triggering indexing.
+// Subsequent polls: triggers indexFn if any file changed.
+func (w *Watcher) pollProject(proj *store.Project, state *projectState) {
+ // Verify root path still exists
+ if _, err := os.Stat(proj.RootPath); err != nil {
+ slog.Warn("watcher.root_gone", "project", proj.Name, "path", proj.RootPath)
+ state.nextPoll = time.Now().Add(maxInterval)
+ return
+ }
+
+ snap, err := captureSnapshot(proj.RootPath)
+ if err != nil {
+ slog.Warn("watcher.snapshot", "project", proj.Name, "err", err)
+ state.nextPoll = time.Now().Add(state.interval)
+ return
+ }
+
+ interval := pollInterval(len(snap))
+
+ if state.snapshot == nil {
+ // First poll — capture baseline, no index trigger
+ slog.Debug("watcher.baseline", "project", proj.Name, "files", len(snap))
+ state.snapshot = snap
+ state.interval = interval
+ state.nextPoll = time.Now().Add(interval)
+ return
+ }
+
+ if snapshotsEqual(state.snapshot, snap) {
+ state.interval = interval
+ state.nextPoll = time.Now().Add(interval)
+ return
+ }
+
+ slog.Info("watcher.changed", "project", proj.Name, "files", len(snap))
+ if err := w.indexFn(proj.Name, proj.RootPath); err != nil {
+ slog.Warn("watcher.index", "project", proj.Name, "err", err)
+ // Keep old snapshot so we retry next cycle
+ state.nextPoll = time.Now().Add(interval)
+ return
+ }
+
+ // Successful index — update snapshot and recalculate interval
+ state.snapshot = snap
+ state.interval = pollInterval(len(snap))
+ state.nextPoll = time.Now().Add(state.interval)
+}
+
+// captureSnapshot walks the file tree using discover.Discover and captures
+// mtime+size for each file.
+func captureSnapshot(rootPath string) (map[string]fileSnapshot, error) {
+ files, err := discover.Discover(rootPath, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ snap := make(map[string]fileSnapshot, len(files))
+ for _, f := range files {
+ info, statErr := os.Stat(f.Path)
+ if statErr != nil {
+ continue
+ }
+ snap[f.RelPath] = fileSnapshot{
+ modTime: info.ModTime(),
+ size: info.Size(),
+ }
+ }
+ return snap, nil
+}
+
+// snapshotsEqual returns true if two snapshots have identical files with same mtime+size.
+func snapshotsEqual(a, b map[string]fileSnapshot) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for path, aSnap := range a {
+ bSnap, ok := b[path]
+ if !ok {
+ return false
+ }
+ if !aSnap.modTime.Equal(bSnap.modTime) || aSnap.size != bSnap.size {
+ return false
+ }
+ }
+ return true
+}
+
+// pollInterval computes the adaptive interval from file count.
+// 1s base + 1s per 500 files, capped at 60s.
+func pollInterval(fileCount int) time.Duration {
+ ms := 1000 + (fileCount/500)*1000
+ if ms > 60000 {
+ ms = 60000
+ }
+ return time.Duration(ms) * time.Millisecond
+}
diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.go
new file mode 100644
index 000000000..0151443de
--- /dev/null
+++ b/internal/watcher/watcher_test.go
@@ -0,0 +1,298 @@
+package watcher
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+func TestSnapshotsEqual(t *testing.T) {
+ now := time.Now()
+
+ a := map[string]fileSnapshot{
+ "main.go": {modTime: now, size: 100},
+ "util.go": {modTime: now, size: 200},
+ }
+ b := map[string]fileSnapshot{
+ "main.go": {modTime: now, size: 100},
+ "util.go": {modTime: now, size: 200},
+ }
+ if !snapshotsEqual(a, b) {
+ t.Error("identical snapshots should be equal")
+ }
+
+ // Different size
+ c := map[string]fileSnapshot{
+ "main.go": {modTime: now, size: 101},
+ "util.go": {modTime: now, size: 200},
+ }
+ if snapshotsEqual(a, c) {
+ t.Error("different size should not be equal")
+ }
+
+ // Different mtime
+ d := map[string]fileSnapshot{
+ "main.go": {modTime: now.Add(time.Second), size: 100},
+ "util.go": {modTime: now, size: 200},
+ }
+ if snapshotsEqual(a, d) {
+ t.Error("different mtime should not be equal")
+ }
+
+ // Missing file
+ e := map[string]fileSnapshot{
+ "main.go": {modTime: now, size: 100},
+ }
+ if snapshotsEqual(a, e) {
+ t.Error("different file count should not be equal")
+ }
+
+ // Extra file
+ f := map[string]fileSnapshot{
+ "main.go": {modTime: now, size: 100},
+ "util.go": {modTime: now, size: 200},
+ "new.go": {modTime: now, size: 50},
+ }
+ if snapshotsEqual(a, f) {
+ t.Error("extra file should not be equal")
+ }
+
+ // Both empty
+ if !snapshotsEqual(map[string]fileSnapshot{}, map[string]fileSnapshot{}) {
+ t.Error("both empty should be equal")
+ }
+}
+
+func TestPollInterval(t *testing.T) {
+ tests := []struct {
+ files int
+ expected time.Duration
+ }{
+ {0, 1 * time.Second},
+ {70, 1 * time.Second},
+ {499, 1 * time.Second},
+ {500, 2 * time.Second},
+ {2000, 5 * time.Second},
+ {5000, 11 * time.Second},
+ {10000, 21 * time.Second},
+ {50000, 60 * time.Second},
+ {100000, 60 * time.Second},
+ }
+ for _, tt := range tests {
+ got := pollInterval(tt.files)
+ if got != tt.expected {
+ t.Errorf("pollInterval(%d) = %v, want %v", tt.files, got, tt.expected)
+ }
+ }
+}
+
+func TestCaptureSnapshot(t *testing.T) {
+ tmpDir := t.TempDir()
+ // Create a Go file that discover.Discover will pick up
+ if err := os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte("package main\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ snap, err := captureSnapshot(tmpDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(snap) != 1 {
+ t.Fatalf("expected 1 file, got %d", len(snap))
+ }
+
+ s, ok := snap["main.go"]
+ if !ok {
+ t.Fatal("expected main.go in snapshot")
+ }
+ if s.size == 0 {
+ t.Error("expected non-zero size")
+ }
+ if s.modTime.IsZero() {
+ t.Error("expected non-zero modtime")
+ }
+}
+
+func TestCaptureSnapshotDetectsChanges(t *testing.T) {
+ tmpDir := t.TempDir()
+ goFile := filepath.Join(tmpDir, "main.go")
+ if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ snap1, err := captureSnapshot(tmpDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Ensure mtime advances (some filesystems have 1s granularity)
+ time.Sleep(10 * time.Millisecond)
+ now := time.Now().Add(time.Second)
+ if err := os.Chtimes(goFile, now, now); err != nil {
+ t.Fatal(err)
+ }
+
+ snap2, err := captureSnapshot(tmpDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if snapshotsEqual(snap1, snap2) {
+ t.Error("snapshots should differ after mtime change")
+ }
+}
+
+func TestWatcherTriggersOnChange(t *testing.T) {
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ tmpDir := t.TempDir()
+ goFile := filepath.Join(tmpDir, "main.go")
+ if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ // Register the project so ListProjects returns it
+ if err := s.UpsertProject(filepath.Base(tmpDir), tmpDir); err != nil {
+ t.Fatal(err)
+ }
+
+ var indexCount atomic.Int32
+ indexFn := func(_, _ string) error {
+ indexCount.Add(1)
+ return nil
+ }
+
+ w := New(s, indexFn)
+
+ // First poll — baseline capture, no index
+ w.pollAll()
+ if indexCount.Load() != 0 {
+ t.Errorf("first poll should not trigger index, got %d", indexCount.Load())
+ }
+
+ // Poll again without changes — no index
+ // Reset nextPoll to allow immediate re-poll
+ for _, state := range w.projects {
+ state.nextPoll = time.Time{}
+ }
+ w.pollAll()
+ if indexCount.Load() != 0 {
+ t.Errorf("no-change poll should not trigger index, got %d", indexCount.Load())
+ }
+
+ // Modify the file
+ now := time.Now().Add(time.Second)
+ if err := os.Chtimes(goFile, now, now); err != nil {
+ t.Fatal(err)
+ }
+
+ // Reset nextPoll and poll again — should trigger
+ for _, state := range w.projects {
+ state.nextPoll = time.Time{}
+ }
+ w.pollAll()
+ if indexCount.Load() != 1 {
+ t.Errorf("changed file should trigger index, got %d", indexCount.Load())
+ }
+}
+
+func TestWatcherCancellation(t *testing.T) {
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ w := New(s, func(_, _ string) error { return nil })
+
+ ctx, cancel := context.WithCancel(context.Background())
+
+ done := make(chan struct{})
+ go func() {
+ w.Run(ctx)
+ close(done)
+ }()
+
+ cancel()
+
+ select {
+ case <-done:
+ // OK — goroutine exited cleanly
+ case <-time.After(3 * time.Second):
+ t.Fatal("watcher did not stop after context cancellation")
+ }
+}
+
+func TestWatcherSkipsMissingRoot(t *testing.T) {
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ // Register a project with a non-existent path
+ if err := s.UpsertProject("ghost", "/nonexistent/path"); err != nil {
+ t.Fatal(err)
+ }
+
+ var indexCount atomic.Int32
+ w := New(s, func(_, _ string) error {
+ indexCount.Add(1)
+ return nil
+ })
+
+ w.pollAll()
+ if indexCount.Load() != 0 {
+ t.Errorf("should not index missing root, got %d", indexCount.Load())
+ }
+}
+
+func TestWatcherNewFileTriggersIndex(t *testing.T) {
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ tmpDir := t.TempDir()
+ goFile := filepath.Join(tmpDir, "main.go")
+ if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := s.UpsertProject(filepath.Base(tmpDir), tmpDir); err != nil {
+ t.Fatal(err)
+ }
+
+ var indexCount atomic.Int32
+ w := New(s, func(_, _ string) error {
+ indexCount.Add(1)
+ return nil
+ })
+
+ // Baseline
+ w.pollAll()
+
+ // Add a new file
+ if err := os.WriteFile(filepath.Join(tmpDir, "util.go"), []byte("package main\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, state := range w.projects {
+ state.nextPoll = time.Time{}
+ }
+ w.pollAll()
+ if indexCount.Load() != 1 {
+ t.Errorf("new file should trigger index, got %d", indexCount.Load())
+ }
+}
diff --git a/skills/codebase-memory-mcp.md b/skills/codebase-memory-mcp.md
new file mode 100644
index 000000000..33d3da368
--- /dev/null
+++ b/skills/codebase-memory-mcp.md
@@ -0,0 +1,154 @@
+# codebase-memory-mcp — Claude Code Skill File
+
+> **Copy this file** to `~/.claude/skills/codebase-memory-mcp/SKILL.md` to teach Claude Code how to use the graph tools effectively. Or add the contents to your project's `CLAUDE.md`.
+
+## When to Use Graph Tools vs Direct Search
+
+| Task | Tool | Why |
+|------|------|-----|
+| Find a specific file by name | `Glob` | Exact match, instant |
+| Find a specific string/pattern | `Grep` | Text search, instant |
+| Understand call chains, dependencies, structure | **graph tools** | Graph traversal, relationship-aware |
+| Plan a refactor or migration | **graph tools** | Full structural context |
+| "What calls this function?" | `trace_call_path(direction="inbound")` | Graph CALLS relationships |
+| "What does X call?" | `trace_call_path(direction="outbound")` | BFS call chain traversal |
+| "What implements this interface?" | `search_graph(relationship="IMPLEMENTS")` | Graph type relationships |
+| Cross-service HTTP calls (list all edges) | `query_graph("MATCH (a)-[r:HTTP_CALLS]->(b) RETURN ...")` | Cypher returns edges with URL+confidence |
+| Cross-service HTTP calls (for one function) | `trace_call_path(direction="both")` | Finds inbound HTTP_CALLS edges too |
+| Async dispatch (Cloud Tasks, Pub/Sub, SQS) | `search_graph(name_pattern=".*CreateTask.*")` then `trace_call_path` | Find dispatch functions, trace CALLS chains |
+| Async dispatch (if ASYNC_CALLS edges exist) | `query_graph("MATCH (a)-[r:ASYNC_CALLS]->(b) RETURN ...")` | Only works when URLs are resolvable literals |
+| Dead code detection | `search_graph(max_degree=0, exclude_entry_points=true)` | Degree-based filtering |
+| REST route inventory | `search_graph(label="Route")` | Route nodes are first-class |
+| Explore an unfamiliar codebase | `get_graph_schema` → `search_graph` | Structured overview |
+| Quick one-off lookup in 1-2 files | `Read` / `Grep` | Faster for simple tasks |
+| Text search (string literals, errors) | `search_code` or `Grep` | Graph doesn't index text content |
+
+**Rule of thumb**: If the task requires understanding **relationships, structure, or flow** across multiple files/packages — use graph tools. If it's a simple text lookup — use Glob/Grep/Read.
+
+## Auto-Sync: Graph Stays Fresh Automatically
+
+After the initial `index_repository` call, a **background watcher** polls for file changes (mtime + size) and triggers incremental re-indexing automatically. You do NOT need to manually reindex after editing files.
+
+### When to Call `index_repository`
+
+| Situation | Action |
+|-----------|--------|
+| Project never indexed before | `index_repository` (required once) |
+| Exploring an unfamiliar codebase | Check `list_projects` — index if missing |
+| After editing files | **Nothing** — auto-sync handles it within 1–60s |
+| After a large `git pull` or branch switch | Optional: `index_repository` for immediate freshness (auto-sync will catch up anyway) |
+| Simple Glob/Grep lookup | Don't index — use Glob/Grep directly |
+
+**Auto-sync details**: Polling interval adapts to repo size (1s for small repos, up to 60s for 50K+ file repos). Non-blocking — never interferes with tool queries.
+
+## Decision Matrix
+
+| Question | Use | NOT |
+|---|---|---|
+| Who calls X? | `trace_call_path(direction="inbound")` | `query_graph` |
+| What does X call? | `trace_call_path(direction="outbound")` | `query_graph` |
+| Full call context (callers + callees) | `trace_call_path(direction="both")` | `direction="outbound"` alone |
+| Find functions by pattern | `search_graph(name_pattern="...")` | `trace_call_path` |
+| Count callers/callees | `search_graph` with `min_degree`/`max_degree` | `query_graph COUNT` (200-row cap) |
+| Dead code | `search_graph(max_degree=0, exclude_entry_points=true)` | `query_graph` |
+| Cross-service HTTP calls (list edges) | `query_graph("MATCH (a)-[r:HTTP_CALLS]->(b) RETURN ...")` | `search_graph(relationship="HTTP_CALLS")` |
+| Async dispatch functions | `search_graph(name_pattern=".*CreateTask.*")` then `trace_call_path` | `search_graph(relationship="ASYNC_CALLS")` |
+| Text search | `search_code` or grep | graph tools |
+| Complex multi-hop patterns | `query_graph` with Cypher + LIMIT | `search_graph` |
+
+## Tool Reference (11 Tools)
+
+| Tool | Purpose | When to Use |
+|------|---------|-------------|
+| `index_repository` | Parse and ingest repo into graph | Only needed once per project — auto-sync keeps it fresh |
+| `trace_call_path` | BFS from/to a function (exact name match) | Primary tool for call chains — requires EXACT name |
+| `search_graph` | Structured search with filters | Find functions, dead code, fan-out, cross-service links |
+| `query_graph` | Cypher-like graph queries (200-row cap) | Complex multi-hop patterns, filtered joins |
+| `get_graph_schema` | Node/edge counts, relationship patterns | Understand what's indexed before querying |
+| `get_code_snippet` | Read source by qualified name | After search finds a target function |
+| `search_code` | Grep-like text search within project | String literals, error messages, TODO comments |
+| `read_file` | Read any file from indexed project | Config files, source code |
+| `list_directory` | List files/directories with glob filter | Explore project structure |
+| `list_projects` | See all indexed projects | Check if reindex is needed (shows `indexed_at`) |
+| `delete_project` | Remove a project from graph | Cleanup stale projects |
+
+## Edge Types
+
+| Type | Meaning |
+|------|---------|
+| `CALLS` | Direct function call within same service |
+| `HTTP_CALLS` | Synchronous cross-service HTTP request |
+| `ASYNC_CALLS` | Async dispatch (Cloud Tasks, Pub/Sub, SQS, SNS, Kafka, RabbitMQ) |
+| `IMPORTS` | Module/package import |
+| `DEFINES` | Module/class defines a function |
+| `DEFINES_METHOD` | Class defines a method |
+| `HANDLES` | Route node handled by a function |
+| `IMPLEMENTS` | Type implements an interface |
+| `CONTAINS_FILE` / `CONTAINS_FOLDER` / `CONTAINS_PACKAGE` | Structural containment |
+
+## Critical Query Pitfalls
+
+**`search_graph(relationship="HTTP_CALLS")` does NOT return edges.** It filters *nodes* by their HTTP_CALLS degree count. To see the actual cross-service links with URLs and confidence scores, use Cypher:
+```
+query_graph("MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence ORDER BY r.confidence DESC LIMIT 30")
+```
+
+**`search_graph(relationship="ASYNC_CALLS")` has the same limitation.** ASYNC_CALLS edges only exist when the URL linker can resolve dispatch URLs to route handlers. When URLs are in config variables or env vars (common for Cloud Tasks, Pub/Sub), the linker can't match them. Instead, find dispatch functions by name pattern and trace via CALLS edges:
+```
+search_graph(name_pattern=".*CreateTask.*|.*create_task.*")
+trace_call_path(function_name="CreateMultidataTask", direction="both")
+```
+
+**`direction="outbound"` misses cross-service callers.** HTTP_CALLS edges from JS/Go frontends to Python backends appear as *inbound* edges on the backend function. Always use `direction="both"` when investigating a function's full context:
+```
+trace_call_path(function_name="validate_order", direction="both", depth=3)
+# Finds: JS frontend → HTTP_CALLS → validate_order → logger (outbound CALLS)
+```
+
+## Key Workflow Patterns
+
+### Discover Then Trace
+
+`trace_call_path` requires an **exact** function name. If unsure, discover first:
+
+```
+search_graph(name_pattern=".*Order.*")
+# → finds "ProcessOrder", "ValidateOrder", etc.
+
+trace_call_path(function_name="ProcessOrder", direction="inbound", depth=3)
+```
+
+### Pagination & Token Efficiency
+
+- **Start small**: Search tools return 10 results by default. Check `has_more` before paginating with `offset`.
+- **Avoid `include_connected`**: Only enable when you need neighbor names (adds ~30% tokens).
+- **`query_graph` has a 200-row cap** that applies BEFORE aggregation — COUNT queries silently undercount.
+- **Route handler names**: Route nodes have `properties.handler` with the actual handler function QN.
+
+### Scope to One Project
+
+When multiple repositories are indexed, always scope queries:
+
+```
+search_graph(label="Function", name_pattern=".*Handler", project="my-api")
+```
+
+## Keeping the Graph Fresh
+
+Auto-sync handles most freshness concerns automatically. Manual intervention is only needed for initial indexing:
+
+| Event | Action |
+|-------|--------|
+| First time using a project | `index_repository` (required once) |
+| After editing/creating/deleting files | **Nothing** — auto-sync detects changes within 1–60s |
+| After `git pull` or branch switch | Optional: `index_repository` for immediate freshness |
+| Switching to a different project | Check `list_projects`, index if missing |
+| Small edits within existing functions | No action needed — graph tracks structure, not line content |
+
+## Performance
+
+- **Indexing**: ~10-30s for medium repos (incremental — only changed files)
+- **Queries**: <1s (direct SQLite, no LLM translation)
+- **Resource usage**: Single binary, ~50MB RAM, SQLite WAL mode
+- **Database**: `~/.cache/codebase-memory-mcp/codebase-memory.db`
+- **Reset**: `rm -rf ~/.cache/codebase-memory-mcp/`