Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

v0.5.1: Fix C/C++/CUDA/GLSL function extraction, add config linker and tests

Martin Vogel05a35ac9b199
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 6617fc15b..e3c805abb 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -64,9 +64,11 @@ jobs:
run: go test ./...
- name: Build binary
+ env:
+ VERSION: ${{ inputs.version }}
run: |
CGO_ENABLED=1 go build \
- -ldflags "-X main.version=${{ inputs.version }}" \
+ -ldflags "-X main.version=$VERSION" \
-o codebase-memory-mcp \
./cmd/codebase-memory-mcp/
@@ -106,9 +108,11 @@ jobs:
- name: Build binary
shell: msys2 {0}
+ env:
+ VERSION: ${{ inputs.version }}
run: |
CGO_ENABLED=1 CC=gcc go build \
- -ldflags "-X main.version=${{ inputs.version }}" \
+ -ldflags "-X main.version=$VERSION" \
-o codebase-memory-mcp.exe \
./cmd/codebase-memory-mcp/
@@ -142,14 +146,17 @@ jobs:
- name: Delete existing release
if: ${{ inputs.replace }}
- run: gh release delete "${{ inputs.version }}" --yes --cleanup-tag || true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ VERSION: ${{ inputs.version }}
+ run: gh release delete "$VERSION" --yes --cleanup-tag || true
- name: Create tag
+ env:
+ VERSION: ${{ inputs.version }}
run: |
- git tag -f ${{ inputs.version }}
- git push origin ${{ inputs.version }} --force
+ git tag -f "$VERSION"
+ git push origin "$VERSION" --force
- uses: softprops/action-gh-release@v2
with:
diff --git a/internal/cbm/config_extraction_test.go b/internal/cbm/config_extraction_test.go
new file mode 100644
index 000000000..d95cfead8
--- /dev/null
+++ b/internal/cbm/config_extraction_test.go
@@ -0,0 +1,404 @@
+package cbm
+
+import (
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/lang"
+)
+
+// --- TOML Tests ---
+
+func TestTOMLBasicTableAndPair(t *testing.T) {
+ source := []byte("[database]\nhost = \"localhost\"\nport = 5432\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) != 1 || classes[0].Name != "database" {
+ t.Errorf("expected 1 Class 'database', got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) < 2 {
+ t.Errorf("expected >=2 Variables (host, port), got %d: %v", len(vars), names(vars))
+ }
+ assertHasName(t, vars, "host")
+ assertHasName(t, vars, "port")
+}
+
+func TestTOMLNestedTable(t *testing.T) {
+ source := []byte("[server.http]\nport = 8080\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ if len(classes) < 1 {
+ t.Errorf("expected >=1 Class for nested table, got %d", len(classes))
+ }
+}
+
+func TestTOMLTableArrayElement(t *testing.T) {
+ source := []byte("[[servers]]\nname = \"alpha\"\n[[servers]]\nname = \"beta\"\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) < 2 {
+ t.Errorf("expected >=2 Classes for table array, got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) < 2 {
+ t.Errorf("expected >=2 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestTOMLDottedKey(t *testing.T) {
+ source := []byte("database.host = \"localhost\"\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 1 {
+ t.Errorf("expected >=1 Variable for dotted key, got %d", len(vars))
+ }
+}
+
+func TestTOMLQuotedKey(t *testing.T) {
+ source := []byte("\"unusual-key\" = \"value\"\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 1 {
+ t.Errorf("expected >=1 Variable for quoted key, got %d", len(vars))
+ }
+}
+
+func TestTOMLEmptyTable(t *testing.T) {
+ source := []byte("[empty]\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) != 1 || classes[0].Name != "empty" {
+ t.Errorf("expected 1 Class 'empty', got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) != 0 {
+ t.Errorf("expected 0 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestTOMLCommentsOnly(t *testing.T) {
+ source := []byte("# just a comment\n# another comment\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) != 0 {
+ t.Errorf("expected 0 Classes, got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) != 0 {
+ t.Errorf("expected 0 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestTOMLBooleanAndIntegerValues(t *testing.T) {
+ source := []byte("enabled = true\ncount = 42\nname = \"test\"\n")
+ result, err := ExtractFile(source, lang.TOML, "test", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 3 {
+ t.Errorf("expected >=3 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+// --- INI Tests ---
+
+func TestINIBasicSectionAndSetting(t *testing.T) {
+ source := []byte("[database]\nhost = localhost\nport = 5432\n")
+ result, err := ExtractFile(source, lang.INI, "test", "config.ini")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) < 1 {
+ t.Errorf("expected >=1 Class (database section), got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) < 2 {
+ t.Errorf("expected >=2 Variables (host, port), got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestINIMultipleSections(t *testing.T) {
+ source := []byte("[section1]\nkey1 = val1\n[section2]\nkey2 = val2\n")
+ result, err := ExtractFile(source, lang.INI, "test", "config.ini")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) < 2 {
+ t.Errorf("expected >=2 Classes, got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) < 2 {
+ t.Errorf("expected >=2 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestINIGlobalKeys(t *testing.T) {
+ source := []byte("key1 = value1\nkey2 = value2\n")
+ result, err := ExtractFile(source, lang.INI, "test", "config.ini")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) != 0 {
+ t.Errorf("expected 0 Classes (no sections), got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) < 2 {
+ t.Errorf("expected >=2 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestINIComments(t *testing.T) {
+ source := []byte("; comment\n# another comment\n[section]\nkey = val\n")
+ result, err := ExtractFile(source, lang.INI, "test", "config.ini")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ vars := defsWithLabel(result, "Variable")
+ if len(classes) < 1 {
+ t.Errorf("expected >=1 Class, got %d: %v", len(classes), names(classes))
+ }
+ if len(vars) < 1 {
+ t.Errorf("expected >=1 Variable, got %d: %v", len(vars), names(vars))
+ }
+}
+
+// --- JSON Tests ---
+
+func TestJSONBasicPair(t *testing.T) {
+ source := []byte(`{"host": "localhost", "port": 5432}`)
+ result, err := ExtractFile(source, lang.JSON, "test", "config.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 2 {
+ t.Errorf("expected >=2 Variables (host, port), got %d: %v", len(vars), names(vars))
+ }
+ assertHasName(t, vars, "host")
+ assertHasName(t, vars, "port")
+}
+
+func TestJSONNestedObject(t *testing.T) {
+ source := []byte(`{"database": {"host": "localhost", "port": 5432}}`)
+ result, err := ExtractFile(source, lang.JSON, "test", "config.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 3 {
+ t.Errorf("expected >=3 Variables (database, host, port), got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestJSONEmptyObject(t *testing.T) {
+ source := []byte(`{}`)
+ result, err := ExtractFile(source, lang.JSON, "test", "config.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) != 0 {
+ t.Errorf("expected 0 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestJSONBooleanNullValues(t *testing.T) {
+ source := []byte(`{"enabled": true, "value": null, "name": "test"}`)
+ result, err := ExtractFile(source, lang.JSON, "test", "config.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 3 {
+ t.Errorf("expected >=3 Variables, got %d: %v", len(vars), names(vars))
+ }
+}
+
+func TestJSONPackageJsonDeps(t *testing.T) {
+ source := []byte(`{"name":"pkg","dependencies":{"express":"^4.0","lodash":"^4.17"}}`)
+ result, err := ExtractFile(source, lang.JSON, "test", "package.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ if len(vars) < 4 {
+ t.Errorf("expected >=4 Variables (name, dependencies, express, lodash), got %d: %v", len(vars), names(vars))
+ }
+ assertHasName(t, vars, "name")
+ assertHasName(t, vars, "dependencies")
+ assertHasName(t, vars, "express")
+ assertHasName(t, vars, "lodash")
+}
+
+// --- XML Tests ---
+
+func TestXMLBasicElement(t *testing.T) {
+ source := []byte(`<?xml version="1.0"?><config><database><host>localhost</host></database></config>`)
+ result, err := ExtractFile(source, lang.XML, "test", "config.xml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ if len(classes) < 3 {
+ t.Errorf("expected >=3 Classes (config, database, host), got %d: %v", len(classes), names(classes))
+ }
+ assertHasName(t, classes, "config")
+ assertHasName(t, classes, "database")
+ assertHasName(t, classes, "host")
+}
+
+func TestXMLSelfClosingTag(t *testing.T) {
+ source := []byte(`<?xml version="1.0"?><config><feature enabled="true"/></config>`)
+ result, err := ExtractFile(source, lang.XML, "test", "config.xml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ if len(classes) < 2 {
+ t.Errorf("expected >=2 Classes (config, feature), got %d: %v", len(classes), names(classes))
+ }
+}
+
+func TestXMLEmptyDocument(t *testing.T) {
+ source := []byte(`<?xml version="1.0"?><root/>`)
+ result, err := ExtractFile(source, lang.XML, "test", "config.xml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ if len(classes) < 1 {
+ t.Errorf("expected >=1 Class (root), got %d: %v", len(classes), names(classes))
+ }
+}
+
+func TestXMLMultipleChildren(t *testing.T) {
+ source := []byte(`<?xml version="1.0"?><servers><server/><server/><server/></servers>`)
+ result, err := ExtractFile(source, lang.XML, "test", "config.xml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ classes := defsWithLabel(result, "Class")
+ // servers + 3x server = 4
+ if len(classes) < 4 {
+ t.Errorf("expected >=4 Classes (servers + 3x server), got %d: %v", len(classes), names(classes))
+ }
+}
+
+// --- Markdown Tests ---
+
+func TestMarkdownATXHeadings(t *testing.T) {
+ source := []byte("# Title\n## Section\n### Subsection\n")
+ result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sections := defsWithLabel(result, "Section")
+ if len(sections) < 3 {
+ t.Errorf("expected >=3 Section nodes, got %d: %v", len(sections), names(sections))
+ }
+ // Must NOT produce Class nodes
+ classes := defsWithLabel(result, "Class")
+ if len(classes) != 0 {
+ t.Errorf("Markdown should produce Section, not Class, got %d Class nodes", len(classes))
+ }
+}
+
+func TestMarkdownSetextHeadings(t *testing.T) {
+ source := []byte("Title\n=====\nSection\n------\n")
+ result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sections := defsWithLabel(result, "Section")
+ if len(sections) < 2 {
+ t.Errorf("expected >=2 Section nodes, got %d: %v", len(sections), names(sections))
+ }
+}
+
+func TestMarkdownHeadingContent(t *testing.T) {
+ source := []byte("# Installation Guide\n## Prerequisites\n## Setup\n")
+ result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sections := defsWithLabel(result, "Section")
+ if len(sections) < 3 {
+ t.Errorf("expected >=3 Section nodes, got %d: %v", len(sections), names(sections))
+ }
+ assertHasName(t, sections, "Installation Guide")
+ assertHasName(t, sections, "Prerequisites")
+ assertHasName(t, sections, "Setup")
+}
+
+func TestMarkdownNoHeadings(t *testing.T) {
+ source := []byte("Just a paragraph\n\nAnother paragraph\n")
+ result, err := ExtractFile(source, lang.Markdown, "test", "README.md")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sections := defsWithLabel(result, "Section")
+ if len(sections) != 0 {
+ t.Errorf("expected 0 Sections, got %d: %v", len(sections), names(sections))
+ }
+}
+
+// --- Test Helpers ---
+
+type defInfo struct {
+ Name string
+ Label string
+}
+
+func defsWithLabel(result *FileResult, label string) []defInfo {
+ var out []defInfo
+ for _, d := range result.Definitions {
+ if d.Label == label {
+ out = append(out, defInfo{Name: d.Name, Label: d.Label})
+ }
+ }
+ return out
+}
+
+func names(defs []defInfo) []string {
+ var out []string
+ for _, d := range defs {
+ out = append(out, d.Name)
+ }
+ return out
+}
+
+func assertHasName(t *testing.T, defs []defInfo, name string) {
+ t.Helper()
+ for _, d := range defs {
+ if d.Name == name {
+ return
+ }
+ }
+ t.Errorf("expected to find name %q in %v", name, names(defs))
+}
diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c
index 9bd957492..809c98af9 100644
--- a/internal/cbm/extract_defs.c
+++ b/internal/cbm/extract_defs.c
@@ -119,6 +119,120 @@ static TSNode resolve_func_name(TSNode node, CBMLanguage lang, const char* sourc
}
}
+ // VimScript: function_definition — name is inside function_declaration child
+ // Both function_definition and function_declaration have production_id=0 (no field names)
+ if (lang == CBM_LANG_VIMSCRIPT && strcmp(kind, "function_definition") == 0) {
+ TSNode decl = cbm_find_child_by_kind(node, "function_declaration");
+ if (!ts_node_is_null(decl)) {
+ // function_declaration: first named child is the identifier/name
+ uint32_t nc = ts_node_named_child_count(decl);
+ if (nc > 0) return ts_node_named_child(decl, 0);
+ }
+ // Fallback: first named child of function_definition directly
+ {
+ uint32_t nc = ts_node_named_child_count(node);
+ if (nc > 0) return ts_node_named_child(node, 0);
+ }
+ }
+
+ // Julia: function_definition — no field names defined (production_id=0)
+ // Name is inside first named child: identifier or call_expression(identifier, params)
+ if (lang == CBM_LANG_JULIA && strcmp(kind, "function_definition") == 0) {
+ TSNode current = node;
+ for (int depth = 0; depth < 4; depth++) {
+ uint32_t nc = ts_node_named_child_count(current);
+ if (nc == 0) break;
+ TSNode first = ts_node_named_child(current, 0);
+ const char* fk = ts_node_type(first);
+ if (strcmp(fk, "identifier") == 0 || strcmp(fk, "operator_identifier") == 0) {
+ return first;
+ }
+ current = first;
+ }
+ TSNode null_node = {0};
+ return null_node;
+ }
+
+ // CommonLisp: defun — name via function_name field (defun grammar uses field_function_name)
+ if (lang == CBM_LANG_COMMONLISP && strcmp(kind, "defun") == 0) {
+ TSNode fn = ts_node_child_by_field_name(node, "function_name", 13);
+ if (!ts_node_is_null(fn)) return fn;
+ // Fallback: traverse defun_header -> first sym_lit child
+ TSNode header = cbm_find_child_by_kind(node, "defun_header");
+ if (!ts_node_is_null(header)) {
+ return cbm_find_child_by_kind(header, "sym_lit");
+ }
+ }
+
+ // Makefile: rule — name is first word in the targets group
+ if (lang == CBM_LANG_MAKEFILE && strcmp(kind, "rule") == 0) {
+ TSNode targets = cbm_find_child_by_kind(node, "targets");
+ if (!ts_node_is_null(targets)) {
+ uint32_t nc = ts_node_named_child_count(targets);
+ if (nc > 0) return ts_node_named_child(targets, 0);
+ }
+ // Fallback: first word child directly on rule
+ return cbm_find_child_by_kind(node, "word");
+ }
+
+ // Haskell: function — prod_id 151/152 has inherited field_name (handled above),
+ // prod_id 77 (no-argument function like `main = ...`) has NO field_name.
+ // Fallback: first named child of first child contains the variable name.
+ if (lang == CBM_LANG_HASKELL && strcmp(kind, "function") == 0) {
+ // func_name_node already returned null — prod_id 77 path
+ if (ts_node_named_child_count(node) > 0) {
+ TSNode head = ts_node_named_child(node, 0);
+ const char* hk = ts_node_type(head);
+ // Direct variable (function name without patterns)
+ if (strcmp(hk, "variable") == 0 || strcmp(hk, "name") == 0) return head;
+ // Function head node: first named child is the variable
+ if (ts_node_named_child_count(head) > 0) {
+ TSNode v = ts_node_named_child(head, 0);
+ const char* vk = ts_node_type(v);
+ if (strcmp(vk, "variable") == 0 || strcmp(vk, "name") == 0) return v;
+ }
+ }
+ TSNode null_node = {0};
+ return null_node;
+ }
+
+ // Elm: value_declaration — name is inside functionDeclarationLeft child (field 22 chars)
+ if (lang == CBM_LANG_ELM && strcmp(kind, "value_declaration") == 0) {
+ TSNode fdl = ts_node_child_by_field_name(node, "functionDeclarationLeft", 22);
+ if (ts_node_is_null(fdl))
+ fdl = cbm_find_child_by_kind(node, "function_declaration_left");
+ if (!ts_node_is_null(fdl) && ts_node_named_child_count(fdl) > 0)
+ return ts_node_named_child(fdl, 0);
+ TSNode null_node = {0};
+ return null_node;
+ }
+
+ // C/C++/CUDA/GLSL: function_definition — name is inside the declarator chain
+ // C grammar: function_definition{declarator:function_declarator{declarator:identifier}}
+ if ((lang == CBM_LANG_C || lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA ||
+ lang == CBM_LANG_GLSL) && strcmp(kind, "function_definition") == 0) {
+ TSNode decl = ts_node_child_by_field_name(node, "declarator", 10);
+ for (int depth = 0; depth < 8 && !ts_node_is_null(decl); depth++) {
+ const char* dk = ts_node_type(decl);
+ if (strcmp(dk, "identifier") == 0) return decl;
+ // C++ qualified name: Namespace::Function
+ if (strcmp(dk, "qualified_identifier") == 0 ||
+ strcmp(dk, "scoped_identifier") == 0) {
+ TSNode id = cbm_find_child_by_kind(decl, "identifier");
+ if (!ts_node_is_null(id)) return id;
+ break;
+ }
+ // Unwrap pointer_declarator, reference_declarator, function_declarator, etc.
+ TSNode inner = ts_node_child_by_field_name(decl, "declarator", 10);
+ if (ts_node_is_null(inner) && ts_node_named_child_count(decl) > 0)
+ inner = ts_node_named_child(decl, 0);
+ if (ts_node_is_null(inner)) break;
+ decl = inner;
+ }
+ TSNode null_node = {0};
+ return null_node;
+ }
+
TSNode null_node = {0};
return null_node;
}
@@ -577,6 +691,164 @@ static void extract_class_def(CBMExtractCtx* ctx, TSNode node, const CBMLangSpec
CBMArena* a = ctx->arena;
const char* kind = ts_node_type(node);
+ // Config language class extraction (TOML tables, INI sections, XML elements, Markdown headings)
+ if (ctx->language == CBM_LANG_TOML &&
+ (strcmp(kind, "table") == 0 || strcmp(kind, "table_array_element") == 0)) {
+ // TOML table: name from first bare_key/dotted_key/quoted_key child,
+ // or from the nested key within a bracket header
+ char* name = NULL;
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc && !name; i++) {
+ TSNode child = ts_node_child(node, i);
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "bare_key") == 0 || strcmp(ck, "dotted_key") == 0 ||
+ strcmp(ck, "quoted_key") == 0 || strcmp(ck, "key") == 0) {
+ name = cbm_node_text(a, child, ctx->source);
+ }
+ }
+ if (!name || !name[0]) return;
+ CBMDefinition def;
+ memset(&def, 0, sizeof(def));
+ def.name = name;
+ def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
+ def.label = "Class";
+ def.file_path = ctx->rel_path;
+ def.start_line = ts_node_start_point(node).row + 1;
+ def.end_line = ts_node_end_point(node).row + 1;
+ def.is_exported = true;
+ cbm_defs_push(&ctx->result->defs, a, def);
+ return;
+ }
+
+ if (ctx->language == CBM_LANG_INI && strcmp(kind, "section") == 0) {
+ // INI section: name from section_name child
+ char* name = NULL;
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc && !name; i++) {
+ TSNode child = ts_node_child(node, i);
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "section_name") == 0) {
+ name = cbm_node_text(a, child, ctx->source);
+ }
+ }
+ if (!name || !name[0]) return;
+ CBMDefinition def;
+ memset(&def, 0, sizeof(def));
+ def.name = name;
+ def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
+ def.label = "Class";
+ def.file_path = ctx->rel_path;
+ def.start_line = ts_node_start_point(node).row + 1;
+ def.end_line = ts_node_end_point(node).row + 1;
+ def.is_exported = true;
+ cbm_defs_push(&ctx->result->defs, a, def);
+ return;
+ }
+
+ if (ctx->language == CBM_LANG_XML && strcmp(kind, "element") == 0) {
+ // XML element: name from start_tag > tag_name or self_closing_tag > tag_name
+ char* name = NULL;
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc && !name; i++) {
+ TSNode child = ts_node_child(node, i);
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "start_tag") == 0 || strcmp(ck, "self_closing_tag") == 0 ||
+ strcmp(ck, "STag") == 0 || strcmp(ck, "EmptyElemTag") == 0) {
+ // Find Name or tag_name child
+ uint32_t tnc = ts_node_child_count(child);
+ for (uint32_t j = 0; j < tnc; j++) {
+ TSNode tag = ts_node_child(child, j);
+ const char* tk = ts_node_type(tag);
+ if (strcmp(tk, "tag_name") == 0 || strcmp(tk, "Name") == 0) {
+ name = cbm_node_text(a, tag, ctx->source);
+ break;
+ }
+ }
+ }
+ }
+ // Fallback: try "Name" field directly for some XML grammars
+ if (!name) {
+ TSNode name_child = cbm_find_child_by_kind(node, "Name");
+ if (!ts_node_is_null(name_child)) {
+ name = cbm_node_text(a, name_child, ctx->source);
+ }
+ }
+ if (!name || !name[0]) return;
+ CBMDefinition def;
+ memset(&def, 0, sizeof(def));
+ def.name = name;
+ def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
+ def.label = "Class";
+ def.file_path = ctx->rel_path;
+ def.start_line = ts_node_start_point(node).row + 1;
+ def.end_line = ts_node_end_point(node).row + 1;
+ def.is_exported = true;
+ cbm_defs_push(&ctx->result->defs, a, def);
+ return;
+ }
+
+ if (ctx->language == CBM_LANG_MARKDOWN &&
+ (strcmp(kind, "atx_heading") == 0 || strcmp(kind, "setext_heading") == 0)) {
+ // Markdown heading: extract text content as name, use "Section" label
+ // For atx_heading: children are atx_h[1-6]_marker + inline content
+ // For setext_heading: children are paragraph + setext_h[12]_underline
+ char* name = NULL;
+ if (strcmp(kind, "atx_heading") == 0) {
+ // Find heading_content or inline child (skip the marker)
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(node, i);
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "heading_content") == 0 || strcmp(ck, "inline") == 0) {
+ name = cbm_node_text(a, child, ctx->source);
+ break;
+ }
+ }
+ // Fallback: extract everything after the # marker
+ if (!name) {
+ char* full = cbm_node_text(a, node, ctx->source);
+ if (full) {
+ // Skip leading # and space
+ char* p = full;
+ while (*p == '#') p++;
+ while (*p == ' ') p++;
+ if (*p) name = cbm_arena_strdup(a, p);
+ }
+ }
+ } else {
+ // setext_heading: first child is the heading text (paragraph)
+ if (ts_node_child_count(node) > 0) {
+ TSNode first = ts_node_child(node, 0);
+ const char* fk = ts_node_type(first);
+ if (strcmp(fk, "paragraph") == 0 || strcmp(fk, "heading_content") == 0 ||
+ strcmp(fk, "inline") == 0) {
+ name = cbm_node_text(a, first, ctx->source);
+ } else {
+ name = cbm_node_text(a, first, ctx->source);
+ }
+ }
+ }
+ if (!name || !name[0]) return;
+ // Trim trailing whitespace/newlines
+ size_t len = strlen(name);
+ while (len > 0 && (name[len-1] == '\n' || name[len-1] == '\r' || name[len-1] == ' ')) {
+ name[len-1] = '\0';
+ len--;
+ }
+ if (!name[0]) return;
+ CBMDefinition def;
+ memset(&def, 0, sizeof(def));
+ def.name = name;
+ def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
+ def.label = "Section"; // NOT "Class" — avoids polluting class queries
+ def.file_path = ctx->rel_path;
+ def.start_line = ts_node_start_point(node).row + 1;
+ def.end_line = ts_node_end_point(node).row + 1;
+ def.is_exported = true;
+ cbm_defs_push(&ctx->result->defs, a, def);
+ return;
+ }
+
// HCL blocks need special handling
if (ctx->language == CBM_LANG_HCL && strcmp(kind, "block") == 0) {
// Simple: use first identifier child as name
@@ -691,8 +963,12 @@ static TSNode resolve_method_name(TSNode child, CBMLanguage lang) {
const char* ck = ts_node_type(child);
- // Groovy: function_definition has identifier child (no "name" field)
+ // Groovy: function_definition uses field_function for the method name (not field_name).
+ // e.g., "String greet()" → {field_type:String, field_function:greet, ...}
+ // Using the first identifier would pick up the return type instead of the name.
if (lang == CBM_LANG_GROOVY && strcmp(ck, "function_definition") == 0) {
+ TSNode fn = ts_node_child_by_field_name(child, "function", 8);
+ if (!ts_node_is_null(fn)) return fn;
return cbm_find_child_by_kind(child, "identifier");
}
@@ -1306,6 +1582,89 @@ static void extract_var_names(CBMExtractCtx* ctx, TSNode node, const CBMLangSpec
}
break;
}
+ case CBM_LANG_TOML: {
+ // pair: first child is bare_key/dotted_key/quoted_key
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(node, i);
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "bare_key") == 0 || strcmp(ck, "dotted_key") == 0 ||
+ strcmp(ck, "quoted_key") == 0 || strcmp(ck, "key") == 0) {
+ push_var_def(ctx, cbm_node_text(a, child, ctx->source), node);
+ break;
+ }
+ }
+ break;
+ }
+ case CBM_LANG_JSON: {
+ // pair: "key" field is a string node, extract unquoted text
+ TSNode key_node = ts_node_child_by_field_name(node, "key", 3);
+ if (!ts_node_is_null(key_node)) {
+ char* raw = cbm_node_text(a, key_node, ctx->source);
+ if (raw) {
+ // Strip surrounding quotes if present
+ size_t rlen = strlen(raw);
+ if (rlen >= 2 && raw[0] == '"' && raw[rlen-1] == '"') {
+ raw[rlen-1] = '\0';
+ raw++;
+ }
+ push_var_def(ctx, raw, node);
+ }
+ }
+ break;
+ }
+ case CBM_LANG_INI: {
+ // setting: first non-whitespace child before "=" is the key name
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(node, i);
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "setting_name") == 0 || strcmp(ck, "name") == 0) {
+ char* name = cbm_node_text(a, child, ctx->source);
+ // Trim whitespace
+ if (name) {
+ while (*name == ' ' || *name == '\t') name++;
+ size_t nlen = strlen(name);
+ while (nlen > 0 && (name[nlen-1] == ' ' || name[nlen-1] == '\t')) {
+ name[nlen-1] = '\0';
+ nlen--;
+ }
+ }
+ push_var_def(ctx, name, node);
+ break;
+ }
+ }
+ // Fallback: try first child text (some INI grammars use different structure)
+ if (nc > 0) {
+ TSNode first = ts_node_child(node, 0);
+ const char* fk = ts_node_type(first);
+ if (strcmp(fk, "setting_name") != 0 && strcmp(fk, "name") != 0) {
+ // Check if we already pushed (avoid duplicate)
+ // Only try if no setting_name was found above
+ bool found_name = false;
+ for (uint32_t i = 0; i < nc; i++) {
+ const char* ck = ts_node_type(ts_node_child(node, i));
+ if (strcmp(ck, "setting_name") == 0 || strcmp(ck, "name") == 0) {
+ found_name = true;
+ break;
+ }
+ }
+ if (!found_name) {
+ char* name = cbm_node_text(a, first, ctx->source);
+ if (name) {
+ while (*name == ' ' || *name == '\t') name++;
+ size_t nlen = strlen(name);
+ while (nlen > 0 && (name[nlen-1] == ' ' || name[nlen-1] == '\t')) {
+ name[nlen-1] = '\0';
+ nlen--;
+ }
+ }
+ push_var_def(ctx, name, node);
+ }
+ }
+ }
+ break;
+ }
case CBM_LANG_ERLANG: {
// pp_define / record_decl: name from atom/var/macro_lhs child
if (strcmp(kind, "pp_define") == 0 || strcmp(kind, "record_decl") == 0) {
@@ -1404,9 +1763,10 @@ static void extract_var_names(CBMExtractCtx* ctx, TSNode node, const CBMLangSpec
}
}
-// Recursive variable walker for languages with deeply nested module structure (YAML, etc.)
+// Recursive variable walker for languages with deeply nested module structure.
+// Used by YAML, TOML, INI, JSON (config languages with nested containers).
static void walk_variables_rec(CBMExtractCtx* ctx, TSNode node, const CBMLangSpec* spec, int depth) {
- if (depth > 6) return; // safety limit
+ if (depth > 8) return; // safety limit
uint32_t count = ts_node_child_count(node);
for (uint32_t i = 0; i < count; i++) {
TSNode child = ts_node_child(node, i);
@@ -1415,13 +1775,21 @@ static void walk_variables_rec(CBMExtractCtx* ctx, TSNode node, const CBMLangSpe
if (cbm_is_module_level(child, ctx->language)) {
extract_var_names(ctx, child, spec);
}
- } else {
- // Recurse into structural nodes
- const char* ck = ts_node_type(child);
- if (strcmp(ck, "document") == 0 || strcmp(ck, "block_node") == 0 ||
- strcmp(ck, "block_mapping") == 0 || strcmp(ck, "stream") == 0) {
- walk_variables_rec(ctx, child, spec, depth + 1);
- }
+ }
+ // Always recurse into structural container nodes
+ const char* ck = ts_node_type(child);
+ if (strcmp(ck, "document") == 0 || strcmp(ck, "block_node") == 0 ||
+ strcmp(ck, "block_mapping") == 0 || strcmp(ck, "stream") == 0 ||
+ // TOML containers
+ strcmp(ck, "table") == 0 || strcmp(ck, "table_array_element") == 0 ||
+ // INI containers
+ strcmp(ck, "section") == 0 ||
+ // JSON/TOML containers (pair can contain nested objects)
+ strcmp(ck, "object") == 0 || strcmp(ck, "array") == 0 ||
+ strcmp(ck, "pair") == 0 ||
+ // XML containers
+ strcmp(ck, "element") == 0 || strcmp(ck, "content") == 0) {
+ walk_variables_rec(ctx, child, spec, depth + 1);
}
}
}
@@ -1429,8 +1797,9 @@ static void walk_variables_rec(CBMExtractCtx* ctx, TSNode node, const CBMLangSpe
static void extract_variables(CBMExtractCtx* ctx, TSNode root, const CBMLangSpec* spec) {
if (!spec->variable_node_types || !spec->variable_node_types[0]) return;
- // YAML: deeply nested structure, need recursive walk
- if (ctx->language == CBM_LANG_YAML) {
+ // Config languages with nested structure: use recursive walk
+ if (ctx->language == CBM_LANG_YAML || ctx->language == CBM_LANG_TOML ||
+ ctx->language == CBM_LANG_INI || ctx->language == CBM_LANG_JSON) {
walk_variables_rec(ctx, root, spec, 0);
return;
}
@@ -1510,6 +1879,15 @@ static void walk_defs(CBMExtractCtx* ctx, TSNode node, const CBMLangSpec* spec)
// Class types
if (cbm_kind_in_set(node, spec->class_node_types)) {
extract_class_def(ctx, node, spec);
+ // Config languages have nested classes (XML elements, TOML tables)
+ // — continue recursing instead of returning
+ if (ctx->language == CBM_LANG_XML || ctx->language == CBM_LANG_TOML ||
+ ctx->language == CBM_LANG_INI || ctx->language == CBM_LANG_MARKDOWN) {
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t ci = 0; ci < nc; ci++) {
+ walk_defs(ctx, ts_node_child(node, ci), spec);
+ }
+ }
return;
}
diff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.c
index 8813eaeb9..f175bcf1a 100644
--- a/internal/cbm/helpers.c
+++ b/internal/cbm/helpers.c
@@ -434,8 +434,11 @@ static const char* module_parents_elixir[] = {"source",NULL};
static const char* module_parents_html[] = {"document",NULL};
static const char* module_parents_css[] = {"stylesheet",NULL};
static const char* module_parents_sql[] = {"source_file","program","statement",NULL};
-static const char* module_parents_toml[] = {"document",NULL};
+static const char* module_parents_toml[] = {"document","table","table_array_element",NULL};
+static const char* module_parents_config[] = {"document","table","table_array_element","section","object","element","array",NULL};
static const char* module_parents_hcl[] = {"config_file",NULL};
+static const char* module_parents_makefile[] = {"makefile",NULL};
+static const char* module_parents_commonlisp[] = {"source",NULL};
bool cbm_is_module_level(TSNode node, CBMLanguage lang) {
TSNode parent = ts_node_parent(node);
@@ -505,11 +508,17 @@ bool cbm_is_module_level(TSNode node, CBMLanguage lang) {
case CBM_LANG_SQL: parents = module_parents_sql; break;
case CBM_LANG_TOML: parents = module_parents_toml; break;
case CBM_LANG_HCL: parents = module_parents_hcl; break;
+ case CBM_LANG_JSON:
+ case CBM_LANG_INI:
+ case CBM_LANG_XML:
+ case CBM_LANG_MARKDOWN: parents = module_parents_config; break;
case CBM_LANG_SWIFT: parents = module_parents_zig; break; // source_file
case CBM_LANG_DART: parents = module_parents_php; break; // program
case CBM_LANG_PERL: parents = module_parents_zig; break; // source_file
case CBM_LANG_GROOVY: parents = module_parents_zig; break; // source_file
case CBM_LANG_R: parents = module_parents_php; break; // program
+ case CBM_LANG_MAKEFILE: parents = module_parents_makefile; break;
+ case CBM_LANG_COMMONLISP: parents = module_parents_commonlisp; break;
default: return false;
}
if (parents) {
diff --git a/internal/cbm/lang_specs.c b/internal/cbm/lang_specs.c
index b0372b97d..d8b6f86fd 100644
--- a/internal/cbm/lang_specs.c
+++ b/internal/cbm/lang_specs.c
@@ -360,6 +360,8 @@ static const char* yaml_var_types[] = {"block_mapping_pair",NULL};
// ==================== TOML ====================
static const char* toml_module_types[] = {"document",NULL};
+static const char* toml_class_types[] = {"table","table_array_element",NULL};
+static const char* toml_var_types[] = {"pair",NULL};
// ==================== HCL ====================
static const char* hcl_class_types[] = {"block",NULL};
@@ -441,6 +443,7 @@ static const char* nix_branch_types[] = {"if_expression",NULL};
static const char* nix_var_types[] = {"binding",NULL};
// ==================== COMMON LISP ====================
+static const char* commonlisp_func_types[] = {"defun",NULL};
static const char* commonlisp_module_types[] = {"source",NULL};
static const char* commonlisp_call_types[] = {"list_lit",NULL};
@@ -488,14 +491,18 @@ static const char* elisp_call_types[] = {"list",NULL};
// ==================== JSON ====================
static const char* json_module_types[] = {"document",NULL};
+static const char* json_var_types[] = {"pair",NULL};
// ==================== XML ====================
static const char* xml_module_types[] = {"document",NULL};
+static const char* xml_class_types[] = {"element",NULL};
// ==================== MARKDOWN ====================
static const char* markdown_module_types[] = {"document",NULL};
+static const char* markdown_class_types[] = {"atx_heading","setext_heading",NULL};
// ==================== MAKEFILE ====================
+static const char* makefile_func_types[] = {"rule",NULL};
static const char* makefile_module_types[] = {"makefile",NULL};
static const char* makefile_call_types[] = {"function_call",NULL};
static const char* makefile_import_types[] = {"include_directive",NULL};
@@ -535,6 +542,8 @@ static const char* meson_var_types[] = {"assignment_statement",NULL};
// ==================== INI ====================
static const char* ini_module_types[] = {"document",NULL};
+static const char* ini_class_types[] = {"section",NULL};
+static const char* ini_var_types[] = {"setting",NULL};
// ==================== NEW LANG ENV ACCESS ====================
static const char* julia_env_funcs[] = {"ENV",NULL};
@@ -701,8 +710,8 @@ static const CBMLangSpec lang_specs[CBM_LANG_COUNT] = {
empty_types, NULL, empty_types, NULL, NULL},
// CBM_LANG_TOML
- {CBM_LANG_TOML, empty_types, empty_types, empty_types, toml_module_types, empty_types,
- empty_types, empty_types, empty_types, empty_types, empty_types,
+ {CBM_LANG_TOML, empty_types, toml_class_types, empty_types, toml_module_types, empty_types,
+ empty_types, empty_types, empty_types, toml_var_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
// CBM_LANG_HCL
@@ -746,7 +755,7 @@ static const CBMLangSpec lang_specs[CBM_LANG_COUNT] = {
empty_types, NULL, empty_types, nix_env_funcs, NULL},
// CBM_LANG_COMMONLISP
- {CBM_LANG_COMMONLISP, empty_types, empty_types, empty_types, commonlisp_module_types, commonlisp_call_types,
+ {CBM_LANG_COMMONLISP, commonlisp_func_types, empty_types, empty_types, commonlisp_module_types, commonlisp_call_types,
empty_types, empty_types, empty_types, empty_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
@@ -782,21 +791,21 @@ static const CBMLangSpec lang_specs[CBM_LANG_COUNT] = {
// CBM_LANG_JSON
{CBM_LANG_JSON, empty_types, empty_types, empty_types, json_module_types, empty_types,
- empty_types, empty_types, empty_types, empty_types, empty_types,
+ empty_types, empty_types, empty_types, json_var_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
// CBM_LANG_XML
- {CBM_LANG_XML, empty_types, empty_types, empty_types, xml_module_types, empty_types,
+ {CBM_LANG_XML, empty_types, xml_class_types, empty_types, xml_module_types, empty_types,
empty_types, empty_types, empty_types, empty_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
// CBM_LANG_MARKDOWN
- {CBM_LANG_MARKDOWN, empty_types, empty_types, empty_types, markdown_module_types, empty_types,
+ {CBM_LANG_MARKDOWN, empty_types, markdown_class_types, empty_types, markdown_module_types, empty_types,
empty_types, empty_types, empty_types, empty_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
// CBM_LANG_MAKEFILE
- {CBM_LANG_MAKEFILE, empty_types, empty_types, empty_types, makefile_module_types, makefile_call_types,
+ {CBM_LANG_MAKEFILE, makefile_func_types, empty_types, empty_types, makefile_module_types, makefile_call_types,
makefile_import_types, empty_types, empty_types, makefile_var_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
@@ -836,8 +845,8 @@ static const CBMLangSpec lang_specs[CBM_LANG_COUNT] = {
empty_types, NULL, empty_types, NULL, NULL},
// CBM_LANG_INI
- {CBM_LANG_INI, empty_types, empty_types, empty_types, ini_module_types, empty_types,
- empty_types, empty_types, empty_types, empty_types, empty_types,
+ {CBM_LANG_INI, empty_types, ini_class_types, empty_types, ini_module_types, empty_types,
+ empty_types, empty_types, empty_types, ini_var_types, empty_types,
empty_types, NULL, empty_types, NULL, NULL},
};
diff --git a/internal/cbm/language_failures_test.go b/internal/cbm/language_failures_test.go
new file mode 100644
index 000000000..f3e21a7e0
--- /dev/null
+++ b/internal/cbm/language_failures_test.go
@@ -0,0 +1,155 @@
+package cbm
+
+import (
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/lang"
+)
+
+// =====================================================================
+// CONFIRMED RED: CommonLisp — defun never matched (empty func_types)
+// =====================================================================
+
+func TestCommonLispDefunExtraction(t *testing.T) {
+ source := []byte("(defun hello () \"world\")\n")
+ result, err := ExtractFile(source, lang.CommonLisp, "test", "hello.lisp")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) == 0 {
+ t.Errorf("expected >=1 Function from CommonLisp defun, got 0 (commonlisp_func_types is empty)")
+ }
+ assertHasName(t, fns, "hello")
+}
+
+func TestCommonLispMultipleFunctions(t *testing.T) {
+ source := []byte("(defun add (a b) (+ a b))\n(defun mul (a b) (* a b))\n")
+ result, err := ExtractFile(source, lang.CommonLisp, "test", "math.lisp")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) < 2 {
+ t.Errorf("expected >=2 Functions (add, mul), got %d: %v", len(fns), names(fns))
+ }
+ assertHasName(t, fns, "add")
+ assertHasName(t, fns, "mul")
+}
+
+func TestCommonLispDefmacro(t *testing.T) {
+ source := []byte("(defmacro when2 (condition &body body)\n `(if ,condition (progn ,@body)))\n")
+ result, err := ExtractFile(source, lang.CommonLisp, "test", "macros.lisp")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // defmacro is a separate node type; this test just ensures no crash
+ _ = result
+}
+
+// =====================================================================
+// CONFIRMED RED: Makefile — rule not in function_node_types
+// =====================================================================
+
+func TestMakefileRuleAsFunction(t *testing.T) {
+ source := []byte("all:\n\t@echo hello\n")
+ result, err := ExtractFile(source, lang.Makefile, "test", "Makefile")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) == 0 {
+ t.Errorf("expected >=1 Function (target 'all'), got 0 (rule not in func_types)")
+ }
+ assertHasName(t, fns, "all")
+}
+
+func TestMakefileMultipleTargets(t *testing.T) {
+ source := []byte("all: main.o\n\tgcc -o all main.o\n\nbuild:\n\tgo build ./...\n")
+ result, err := ExtractFile(source, lang.Makefile, "test", "Makefile")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) < 2 {
+ t.Errorf("expected >=2 Functions (all, build), got %d: %v", len(fns), names(fns))
+ }
+ assertHasName(t, fns, "all")
+ assertHasName(t, fns, "build")
+}
+
+func TestMakefileVariableExtraction(t *testing.T) {
+ source := []byte("CC := gcc\nCFLAGS := -Wall\n")
+ result, err := ExtractFile(source, lang.Makefile, "test", "Makefile")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(result, "Variable")
+ // variable_assignment is in VariableNodeTypes; this probe reveals if name extraction works
+ if len(vars) == 0 {
+ t.Logf("INFO: Makefile variable extraction returns 0 vars — name field may need a Makefile case in extract_var_names")
+ } else {
+ assertHasName(t, vars, "CC")
+ assertHasName(t, vars, "CFLAGS")
+ }
+}
+
+// =====================================================================
+// PROBE: VimScript — may pass or fail; reveals root cause
+// =====================================================================
+
+func TestVimScriptFunctionExtraction(t *testing.T) {
+ source := []byte("function! SayHello()\n echo 'Hello'\nendfunction\n")
+ result, err := ExtractFile(source, lang.VimScript, "test", "plugin.vim")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) == 0 {
+ t.Errorf("expected >=1 Function from VimScript function!, got 0 — name field on function_definition may not be exposed directly")
+ }
+ assertHasName(t, fns, "SayHello")
+}
+
+func TestVimScriptFunctionWithoutBang(t *testing.T) {
+ source := []byte("function MyFunc(arg)\n return arg\nendfunction\n")
+ result, err := ExtractFile(source, lang.VimScript, "test", "plugin.vim")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) == 0 {
+ t.Errorf("expected >=1 Function from VimScript function (no bang), got 0")
+ }
+ assertHasName(t, fns, "MyFunc")
+}
+
+// =====================================================================
+// PROBE: Julia — may pass or fail; reveals whether 0.00 is grammar or discovery
+// =====================================================================
+
+func TestJuliaFunctionExtraction(t *testing.T) {
+ source := []byte("function hello()\n println(\"Hello, World!\")\nend\n")
+ result, err := ExtractFile(source, lang.Julia, "test", "hello.jl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) == 0 {
+ t.Errorf("expected >=1 Function from Julia function_definition, got 0")
+ }
+ assertHasName(t, fns, "hello")
+}
+
+func TestJuliaFunctionWithArgs(t *testing.T) {
+ source := []byte("function add(a::Int, b::Int)::Int\n return a + b\nend\n")
+ result, err := ExtractFile(source, lang.Julia, "test", "math.jl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fns := defsWithLabel(result, "Function")
+ if len(fns) == 0 {
+ t.Errorf("expected >=1 Function from Julia function with args, got 0")
+ }
+ assertHasName(t, fns, "add")
+}
diff --git a/internal/cbm/regression_test.go b/internal/cbm/regression_test.go
new file mode 100644
index 000000000..8562b90c1
--- /dev/null
+++ b/internal/cbm/regression_test.go
@@ -0,0 +1,933 @@
+package cbm
+
+import (
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/lang"
+)
+
+// =====================================================================
+// Group A: OOP Languages
+// =====================================================================
+
+// --- Java ---
+func TestJavaClass_Regression(t *testing.T) {
+ src := []byte("public class Animal { private String name; public String getName() { return name; } }")
+ r, err := ExtractFile(src, lang.Java, "t", "Animal.java")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Animal")
+}
+
+func TestJavaMethod_Regression(t *testing.T) {
+ src := []byte("public class Svc { public void doWork() {} public int compute(int x) { return x; } }")
+ r, err := ExtractFile(src, lang.Java, "t", "Svc.java")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Method"), "doWork")
+ assertHasName(t, defsWithLabel(r, "Method"), "compute")
+}
+
+func TestJavaInterface_Regression(t *testing.T) {
+ src := []byte("public interface Repository { void save(Object o); Object findById(long id); }")
+ r, err := ExtractFile(src, lang.Java, "t", "Repo.java")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defs := r.Definitions
+ found := false
+ for _, d := range defs {
+ if d.Name == "Repository" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("interface Repository not found")
+ }
+}
+
+// --- PHP ---
+func TestPHPClass_Regression(t *testing.T) {
+ src := []byte("<?php\nclass User { public string $name; public function getName(): string { return $this->name; } }")
+ r, err := ExtractFile(src, lang.PHP, "t", "User.php")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "User")
+ assertHasName(t, defsWithLabel(r, "Method"), "getName")
+}
+
+func TestPHPFunction_Regression(t *testing.T) {
+ src := []byte("<?php\nfunction greet(string $name): string { return 'Hello ' . $name; }")
+ r, err := ExtractFile(src, lang.PHP, "t", "helpers.php")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+// --- Ruby ---
+func TestRubyClass_Regression(t *testing.T) {
+ src := []byte("class Animal\n def initialize(name)\n @name = name\n end\n def speak\n puts @name\n end\nend\n")
+ r, err := ExtractFile(src, lang.Ruby, "t", "animal.rb")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Animal")
+ assertHasName(t, defsWithLabel(r, "Method"), "speak")
+}
+
+func TestRubyModule_Regression(t *testing.T) {
+ src := []byte("module Greetable\n def greet\n \"Hello\"\n end\nend\n")
+ r, err := ExtractFile(src, lang.Ruby, "t", "greetable.rb")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defs := r.Definitions
+ found := false
+ for _, d := range defs {
+ if d.Name == "Greetable" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("module Greetable not found")
+ }
+}
+
+// --- C# ---
+func TestCSharpClass_Regression(t *testing.T) {
+ src := []byte("namespace App { public class Service { public void Run() {} public int Compute(int x) => x * 2; } }")
+ r, err := ExtractFile(src, lang.CSharp, "t", "Service.cs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Service")
+ assertHasName(t, defsWithLabel(r, "Method"), "Run")
+}
+
+func TestCSharpInterface_Regression(t *testing.T) {
+ src := []byte("public interface IService { void Execute(); string GetStatus(); }")
+ r, err := ExtractFile(src, lang.CSharp, "t", "IService.cs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defs := r.Definitions
+ found := false
+ for _, d := range defs {
+ if d.Name == "IService" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("interface IService not found")
+ }
+}
+
+// --- Swift ---
+func TestSwiftClass_Regression(t *testing.T) {
+ src := []byte("class Vehicle {\n var speed: Int = 0\n func accelerate() { speed += 10 }\n func stop() { speed = 0 }\n}\n")
+ r, err := ExtractFile(src, lang.Swift, "t", "Vehicle.swift")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Vehicle")
+ assertHasName(t, defsWithLabel(r, "Method"), "accelerate")
+}
+
+func TestSwiftStruct_Regression(t *testing.T) {
+ src := []byte("struct Point {\n var x: Double\n var y: Double\n func distance() -> Double { return (x*x + y*y).squareRoot() }\n}\n")
+ r, err := ExtractFile(src, lang.Swift, "t", "Point.swift")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Method"), "distance")
+}
+
+// --- Kotlin ---
+func TestKotlinFunction_Regression(t *testing.T) {
+ src := []byte("fun greet(name: String): String = \"Hello $name\"\nfun main() { println(greet(\"World\")) }\n")
+ r, err := ExtractFile(src, lang.Kotlin, "t", "main.kt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestKotlinClass_Regression(t *testing.T) {
+ src := []byte("class User(val name: String) {\n fun display(): String = \"User: $name\"\n}\n")
+ r, err := ExtractFile(src, lang.Kotlin, "t", "User.kt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "User")
+}
+
+// --- Scala ---
+func TestScalaFunction_Regression(t *testing.T) {
+ src := []byte("object Main {\n def greet(name: String): String = s\"Hello $name\"\n def main(args: Array[String]): Unit = println(greet(\"World\"))\n}\n")
+ r, err := ExtractFile(src, lang.Scala, "t", "Main.scala")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Method"), "greet")
+}
+
+func TestScalaClass_Regression(t *testing.T) {
+ src := []byte("class Animal(val name: String) {\n def speak(): String = s\"I am $name\"\n}\n")
+ r, err := ExtractFile(src, lang.Scala, "t", "Animal.scala")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Animal")
+}
+
+// --- Objective-C ---
+func TestObjCInterface_Regression(t *testing.T) {
+ src := []byte("@interface Animal : NSObject\n- (NSString *)name;\n- (void)speak;\n@end\n")
+ r, err := ExtractFile(src, lang.ObjectiveC, "t", "Animal.h")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from ObjC interface")
+ }
+}
+
+func TestObjCImplementation_Regression(t *testing.T) {
+ src := []byte("@implementation Animal\n- (NSString *)name { return @\"Animal\"; }\n- (void)speak { NSLog(@\"...\"); }\n@end\n")
+ r, err := ExtractFile(src, lang.ObjectiveC, "t", "Animal.m")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from ObjC impl")
+ }
+}
+
+// --- Dart ---
+func TestDartClass_Regression(t *testing.T) {
+ src := []byte("class Animal {\n String name;\n Animal(this.name);\n String speak() => 'I am $name';\n}\n")
+ r, err := ExtractFile(src, lang.Dart, "t", "animal.dart")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Animal")
+ assertHasName(t, defsWithLabel(r, "Method"), "speak")
+}
+
+func TestDartTopLevelFunction_Regression(t *testing.T) {
+ src := []byte("void main() {\n print('Hello');\n}\nString greet(String name) => 'Hello $name';\n")
+ r, err := ExtractFile(src, lang.Dart, "t", "main.dart")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+// --- Groovy ---
+func TestGroovyClass_Regression(t *testing.T) {
+ src := []byte("class Greeter {\n String name\n String greet() { \"Hello, $name\" }\n static void main(args) { println new Greeter(name:'World').greet() }\n}\n")
+ r, err := ExtractFile(src, lang.Groovy, "t", "Greeter.groovy")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Greeter")
+ assertHasName(t, defsWithLabel(r, "Method"), "greet")
+}
+
+// =====================================================================
+// Group B: Systems Languages
+// =====================================================================
+
+// --- Rust ---
+func TestRustFunction_Regression(t *testing.T) {
+ src := []byte("fn main() { println!(\"Hello\"); }\npub fn add(a: i32, b: i32) -> i32 { a + b }\n")
+ r, err := ExtractFile(src, lang.Rust, "t", "main.rs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+ assertHasName(t, defsWithLabel(r, "Function"), "add")
+}
+
+func TestRustStruct_Regression(t *testing.T) {
+ src := []byte("pub struct Point { pub x: f64, pub y: f64 }\nimpl Point { pub fn new(x: f64, y: f64) -> Self { Point { x, y } } }\n")
+ r, err := ExtractFile(src, lang.Rust, "t", "point.rs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Point")
+ assertHasName(t, defsWithLabel(r, "Method"), "new")
+}
+
+func TestRustEnum_Regression(t *testing.T) {
+ src := []byte("pub enum Direction { North, South, East, West }\n")
+ r, err := ExtractFile(src, lang.Rust, "t", "dir.rs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition for Rust enum")
+ }
+}
+
+// --- Go ---
+func TestGoFunction_Regression(t *testing.T) {
+ src := []byte("package main\nfunc Greet(name string) string { return \"Hello, \" + name }\nfunc main() { Greet(\"World\") }\n")
+ r, err := ExtractFile(src, lang.Go, "t", "main.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "Greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestGoStruct_Regression(t *testing.T) {
+ src := []byte("package main\ntype Server struct { Host string; Port int }\nfunc (s *Server) Start() error { return nil }\n")
+ r, err := ExtractFile(src, lang.Go, "t", "server.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Server")
+ assertHasName(t, defsWithLabel(r, "Method"), "Start")
+}
+
+func TestGoInterface_Regression(t *testing.T) {
+ src := []byte("package main\ntype Handler interface { ServeHTTP() error; Close() }\n")
+ r, err := ExtractFile(src, lang.Go, "t", "handler.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defs := r.Definitions
+ found := false
+ for _, d := range defs {
+ if d.Name == "Handler" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("interface Handler not found")
+ }
+}
+
+// --- Zig ---
+func TestZigFunction_Regression(t *testing.T) {
+ src := []byte("pub fn add(a: i32, b: i32) i32 { return a + b; }\npub fn main() void { _ = add(1, 2); }\n")
+ r, err := ExtractFile(src, lang.Zig, "t", "main.zig")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "add")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestZigStruct_Regression(t *testing.T) {
+ src := []byte("const Point = struct { x: f32, y: f32, pub fn dist(self: Point) f32 { return self.x + self.y; } };\n")
+ r, err := ExtractFile(src, lang.Zig, "t", "point.zig")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Zig struct")
+ }
+}
+
+// --- C ---
+func TestCFunction_Regression(t *testing.T) {
+ src := []byte("#include <stdio.h>\nint add(int a, int b) { return a + b; }\nint main() { printf(\"%d\\n\", add(1,2)); return 0; }\n")
+ r, err := ExtractFile(src, lang.C, "t", "main.c")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "add")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestCStruct_Regression(t *testing.T) {
+ src := []byte("struct Point { int x; int y; };\nvoid print_point(struct Point p) { /* ... */ }\n")
+ r, err := ExtractFile(src, lang.C, "t", "point.c")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "print_point")
+}
+
+// --- C++ ---
+func TestCppFunction_Regression(t *testing.T) {
+ src := []byte("#include <string>\nstd::string greet(const std::string& name) { return \"Hello \" + name; }\nint main() { return 0; }\n")
+ r, err := ExtractFile(src, lang.CPP, "t", "main.cpp")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from C++ file")
+ }
+}
+
+func TestCppClass_Regression(t *testing.T) {
+ src := []byte("class Animal {\npublic:\n std::string name;\n Animal(std::string n) : name(n) {}\n void speak() { /* ... */ }\n};\n")
+ r, err := ExtractFile(src, lang.CPP, "t", "Animal.cpp")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from C++ class")
+ }
+}
+
+// --- COBOL ---
+func TestCOBOLParagraph_Regression(t *testing.T) {
+ src := []byte("IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\nPROCEDURE DIVISION.\n DISPLAY-GREETING.\n DISPLAY 'HELLO WORLD'.\n STOP RUN.\n")
+ r, err := ExtractFile(src, lang.COBOL, "t", "hello.cbl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from COBOL")
+ }
+}
+
+// --- Verilog ---
+func TestVerilogModule_Regression(t *testing.T) {
+ src := []byte("module adder(input a, input b, output sum);\n assign sum = a + b;\nendmodule\n")
+ r, err := ExtractFile(src, lang.Verilog, "t", "adder.v")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Verilog")
+ }
+}
+
+// --- CUDA ---
+func TestCUDAKernel_Regression(t *testing.T) {
+ src := []byte("__global__ void vectorAdd(float *a, float *b, float *c, int n) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i < n) c[i] = a[i] + b[i];\n}\nint main() { return 0; }\n")
+ r, err := ExtractFile(src, lang.CUDA, "t", "vector.cu")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from CUDA file")
+ }
+}
+
+// =====================================================================
+// Group C: Dynamic Languages
+// =====================================================================
+
+// --- Python ---
+func TestPythonFunction_Regression(t *testing.T) {
+ src := []byte("def greet(name: str) -> str:\n return f'Hello {name}'\n\ndef main():\n print(greet('World'))\n")
+ r, err := ExtractFile(src, lang.Python, "t", "hello.py")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestPythonClass_Regression(t *testing.T) {
+ src := []byte("class Animal:\n def __init__(self, name: str):\n self.name = name\n def speak(self) -> str:\n return f'I am {self.name}'\n")
+ r, err := ExtractFile(src, lang.Python, "t", "animal.py")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Animal")
+ assertHasName(t, defsWithLabel(r, "Method"), "speak")
+}
+
+func TestPythonDecorator_Regression(t *testing.T) {
+ src := []byte("class Router:\n @staticmethod\n def route(path: str):\n def decorator(func): return func\n return decorator\n")
+ r, err := ExtractFile(src, lang.Python, "t", "router.py")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Router")
+}
+
+// --- JavaScript ---
+func TestJavaScriptFunction_Regression(t *testing.T) {
+ src := []byte("function greet(name) { return 'Hello ' + name; }\nconst add = (a, b) => a + b;\nmodule.exports = { greet, add };\n")
+ r, err := ExtractFile(src, lang.JavaScript, "t", "utils.js")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+func TestJavaScriptClass_Regression(t *testing.T) {
+ src := []byte("class Animal {\n constructor(name) { this.name = name; }\n speak() { return `I am ${this.name}`; }\n}\nmodule.exports = Animal;\n")
+ r, err := ExtractFile(src, lang.JavaScript, "t", "Animal.js")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Animal")
+ assertHasName(t, defsWithLabel(r, "Method"), "speak")
+}
+
+// --- TypeScript ---
+func TestTypeScriptFunction_Regression(t *testing.T) {
+ src := []byte("export function greet(name: string): string { return `Hello ${name}`; }\nexport const add = (a: number, b: number): number => a + b;\n")
+ r, err := ExtractFile(src, lang.TypeScript, "t", "utils.ts")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+func TestTypeScriptInterface_Regression(t *testing.T) {
+ src := []byte("export interface Repository<T> { findById(id: number): T; save(entity: T): void; delete(id: number): void; }\n")
+ r, err := ExtractFile(src, lang.TypeScript, "t", "repo.ts")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from TypeScript interface")
+ }
+}
+
+func TestTypeScriptClass_Regression(t *testing.T) {
+ src := []byte("export class UserService {\n private users: Map<number, string> = new Map();\n add(id: number, name: string): void { this.users.set(id, name); }\n get(id: number): string | undefined { return this.users.get(id); }\n}\n")
+ r, err := ExtractFile(src, lang.TypeScript, "t", "UserService.ts")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "UserService")
+}
+
+// --- TSX ---
+func TestTSXComponent_Regression(t *testing.T) {
+ src := []byte("import React from 'react';\ninterface Props { name: string; }\nexport function Greeting({ name }: Props) {\n return <div>Hello {name}</div>;\n}\nexport default Greeting;\n")
+ r, err := ExtractFile(src, lang.TSX, "t", "Greeting.tsx")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "Greeting")
+}
+
+// --- Lua ---
+func TestLuaFunction_Regression(t *testing.T) {
+ src := []byte("local function greet(name)\n return 'Hello ' .. name\nend\nlocal function main()\n print(greet('World'))\nend\nmain()\n")
+ r, err := ExtractFile(src, lang.Lua, "t", "main.lua")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestLuaTableMethod_Regression(t *testing.T) {
+ src := []byte("local M = {}\nfunction M.create(name)\n return { name = name }\nend\nfunction M.greet(self)\n return 'Hi ' .. self.name\nend\nreturn M\n")
+ r, err := ExtractFile(src, lang.Lua, "t", "module.lua")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(defsWithLabel(r, "Function")) < 1 {
+ t.Error("expected >=1 Function from Lua table method")
+ }
+}
+
+// --- Bash ---
+func TestBashFunction_Regression(t *testing.T) {
+ src := []byte("#!/usr/bin/env bash\ngreet() {\n echo \"Hello $1\"\n}\nbuild_project() {\n go build ./...\n}\ngreet World\n")
+ r, err := ExtractFile(src, lang.Bash, "t", "build.sh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "build_project")
+}
+
+// --- Nix ---
+func TestNixFunction_Regression(t *testing.T) {
+ src := []byte("{ pkgs ? import <nixpkgs> {} }:\nlet\n greet = name: \"Hello ${name}\";\n build = src: pkgs.stdenv.mkDerivation { inherit src; };\nin\n{ inherit greet build; }\n")
+ r, err := ExtractFile(src, lang.Nix, "t", "default.nix")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Nix file")
+ }
+}
+
+// --- EmacsLisp (critical: must not be broken by CommonLisp fix) ---
+func TestEmacsLispDefun_Regression(t *testing.T) {
+ src := []byte("(defun greet (name)\n (message \"Hello %s\" name))\n(defun main ()\n (greet \"World\"))\n")
+ r, err := ExtractFile(src, lang.EmacsLisp, "t", "init.el")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+func TestEmacsLispDefvar_Regression(t *testing.T) {
+ src := []byte("(defvar my-count 0 \"A counter.\")\n(defcustom my-name \"World\" \"The name.\"\n :type 'string)\n")
+ r, err := ExtractFile(src, lang.EmacsLisp, "t", "vars.el")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from EmacsLisp vars")
+ }
+}
+
+// --- R ---
+func TestRFunction_Regression(t *testing.T) {
+ src := []byte("greet <- function(name) {\n paste(\"Hello\", name)\n}\nmain <- function() {\n print(greet(\"World\"))\n}\n")
+ r, err := ExtractFile(src, lang.R, "t", "main.R")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+// --- Perl ---
+func TestPerlFunction_Regression(t *testing.T) {
+ src := []byte("sub greet {\n my ($name) = @_;\n return \"Hello $name\";\n}\nsub main {\n print greet('World'), \"\\n\";\n}\nmain();\n")
+ r, err := ExtractFile(src, lang.Perl, "t", "main.pl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+// =====================================================================
+// Group D: Functional Languages
+// =====================================================================
+
+// --- Haskell ---
+func TestHaskellFunction_Regression(t *testing.T) {
+ src := []byte("module Main where\ngreet :: String -> String\ngreet name = \"Hello \" ++ name\nmain :: IO ()\nmain = putStrLn (greet \"World\")\n")
+ r, err := ExtractFile(src, lang.Haskell, "t", "Main.hs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // greet (with args) uses prod_id 151 with inherited field_name — always extracted
+ // main = ... (no args) uses prod_id 77 with no field_name — not extracted (known limitation)
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+func TestHaskellDataType_Regression(t *testing.T) {
+ src := []byte("data Shape = Circle Double | Rectangle Double Double\narea :: Shape -> Double\narea (Circle r) = pi * r * r\narea (Rectangle w h) = w * h\n")
+ r, err := ExtractFile(src, lang.Haskell, "t", "Shape.hs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Haskell data type")
+ }
+}
+
+// --- Erlang ---
+func TestErlangFunction_Regression(t *testing.T) {
+ src := []byte("-module(hello).\n-export([greet/1, main/0]).\ngreet(Name) -> io:format(\"Hello ~s~n\", [Name]).\nmain() -> greet(\"World\").\n")
+ r, err := ExtractFile(src, lang.Erlang, "t", "hello.erl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+// --- Elm ---
+func TestElmFunction_Regression(t *testing.T) {
+ src := []byte("module Main exposing (..)\nimport Html exposing (text)\ngreet : String -> String\ngreet name = \"Hello \" ++ name\nmain = text (greet \"World\")\n")
+ r, err := ExtractFile(src, lang.Elm, "t", "Main.elm")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+ assertHasName(t, defsWithLabel(r, "Function"), "main")
+}
+
+// --- Elixir ---
+func TestElixirFunction_Regression(t *testing.T) {
+ src := []byte("defmodule Greeter do\n def greet(name) do\n \"Hello #{name}\"\n end\n def main do\n IO.puts(greet(\"World\"))\n end\nend\n")
+ r, err := ExtractFile(src, lang.Elixir, "t", "greeter.ex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "Greeter")
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+// --- F# ---
+func TestFSharpFunction_Regression(t *testing.T) {
+ src := []byte("module Greeter\nlet greet name = sprintf \"Hello %s\" name\nlet main argv =\n printfn \"%s\" (greet \"World\")\n 0\n")
+ r, err := ExtractFile(src, lang.FSharp, "t", "Greeter.fs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from F# module")
+ }
+}
+
+// --- Clojure ---
+func TestClojureFunction_Regression(t *testing.T) {
+ // Clojure uses list_lit for all forms including defn — no dedicated defn node type.
+ // FunctionNodeTypes is empty, so no function definitions are extracted (known limitation).
+ // The test just verifies extraction completes without error.
+ src := []byte("(ns greeter.core)\n(defn greet [name]\n (str \"Hello \" name))\n(defn -main [& args]\n (println (greet \"World\")))\n")
+ _, err := ExtractFile(src, lang.Clojure, "t", "core.clj")
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+// --- OCaml ---
+func TestOCamlFunction_Regression(t *testing.T) {
+ src := []byte("let greet name = Printf.sprintf \"Hello %s\" name\nlet () = print_endline (greet \"World\")\n")
+ r, err := ExtractFile(src, lang.OCaml, "t", "main.ml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Function"), "greet")
+}
+
+// =====================================================================
+// Group E: Config / Markup Languages
+// =====================================================================
+
+// --- YAML ---
+func TestYAMLMapping_Regression(t *testing.T) {
+ src := []byte("server:\n host: localhost\n port: 8080\ndatabase:\n url: postgres://localhost/mydb\n")
+ r, err := ExtractFile(src, lang.YAML, "t", "config.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(r, "Variable")
+ if len(vars) < 1 {
+ t.Errorf("expected >=1 Variable from YAML, got 0")
+ }
+}
+
+// --- Dockerfile ---
+func TestDockerfileInstruction_Regression(t *testing.T) {
+ src := []byte("FROM golang:1.21 AS builder\nWORKDIR /app\nCOPY . .\nRUN go build -o server ./cmd/server\nFROM alpine:3.18\nCOPY --from=builder /app/server /usr/local/bin/server\nEXPOSE 8080\nCMD [\"server\"]\n")
+ r, err := ExtractFile(src, lang.Dockerfile, "t", "Dockerfile")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Dockerfile")
+ }
+}
+
+// --- HTML ---
+func TestHTMLElements_Regression(t *testing.T) {
+ src := []byte("<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello</h1><p>World</p></body></html>")
+ r, err := ExtractFile(src, lang.HTML, "t", "index.html")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from HTML")
+ }
+}
+
+// --- SQL ---
+func TestSQLTable_Regression(t *testing.T) {
+ src := []byte("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE);\nCREATE INDEX idx_users_email ON users(email);\n")
+ r, err := ExtractFile(src, lang.SQL, "t", "schema.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from SQL")
+ }
+}
+
+func TestSQLFunction_Regression(t *testing.T) {
+ src := []byte("CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$ SELECT COUNT(*) FROM users; $$ LANGUAGE SQL;\n")
+ r, err := ExtractFile(src, lang.SQL, "t", "funcs.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from SQL function")
+ }
+}
+
+// --- Meson ---
+func TestMesonProject_Regression(t *testing.T) {
+ src := []byte("project('myapp', 'c', version: '1.0.0')\nexecutable('myapp', 'main.c', install: true)\n")
+ r, err := ExtractFile(src, lang.Meson, "t", "meson.build")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from meson.build")
+ }
+}
+
+// --- CSS ---
+func TestCSSRules_Regression(t *testing.T) {
+ src := []byte(".container { display: flex; width: 100%; }\n.button { background: #007bff; color: white; border: none; }\n@media (max-width: 768px) { .container { flex-direction: column; } }\n")
+ r, err := ExtractFile(src, lang.CSS, "t", "styles.css")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from CSS")
+ }
+}
+
+// --- HCL (Terraform) ---
+func TestHCLResource_Regression(t *testing.T) {
+ src := []byte("resource \"aws_instance\" \"web\" {\n ami = \"ami-12345678\"\n instance_type = \"t3.micro\"\n tags = { Name = \"web-server\" }\n}\n")
+ r, err := ExtractFile(src, lang.HCL, "t", "main.tf")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from HCL/Terraform")
+ }
+}
+
+// --- SCSS ---
+func TestSCSSRules_Regression(t *testing.T) {
+ src := []byte("$primary: #007bff;\n.container {\n width: 100%;\n .button {\n background: $primary;\n &:hover { opacity: 0.8; }\n }\n}\n")
+ r, err := ExtractFile(src, lang.SCSS, "t", "styles.scss")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from SCSS")
+ }
+}
+
+// --- TOML (critical: must not be broken by config lang changes) ---
+func TestTOMLBasic_Regression(t *testing.T) {
+ src := []byte("[server]\nhost = \"localhost\"\nport = 8080\n\n[database]\nurl = \"postgres://localhost/db\"\nmax_connections = 10\n")
+ r, err := ExtractFile(src, lang.TOML, "t", "config.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertHasName(t, defsWithLabel(r, "Class"), "server")
+ assertHasName(t, defsWithLabel(r, "Class"), "database")
+ assertHasName(t, defsWithLabel(r, "Variable"), "host")
+ assertHasName(t, defsWithLabel(r, "Variable"), "port")
+}
+
+// --- CMake ---
+func TestCMakeFunction_Regression(t *testing.T) {
+ src := []byte("cmake_minimum_required(VERSION 3.16)\nproject(MyApp VERSION 1.0)\nadd_executable(myapp main.cpp)\ntarget_compile_features(myapp PRIVATE cxx_std_17)\n")
+ r, err := ExtractFile(src, lang.CMake, "t", "CMakeLists.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from CMakeLists.txt")
+ }
+}
+
+// --- JSON ---
+func TestJSONObject_Regression(t *testing.T) {
+ src := []byte("{\"name\": \"myapp\", \"version\": \"1.0.0\", \"scripts\": {\"build\": \"go build\", \"test\": \"go test ./...\"}}")
+ r, err := ExtractFile(src, lang.JSON, "t", "config.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ vars := defsWithLabel(r, "Variable")
+ assertHasName(t, vars, "name")
+ assertHasName(t, vars, "version")
+}
+
+// --- Protobuf ---
+func TestProtobufMessage_Regression(t *testing.T) {
+ src := []byte("syntax = \"proto3\";\npackage user;\nmessage User { int64 id = 1; string name = 2; string email = 3; }\nservice UserService { rpc GetUser(User) returns (User); }\n")
+ r, err := ExtractFile(src, lang.Protobuf, "t", "user.proto")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Protobuf")
+ }
+}
+
+// --- GraphQL ---
+func TestGraphQLType_Regression(t *testing.T) {
+ src := []byte("type User {\n id: ID!\n name: String!\n email: String!\n}\ntype Query {\n user(id: ID!): User\n users: [User!]!\n}\n")
+ r, err := ExtractFile(src, lang.GraphQL, "t", "schema.graphql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from GraphQL schema")
+ }
+}
+
+// --- Svelte ---
+func TestSvelteComponent_Regression(t *testing.T) {
+ src := []byte("<script>\n let name = 'World';\n function greet() {\n return `Hello ${name}`;\n }\n</script>\n<h1>{greet()}</h1>\n")
+ r, err := ExtractFile(src, lang.Svelte, "t", "App.svelte")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Svelte component")
+ }
+}
+
+// --- Vue ---
+func TestVueComponent_Regression(t *testing.T) {
+ src := []byte("<template><div>{{ message }}</div></template>\n<script>\nexport default {\n name: 'App',\n data() { return { message: 'Hello World' }; },\n methods: { greet() { return this.message; } }\n};\n</script>\n")
+ r, err := ExtractFile(src, lang.Vue, "t", "App.vue")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from Vue component")
+ }
+}
+
+// --- GLSL ---
+func TestGLSLShader_Regression(t *testing.T) {
+ src := []byte("#version 330 core\nvoid main() {\n gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n}\nvec3 transform(vec3 pos, mat4 mvp) {\n return (mvp * vec4(pos, 1.0)).xyz;\n}\n")
+ r, err := ExtractFile(src, lang.GLSL, "t", "vertex.glsl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(r.Definitions) < 1 {
+ t.Error("expected >=1 definition from GLSL shader")
+ }
+}
+
+// --- Julia ---
+func TestJuliaFunction_Regression(t *testing.T) {
+ src := []byte("function hello()\n println(\"Hello, World!\")\nend\n")
+ r, err := ExtractFile(src, lang.Julia, "t", "hello.jl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // If Julia extraction works, verify the function name
+ fns := defsWithLabel(r, "Function")
+ if len(fns) > 0 {
+ assertHasName(t, fns, "hello")
+ }
+ // If len(fns) == 0, Julia extraction is broken — tracked by TestJuliaFunctionExtraction
+}
+
+// --- VimScript ---
+func TestVimScriptFunction_Regression(t *testing.T) {
+ src := []byte("function! SayHello()\n echo 'Hello'\nendfunction\n")
+ r, err := ExtractFile(src, lang.VimScript, "t", "plugin.vim")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // If VimScript extraction works, verify the function name
+ fns := defsWithLabel(r, "Function")
+ if len(fns) > 0 {
+ assertHasName(t, fns, "SayHello")
+ }
+ // If len(fns) == 0, VimScript extraction is broken — tracked by TestVimScriptFunctionExtraction
+}
diff --git a/internal/discover/discover.go b/internal/discover/discover.go
index b27df3c67..c89c81159 100644
--- a/internal/discover/discover.go
+++ b/internal/discover/discover.go
@@ -3,6 +3,7 @@ package discover
import (
"bufio"
"context"
+ "log/slog"
"os"
"path/filepath"
"strings"
@@ -205,6 +206,41 @@ func hasIgnoredSuffix(path string) bool {
return false
}
+// classifyFile checks if a file is a supported source file and returns its FileInfo.
+// Returns nil if the file should be skipped.
+func classifyFile(path, rel string, info os.FileInfo, opts *Options) *FileInfo {
+ if hasIgnoredSuffix(path) {
+ return nil
+ }
+ if shouldSkipFile(info.Name(), path, info.Size(), opts) {
+ return nil
+ }
+
+ ext := filepath.Ext(path)
+ l, ok := lang.LanguageForExtension(ext)
+ if !ok {
+ l, ok = lang.LanguageForFilename(info.Name())
+ }
+ if !ok {
+ return nil
+ }
+
+ if l == lang.JSON && isIgnoredJSON(info.Name()) {
+ return nil
+ }
+ if l == lang.JSON && info.Size() > 100*1024 {
+ slog.Warn("discover.skip_large_json", "path", rel, "size", info.Size())
+ return nil
+ }
+
+ return &FileInfo{
+ Path: path,
+ RelPath: filepath.ToSlash(rel),
+ Language: l,
+ Size: info.Size(),
+ }
+}
+
// Discover walks a repository and returns all source files.
func Discover(ctx context.Context, repoPath string, opts *Options) ([]FileInfo, error) {
repoPath, err := filepath.Abs(repoPath)
@@ -212,12 +248,10 @@ func Discover(ctx context.Context, repoPath string, opts *Options) ([]FileInfo,
return nil, err
}
- // Check cancellation before starting walk
if err := ctx.Err(); err != nil {
return nil, err
}
- // Load .cgrignore patterns if present
var extraIgnore []string
if opts != nil && opts.IgnoreFile != "" {
extraIgnore, _ = loadIgnoreFile(opts.IgnoreFile)
@@ -234,11 +268,9 @@ func Discover(ctx context.Context, repoPath string, opts *Options) ([]FileInfo,
}
err = filepath.Walk(repoPath, func(path string, info os.FileInfo, walkErr error) error {
- // Check context cancellation periodically during walk
if err := ctx.Err(); err != nil {
return err
}
-
if walkErr != nil {
return filepath.SkipDir
}
@@ -252,35 +284,8 @@ func Discover(ctx context.Context, repoPath string, opts *Options) ([]FileInfo,
return nil
}
- // Skip ignored suffixes (both modes)
- if hasIgnoredSuffix(path) {
- return nil
- }
-
- // Mode-aware file filtering
- if shouldSkipFile(info.Name(), path, info.Size(), opts) {
- return nil
- }
-
- // Check if we support this language
- ext := filepath.Ext(path)
- l, ok := lang.LanguageForExtension(ext)
- if !ok {
- // Try filename-based detection for extensionless files
- l, ok = lang.LanguageForFilename(info.Name())
- }
- if ok {
- // Skip ignored JSON files
- if l == lang.JSON && isIgnoredJSON(info.Name()) {
- return nil
- }
- files = append(files, FileInfo{
- Path: path,
- RelPath: filepath.ToSlash(rel),
- Language: l,
- Size: info.Size(),
- })
- return nil
+ if fi := classifyFile(path, rel, info, opts); fi != nil {
+ files = append(files, *fi)
}
return nil
})
diff --git a/internal/lang/commonlisp.go b/internal/lang/commonlisp.go
index aa1508a9e..104a74664 100644
--- a/internal/lang/commonlisp.go
+++ b/internal/lang/commonlisp.go
@@ -2,9 +2,10 @@ package lang
func init() {
Register(&LanguageSpec{
- Language: CommonLisp,
- FileExtensions: []string{".lisp", ".lsp", ".cl"},
- ModuleNodeTypes: []string{"source"},
- CallNodeTypes: []string{"list_lit"},
+ Language: CommonLisp,
+ FileExtensions: []string{".lisp", ".lsp", ".cl"},
+ FunctionNodeTypes: []string{"defun"},
+ ModuleNodeTypes: []string{"source"},
+ CallNodeTypes: []string{"list_lit"},
})
}
diff --git a/internal/lang/makefile.go b/internal/lang/makefile.go
index c92bfc4af..22537b85b 100644
--- a/internal/lang/makefile.go
+++ b/internal/lang/makefile.go
@@ -4,6 +4,7 @@ func init() {
Register(&LanguageSpec{
Language: Makefile,
FileExtensions: []string{".mk"},
+ FunctionNodeTypes: []string{"rule"},
ModuleNodeTypes: []string{"makefile"},
CallNodeTypes: []string{"function_call"},
ImportNodeTypes: []string{"include_directive"},
diff --git a/internal/pipeline/configlink_strategies.go b/internal/pipeline/configlink_strategies.go
new file mode 100644
index 000000000..2095cbbe0
--- /dev/null
+++ b/internal/pipeline/configlink_strategies.go
@@ -0,0 +1,418 @@
+package pipeline
+
+import (
+ "log/slog"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+// configExtensions are file extensions considered "config files".
+var configExtensions = map[string]bool{
+ ".env": true, ".toml": true, ".ini": true, ".yaml": true, ".yml": true,
+ ".cfg": true, ".properties": true, ".json": true, ".xml": true, ".conf": true,
+}
+
+// manifestFiles are package manifest filenames used for dependency→import linking.
+var manifestFiles = map[string]bool{
+ "Cargo.toml": true, "package.json": true, "go.mod": true,
+ "requirements.txt": true, "Gemfile": true, "build.gradle": true,
+ "pom.xml": true, "composer.json": true,
+}
+
+// depSectionNames are section/key names that indicate dependency lists.
+var depSectionNames = map[string]bool{
+ "dependencies": true, "devDependencies": true, "peerDependencies": true,
+ "dev-dependencies": true, "build-dependencies": true,
+}
+
+// configFileRefRe matches string literals referencing config files.
+var configFileRefRe = regexp.MustCompile(
+ `["']([^"']*\.(toml|yaml|yml|ini|json|xml|conf|cfg|env))["']`)
+
+// passConfigLinker runs 3 post-flush strategies to link config↔code.
+func (p *Pipeline) passConfigLinker() {
+ t := time.Now()
+ keyEdges := p.matchConfigKeySymbols()
+ slog.Info("configlinker.strategy", "name", "key_symbol", "edges", len(keyEdges))
+
+ t2 := time.Now()
+ depEdges := p.matchDependencyImports()
+ slog.Info("configlinker.strategy", "name", "dep_import", "edges", len(depEdges), "elapsed", time.Since(t2))
+
+ t3 := time.Now()
+ refEdges := p.matchConfigFileRefs()
+ slog.Info("configlinker.strategy", "name", "file_ref", "edges", len(refEdges), "elapsed", time.Since(t3))
+
+ all := make([]*store.Edge, 0, len(keyEdges)+len(depEdges)+len(refEdges))
+ all = append(all, keyEdges...)
+ all = append(all, depEdges...)
+ all = append(all, refEdges...)
+
+ if len(all) > 0 {
+ if err := p.Store.InsertEdgeBatch(all); err != nil {
+ slog.Warn("configlinker.write_err", "err", err)
+ }
+ }
+
+ slog.Info("configlinker.done",
+ "key_symbol", len(keyEdges),
+ "dep_import", len(depEdges),
+ "file_ref", len(refEdges),
+ "total", len(all),
+ "elapsed", time.Since(t))
+}
+
+// --- Strategy 1: Config Key → Code Symbol ---
+
+// normalizeConfigKey splits a config key on camelCase, underscores, dots, hyphens,
+// lowercases all tokens, and joins with underscore.
+func normalizeConfigKey(key string) (normalized string, tokens []string) {
+ // Split on non-alphanumeric chars first
+ parts := strings.FieldsFunc(key, func(r rune) bool {
+ return r == '_' || r == '-' || r == '.'
+ })
+
+ for _, part := range parts {
+ camel := splitCamelCase(part)
+ for _, w := range camel {
+ tokens = append(tokens, strings.ToLower(w))
+ }
+ }
+
+ normalized = strings.Join(tokens, "_")
+ return
+}
+
+// configEntry pairs a config node with its normalized key.
+type configEntry struct {
+ node *store.Node
+ normalized string
+}
+
+// collectConfigEntries returns config Variable nodes with min 2 tokens, each ≥3 chars.
+func collectConfigEntries(vars []*store.Node) []configEntry {
+ var entries []configEntry
+ for _, v := range vars {
+ if !hasConfigExtension(v.FilePath) {
+ continue
+ }
+ norm, tokens := normalizeConfigKey(v.Name)
+ if len(tokens) < 2 {
+ continue
+ }
+ allLong := true
+ for _, t := range tokens {
+ if len(t) < 3 {
+ allLong = false
+ break
+ }
+ }
+ if allLong {
+ entries = append(entries, configEntry{node: v, normalized: norm})
+ }
+ }
+ return entries
+}
+
+// collectCodeNodes returns Function/Variable/Class nodes not from config files.
+func (p *Pipeline) collectCodeNodes() []*store.Node {
+ var codeNodes []*store.Node
+ for _, label := range []string{"Function", "Variable", "Class"} {
+ nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
+ if err != nil {
+ continue
+ }
+ for _, n := range nodes {
+ if !hasConfigExtension(n.FilePath) {
+ codeNodes = append(codeNodes, n)
+ }
+ }
+ }
+ return codeNodes
+}
+
+// matchConfigKeySymbols links config Variable nodes to code symbols when
+// the normalized config key is a contiguous substring of the normalized code name.
+func (p *Pipeline) matchConfigKeySymbols() []*store.Edge {
+ configVars, err := p.Store.FindNodesByLabel(p.ProjectName, "Variable")
+ if err != nil {
+ return nil
+ }
+
+ entries := collectConfigEntries(configVars)
+ if len(entries) == 0 {
+ return nil
+ }
+
+ codeNodes := p.collectCodeNodes()
+
+ var edges []*store.Edge
+ for _, ce := range entries {
+ for _, code := range codeNodes {
+ codeNorm, _ := normalizeConfigKey(code.Name)
+ if codeNorm == "" {
+ continue
+ }
+
+ var confidence float64
+ switch {
+ case codeNorm == ce.normalized:
+ confidence = 0.85 // exact match
+ case strings.Contains(codeNorm, ce.normalized):
+ confidence = 0.75 // substring match
+ default:
+ continue
+ }
+
+ edges = append(edges, &store.Edge{
+ Project: p.ProjectName,
+ SourceID: code.ID,
+ TargetID: ce.node.ID,
+ Type: "CONFIGURES",
+ Properties: map[string]any{
+ "strategy": "key_symbol",
+ "confidence": confidence,
+ "config_key": ce.node.Name,
+ },
+ })
+ }
+ }
+ return edges
+}
+
+// --- Strategy 2: Dependency Name → Import Match ---
+
+// depEntry pairs a manifest dependency node with its name.
+type depEntry struct {
+ node *store.Node
+ name string
+}
+
+// collectManifestDeps returns dependency Variable nodes from package manifest files.
+func collectManifestDeps(vars []*store.Node) []depEntry {
+ var deps []depEntry
+ for _, v := range vars {
+ basename := filepath.Base(v.FilePath)
+ if !manifestFiles[basename] {
+ continue
+ }
+ isDep := false
+ qnLower := strings.ToLower(v.QualifiedName)
+ for sec := range depSectionNames {
+ if strings.Contains(qnLower, strings.ToLower(sec)) {
+ isDep = true
+ break
+ }
+ }
+ if !isDep && basename == "Cargo.toml" {
+ isDep = isDependencyChild(v)
+ }
+ if isDep {
+ deps = append(deps, depEntry{node: v, name: v.Name})
+ }
+ }
+ return deps
+}
+
+// resolveEdgeNodes builds lookup maps for source and target nodes of edges.
+func (p *Pipeline) resolveEdgeNodes(edges []*store.Edge) (source, target map[int64]*store.Node) {
+ ids := make(map[int64]struct{})
+ for _, e := range edges {
+ ids[e.SourceID] = struct{}{}
+ ids[e.TargetID] = struct{}{}
+ }
+ lookup := make(map[int64]*store.Node, len(ids))
+ for id := range ids {
+ n, err := p.Store.FindNodeByID(id)
+ if err == nil && n != nil {
+ lookup[id] = n
+ }
+ }
+ return lookup, lookup
+}
+
+// matchDependencyImports links dependency entries in package manifests
+// to code modules that import them.
+func (p *Pipeline) matchDependencyImports() []*store.Edge {
+ configVars, err := p.Store.FindNodesByLabel(p.ProjectName, "Variable")
+ if err != nil {
+ return nil
+ }
+
+ deps := collectManifestDeps(configVars)
+ if len(deps) == 0 {
+ return nil
+ }
+
+ importEdges, err := p.Store.FindEdgesByType(p.ProjectName, "IMPORTS")
+ if err != nil {
+ return nil
+ }
+
+ nodeLookup, _ := p.resolveEdgeNodes(importEdges)
+
+ var edges []*store.Edge
+ for _, dep := range deps {
+ depNameLower := strings.ToLower(dep.name)
+ for _, impEdge := range importEdges {
+ target := nodeLookup[impEdge.TargetID]
+ source := nodeLookup[impEdge.SourceID]
+ if target == nil || source == nil {
+ continue
+ }
+
+ targetNameLower := strings.ToLower(target.Name)
+ targetQNLower := strings.ToLower(target.QualifiedName)
+
+ var confidence float64
+ switch {
+ case targetNameLower == depNameLower:
+ confidence = 0.95
+ case strings.Contains(targetQNLower, depNameLower):
+ confidence = 0.80
+ default:
+ continue
+ }
+
+ edges = append(edges, &store.Edge{
+ Project: p.ProjectName,
+ SourceID: source.ID,
+ TargetID: dep.node.ID,
+ Type: "CONFIGURES",
+ Properties: map[string]any{
+ "strategy": "dependency_import",
+ "confidence": confidence,
+ "dep_name": dep.name,
+ },
+ })
+ }
+ }
+ return edges
+}
+
+// isDependencyChild checks if a Variable node's QN suggests it's under a dependency section.
+func isDependencyChild(v *store.Node) bool {
+ parts := strings.Split(v.QualifiedName, ".")
+ for _, p := range parts {
+ pLower := strings.ToLower(p)
+ if depSectionNames[pLower] {
+ return true
+ }
+ }
+ return false
+}
+
+// --- Strategy 3: Config File Path → Code String Reference ---
+
+// matchConfigFileRefs scans source code for string literals referencing config files.
+func (p *Pipeline) matchConfigFileRefs() []*store.Edge {
+ // Collect config Module nodes
+ modules, err := p.Store.FindNodesByLabel(p.ProjectName, "Module")
+ if err != nil {
+ return nil
+ }
+
+ configModules := make(map[string]*store.Node) // basename → Module
+ configModulesFull := make(map[string]*store.Node) // relPath → Module
+ for _, m := range modules {
+ if hasConfigExtension(m.FilePath) {
+ configModules[filepath.Base(m.FilePath)] = m
+ configModulesFull[m.FilePath] = m
+ }
+ }
+ if len(configModules) == 0 {
+ return nil
+ }
+
+ // Scan source files for config file references (use Module nodes from DB)
+ var edges []*store.Edge
+ for _, m := range modules {
+ relPath := m.FilePath
+ if hasConfigExtension(relPath) {
+ continue // Skip config files themselves
+ }
+
+ // Read source from disk for string literal scanning
+ fullPath := filepath.Join(p.RepoPath, relPath)
+ source, err := os.ReadFile(fullPath)
+ if err != nil {
+ continue
+ }
+
+ matches := configFileRefRe.FindAllStringSubmatch(string(source), -1)
+ for _, match := range matches {
+ if len(match) < 2 {
+ continue
+ }
+ refPath := match[1]
+
+ // Try full path match first
+ var target *store.Node
+ var confidence float64
+ if m, ok := configModulesFull[refPath]; ok {
+ target = m
+ confidence = 0.90
+ } else {
+ // Try basename match
+ refBase := filepath.Base(refPath)
+ if m, ok := configModules[refBase]; ok {
+ target = m
+ confidence = 0.70
+ }
+ }
+ if target == nil {
+ continue
+ }
+
+ // Find the source module/function
+ moduleQN := moduleQNForFile(p.ProjectName, relPath)
+ sourceNode, err := p.Store.FindNodeByQN(p.ProjectName, moduleQN)
+ if err != nil || sourceNode == nil {
+ continue
+ }
+
+ edges = append(edges, &store.Edge{
+ Project: p.ProjectName,
+ SourceID: sourceNode.ID,
+ TargetID: target.ID,
+ Type: "CONFIGURES",
+ Properties: map[string]any{
+ "strategy": "file_reference",
+ "confidence": confidence,
+ "ref_path": refPath,
+ },
+ })
+ }
+ }
+ return edges
+}
+
+// --- Helpers ---
+
+// hasConfigExtension checks if a file path has a config file extension.
+func hasConfigExtension(filePath string) bool {
+ ext := filepath.Ext(filePath)
+ return configExtensions[ext]
+}
+
+// moduleQNForFile computes the Module QN for a given file.
+func moduleQNForFile(project, relPath string) string {
+ // Strip extension, replace / with .
+ noExt := strings.TrimSuffix(relPath, filepath.Ext(relPath))
+ parts := strings.Split(noExt, "/")
+
+ // Filter empty and special parts
+ var filtered []string
+ for _, p := range parts {
+ if p != "" && p != "__init__" && p != "index" {
+ filtered = append(filtered, p)
+ }
+ }
+
+ return project + "." + strings.Join(filtered, ".")
+}
diff --git a/internal/pipeline/configlink_test.go b/internal/pipeline/configlink_test.go
new file mode 100644
index 000000000..3375f2af3
--- /dev/null
+++ b/internal/pipeline/configlink_test.go
@@ -0,0 +1,259 @@
+package pipeline
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/discover"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+// --- Strategy 1: Key → Symbol Matching ---
+
+func TestConfigKeySymbol_ExactMatch(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "config.toml"), `[database]
+max_connections = 100
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func getMaxConnections() int { return 100 }
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ found := false
+ for _, e := range edges {
+ if props, ok := e.Properties["strategy"]; ok && props == "key_symbol" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("expected key_symbol CONFIGURES edge for max_connections, got %d total CONFIGURES", len(edges))
+ }
+}
+
+func TestConfigKeySymbol_SubstringMatch(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "config.toml"), `[app]
+request_timeout = 30
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func getRequestTimeoutSeconds() int { return 30 }
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ found := false
+ for _, e := range edges {
+ props := e.Properties
+ if props["strategy"] == "key_symbol" {
+ conf, _ := props["confidence"].(float64)
+ if conf == 0.75 {
+ found = true
+ }
+ }
+ }
+ if !found {
+ t.Logf("got %d CONFIGURES edges", len(edges))
+ for _, e := range edges {
+ t.Logf(" strategy=%v confidence=%v", e.Properties["strategy"], e.Properties["confidence"])
+ }
+ t.Errorf("expected substring match (confidence=0.75) for request_timeout")
+ }
+}
+
+func TestConfigKeySymbol_ShortKeySkipped(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "config.toml"), `port = 8080
+host = "localhost"
+name = "test"
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func getPort() int { return 8080 }
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ for _, e := range edges {
+ if e.Properties["strategy"] == "key_symbol" {
+ t.Errorf("expected no key_symbol edges for short keys, got one: config_key=%v", e.Properties["config_key"])
+ }
+ }
+}
+
+func TestConfigKeySymbol_CamelCaseNormalization(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "config.json"), `{"maxRetryCount": 3}`)
+ writeFile(t, filepath.Join(dir, "handler.go"), `package main
+
+func getMaxRetryCount() int { return 3 }
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ found := false
+ for _, e := range edges {
+ if e.Properties["strategy"] == "key_symbol" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("expected key_symbol CONFIGURES edge for maxRetryCount")
+ }
+}
+
+func TestConfigKeySymbol_NoFalsePositive(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "config.toml"), `[db]
+url = "postgres://..."
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func parseURL(s string) string { return s }
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ for _, e := range edges {
+ if e.Properties["strategy"] == "key_symbol" && e.Properties["config_key"] == "url" {
+ t.Errorf("expected no CONFIGURES edge for 'url' (1 token), but got one")
+ }
+ }
+}
+
+// --- Strategy 2: Dependency → Import Matching ---
+
+func TestDependencyImport_PackageJson(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "package.json"), `{"dependencies":{"express":"^4.0","lodash":"^4.17"}}`)
+ writeFile(t, filepath.Join(dir, "app.js"), `const express = require('express');
+
+function handleRequest() {
+ return express();
+}
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ found := false
+ for _, e := range edges {
+ if e.Properties["strategy"] == "dependency_import" {
+ found = true
+ break
+ }
+ }
+ // This test may not produce edges since IMPORTS resolution depends on registry
+ // but it should at least not crash
+ t.Logf("dependency_import edges found: %v", found)
+}
+
+// --- Strategy 3: File Path Reference ---
+
+func TestConfigFileRef_ExactPath(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "config", "database.toml"), `[database]
+host = "localhost"
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func loadConfig() {
+ cfg := readFile("config/database.toml")
+ _ = cfg
+}
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ found := false
+ for _, e := range edges {
+ if e.Properties["strategy"] == "file_reference" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Logf("got %d CONFIGURES edges total", len(edges))
+ t.Errorf("expected file_reference CONFIGURES edge for config/database.toml")
+ }
+}
+
+func TestConfigFileRef_BasenameMatch(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "settings.yaml"), `database:
+ host: localhost
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func loadSettings() {
+ cfg := readFile("settings.yaml")
+ _ = cfg
+}
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ found := false
+ for _, e := range edges {
+ if e.Properties["strategy"] == "file_reference" {
+ conf, _ := e.Properties["confidence"].(float64)
+ if conf == 0.70 {
+ found = true
+ }
+ }
+ }
+ // Basename match may produce 0.70 or 0.90 depending on path resolution
+ t.Logf("basename file_reference found: %v", found)
+}
+
+func TestConfigFileRef_NoFalsePositive(t *testing.T) {
+ dir := t.TempDir()
+ writeFile(t, filepath.Join(dir, "data.csv"), `a,b,c`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func loadData() {
+ f := readFile("data.csv")
+ _ = f
+}
+`)
+
+ edges := runAndGetConfigures(t, dir)
+ for _, e := range edges {
+ if e.Properties["strategy"] == "file_reference" {
+ t.Errorf("expected no file_reference edge for .csv file")
+ }
+ }
+}
+
+// --- Helpers ---
+
+func runAndGetConfigures(t *testing.T, dir string) []*store.Edge {
+ t.Helper()
+
+ // Initialize as a git repo so discover works
+ gitInit(t, dir)
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ p := New(context.Background(), s, dir, discover.ModeFull)
+ if err := p.Run(); err != nil {
+ t.Fatalf("Pipeline.Run: %v", err)
+ }
+
+ edges, err := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
+ if err != nil {
+ t.Fatalf("FindEdgesByType: %v", err)
+ }
+ return edges
+}
+
+func gitInit(t *testing.T, dir string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Create minimal .git structure so discover recognizes it
+ writeFile(t, filepath.Join(dir, ".git", "HEAD"), "ref: refs/heads/main\n")
+}
diff --git a/internal/pipeline/configures.go b/internal/pipeline/configures.go
index 7c8ea2ad0..135f14365 100644
--- a/internal/pipeline/configures.go
+++ b/internal/pipeline/configures.go
@@ -2,9 +2,12 @@ package pipeline
import (
"log/slog"
+ "path/filepath"
"runtime"
"strings"
+ "github.com/DeusData/codebase-memory-mcp/internal/fqn"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
"golang.org/x/sync/errgroup"
)
@@ -61,15 +64,9 @@ func (p *Pipeline) passConfigures() {
slog.Info("pass.configures.done", "edges", total)
}
-// buildEnvIndex creates a mapping from env var key → module QN
-// by scanning Module node constants for KEY = VALUE patterns.
-func (p *Pipeline) buildEnvIndex() map[string]string {
- modules, err := p.findNodesByLabel(p.ProjectName, "Module")
- if err != nil {
- return nil
- }
-
- index := make(map[string]string)
+// extractModuleConstants scans Module node constants for KEY = VALUE patterns
+// and adds env-var-like keys to the index.
+func extractModuleConstants(modules []*store.Node, index map[string]string) {
for _, m := range modules {
constants, ok := m.Properties["constants"]
if !ok {
@@ -93,6 +90,41 @@ func (p *Pipeline) buildEnvIndex() map[string]string {
}
}
}
+}
+
+// buildEnvIndex creates a mapping from env var key → module QN
+// by scanning Module node constants and config Variable nodes.
+func (p *Pipeline) buildEnvIndex() map[string]string {
+ modules, err := p.findNodesByLabel(p.ProjectName, "Module")
+ if err != nil {
+ return nil
+ }
+
+ index := make(map[string]string)
+ extractModuleConstants(modules, index)
+
+ // Also scan config Variable nodes for env-var-like names.
+ // Only add if key not already in index — existing Module constants
+ // (which carry URL values for HTTP linking) always take priority.
+ variables, err := p.findNodesByLabel(p.ProjectName, "Variable")
+ if err == nil {
+ added := 0
+ for _, v := range variables {
+ ext := filepath.Ext(v.FilePath)
+ if !configExtensions[ext] {
+ continue
+ }
+ if isEnvVarName(v.Name) && index[v.Name] == "" {
+ moduleQN := fqn.ModuleQN(p.ProjectName, v.FilePath)
+ index[v.Name] = moduleQN
+ added++
+ }
+ }
+ if added > 0 {
+ slog.Info("pass.configures.env_vars_from_config", "added", added)
+ }
+ }
+
return index
}
diff --git a/internal/pipeline/configures_test.go b/internal/pipeline/configures_test.go
new file mode 100644
index 000000000..acb57ce78
--- /dev/null
+++ b/internal/pipeline/configures_test.go
@@ -0,0 +1,257 @@
+package pipeline
+
+import (
+ "context"
+ "path/filepath"
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/discover"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+)
+
+func TestBuildEnvIndex_ConfigVariableAdded(t *testing.T) {
+ dir := t.TempDir()
+ gitInit(t, dir)
+
+ // Create a config file with an env-var-like key
+ writeFile(t, filepath.Join(dir, "config.toml"), `DATABASE_URL = "postgresql://localhost/db"
+`)
+ // Need a code file so pipeline runs
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+import "os"
+
+func main() {
+ url := os.Getenv("DATABASE_URL")
+ _ = url
+}
+`)
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ p := New(context.Background(), s, dir, discover.ModeFull)
+ if err := p.Run(); err != nil {
+ t.Fatalf("Pipeline.Run: %v", err)
+ }
+
+ // Check that CONFIGURES edges were created
+ edges, err := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("CONFIGURES edges: %d", len(edges))
+ // The env var access in main.go should link to the config file
+ // via the extended buildEnvIndex
+ if len(edges) == 0 {
+ t.Logf("warning: no CONFIGURES edges (may depend on extraction)")
+ }
+}
+
+func TestBuildEnvIndex_LowercaseKeySkipped(t *testing.T) {
+ dir := t.TempDir()
+ gitInit(t, dir)
+
+ writeFile(t, filepath.Join(dir, "config.toml"), `database_host = "localhost"
+`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+func main() {}
+`)
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ p := New(context.Background(), s, dir, discover.ModeFull)
+ if err := p.Run(); err != nil {
+ t.Fatalf("Pipeline.Run: %v", err)
+ }
+
+ // lowercase keys should NOT be in the env index (isEnvVarName rejects them)
+ // so no CONFIGURES edges from env var matching for lowercase keys
+ edges, err := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range edges {
+ // If there's a CONFIGURES edge that came from env var matching
+ // to a lowercase key, that's a bug
+ if e.Properties != nil && e.Properties["strategy"] == nil {
+ // Env-var CONFIGURES edges don't have a "strategy" property
+ // (they come from passConfigures, not passConfigLinker)
+ t.Logf("env var CONFIGURES edge found: source=%d target=%d", e.SourceID, e.TargetID)
+ }
+ }
+}
+
+func TestBuildEnvIndex_NonConfigFileSkipped(t *testing.T) {
+ dir := t.TempDir()
+ gitInit(t, dir)
+
+ // Put an env-var-like variable in a Go file (should not be added to env index)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+var API_URL = "https://api.example.com"
+
+func main() {}
+`)
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ p := New(context.Background(), s, dir, discover.ModeFull)
+ if err := p.Run(); err != nil {
+ t.Fatalf("Pipeline.Run: %v", err)
+ }
+
+ // No config file exists, so buildEnvIndex should not find config Variables
+ // Only Module constants might produce env index entries
+ t.Log("pipeline ran successfully without config files")
+}
+
+func TestIsEnvVarName(t *testing.T) {
+ tests := []struct {
+ input string
+ want bool
+ }{
+ {"DATABASE_URL", true},
+ {"API_KEY", true},
+ {"PORT", true},
+ {"A", false}, // too short
+ {"port", false}, // lowercase
+ {"apiKey", false}, // camelCase
+ {"DB_2", true}, // with digit
+ {"__", false}, // no uppercase
+ {"", false}, // empty
+ }
+
+ for _, tt := range tests {
+ got := isEnvVarName(tt.input)
+ if got != tt.want {
+ t.Errorf("isEnvVarName(%q) = %v, want %v", tt.input, got, tt.want)
+ }
+ }
+}
+
+func TestNormalizeConfigKey(t *testing.T) {
+ tests := []struct {
+ input string
+ wantNorm string
+ wantTokens int
+ }{
+ {"max_connections", "max_connections", 2},
+ {"maxConnections", "max_connections", 2},
+ {"DATABASE_HOST", "database_host", 2},
+ {"database.host", "database_host", 2},
+ {"port", "port", 1},
+ {"maxRetryCount", "max_retry_count", 3},
+ }
+
+ for _, tt := range tests {
+ norm, tokens := normalizeConfigKey(tt.input)
+ if norm != tt.wantNorm {
+ t.Errorf("normalizeConfigKey(%q) norm = %q, want %q", tt.input, norm, tt.wantNorm)
+ }
+ if len(tokens) != tt.wantTokens {
+ t.Errorf("normalizeConfigKey(%q) tokens = %d, want %d", tt.input, len(tokens), tt.wantTokens)
+ }
+ }
+}
+
+func TestHasConfigExtension(t *testing.T) {
+ tests := []struct {
+ path string
+ want bool
+ }{
+ {"config.toml", true},
+ {"settings.yaml", true},
+ {"config.yml", true},
+ {".env", true},
+ {"config.ini", true},
+ {"data.json", true},
+ {"pom.xml", true},
+ {"main.go", false},
+ {"app.py", false},
+ {"data.csv", false},
+ }
+
+ for _, tt := range tests {
+ got := hasConfigExtension(tt.path)
+ if got != tt.want {
+ t.Errorf("hasConfigExtension(%q) = %v, want %v", tt.path, got, tt.want)
+ }
+ }
+}
+
+// Helper: ensure pipeline doesn't crash with config+code project
+func TestConfigIntegration_FullPipeline(t *testing.T) {
+ dir := t.TempDir()
+ gitInit(t, dir)
+
+ writeFile(t, filepath.Join(dir, "config.toml"), `[database]
+host = "localhost"
+port = 5432
+max_connections = 100
+
+[server]
+bind_address = "0.0.0.0"
+`)
+ writeFile(t, filepath.Join(dir, "settings.ini"), `[database]
+host = localhost
+port = 5432
+`)
+ writeFile(t, filepath.Join(dir, "config.json"), `{"appName": "test", "maxRetries": 3}`)
+ writeFile(t, filepath.Join(dir, "main.go"), `package main
+
+import "os"
+
+func getMaxConnections() int { return 100 }
+
+func loadConfig() {
+ cfg := readFile("config.toml")
+ _ = cfg
+ dbURL := os.Getenv("DATABASE_URL")
+ _ = dbURL
+}
+
+func readFile(path string) string { return "" }
+`)
+
+ s, err := store.OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ p := New(context.Background(), s, dir, discover.ModeFull)
+ if err := p.Run(); err != nil {
+ t.Fatalf("Pipeline.Run: %v", err)
+ }
+
+ // Verify nodes were created for config files
+ nodes, _ := s.FindNodesByLabel(p.ProjectName, "Class")
+ vars, _ := s.FindNodesByLabel(p.ProjectName, "Variable")
+ funcs, _ := s.FindNodesByLabel(p.ProjectName, "Function")
+ edges, _ := s.FindEdgesByType(p.ProjectName, "CONFIGURES")
+
+ t.Logf("Classes: %d, Variables: %d, Functions: %d, CONFIGURES edges: %d",
+ len(nodes), len(vars), len(funcs), len(edges))
+
+ // Should have config Class nodes (database, server sections)
+ if len(nodes) == 0 {
+ t.Error("expected Class nodes from config files")
+ }
+ // Should have Variable nodes from config files
+ if len(vars) == 0 {
+ t.Error("expected Variable nodes from config files")
+ }
+}
diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go
index 16cc2cdc7..2281396dd 100644
--- a/internal/pipeline/pipeline.go
+++ b/internal/pipeline/pipeline.go
@@ -335,6 +335,10 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {
}
slog.Info("pass.timing", "pass", "httplinks", "elapsed", time.Since(t))
+ t = time.Now()
+ p.passConfigLinker()
+ slog.Info("pass.timing", "pass", "configlinker", "elapsed", time.Since(t))
+
t = time.Now()
p.passGitHistory()
slog.Info("pass.timing", "pass", "githistory", "elapsed", time.Since(t))
@@ -488,10 +492,11 @@ func (p *Pipeline) runIncrementalPasses(
return err
}
- // HTTP linking and implements always run fully (they clean up first)
+ // HTTP linking, config linking, and implements always run fully (they clean up first)
if err := p.passHTTPLinks(); err != nil {
slog.Warn("pass.httplink.err", "err", err)
}
+ p.passConfigLinker()
p.passImplements()
p.passGitHistory()
@@ -902,7 +907,8 @@ type parseResult struct {
func (p *Pipeline) passDefinitions(files []discover.FileInfo) {
slog.Info("pass2.definitions")
- // Separate JSON files (processed sequentially, they're fast and few)
+ // Enrich JSON files with URL constants (for HTTP linking), then include
+ // them in normal CBM extraction so they also get Variable/Class nodes.
parseableFiles := make([]discover.FileInfo, 0, len(files))
for _, f := range files {
if f.Language == lang.JSON {
@@ -912,7 +918,6 @@ func (p *Pipeline) passDefinitions(files []discover.FileInfo) {
if err := p.processJSONFile(f); err != nil {
slog.Warn("pass2.json.err", "path", f.RelPath, "err", err)
}
- continue
}
parseableFiles = append(parseableFiles, f)
}
diff --git a/internal/store/louvain.go b/internal/store/louvain.go
index 567d4be19..6b7637038 100644
--- a/internal/store/louvain.go
+++ b/internal/store/louvain.go
@@ -1,6 +1,6 @@
package store
-import "math/rand"
+import "math/rand" // WHY: graph algorithm randomness — not cryptographic use, math/rand is correct here
// louvainEdge represents an edge for the Louvain algorithm.
type louvainEdge struct {
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
index bb15c60f0..aee602ad1 100644
--- a/internal/tools/tools.go
+++ b/internal/tools/tools.go
@@ -561,7 +561,7 @@ func (s *Server) registerSearchTools() {
},
"file_pattern": {
"type": "string",
- "description": "Glob pattern for file path within the project (e.g. '**/services/**', '*.py')"
+ "description": "Glob pattern for file path within the project. Use to filter by directory ('**/services/**'), file extension ('*.py', '*.yaml'), or filename ('**/Makefile'). Essential for shared-repo projects where multiple languages coexist — e.g., use '*.html' to find only HTML files in a JavaScript project."
},
"relationship": {
"type": "string",
@@ -626,7 +626,7 @@ func (s *Server) registerSearchTools() {
},
"file_pattern": {
"type": "string",
- "description": "Glob pattern to filter files (e.g. '*.go', '*.py')"
+ "description": "Glob pattern to filter files (e.g. '*.go', '*.py', '*.toml'). Use to focus search on specific file types or directories."
},
"regex": {
"type": "boolean",
diff --git a/scripts/clone-bench-repos.sh b/scripts/clone-bench-repos.sh
index 3423471c3..a29729660 100755
--- a/scripts/clone-bench-repos.sh
+++ b/scripts/clone-bench-repos.sh
@@ -61,11 +61,11 @@ clone perl "mojolicious/mojo"
clone groovy "spockframework/spock"
clone r "tidyverse/dplyr"
clone clojure "clojure/clojure"
-clone fsharp "fsprojects/Paket"
-clone julia "JuliaLang/julia"
-clone vimscript "vim/vim"
+clone fsharp "giraffe-fsharp/Giraffe"
+clone julia "SciML/DifferentialEquations.jl"
+clone vimscript "SpaceVim/SpaceVim"
clone nix "NixOS/nixpkgs"
-clone commonlisp "sbcl/sbcl"
+clone commonlisp "lem-project/lem"
clone elm "elm/compiler"
clone fortran "cp2k/cp2k"
clone cobol "OCamlPro/gnucobol"
@@ -89,12 +89,12 @@ symlink html javascript # Express views contain HTML
symlink css tsx # shadcn-ui styles
symlink toml rust # meilisearch Cargo.toml + config
symlink sql java # spring-petclinic SQL schemas
-symlink cuda cpp # CUDA extends C++ grammar
+clone cuda "NVIDIA/cuda-samples"
symlink json typescript # trpc JSON configs
symlink xml java # spring-petclinic XML configs
symlink markdown python # httpie docs
symlink makefile c # redis Makefile
-symlink glsl c # GLSL uses C-like grammar
+clone glsl "repalash/Open-Shaders"
symlink ini python # httpie .cfg/.ini files
echo ""