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.

test(repro): large graph-quality INVARIANT test group

Martin Vogelc66719a7ce67
diff --git a/Makefile.cbm b/Makefile.cbm
index a76a34239..fbc666760 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -423,7 +423,10 @@ TEST_REPRO_SRCS = \
tests/repro/repro_new_py_tuple_unpack.c \
tests/repro/repro_new_cypher_limit_zero.c \
tests/repro/repro_issue363.c \
- tests/repro/repro_issue581.c
+ tests/repro/repro_issue581.c \
+ tests/repro/repro_invariant_calls.c \
+ tests/repro/repro_invariant_graph.c \
+ tests/repro/repro_invariant_breadth.c
ALL_TEST_SRCS =$(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_ZSTD_SRCS) $(TEST_ARTIFACT_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_PHP_LSP_SRCS) $(TEST_CS_LSP_SRCS) $(TEST_CS_LSP_BENCH_SRCS) $(TEST_SCOPE_SRCS) $(TEST_TYPE_REP_SRCS) $(TEST_PY_LSP_SRCS) $(TEST_PY_LSP_BENCH_SRCS) $(TEST_PY_LSP_STRESS_SRCS) $(TEST_PY_LSP_SCALE_SRCS) $(TEST_TS_LSP_SRCS) $(TEST_JAVA_LSP_SRCS) $(TEST_KOTLIN_LSP_SRCS) $(TEST_RUST_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_HTTPD_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_STACK_OVERFLOW_SRCS) $(TEST_INTEGRATION_SRCS)
diff --git a/tests/repro/repro_invariant_breadth.c b/tests/repro/repro_invariant_breadth.c
new file mode 100644
index 000000000..b4becd790
--- /dev/null
+++ b/tests/repro/repro_invariant_breadth.c
@@ -0,0 +1,600 @@
+/*
+ * repro_invariant_breadth.c -- Cross-language CALLS callable-sourcing invariant.
+ *
+ * INVARIANT (gap #6, QUALITY_ANALYSIS.md):
+ * For every language, a function call written INSIDE a function body must
+ * produce a CALLS edge whose source node carries label "Function" or "Method"
+ * (i.e. callable-sourced). It must NOT be sourced at a "Module" node.
+ * Calls at the top level of a file may legitimately be Module-sourced; only
+ * in-body calls are asserted here.
+ *
+ * QUALITY_ANALYSIS.md gap #6 reports 27 languages failing this. This file
+ * is the "large breadth table" — one per-language case, table-driven, asserting
+ * the invariant across 26 languages.
+ *
+ * Fixture design rule:
+ * Each fixture defines exactly TWO functions: a callee (helper) and a caller
+ * (run) that calls helper strictly INSIDE its body. There are NO top-level
+ * calls in any fixture. This means ANY Module-sourced CALLS edge is a
+ * direct violation of the invariant.
+ *
+ * Expected RED/GREEN split (as of QUALITY_ANALYSIS.md, 2026-06-24):
+ * GREEN (already correctly callable-sourced, regression guards):
+ * elixir, ocaml, fortran, pascal, cuda, d, glsl, hlsl, ispc,
+ * odin, slang, squirrel, vimscript, cairo (14 cases)
+ *
+ * RED (module-sourced or no CALLS at all -- reproduces the gap):
+ * r, julia, dart, groovy, commonlisp, powershell, ada, clojure,
+ * fsharp, racket, rescript, scheme (12 cases)
+ *
+ * Note: the "suspicious" group (r, julia, ...) from QUALITY_ANALYSIS may be
+ * GREEN because the calls-breadth table (test_lang_contract.c) already shows
+ * expect_calls=true for most. The module-sourcing assertion is STRICTER: a
+ * language can produce a CALLS edge (calls >= 1) but still fail here if the
+ * edge is sourced at Module rather than Function. Individual case comments
+ * explain the known failure mode where root-caused.
+ *
+ * How to read results:
+ * PASS -- callable-sourced (Function/Method), no Module-sourced in-body calls.
+ * If currently GREEN: regression guard -- a future grammar/pipeline
+ * change that breaks sourcing will turn it RED.
+ * If currently RED: the bug is confirmed reproduced; fix the
+ * enclosing-function detection for this language.
+ */
+
+#include "test_framework.h"
+#include "repro_harness.h"
+#include <store/store.h>
+
+#include <stdio.h>
+#include <string.h>
+
+/* ---- helper: count CALLS edges by source-node label --------------------- */
+
+static int ib_calls_from_label(cbm_store_t *store, const char *project,
+ const char *label) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(store, project, "CALLS",
+ &edges, &edge_count) != CBM_STORE_OK) {
+ return -1;
+ }
+ int total = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src = {0};
+ if (cbm_store_find_node_by_id(store, edges[i].source_id,
+ &src) != CBM_STORE_OK) {
+ continue;
+ }
+ if (src.label && strcmp(src.label, label) == 0) {
+ total++;
+ }
+ cbm_node_free_fields(&src);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return total;
+}
+
+static int ib_callable_calls(cbm_store_t *store, const char *project) {
+ int fn = ib_calls_from_label(store, project, "Function");
+ int mt = ib_calls_from_label(store, project, "Method");
+ if (fn < 0 || mt < 0) {
+ return -1;
+ }
+ return fn + mt;
+}
+
+static int ib_module_calls(cbm_store_t *store, const char *project) {
+ return ib_calls_from_label(store, project, "Module");
+}
+
+/* ---- per-case result struct --------------------------------------------- */
+
+typedef struct {
+ int ok; /* graph DB opened */
+ int calls; /* total CALLS edges */
+ int callable_calls; /* CALLS sourced at Function or Method */
+ int module_calls; /* CALLS sourced at Module */
+} IBMetrics;
+
+static IBMetrics ib_metrics(const char *filename, const char *content) {
+ RProj lp;
+ cbm_store_t *store = rh_index(&lp, filename, content);
+ IBMetrics m = {0};
+ if (store) {
+ m.ok = 1;
+ m.calls = rh_count_edges(store, lp.project, "CALLS");
+ m.callable_calls = ib_callable_calls(store, lp.project);
+ m.module_calls = ib_module_calls(store, lp.project);
+ }
+ rh_cleanup(&lp, store);
+ return m;
+}
+
+/* ---- breadth case table ------------------------------------------------- */
+
+typedef struct {
+ const char *lang; /* human-readable language name */
+ const char *filename; /* fixture filename (extension selects grammar) */
+ const char *src; /* fixture source — caller inside a function body only */
+ int expect_callable; /* 1: calls should be callable-sourced (GREEN target) */
+ const char *gap_note; /* root cause for known gaps (NULL if expected GREEN) */
+} IBCase;
+
+/*
+ * Fixture rule: helper() is the callee; run() is the caller.
+ * The call to helper() is strictly inside the body of run().
+ * No top-level calls anywhere in the fixture.
+ */
+static const IBCase IB_CASES[] = {
+
+ /* ------------------------------------------------------------------ */
+ /* SUSPICIOUS / LIKELY-BROKEN GROUP */
+ /* QUALITY_ANALYSIS lists these as "expected-true but suspicious". */
+ /* They have expect_calls=true in the calls-breadth table, meaning a */
+ /* CALLS edge is produced -- but it may still be Module-sourced. */
+ /* ------------------------------------------------------------------ */
+
+ {
+ "r", "a.R",
+ "helper <- function(x) {\n"
+ " x * 2\n"
+ "}\n"
+ "\n"
+ "run <- function() {\n"
+ " helper(21)\n"
+ "}\n",
+ /*
+ * R: extract_calls.c has an R branch that reads the callee from the
+ * call node's first child. However, enclosing-function detection
+ * for R may fall back to Module if func_kinds_for_lang does not
+ * include R's "function_definition" node type. RED when the CALLS
+ * edge is sourced at Module instead of the "run" Function node.
+ */
+ 0, "R enclosing-function detection likely missing from func_kinds_for_lang; "
+ "call may be sourced at Module"
+ },
+
+ {
+ "julia", "a.jl",
+ "function helper(x)\n"
+ " return x + 1\n"
+ "end\n"
+ "\n"
+ "function run(n)\n"
+ " return helper(n)\n"
+ "end\n",
+ /*
+ * Julia: same issue -- function body extraction may not detect the
+ * enclosing Julia function node correctly, sourcing the call at Module.
+ */
+ 0, "Julia enclosing-function detection may not map function_definition to "
+ "a callable QN; call sourced at Module"
+ },
+
+ /* ------------------------------------------------------------------ */
+ /* EXPECTED-GREEN GROUP (regression guards) */
+ /* These languages have correct callable-sourcing in the current build.*/
+ /* A regression that breaks enclosing-function detection for any of */
+ /* them will turn the corresponding case RED. */
+ /* ------------------------------------------------------------------ */
+
+ {
+ "elixir", "a.ex",
+ "defmodule Sample do\n"
+ " def helper(x) do\n"
+ " x + 1\n"
+ " end\n"
+ "\n"
+ " def run do\n"
+ " helper(41)\n"
+ " end\n"
+ "end\n",
+ 1, NULL
+ },
+
+ {
+ "ocaml", "a.ml",
+ "let helper x = x + 1\n"
+ "\n"
+ "let run () =\n"
+ " let result = helper 41 in\n"
+ " print_int result\n",
+ 1, NULL
+ },
+
+ {
+ "fortran", "a.f90",
+ "function helper(x) result(y)\n"
+ " integer, intent(in) :: x\n"
+ " integer :: y\n"
+ " y = x + 1\n"
+ "end function helper\n"
+ "\n"
+ "function run(n) result(total)\n"
+ " integer, intent(in) :: n\n"
+ " integer :: total\n"
+ " total = helper(n) + helper(n + 1)\n"
+ "end function run\n",
+ 1, NULL
+ },
+
+ {
+ "pascal", "a.pas",
+ "procedure Helper(x: Integer);\n"
+ "begin\n"
+ " WriteLn(x);\n"
+ "end;\n"
+ "\n"
+ "procedure Run;\n"
+ "begin\n"
+ " Helper(1);\n"
+ "end;\n",
+ 1, NULL
+ },
+
+ {
+ "cuda", "a.cu",
+ "__device__ int helper(int x) {\n"
+ " return x * 2;\n"
+ "}\n"
+ "\n"
+ "__global__ void run(int *out) {\n"
+ " out[0] = helper(21);\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "d", "a.d",
+ "int helper(int x)\n"
+ "{\n"
+ " return x + 1;\n"
+ "}\n"
+ "\n"
+ "void run()\n"
+ "{\n"
+ " int y = helper(41);\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "glsl", "a.glsl",
+ "float helper(float x) {\n"
+ " return x * 2.0;\n"
+ "}\n"
+ "\n"
+ "void run() {\n"
+ " float y = helper(3.0);\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "hlsl", "a.hlsl",
+ "float helper(float x)\n"
+ "{\n"
+ " return x * 2.0;\n"
+ "}\n"
+ "\n"
+ "float run(float v)\n"
+ "{\n"
+ " return helper(v) + 1.0;\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "ispc", "a.ispc",
+ "static inline uniform float helper(uniform float x) {\n"
+ " return x * 2.0f;\n"
+ "}\n"
+ "\n"
+ "export void run(uniform float in[], uniform float out[],\n"
+ " uniform int n) {\n"
+ " foreach (i = 0 ... n) {\n"
+ " out[i] = helper(in[i]);\n"
+ " }\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "odin", "a.odin",
+ "package fixture\n"
+ "\n"
+ "helper :: proc() -> int {\n"
+ "\treturn 42\n"
+ "}\n"
+ "\n"
+ "run :: proc() {\n"
+ "\tx := helper()\n"
+ "\t_ = x\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "slang", "a.slang",
+ "void helper()\n"
+ "{\n"
+ " int x = 1;\n"
+ "}\n"
+ "\n"
+ "void run()\n"
+ "{\n"
+ " helper();\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "squirrel", "a.nut",
+ "function helper(x) {\n"
+ " return x + 1;\n"
+ "}\n"
+ "\n"
+ "function run() {\n"
+ " return helper(41);\n"
+ "}\n",
+ 1, NULL
+ },
+
+ {
+ "vimscript", "a.vim",
+ "function! Helper() abort\n"
+ " return 1\n"
+ "endfunction\n"
+ "\n"
+ "function! Run() abort\n"
+ " call Helper()\n"
+ "endfunction\n",
+ 1, NULL
+ },
+
+ {
+ "cairo", "a.cairo",
+ "fn helper(x: felt252) -> felt252 {\n"
+ " x + 1\n"
+ "}\n"
+ "\n"
+ "fn run() -> felt252 {\n"
+ " helper(41)\n"
+ "}\n",
+ 1, NULL
+ },
+
+ /* ------------------------------------------------------------------ */
+ /* KNOWN-GAP GROUP */
+ /* These languages fail in the existing calls-breadth contract too */
+ /* (expect_calls=false in test_lang_contract.c CALL_CASES). */
+ /* The primary gap is callee extraction; callable-sourcing cannot be */
+ /* verified until a CALLS edge exists. Both invariants are asserted: */
+ /* calls >= 1 AND module_calls == 0. */
+ /* ------------------------------------------------------------------ */
+
+ {
+ "dart", "a.dart",
+ "void helper() {\n"
+ " print('helper');\n"
+ "}\n"
+ "\n"
+ "void run() {\n"
+ " helper();\n"
+ "}\n",
+ /*
+ * Dart: selector call node carries no callee field and the first child
+ * is not an identifier; no dart branch in extract_calls.c. No CALLS
+ * edge is produced at all, so callable-sourcing cannot be tested
+ * independently. Both gaps (no CALLS + callable-sourcing) are RED.
+ */
+ 0, "selector call node: no callee field, first child not identifier; "
+ "no dart branch in extract_calls.c"
+ },
+
+ {
+ "groovy", "a.groovy",
+ "def helper() {\n"
+ " println 'helping'\n"
+ "}\n"
+ "\n"
+ "def run() {\n"
+ " helper()\n"
+ "}\n",
+ /*
+ * Groovy: function_call callee not on a function/name field and first
+ * child is not 'identifier'; no groovy branch in extract_calls.c.
+ */
+ 0, "function_call callee not on function/name field; "
+ "first child is not identifier; no groovy branch in extract_calls.c"
+ },
+
+ {
+ "commonlisp", "a.lisp",
+ "(defun helper (x)\n"
+ " (* x 2))\n"
+ "\n"
+ "(defun run ()\n"
+ " (helper 21))\n",
+ /*
+ * Common Lisp: list_lit call head is sym_lit not identifier;
+ * no commonlisp branch in extract_callee_name.
+ */
+ 0, "list_lit call head is sym_lit not identifier; "
+ "no commonlisp branch in extract_callee_name"
+ },
+
+ {
+ "powershell", "a.ps1",
+ "function helper {\n"
+ " Write-Output 'hi'\n"
+ "}\n"
+ "\n"
+ "function run {\n"
+ " helper\n"
+ "}\n",
+ /*
+ * PowerShell: command node child is command_name not identifier;
+ * extract_scripting_callee handles MATLAB not PowerShell.
+ */
+ 0, "command node child is command_name not identifier; "
+ "extract_scripting_callee handles MATLAB not PowerShell"
+ },
+
+ {
+ "ada", "a.adb",
+ "procedure Run is\n"
+ " procedure Helper is\n"
+ " begin\n"
+ " null;\n"
+ " end Helper;\n"
+ "begin\n"
+ " Helper;\n"
+ "end Run;\n",
+ /*
+ * Ada: procedure_call_statement callee did not resolve to a CALLS edge;
+ * no Ada branch in extract_calls.c.
+ */
+ 0, "procedure_call_statement callee not resolved; "
+ "no Ada branch in extract_calls.c"
+ },
+
+ {
+ "clojure", "a.clj",
+ "(defn helper [] 42)\n"
+ "\n"
+ "(defn run [] (helper))\n",
+ /*
+ * Clojure: lisp call is a list_lit whose head is a sym_lit (not a
+ * field, not a first-child 'identifier'); no lisp branch in
+ * extract_callee_name.
+ */
+ 0, "list_lit head is sym_lit not identifier; "
+ "no lisp/clojure branch in extract_callee_name"
+ },
+
+ {
+ "fsharp", "a.fs",
+ "let helper x = x + 1\n"
+ "\n"
+ "let run () = helper 41\n",
+ /*
+ * F#: application_expression callee head is a long_identifier_or_op
+ * wrapper, not a bare identifier/field; no fsharp callee branch.
+ */
+ 0, "application_expression callee head is long_identifier_or_op wrapper; "
+ "no fsharp callee branch in extract_callee_name"
+ },
+
+ {
+ "racket", "a.rkt",
+ "#lang racket\n"
+ "\n"
+ "(define (helper x)\n"
+ " (+ x 1))\n"
+ "\n"
+ "(define (run)\n"
+ " (helper 41))\n",
+ /*
+ * Racket: lisp call is a 'list' whose head is a 'symbol' (grammar has
+ * no 'identifier' node); no racket branch in extract_callee_name.
+ */
+ 0, "list head is symbol not identifier; "
+ "no racket branch in extract_callee_name"
+ },
+
+ {
+ "rescript", "a.res",
+ "let helper = (x) => x + 1\n"
+ "\n"
+ "let run = () => helper(41)\n",
+ /*
+ * ReScript: call_expression 'function' field is a 'value_identifier'
+ * (not in extract_callee_from_fields' accepted type list).
+ */
+ 0, "call_expression function field is value_identifier; "
+ "not in extract_callee_from_fields accepted type list"
+ },
+
+ {
+ "scheme", "a.scm",
+ "(define (helper x)\n"
+ " (* x 2))\n"
+ "\n"
+ "(define (run)\n"
+ " (helper 21))\n",
+ /*
+ * Scheme: lisp call is a 'list' whose head is a 'symbol';
+ * no scheme branch in extract_callee_name.
+ */
+ 0, "list head is symbol not identifier; "
+ "no scheme branch in extract_callee_name"
+ },
+};
+
+enum { IB_CASES_COUNT = (int)(sizeof(IB_CASES) / sizeof(IB_CASES[0])) };
+
+/* ---- single table-driven test ------------------------------------------- */
+
+/*
+ * repro_invariant_breadth_callable_sourcing
+ *
+ * Iterates every case in IB_CASES. For each language:
+ * 1. Indexes the single-file fixture through the full production pipeline.
+ * 2. Counts CALLS edges and their source-node labels.
+ * 3. Asserts:
+ * a. store opened (pipeline did not crash hard)
+ * b. calls >= 1 (the call was detected at all)
+ * c. callable_calls >= 1 (at least one CALLS edge is Function/Method-sourced)
+ * d. module_calls == 0 (no CALLS edge is Module-sourced for an in-body call)
+ *
+ * For expect_callable=0 cases (known gaps), the test still asserts all four
+ * conditions -- so those cases are RED (that IS the deliverable: a confirmed,
+ * reproducible, durable bug registration for each gap language).
+ *
+ * For expect_callable=1 cases (regression guards), the test must PASS.
+ * A future grammar or pipeline regression that breaks callable-sourcing for
+ * a GREEN language will immediately turn it RED here.
+ */
+TEST(repro_invariant_breadth_callable_sourcing) {
+ int failures = 0;
+
+ for (int i = 0; i < IB_CASES_COUNT; i++) {
+ const IBCase *c = &IB_CASES[i];
+ IBMetrics m = ib_metrics(c->filename, c->src);
+
+ int pass = (m.ok && m.calls >= 1 && m.callable_calls >= 1 &&
+ m.module_calls == 0);
+
+ if (!pass) {
+ fprintf(stderr,
+ " [INV-BREADTH] FAIL %-12s ok=%d calls=%d "
+ "callable=%d module=%d%s%s\n",
+ c->lang, m.ok, m.calls, m.callable_calls,
+ m.module_calls,
+ c->gap_note ? " -- " : "",
+ c->gap_note ? c->gap_note : "");
+ failures++;
+ } else {
+ fprintf(stderr,
+ " [INV-BREADTH] PASS %-12s calls=%d callable=%d "
+ "module=%d\n",
+ c->lang, m.calls, m.callable_calls, m.module_calls);
+ }
+ }
+
+ fprintf(stderr,
+ " [INV-BREADTH] %d langs checked: %d FAILURES "
+ "(each = callable-sourcing invariant violated or no CALLS at all)\n",
+ IB_CASES_COUNT, failures);
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* ---- suite --------------------------------------------------------------- */
+
+SUITE(repro_invariant_breadth) {
+ RUN_TEST(repro_invariant_breadth_callable_sourcing);
+}
diff --git a/tests/repro/repro_invariant_calls.c b/tests/repro/repro_invariant_calls.c
new file mode 100644
index 000000000..688bb5a9d
--- /dev/null
+++ b/tests/repro/repro_invariant_calls.c
@@ -0,0 +1,403 @@
+/*
+ * repro_invariant_calls.c — Source-position-aware CALLS attribution invariant.
+ *
+ * INVARIANT:
+ * For any project where EVERY call site is located INSIDE a function or
+ * method body (no top-level/module-level calls), EVERY CALLS edge in the
+ * graph must be sourced at a node whose label is "Function" or "Method".
+ * Zero CALLS edges may be sourced at a "Module" node.
+ *
+ * BASIS (QUALITY_ANALYSIS.md, 2026-06-24):
+ * Graph quality audit over the real codebase-memory-mcp repo showed only
+ * 3.69% of CALLS edges are callable-sourced (207/5607). The dominant
+ * failure mode is cbm_enclosing_func_qn returning the module QN when
+ * cbm_find_enclosing_func cannot walk the TSNode ancestry back to a
+ * function node. Root cause: func_kinds_for_lang (helpers.c:644) uses a
+ * hardcoded per-language list that is not always in sync with the actual
+ * grammar node types emitted by each tree-sitter grammar; when no ancestor
+ * type matches the list, cbm_find_enclosing_func returns a null node and
+ * cbm_enclosing_func_qn falls back to the module QN. The LSP rescue path
+ * (pass_lsp_cross.c) cannot compensate because it joins on exact
+ * caller_qn equality — a Module QN from tree-sitter is never equal to a
+ * Function QN from LSP, so the LSP result is silently discarded.
+ *
+ * EXPECTED per language (based on helpers.c func_kinds_for_lang):
+ * GREEN (callable source expected to work):
+ * Go — func_kinds_go = {function_declaration, method_declaration}
+ * Standard grammar; tree-sitter-go is mature; enclosing-func
+ * walk works reliably. Python/Go confirmed correct in
+ * QUALITY_ANALYSIS grep validation.
+ * Python — func_kinds_python = {function_definition}
+ * Standard grammar; confirmed correct in QUALITY_ANALYSIS.
+ *
+ * RED (callable source expected to fall back to Module on current code):
+ * C — func_kinds_cpp = {function_definition}
+ * C uses the same list as C++. QUALITY_ANALYSIS top-file
+ * list is dominated by C files (extract_defs.c: 182 Module-
+ * sourced CALLS, c_lsp.c: 86). The enclosing-func walk for
+ * C requires the call-expression's ancestor chain to include
+ * a function_definition node; C test failures are explicitly
+ * cited as expected-red in the quality contracts suite.
+ * C++ — same func_kinds as C. Out-of-line method definitions
+ * (Foo::bar) also lose the class qualifier (see issue #554).
+ * QUALITY_ANALYSIS explicitly lists C/C++ callable-source
+ * failures as known-red in the node_creation_probe contract.
+ * TypeScript — func_kinds_js = {function_declaration, method_definition,
+ * arrow_function, ...}. Method definitions and arrow
+ * function fields are supported, but class method bodies
+ * emitted by the TS grammar use "method_definition" — listed
+ * in func_kinds_js — so TS SHOULD be green for ordinary
+ * function bodies. HOWEVER, QUALITY_ANALYSIS section 6 lists
+ * TS in the breadth-suite gap set (ts_lsp.c: 95 Module-
+ * sourced CALLS in the real graph). This fixture uses a
+ * plain function calling another, the simplest case; we
+ * expect GREEN. If TS still fails the test will document it.
+ * Java — func_kinds_java = {method_declaration, constructor_declaration}
+ * Java LSP is supported. The real-graph audit shows
+ * java_lsp.h: 90 Module-sourced CALLS. A plain method
+ * calling another in the same class should be the simplest
+ * possible case; we expect GREEN but the audit evidence
+ * suggests it may be RED.
+ * C# — func_kinds_csharp = {method_declaration, constructor_declaration}
+ * Analogous to Java. Similar LSP support. Expected GREEN for
+ * the minimal case, but marked as potentially RED per breadth
+ * suite evidence.
+ * Rust — func_kinds_rust = {function_item}
+ * Rust LSP is hybrid but cbm_pxc_has_cross_lsp returns false
+ * for CBM_LANG_RUST (pass_lsp_cross.c:281). The enclosing-
+ * func walk uses only tree-sitter. Expected RED because
+ * QUALITY_ANALYSIS section 6 notes Rust in the failing set
+ * and rust_lsp.h: 102 Module-sourced CALLS appears in the
+ * top-file list.
+ *
+ * ASSERTION (per edge):
+ * For every cbm_edge_t e where e.type == "CALLS":
+ * cbm_store_find_node_by_id(store, e.source_id, &src) == CBM_STORE_OK
+ * AND (strcmp(src.label, "Function") == 0 || strcmp(src.label, "Method") == 0)
+ * Equivalently: module_sourced_count == 0.
+ *
+ * NOTE: inline comments below use line comments only (no block comments
+ * inside block comments per coding rules).
+ */
+
+#include "test_framework.h"
+#include "repro_harness.h"
+#include <store/store.h>
+
+#include <string.h>
+
+/* ── Shared runner ──────────────────────────────────────────────────────── */
+
+/*
+ * assert_calls_callable_sourced
+ *
+ * Index `files[0..nfiles)` through the production pipeline, collect all CALLS
+ * edges, and assert that each edge's source node has label "Function" or
+ * "Method" (never "Module").
+ *
+ * Returns 0 (PASS) when the invariant holds.
+ * Returns 1 (FAIL) when one or more Module-sourced CALLS edges are found.
+ *
+ * lang_tag is a human-readable string used in failure messages only.
+ */
+static int assert_calls_callable_sourced(const char *lang_tag,
+ const RFile *files, int nfiles) {
+ RProj lp;
+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);
+ if (!store) {
+ printf(" %sFAIL%s [%s] rh_index_files returned NULL\n",
+ "\033[31m", "\033[0m", lang_tag);
+ return 1;
+ }
+
+ cbm_edge_t *edges = NULL;
+ int nedges = 0;
+ int rc = cbm_store_find_edges_by_type(store, lp.project, "CALLS",
+ &edges, &nedges);
+ if (rc != CBM_STORE_OK) {
+ printf(" %sFAIL%s [%s] cbm_store_find_edges_by_type rc=%d\n",
+ "\033[31m", "\033[0m", lang_tag, rc);
+ rh_cleanup(&lp, store);
+ return 1;
+ }
+
+ /*
+ * We must find at least one CALLS edge — a fixture with zero calls would
+ * trivially satisfy the invariant and give no signal. Treat zero edges as
+ * a test-setup problem, not a pass.
+ */
+ if (nedges == 0) {
+ printf(" %sFAIL%s [%s] no CALLS edges found (fixture problem: "
+ "expected >= 1)\n",
+ "\033[31m", "\033[0m", lang_tag);
+ cbm_store_free_edges(edges, nedges);
+ rh_cleanup(&lp, store);
+ return 1;
+ }
+
+ int module_sourced = 0;
+ for (int i = 0; i < nedges; i++) {
+ cbm_node_t src;
+ if (cbm_store_find_node_by_id(store, edges[i].source_id, &src)
+ != CBM_STORE_OK) {
+ continue; /* dangling edge — ignore for this invariant */
+ }
+ const char *lbl = src.label ? src.label : "(null)";
+ if (strcmp(lbl, "Function") != 0 && strcmp(lbl, "Method") != 0) {
+ module_sourced++;
+ }
+ }
+
+ cbm_store_free_edges(edges, nedges);
+ rh_cleanup(&lp, store);
+
+ if (module_sourced > 0) {
+ printf(" %sFAIL%s [%s] %d/%d CALLS edge(s) sourced at non-callable "
+ "node (expected 0 module-sourced)\n",
+ "\033[31m", "\033[0m", lang_tag, module_sourced, nedges);
+ return 1;
+ }
+ return 0; /* all edges callable-sourced */
+}
+
+/* ── C ──────────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_c
+ *
+ * Expected: RED on current code.
+ * Root cause: func_kinds_cpp = {"function_definition"} is used for C too.
+ * The C files dominate the Module-sourced CALLS list in QUALITY_ANALYSIS
+ * (extract_defs.c: 182, c_lsp.c: 86). Even the simplest intra-file call
+ * between two C functions falls back to Module sourcing because the
+ * cbm_enclosing_func_qn path does not correctly resolve the caller QN and
+ * the LSP rescue is blocked by the exact-QN equality join requirement.
+ */
+TEST(repro_invariant_calls_c) {
+ static const char src[] =
+ "static int add(int a, int b) { return a + b; }\n"
+ "\n"
+ "int compute(int x) {\n"
+ " return add(x, 1);\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "main.c", src },
+ };
+ return assert_calls_callable_sourced("C",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── C++ ────────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_cpp
+ *
+ * Expected: RED on current code.
+ * Shares the same func_kinds as C. Out-of-line method definitions additionally
+ * drop the class qualifier (issue #554 / helpers.c cbm_enclosing_func_qn).
+ * Uses both a free function and a member method so the test covers both forms.
+ */
+TEST(repro_invariant_calls_cpp) {
+ static const char src[] =
+ "static int helper(int x) { return x * 2; }\n"
+ "\n"
+ "class Processor {\n"
+ "public:\n"
+ " int run(int v);\n"
+ "};\n"
+ "\n"
+ "int Processor::run(int v) {\n"
+ " return helper(v);\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "main.cpp", src },
+ };
+ return assert_calls_callable_sourced("C++",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── Go ─────────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_go
+ *
+ * Expected: GREEN on current code.
+ * func_kinds_go = {function_declaration, method_declaration}.
+ * Go grammar is mature; tree-sitter-go is stable. QUALITY_ANALYSIS confirms
+ * Python/Go callable attribution as correct via grep validation.
+ * This case is a regression guard: if it goes RED a future change has broken
+ * Go callable attribution.
+ */
+TEST(repro_invariant_calls_go) {
+ static const char src[] =
+ "package main\n"
+ "\n"
+ "func add(a, b int) int {\n"
+ " return a + b\n"
+ "}\n"
+ "\n"
+ "func compute(x int) int {\n"
+ " return add(x, 1)\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "main.go", src },
+ };
+ return assert_calls_callable_sourced("Go",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── Python ─────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_python
+ *
+ * Expected: GREEN on current code.
+ * func_kinds_python = {function_definition}.
+ * QUALITY_ANALYSIS grep-validated Python callable attribution as correct.
+ * Regression guard.
+ */
+TEST(repro_invariant_calls_python) {
+ static const char src[] =
+ "def add(a, b):\n"
+ " return a + b\n"
+ "\n"
+ "def compute(x):\n"
+ " return add(x, 1)\n";
+
+ static const RFile files[] = {
+ { "main.py", src },
+ };
+ return assert_calls_callable_sourced("Python",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── TypeScript ─────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_ts
+ *
+ * Expected: GREEN for a plain function-calls-function fixture (func_kinds_js
+ * includes function_declaration and arrow_function). However QUALITY_ANALYSIS
+ * shows ts_lsp.c with 95 Module-sourced CALLS in the real graph, so this may
+ * be RED. The test documents whichever state holds currently.
+ */
+TEST(repro_invariant_calls_ts) {
+ static const char src[] =
+ "function add(a: number, b: number): number {\n"
+ " return a + b;\n"
+ "}\n"
+ "\n"
+ "function compute(x: number): number {\n"
+ " return add(x, 1);\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "main.ts", src },
+ };
+ return assert_calls_callable_sourced("TypeScript",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── Java ───────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_java
+ *
+ * Expected: likely RED, possibly GREEN.
+ * func_kinds_java = {method_declaration, constructor_declaration}.
+ * java_lsp.h shows 90 Module-sourced CALLS in the real graph. The simplest
+ * same-class method call is the minimal fixture; if even this fails the
+ * attribution gap is comprehensive.
+ */
+TEST(repro_invariant_calls_java) {
+ static const char src[] =
+ "public class Calculator {\n"
+ " private int add(int a, int b) {\n"
+ " return a + b;\n"
+ " }\n"
+ "\n"
+ " public int compute(int x) {\n"
+ " return add(x, 1);\n"
+ " }\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "Calculator.java", src },
+ };
+ return assert_calls_callable_sourced("Java",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── C# ─────────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_csharp
+ *
+ * Expected: likely RED, possibly GREEN.
+ * func_kinds_csharp = {method_declaration, constructor_declaration}.
+ * Analogous evidence to Java from QUALITY_ANALYSIS breadth suite gaps.
+ */
+TEST(repro_invariant_calls_csharp) {
+ static const char src[] =
+ "public class Calculator {\n"
+ " private int Add(int a, int b) {\n"
+ " return a + b;\n"
+ " }\n"
+ "\n"
+ " public int Compute(int x) {\n"
+ " return Add(x, 1);\n"
+ " }\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "Calculator.cs", src },
+ };
+ return assert_calls_callable_sourced("C#",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── Rust ───────────────────────────────────────────────────────────────── */
+
+/*
+ * repro_invariant_calls_rust
+ *
+ * Expected: RED on current code.
+ * func_kinds_rust = {function_item}.
+ * cbm_pxc_has_cross_lsp returns false for CBM_LANG_RUST (pass_lsp_cross.c:281)
+ * so the cross-file LSP rescue path never runs for Rust. rust_lsp.h appears
+ * with 102 Module-sourced CALLS in the QUALITY_ANALYSIS top-file list.
+ * Even a single-file intra-function call will fall back to Module sourcing
+ * because the tree-sitter enclosing-func walk alone is insufficient.
+ */
+TEST(repro_invariant_calls_rust) {
+ static const char src[] =
+ "fn add(a: i32, b: i32) -> i32 {\n"
+ " a + b\n"
+ "}\n"
+ "\n"
+ "fn compute(x: i32) -> i32 {\n"
+ " add(x, 1)\n"
+ "}\n";
+
+ static const RFile files[] = {
+ { "main.rs", src },
+ };
+ return assert_calls_callable_sourced("Rust",
+ files, (int)(sizeof(files) / sizeof(files[0])));
+}
+
+/* ── Suite ──────────────────────────────────────────────────────────────── */
+
+SUITE(repro_invariant_calls) {
+ RUN_TEST(repro_invariant_calls_c);
+ RUN_TEST(repro_invariant_calls_cpp);
+ RUN_TEST(repro_invariant_calls_go);
+ RUN_TEST(repro_invariant_calls_python);
+ RUN_TEST(repro_invariant_calls_ts);
+ RUN_TEST(repro_invariant_calls_java);
+ RUN_TEST(repro_invariant_calls_csharp);
+ RUN_TEST(repro_invariant_calls_rust);
+}
diff --git a/tests/repro/repro_invariant_graph.c b/tests/repro/repro_invariant_graph.c
new file mode 100644
index 000000000..833c09adf
--- /dev/null
+++ b/tests/repro/repro_invariant_graph.c
@@ -0,0 +1,388 @@
+/*
+ * repro_invariant_graph.c — Graph quality invariant tests.
+ *
+ * Derived from gaps documented in:
+ * /Users/martinvogel/project_dir/cbm-quality-contracts/QUALITY_ANALYSIS.md
+ *
+ * Each test is one invariant in SUITE(repro_invariant_graph). Expectations
+ * are documented per-test below. Tests that are RED today are annotated
+ * with "WHY RED" pointing to the exact source location responsible.
+ *
+ * No block comments using slash-star inside these block comments.
+ * (All inner documentation uses line comments to avoid nested-comment issues.)
+ */
+
+#include "test_framework.h"
+#include "repro_harness.h"
+#include <store/store.h>
+#include <discover/discover.h>
+
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+/* ─────────────────────────────────────────────────────────────────────────
+ * INVARIANT 1: Discovery hygiene — .claude-worktrees must be skipped.
+ *
+ * QUALITY_ANALYSIS.md gap #1: discovery still indexes .claude-worktrees,
+ * tripling the indexed surface. Discovery already skips .git, node_modules,
+ * and .claude, so those are regression guards (expected GREEN).
+ *
+ * Fixture layout (no .git dir — plain directory):
+ *
+ * <tmpdir>/
+ * main.py <- must be discovered (control)
+ * .claude-worktrees/stale/x.py <- MUST NOT be discovered (RED today)
+ * .git/HEAD <- must be skipped (GREEN guard)
+ * node_modules/dep/index.js <- must be skipped (GREEN guard)
+ * .claude/settings.json <- must be skipped (GREEN guard)
+ *
+ * Primary RED assertion:
+ * No discovered file has rel_path starting with ".claude-worktrees/".
+ *
+ * WHY RED today:
+ * src/discover/discover.c hard-codes the skip-list of directory names.
+ * ".claude" is in the list but ".claude-worktrees" is not. The walk
+ * therefore descends into .claude-worktrees/ and returns x.py.
+ * ──────────────────────────────────────────────────────────────────────── */
+TEST(invariant_discovery_hygiene) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "%s/cbm_inv_disc_XXXXXX", cbm_tmpdir());
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmpdir));
+
+ /* control file — must be present after discovery */
+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, "main.py"),
+ "def main(): pass\n"));
+
+ /* RED: .claude-worktrees child is a source file and must be excluded */
+ ASSERT_EQ(0, th_write_file(
+ TH_PATH(tmpdir, ".claude-worktrees/stale/x.py"),
+ "def stale(): pass\n"));
+
+ /* GREEN guards — these should already be excluded */
+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, ".git/HEAD"),
+ "ref: refs/heads/main\n"));
+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, "node_modules/dep/index.js"),
+ "module.exports = {};\n"));
+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, ".claude/settings.json"),
+ "{}\n"));
+
+ cbm_file_info_t *files = NULL;
+ int count = 0;
+ int rc = cbm_discover(tmpdir, NULL, &files, &count);
+ ASSERT_EQ(0, rc);
+
+ bool main_found = false;
+ bool worktree_found = false;
+ bool git_found = false;
+ bool node_modules_found = false;
+ bool claude_found = false;
+
+ for (int i = 0; i < count; i++) {
+ const char *rp = files[i].rel_path;
+ if (strcmp(rp, "main.py") == 0) {
+ main_found = true;
+ }
+ if (strncmp(rp, ".claude-worktrees/", 18) == 0) {
+ worktree_found = true;
+ }
+ if (strncmp(rp, ".git/", 5) == 0) {
+ git_found = true;
+ }
+ if (strncmp(rp, "node_modules/", 13) == 0) {
+ node_modules_found = true;
+ }
+ if (strncmp(rp, ".claude/", 8) == 0) {
+ claude_found = true;
+ }
+ }
+ cbm_discover_free(files, count);
+ th_rmtree(tmpdir);
+
+ /* Control: main.py must always be discovered */
+ ASSERT_TRUE(main_found);
+
+ /* GREEN regression guards */
+ ASSERT_FALSE(git_found);
+ ASSERT_FALSE(node_modules_found);
+ ASSERT_FALSE(claude_found);
+
+ /*
+ * RED: .claude-worktrees is not in the skip-list.
+ * discover.c will descend into it and return .claude-worktrees/stale/x.py.
+ * This ASSERT_FALSE fires RED on current code.
+ *
+ * Fix location: src/discover/discover.c, the hardcoded skip-dirs array
+ * (search for ".claude" in that file); add ".claude-worktrees" next to it.
+ */
+ ASSERT_FALSE(worktree_found);
+
+ PASS();
+}
+
+/* ─────────────────────────────────────────────────────────────────────────
+ * INVARIANT 2: FQN same-stem distinctness.
+ *
+ * QUALITY_ANALYSIS.md gap #4: fqn.c strips the file extension from the last
+ * path component. Two files that share a stem — "api.h" and "api.c" — both
+ * produce the module QN "<project>.api". Symbols defined in each file then
+ * share the same module-level owner, causing attribution ambiguity.
+ *
+ * Fixture:
+ * api.h — declares: void api_init(void); (C header)
+ * api.c — defines: void api_init(void) {} (C source)
+ *
+ * Invariant: both symbols are present in the store, AND their qualified names
+ * are DISTINCT (not collapsed to the same QN by extension-stripping).
+ *
+ * WHY RED today:
+ * cbm_fqn_compute() in internal/cbm/helpers.c calls strip_ext_len() on the
+ * rel_path before building the dotted path, so both "api.h" and "api.c"
+ * yield "<project>.api.api_init" — the same QN. The upsert then collapses
+ * them to a single node, so either one symbol is missing or the file_path
+ * field is overwritten by whichever was indexed last. Either way the
+ * invariant "both symbols present with distinct QNs" fails.
+ *
+ * Specifically: after indexing, at least two nodes whose name == "api_init"
+ * must exist, OR two nodes exist whose qualified_name differs in the path
+ * component (one contains "api.h", one contains "api.c" OR they have
+ * distinct file_path values). On buggy code the store holds only ONE
+ * api_init node with a single QN.
+ * ──────────────────────────────────────────────────────────────────────── */
+TEST(invariant_fqn_same_stem_distinct) {
+ static const char api_h[] =
+ "void api_init(void);\n"
+ "void api_shutdown(void);\n";
+
+ static const char api_c[] =
+ "void api_init(void) {}\n"
+ "void api_shutdown(void) {}\n";
+
+ static const RFile files[] = {
+ {"api.h", api_h},
+ {"api.c", api_c},
+ };
+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));
+
+ RProj lp;
+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);
+ ASSERT_NOT_NULL(store);
+
+ /* Find all nodes named "api_init" in this project */
+ cbm_node_t *nodes = NULL;
+ int node_count = 0;
+ int rc = cbm_store_find_nodes_by_name(store, lp.project, "api_init",
+ &nodes, &node_count);
+ ASSERT_EQ(rc, CBM_STORE_OK);
+
+ /* For distinctness: if both symbols survived in the store, they must
+ * have DIFFERENT qualified_names — meaning at least 2 nodes, or exactly
+ * 1 node (collapsed) which makes the test RED.
+ *
+ * We check: either node_count >= 2 (both survived), or if node_count == 1
+ * the file_path is NOT equal to BOTH "api.h" and "api.c" — which would
+ * also indicate collapse. The cleanest assertion: require >= 2 nodes so
+ * both definitions are independently reachable. */
+ int distinct_found = node_count;
+
+ cbm_store_free_nodes(nodes, node_count);
+ rh_cleanup(&lp, store);
+
+ /*
+ * RED: fqn.c strips the extension so "api.h" and "api.c" produce the
+ * same module QN. The upsert OVERWRITES the first node, leaving only one
+ * "api_init" in the store. distinct_found == 1, and this assertion fires.
+ *
+ * Fix: include the extension (or a disambiguating suffix) in the last
+ * path component of the FQN so same-stem files get distinct module QNs.
+ */
+ ASSERT_GTE(distinct_found, 2);
+
+ PASS();
+}
+
+/* ─────────────────────────────────────────────────────────────────────────
+ * INVARIANT 3: No dangling edges (graph integrity guard).
+ *
+ * For every edge of type CALLS, IMPORTS, or CONTAINS_FILE in a freshly
+ * indexed multi-file project, both endpoints (source_id and target_id) must
+ * resolve to an existing node via cbm_store_find_node_by_id.
+ *
+ * This is a REGRESSION GUARD (expected GREEN on current code). If it turns
+ * RED, there is a real graph-integrity bug where an edge was persisted with
+ * an endpoint id that has no corresponding node row.
+ *
+ * Fixture:
+ * caller.py imports callee.py and calls its function.
+ * Two Python files so the pipeline mints IMPORTS and CALLS edges.
+ * ──────────────────────────────────────────────────────────────────────── */
+static int count_dangling_edges(cbm_store_t *store, const char *project,
+ const char *edge_type) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ int rc = cbm_store_find_edges_by_type(store, project, edge_type,
+ &edges, &edge_count);
+ if (rc != CBM_STORE_OK) {
+ return -1;
+ }
+
+ int dangling = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src_node;
+ cbm_node_t tgt_node;
+ if (cbm_store_find_node_by_id(store, edges[i].source_id,
+ &src_node) != CBM_STORE_OK) {
+ dangling++;
+ }
+ if (cbm_store_find_node_by_id(store, edges[i].target_id,
+ &tgt_node) != CBM_STORE_OK) {
+ dangling++;
+ }
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return dangling;
+}
+
+TEST(invariant_no_dangling_edges) {
+ static const char callee_py[] =
+ "def greet(name):\n"
+ " return 'hello ' + name\n";
+
+ static const char caller_py[] =
+ "from callee import greet\n"
+ "\n"
+ "def run():\n"
+ " greet('world')\n";
+
+ static const RFile files[] = {
+ {"callee.py", callee_py},
+ {"caller.py", caller_py},
+ };
+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));
+
+ RProj lp;
+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);
+ ASSERT_NOT_NULL(store);
+
+ int d_calls = count_dangling_edges(store, lp.project, "CALLS");
+ int d_imports = count_dangling_edges(store, lp.project, "IMPORTS");
+ int d_contains = count_dangling_edges(store, lp.project, "CONTAINS_FILE");
+
+ /* All three must succeed (non-negative) */
+ ASSERT_GTE(d_calls, 0);
+ ASSERT_GTE(d_imports, 0);
+ ASSERT_GTE(d_contains, 0);
+
+ rh_cleanup(&lp, store);
+
+ /*
+ * GREEN: no dangling endpoints expected. If any of these fires the
+ * pipeline is persisting edges with orphan node ids — a real integrity bug.
+ */
+ ASSERT_EQ(d_calls, 0);
+ ASSERT_EQ(d_imports, 0);
+ ASSERT_EQ(d_contains, 0);
+
+ PASS();
+}
+
+/* ─────────────────────────────────────────────────────────────────────────
+ * INVARIANT 4: Enclosing-function helper parity — Perl symptom.
+ *
+ * QUALITY_ANALYSIS.md gap #3: cbm_find_enclosing_func() in helpers.c uses a
+ * hardcoded func_kinds_for_lang switch that has drifted from the
+ * function_node_types field in CBMLangSpec (lang_specs.c).
+ *
+ * Evidence from source:
+ * lang_specs.c perl_func_types[] = {"subroutine_declaration_statement", NULL}
+ * helpers.c func_kinds_for_lang(CBM_LANG_PERL) falls through to default
+ * which returns func_kinds_generic[] = {"function_declaration",
+ * "function_definition", "method_declaration",
+ * "method_definition", NULL}
+ *
+ * "subroutine_declaration_statement" is NOT in func_kinds_generic. Therefore
+ * cbm_find_enclosing_func() can NEVER find an enclosing function for Perl
+ * call nodes, and cbm_enclosing_func_qn() always returns the module QN.
+ * Every CALLS edge for Perl code is sourced from Module, not Function.
+ *
+ * Symptom test:
+ * Index a Perl fixture with one subroutine that calls another.
+ * Assert that at least one CALLS edge has a source node with label "Function"
+ * (not "Module"). On buggy code ALL source nodes are Module → RED.
+ *
+ * WHY RED today:
+ * helpers.c func_kinds_for_lang has no CBM_LANG_PERL case. The Perl
+ * tree-sitter grammar emits subroutine_declaration_statement for `sub foo {}`
+ * nodes. Since this type is absent from func_kinds_generic, the enclosing-
+ * function walk exits without finding a parent and falls back to module_qn.
+ *
+ * Fix location:
+ * internal/cbm/helpers.c, function func_kinds_for_lang():
+ * Add a CBM_LANG_PERL case returning {"subroutine_declaration_statement", NULL}.
+ * ──────────────────────────────────────────────────────────────────────── */
+TEST(invariant_enclosing_func_perl_parity) {
+ /* Perl subroutine that calls another subroutine — the call to bar()
+ * is INSIDE the body of foo(), so its enclosing function must be foo,
+ * not the module. The tree-sitter Perl grammar wraps sub declarations in
+ * subroutine_declaration_statement nodes. */
+ static const char perl_src[] =
+ "sub bar {\n"
+ " return 42;\n"
+ "}\n"
+ "\n"
+ "sub foo {\n"
+ " my $x = bar();\n"
+ " return $x;\n"
+ "}\n"
+ "\n"
+ "foo();\n";
+
+ RProj lp;
+ cbm_store_t *store = rh_index(&lp, "main.pl", perl_src);
+ ASSERT_NOT_NULL(store);
+
+ /* Retrieve all CALLS edges for this project */
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ int rc = cbm_store_find_edges_by_type(store, lp.project, "CALLS",
+ &edges, &edge_count);
+ ASSERT_EQ(rc, CBM_STORE_OK);
+
+ /* Walk edges: find at least one whose SOURCE node has label "Function".
+ * On buggy code the source is always Module because the Perl
+ * subroutine_declaration_statement node type is not in func_kinds_generic. */
+ int callable_sourced = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src_node;
+ if (cbm_store_find_node_by_id(store, edges[i].source_id,
+ &src_node) == CBM_STORE_OK) {
+ if (src_node.label &&
+ (strcmp(src_node.label, "Function") == 0 ||
+ strcmp(src_node.label, "Method") == 0)) {
+ callable_sourced++;
+ }
+ }
+ }
+ cbm_store_free_edges(edges, edge_count);
+ rh_cleanup(&lp, store);
+
+ /*
+ * RED: callable_sourced == 0 because helpers.c has no CBM_LANG_PERL case.
+ * The enclosing-function walk never finds subroutine_declaration_statement
+ * (not in func_kinds_generic), so every CALLS edge source is Module.
+ *
+ * GREEN when helpers.c adds CBM_LANG_PERL -> {"subroutine_declaration_statement"}.
+ */
+ ASSERT_GTE(callable_sourced, 1);
+
+ PASS();
+}
+
+/* ── Suite ──────────────────────────────────────────────────────────────── */
+
+SUITE(repro_invariant_graph) {
+ RUN_TEST(invariant_discovery_hygiene);
+ RUN_TEST(invariant_fqn_same_stem_distinct);
+ RUN_TEST(invariant_no_dangling_edges);
+ RUN_TEST(invariant_enclosing_func_perl_parity);
+}
diff --git a/tests/repro/repro_main.c b/tests/repro/repro_main.c
index d7c1bc536..a14753688 100644
--- a/tests/repro/repro_main.c
+++ b/tests/repro/repro_main.c
@@ -59,6 +59,10 @@ extern void suite_repro_issue581(void);
extern void suite_repro_new_ts_class_field_arrow(void);
extern void suite_repro_new_py_tuple_unpack(void);
extern void suite_repro_new_cypher_limit_zero(void);
+/* Large INVARIANT test group (graph-quality systemic invariants, QUALITY_ANALYSIS) */
+extern void suite_repro_invariant_calls(void);
+extern void suite_repro_invariant_graph(void);
+extern void suite_repro_invariant_breadth(void);
int main(void) {
/* Unbuffered: a reproduction may crash/_exit (or a sanitizer may _exit on a
@@ -104,6 +108,9 @@ int main(void) {
RUN_SUITE(repro_new_cypher_limit_zero);
RUN_SUITE(repro_issue363);
RUN_SUITE(repro_issue581);
+ RUN_SUITE(repro_invariant_calls);
+ RUN_SUITE(repro_invariant_graph);
+ RUN_SUITE(repro_invariant_breadth);
TEST_SUMMARY();
}