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.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(mcp): tree-format tool output, exactly-once pagination, lean defaults
Martin Vogelc5bffb7fe6cb
diff --git a/src/cypher/cypher.c b/src/cypher/cypher.cindex 64e10a328..98ffb4c97 100644--- a/src/cypher/cypher.c+++ b/src/cypher/cypher.c@@ -2163,8 +2163,13 @@ static const char *node_string_field(const cbm_node_t *n, const char *prop) {} fields[] = {{"name", offsetof(cbm_node_t, name)},{"qualified_name", offsetof(cbm_node_t, qualified_name)},+ /* Aliases: field-eval agents reach for the short names, and a miss+ * used to return a silent empty column costing a round-trip. */+ {"qn", offsetof(cbm_node_t, qualified_name)},{"label", offsetof(cbm_node_t, label)},{"file_path", offsetof(cbm_node_t, file_path)},+ {"file", offsetof(cbm_node_t, file_path)},+ {"path", offsetof(cbm_node_t, file_path)},};for (size_t i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) {if (strcmp(prop, fields[i].key) == 0) {diff --git a/src/mcp/compact_out.c b/src/mcp/compact_out.cindex db05aa65b..729270225 100644--- a/src/mcp/compact_out.c+++ b/src/mcp/compact_out.c@@ -99,17 +99,17 @@ static bool looks_numeric(const char *s) {static bool needs_quotes(const char *s) {if (!s || !*s) {- return true; /* empty cell must be visible as "" */- }- if (isspace((unsigned char)s[0]) || isspace((unsigned char)s[strlen(s) - 1])) {- return true;+ return false; /* empty cells emit as the "-" placeholder, not quotes */}for (const char *p = s; *p; p++) {- if (*p == ',' || *p == '"' || *p == '\n' || *p == '\r') {+ /* Space-delimited rows: any internal whitespace or quote forces+ * quoting so column positions stay parseable. */+ if (isspace((unsigned char)*p) || *p == '"' || *p == '\r') {return true;}}- if (strcmp(s, "true") == 0 || strcmp(s, "false") == 0 || strcmp(s, "null") == 0) {+ if (strcmp(s, "true") == 0 || strcmp(s, "false") == 0 || strcmp(s, "null") == 0 ||+ strcmp(s, "-") == 0) {return true;}return looks_numeric(s);@@ -140,6 +140,10 @@ static void append_quoted(cbm_sb_t *sb, const char *s) {}static void append_value(cbm_sb_t *sb, const char *s) {+ if (!s || !*s) {+ cbm_sb_append_n(sb, "-", 1); /* stable column positions for empties */+ return;+ }if (needs_quotes(s)) {append_quoted(sb, s);} else {@@ -174,19 +178,19 @@ void cbm_toon_scalar_bool(cbm_sb_t *sb, const char *key, bool v) {/* ── Tables ─────────────────────────────────────────────────────── */+/* Tree-syntax table header: `key: N (cols: a b c)` — count first (agents+ * read scale before rows), column names once, rows indented beneath. */void cbm_toon_table_header(cbm_sb_t *sb, const char *key, int n, const char *const *cols,int ncols) {char num[32];- snprintf(num, sizeof(num), "[%d]{", n);+ snprintf(num, sizeof(num), ": %d (cols:", n);cbm_sb_append(sb, key);cbm_sb_append(sb, num);for (int i = 0; i < ncols; i++) {- if (i > 0) {- cbm_sb_append_n(sb, ",", 1);- }+ cbm_sb_append_n(sb, " ", 1);cbm_sb_append(sb, cols[i]);}- cbm_sb_append_n(sb, "}:\n", 3);+ cbm_sb_append_n(sb, ")\n", 2);}void cbm_toon_row_begin(cbm_sb_t *sb) {@@ -195,7 +199,7 @@ void cbm_toon_row_begin(cbm_sb_t *sb) {void cbm_toon_cell_str(cbm_sb_t *sb, const char *val, bool first) {if (!first) {- cbm_sb_append_n(sb, ",", 1);+ cbm_sb_append_n(sb, " ", 1);}append_value(sb, val ? val : "");}@@ -204,7 +208,7 @@ void cbm_toon_cell_int(cbm_sb_t *sb, long long v, bool first) {char num[32];snprintf(num, sizeof(num), "%lld", v);if (!first) {- cbm_sb_append_n(sb, ",", 1);+ cbm_sb_append_n(sb, " ", 1);}cbm_sb_append(sb, num);}@@ -213,14 +217,14 @@ void cbm_toon_cell_real(cbm_sb_t *sb, double v, bool first) {char num[48];snprintf(num, sizeof(num), "%.4g", v);if (!first) {- cbm_sb_append_n(sb, ",", 1);+ cbm_sb_append_n(sb, " ", 1);}cbm_sb_append(sb, num);}void cbm_toon_cell_bool(cbm_sb_t *sb, bool v, bool first) {if (!first) {- cbm_sb_append_n(sb, ",", 1);+ cbm_sb_append_n(sb, " ", 1);}cbm_sb_append(sb, v ? "true" : "false");}diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 804222436..b16304663 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -13,7 +13,6 @@ enum {MCP_FIELD_SIZE = 1040,MCP_TIMEOUT_MS = 1000,MCP_HALF_SEC_US = 500000,- MCP_MAX_ROWS = 100,MCP_COL_2 = 2,MCP_COL_3 = 3,MCP_COL_4 = 4,@@ -26,7 +25,8 @@ enum {MCP_DEFAULT_DEPTH = 3,MCP_DEFAULT_BFS_DEPTH = 2,MCP_DEFAULT_LIMIT = 10,- MCP_BFS_LIMIT = 100,+ MCP_BFS_LIMIT = 100, /* default per-direction trace budget (limit param raises) */+ MCP_BFS_LIMIT_MAX = 5000, /* hard ceiling for the limit param (context-bomb guard) */MCP_N_DEFAULTS_2 = 2,MCP_URI_PREFIX = 7, /* strlen("file://") */MCP_CONTENT_PREFIX = 15, /* strlen("Content-Length:") */@@ -337,11 +337,12 @@ static const tool_def_t TOOLS[] = {"COVERAGE: the response reports files that were NOT fully indexed — 'skipped' (not ""indexed at all: oversized/read/parse failures) and 'parse_partial' (indexed, but ""constructs inside the listed line ranges could not be parsed and MAY be missing from "- "the graph). Query the persisted signal any time via index_status or "- "structurally via query_graph(graph=\"missed\"). Both signals are best-effort: absence "- "of a flag is NOT a completeness guarantee; prefer grep inside flagged ranges. "- "Separately, 'excluded' + 'not_indexed_files' list what was deliberately NOT indexed "- "(gitignore/.cbmignore/skip-lists) — by design, not failures.",+ "the graph). The embedded lists carry counts plus a FEW EXAMPLES only; the complete "+ "lists are in the per-run 'logfile' (path in the response) and queryable any time via "+ "index_status or structurally via query_graph(graph=\"missed\"). Both signals are "+ "best-effort: absence of a flag is NOT a completeness guarantee; prefer grep inside "+ "flagged ranges. Separately, 'excluded' + 'not_indexed_files' list what was "+ "deliberately NOT indexed (gitignore/.cbmignore/skip-lists) — by design, not failures.","{\"type\":\"object\",\"properties\":{\"repo_path\":{\"type\":\"string\",\"description\":""\"Path to the repository\"},""\"mode\":{\"type\":\"string\","@@ -402,13 +403,17 @@ static const tool_def_t TOOLS[] = {"detect the limit and paginate.\"},\"offset\":{\"type\":\"integer\",\"default\":0,""\"description\":\"Skip the first N matching nodes. Combine with 'limit' to page: ""increment offset by limit and re-call while has_more is true.\"},"- "\"format\":{\"type\":\"string\",\"enum\":[\"toon\",\"json\"],\"default\":\"toon\","+ "\"format\":{\"type\":\"string\",\"enum\":[\"toon\",\"tree\",\"json\"],\"default\":\"toon\",""\"description\":\"Response encoding. toon (default): compact header+rows tables, ""~60% fewer tokens. json: legacy verbose per-node objects.\"},""\"fields\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":""\"Extra per-node property columns for toon output, e.g. complexity, cognitive, "- "signature, docstring, return_type, is_test, lines(int). Missing values emit as "- "empty cells.\"}},"+ "signature, docstring, return_type, is_test, lines(int). Core row columns "+ "(qn/label/file/lines/in/out) are always present — do not request them here. "+ "Missing values emit as empty cells.\"},"+ "\"detail\":{\"type\":\"string\",\"enum\":[\"ids\",\"default\"],\"default\":\"default\","+ "\"description\":\"ids: bare qualified-name enumeration (one column) — cheapest form "+ "for wide sweeps where per-row metadata is noise. default: full rows.\"}},""\"required\":[\"project\"]}"},{"query_graph", "Query graph",@@ -451,10 +456,18 @@ static const tool_def_t TOOLS[] = {"Use INSTEAD OF grep for callers, dependencies, impact analysis, or data flow tracing. ""RESPONSE: compact TOON tables — `callees[N]{qn,hop}:`/`callers[N]{qn,hop}:` headers then ""one row per reached node (hop = BFS distance); risk/test/args columns appear when the "- "matching flags are set. Pass format=\"json\" for legacy verbose objects.",+ "matching flags are set. `truncated: true` means a direction hit the node budget — re-call "+ "with a higher 'limit'. Pass format=\"json\" for legacy verbose objects.","{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"project\":{""\"type\":\"string\"},\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\","- "\"both\"],\"default\":\"both\"},\"depth\":{\"type\":\"integer\",\"default\":3},\"mode\":{"+ "\"both\"],\"default\":\"both\"},\"depth\":{\"type\":\"integer\",\"default\":3},"+ "\"limit\":{\"type\":\"integer\",\"default\":100,\"minimum\":1,\"maximum\":5000,"+ "\"description\":\"Rows per page. callees_total/callers_total always carry the exact full "+ "counts; when a page is truncated the response carries next — see cursor.\"},"+ "\"cursor\":{\"type\":\"string\",\"description\":\"Resume token from a previous response's "+ "'next' field. Pass it back with ALL other arguments identical to get the following page "+ "with no duplicates. Cursors outlive nothing: after a reindex you get a stale_cursor error "+ "— just re-run the original query.\"},\"mode\":{""\"type\":\"string\",\"enum\":[\"calls\",\"data_flow\",\"cross_service\"],\"default\":""\"calls\",\"description\":\"calls: follow CALLS edges. data_flow: follow CALLS+DATA_FLOWS ""with arg expressions. cross_service: follow HTTP_CALLS+ASYNC_CALLS+DATA_FLOWS through "@@ -467,7 +480,7 @@ static const tool_def_t TOOLS[] = {"\"},\"include_tests\":{\"type\":\"boolean\",\"default\":false,""\"description\":\"Include test files in results. When false (default), test files are ""filtered out. When true, test nodes are included with a test column/marker.\"},"- "\"format\":{\"type\":\"string\",\"enum\":[\"toon\",\"json\"],\"default\":\"toon\","+ "\"format\":{\"type\":\"string\",\"enum\":[\"toon\",\"tree\",\"json\"],\"default\":\"toon\",""\"description\":\"Response encoding. toon (default): compact header+rows tables. ""json: legacy verbose per-hop objects.\"}},""\"required\":[\"function_name\",\"project\"]}"},@@ -552,7 +565,10 @@ static const tool_def_t TOOLS[] = {"query_graph(graph=\"missed\"). The report also carries 'not_indexed' — files/dirs excluded ""BY DESIGN (gitignore/.cbmignore/skip-lists): deliberate and deterministic, not failures; ""change the ignore rules and re-index to include them.",- "{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["+ "{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},"+ "\"verbose\":{\"type\":\"boolean\",\"default\":false,\"description\":\"Include the git "+ "context block (worktree/shadow path variants). Only needed when debugging where an index "+ "lives — omitted by default to keep the status lean.\"}},\"required\":[""\"project\"]}"},{"check_index_coverage", "Check index coverage",@@ -2012,6 +2028,8 @@ static char *verify_project_indexed(cbm_store_t *store, const char *project) {return NULL;}+static bool sg_field_blocked(const char *f); /* internal-only fields, defined with search_graph */+static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {char *project = get_project_arg(args);cbm_store_t *store = resolve_store(srv, project);@@ -2037,6 +2055,13 @@ static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_obj_add_int(doc, lbl, "count", schema.node_labels[i].count);yyjson_mut_val *props = yyjson_mut_arr(doc);for (int j = 0; j < schema.node_labels[i].property_count; j++) {+ /* Internal similarity intermediates (fp/sp/bt) are blocked from every+ * tool response — advertising them here invited agents to request+ * fields the server then silently refuses. Filter them from the+ * schema so it only describes obtainable properties. */+ if (sg_field_blocked(schema.node_labels[i].properties[j])) {+ continue;+ }yyjson_mut_arr_add_str(doc, props, schema.node_labels[i].properties[j]);}yyjson_mut_obj_add_val(doc, lbl, "properties", props);@@ -2276,7 +2301,9 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu"WHERE n.project = ?2 "" AND n.label NOT IN ('File','Folder','Module','Section','Variable','Project') "" AND (?6 IS NULL OR n.file_path LIKE ?6) "- "ORDER BY rank "+ /* rank ties are common (boosted floats) — the id tie-break makes+ * offset pages contractually stable across calls. */+ "ORDER BY rank, n.id ""LIMIT ?3 OFFSET ?4";sqlite3_stmt *stmt = NULL;@@ -2558,12 +2585,27 @@ static bool sg_field_blocked(const char *f) {return strcmp(f, "fp") == 0 || strcmp(f, "sp") == 0 || strcmp(f, "bt") == 0;}+/* Core row columns every search result already carries. Requesting one as an+ * extra `fields` entry used to emit a silent empty column (core values are+ * node columns, never in the properties JSON) — field-eval agents burned a+ * round-trip on exactly that. Drop them and teach instead. */+static bool sg_field_is_core(const char *f) {+ return strcmp(f, "qn") == 0 || strcmp(f, "qualified_name") == 0 || strcmp(f, "name") == 0 ||+ strcmp(f, "label") == 0 || strcmp(f, "file") == 0 || strcmp(f, "file_path") == 0 ||+ strcmp(f, "path") == 0 || strcmp(f, "lines") == 0 || strcmp(f, "in") == 0 ||+ strcmp(f, "out") == 0;+}+/* Parse the `fields` argument (array of property names) into out[] as* pointers owned by the returned doc (caller frees the doc after emission).- * Blocked internal fields are silently dropped. */-static int sg_parse_fields(const char *args, const char *out[], int max_out,- yyjson_doc **out_owner) {+ * Blocked internal fields are silently dropped; core-column requests are+ * dropped too and reported via *core_requested so the emitter can hint. */+static int sg_parse_fields(const char *args, const char *out[], int max_out, yyjson_doc **out_owner,+ bool *core_requested) {*out_owner = NULL;+ if (core_requested) {+ *core_requested = false;+ }yyjson_doc *args_doc = yyjson_read(args, strlen(args), 0);yyjson_val *args_root = args_doc ? yyjson_doc_get_root(args_doc) : NULL;yyjson_val *fv = args_root ? yyjson_obj_get(args_root, "fields") : NULL;@@ -2579,7 +2621,16 @@ static int sg_parse_fields(const char *args, const char *out[], int max_out,yyjson_val *item;yyjson_arr_foreach(fv, idx, max, item) {const char *s = yyjson_get_str(item);- if (s && s[0] && !sg_field_blocked(s) && n < max_out) {+ if (!s || !s[0] || sg_field_blocked(s)) {+ continue;+ }+ if (sg_field_is_core(s)) {+ if (core_requested) {+ *core_requested = true;+ }+ continue;+ }+ if (n < max_out) {out[n++] = s;}}@@ -2627,8 +2678,21 @@ static void sg_lines_str(char *out, size_t sz, int start, int end) {/* Emit the regex-path search results as a TOON table. */static void emit_search_results_toon(cbm_sb_t *sb, const cbm_search_output_t *out, int offset,- const char *const *fields, int nfields) {+ const char *const *fields, int nfields, bool detail_ids) {cbm_toon_scalar_int(sb, "total", out->total);+ if (detail_ids) {+ /* ids tier: bare qn enumeration — for "list everything matching X"+ * sweeps where per-row metadata is noise (LocAgent's fold tier). */+ static const char *const id_cols[] = {"qn"};+ cbm_toon_table_header(sb, "results", out->count, id_cols, 1);+ for (int i = 0; i < out->count; i++) {+ cbm_toon_row_begin(sb);+ cbm_toon_cell_str(sb, out->results[i].node.qualified_name, true);+ cbm_toon_row_end(sb);+ }+ cbm_toon_scalar_bool(sb, "has_more", out->total > offset + out->count);+ return;+ }const char *cols[6 + SG_MAX_EXTRA_FIELDS] = {"qn", "label", "file", "lines", "in", "out"};int ncols = 6;for (int f = 0; f < nfields; f++) {@@ -2652,6 +2716,101 @@ static void emit_search_results_toon(cbm_sb_t *sb, const cbm_search_output_t *oucbm_toon_scalar_bool(sb, "has_more", out->total > offset + out->count);}+/* ── Tree format (Phase-2 A/B candidate) ────────────────────────────+ * Prefix-factored, file-grouped output: the shared (qn-prefix, file) pair is+ * printed ONCE per group, rows beneath carry only the short name + data+ * cells. The reconstruction rule (qn = group-prefix + "." + name) is stated+ * once in the header so agents can copy exact join keys into follow-up+ * calls. Research basis: HDT front-coding (prefix factoring), LocAgent tree+ * ablation (tree > flat/DOT for LLM comprehension), Lost-in-Distance+ * (related rows adjacent — grouping by module does exactly that). */++/* qn-prefix = qualified_name minus its last '.'-segment. Returns length. */+static size_t sg_qn_prefix_len(const char *qn) {+ const char *last = qn ? strrchr(qn, '.') : NULL;+ return last ? (size_t)(last - qn) : 0;+}++static int sg_cmp_by_qn(const void *pa, const void *pb) {+ const cbm_search_result_t *a = (const cbm_search_result_t *)pa;+ const cbm_search_result_t *b = (const cbm_search_result_t *)pb;+ const char *qa = a->node.qualified_name ? a->node.qualified_name : "";+ const char *qb = b->node.qualified_name ? b->node.qualified_name : "";+ return strcmp(qa, qb);+}++static void emit_search_results_tree(cbm_sb_t *sb, cbm_search_output_t *out, int offset,+ const char *const *fields, int nfields) {+ char buf[CBM_SZ_512];+ char extra_cols[CBM_SZ_256] = "";+ for (int f = 0; f < nfields; f++) {+ strncat(extra_cols, " ", sizeof(extra_cols) - strlen(extra_cols) - 1);+ strncat(extra_cols, fields[f], sizeof(extra_cols) - strlen(extra_cols) - 1);+ }+ snprintf(buf, sizeof(buf),+ "total: %d\nresults: %d (rows: name label lines in out%s; "+ "qn = group prefix + \".\" + name)\n",+ out->total, out->count, extra_cols);+ cbm_sb_append(sb, buf);+ /* Sort by qn so same-prefix rows are adjacent (module clustering). */+ if (out->count > 1) {+ qsort(out->results, (size_t)out->count, sizeof(cbm_search_result_t), sg_cmp_by_qn);+ }+ char cur_group[CBM_SZ_1K] = "";+ for (int i = 0; i < out->count; i++) {+ const cbm_search_result_t *sr = &out->results[i];+ const char *qn = sr->node.qualified_name ? sr->node.qualified_name : "";+ const char *file = sr->node.file_path ? sr->node.file_path : "";+ size_t plen = sg_qn_prefix_len(qn);+ char group[CBM_SZ_1K];+ snprintf(group, sizeof(group), "%.*s (%s)", (int)plen, qn, file);+ if (strcmp(group, cur_group) != 0) {+ snprintf(cur_group, sizeof(cur_group), "%s", group);+ cbm_sb_append(sb, group);+ cbm_sb_append(sb, ":\n");+ }+ const char *shortname = plen ? qn + plen + 1 : qn;+ char lines[CBM_SZ_32];+ sg_lines_str(lines, sizeof(lines), sr->node.start_line, sr->node.end_line);+ char row[CBM_SZ_1K];+ snprintf(row, sizeof(row), " %s %s %s %d %d", shortname,+ sr->node.label ? sr->node.label : "", lines, sr->in_degree, sr->out_degree);+ cbm_sb_append(sb, row);+ /* Extra property columns (fields param), space-delimited; missing+ * values emit as "-" so column positions stay stable. */+ if (nfields > 0) {+ yyjson_doc *pd = (sr->node.properties_json && sr->node.properties_json[0])+ ? yyjson_read(sr->node.properties_json,+ strlen(sr->node.properties_json), 0)+ : NULL;+ yyjson_val *pr = pd ? yyjson_doc_get_root(pd) : NULL;+ for (int f = 0; f < nfields; f++) {+ yyjson_val *v = (pr && yyjson_is_obj(pr)) ? yyjson_obj_get(pr, fields[f]) : NULL;+ char cell[CBM_SZ_256];+ if (v && yyjson_is_str(v)) {+ snprintf(cell, sizeof(cell), " %s", yyjson_get_str(v));+ } else if (v && yyjson_is_int(v)) {+ snprintf(cell, sizeof(cell), " %lld", (long long)yyjson_get_int(v));+ } else if (v && yyjson_is_real(v)) {+ snprintf(cell, sizeof(cell), " %.3g", yyjson_get_real(v));+ } else if (v && yyjson_is_bool(v)) {+ snprintf(cell, sizeof(cell), " %s", yyjson_get_bool(v) ? "true" : "false");+ } else {+ snprintf(cell, sizeof(cell), " -");+ }+ cbm_sb_append(sb, cell);+ }+ if (pd) {+ yyjson_doc_free(pd);+ }+ }+ cbm_sb_append(sb, "\n");+ }+ snprintf(buf, sizeof(buf), "has_more: %s\n",+ out->total > offset + out->count ? "true" : "false");+ cbm_sb_append(sb, buf);+}+/* Emit semantic vector-search results as a TOON table. */static void emit_semantic_results_toon(cbm_sb_t *sb, const cbm_vector_result_t *vresults,int vcount) {@@ -2680,12 +2839,16 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {/* Response encoding: TOON tables by default (compact, header+rows).* format:"json" restores the legacy verbose per-node objects; nested- * neighbor lists (include_connected) need them, so they force JSON. */+ * neighbor lists (include_connected) need them, so they force JSON.+ * format:"tree" is the Phase-2 A/B candidate: rows grouped by+ * (qn-prefix, file) with the shared prefix printed once. */char *format_arg = cbm_mcp_get_string_arg(args, "format");bool legacy_json = format_arg && strcmp(format_arg, "json") == 0;+ bool tree_format = format_arg && strcmp(format_arg, "tree") == 0;free(format_arg);if (cbm_mcp_get_bool_arg(args, "include_connected")) {legacy_json = true;+ tree_format = false;}/* BM25 path: if `query` is set, run FTS5 full-text search with ranking@@ -2750,7 +2913,12 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {if (!legacy_json) {const char *fields[SG_MAX_EXTRA_FIELDS];yyjson_doc *fields_owner = NULL;- int nfields = sg_parse_fields(args, fields, SG_MAX_EXTRA_FIELDS, &fields_owner);+ char *sg_detail = cbm_mcp_get_string_arg(args, "detail");+ bool detail_ids = sg_detail && strcmp(sg_detail, "ids") == 0;+ free(sg_detail);+ bool core_fields_requested = false;+ int nfields = sg_parse_fields(args, fields, SG_MAX_EXTRA_FIELDS, &fields_owner,+ &core_fields_requested);cbm_vector_result_t *vresults = NULL;int vcount = 0;@@ -2771,7 +2939,21 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {cbm_search_output_t tout = {0};if (!semantic_only) {cbm_store_search(store, ¶ms, &tout);- emit_search_results_toon(&sb, &tout, offset, fields, nfields);+ /* Grouped tree output is THE default; the flat table remains+ * only for detail:"ids" (single column — nothing to group). */+ (void)tree_format;+ if (detail_ids) {+ emit_search_results_toon(&sb, &tout, offset, fields, nfields, detail_ids);+ } else {+ emit_search_results_tree(&sb, &tout, offset, fields, nfields);+ }+ if (core_fields_requested) {+ cbm_toon_scalar_str(+ &sb, "hint",+ "some requested fields (file/name/qn/label/lines) are already core "+ "row columns and were skipped — `fields` is for extra property "+ "columns like complexity, cognitive, signature");+ }if (tout.total == 0) {if (name_pattern && label) {cbm_toon_scalar_str(&sb, "hint",@@ -3569,6 +3751,10 @@ static char *handle_index_status(cbm_mcp_server_t *srv, const char *args) {char *project = get_project_arg(args);cbm_store_t *store = resolve_store(srv, project);REQUIRE_STORE(store, project);+ /* The git context block (worktree/shadow path variants) only matters when+ * debugging index-location issues — gate it so the common status call+ * stays lean. */+ bool verbose = cbm_mcp_get_bool_arg(args, "verbose");yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root = yyjson_mut_obj(doc);@@ -3585,7 +3771,9 @@ static char *handle_index_status(cbm_mcp_server_t *srv, const char *args) {if (cbm_store_get_project(store, project, &proj_info) == CBM_STORE_OK) {yyjson_mut_obj_add_strcpy(doc, root, "root_path",proj_info.root_path ? proj_info.root_path : "");- add_git_context_json(doc, root, proj_info.root_path);+ if (verbose) {+ add_git_context_json(doc, root, proj_info.root_path);+ }safe_str_free(&proj_info.name);safe_str_free(&proj_info.indexed_at);safe_str_free(&proj_info.root_path);@@ -4620,6 +4808,18 @@ static int pick_resolved_node(const cbm_node_t *nodes, int count, bool *ambiguoureturn best;}+static int node_hop_cmp_hop_id(const void *pa, const void *pb) {+ const cbm_node_hop_t *a = (const cbm_node_hop_t *)pa;+ const cbm_node_hop_t *b = (const cbm_node_hop_t *)pb;+ if (a->hop != b->hop) {+ return a->hop < b->hop ? -1 : 1;+ }+ if (a->node.id != b->node.id) {+ return a->node.id < b->node.id ? -1 : 1;+ }+ return 0;+}+/* BFS from EVERY node sharing the resolved name and merge the results, so the* caller/callee set is complete even when one logical symbol is represented by* more than one graph node — e.g. a real .ts implementation plus an ambient@@ -4629,17 +4829,24 @@ static int pick_resolved_node(const cbm_node_t *nodes, int count, bool *ambiguou* transfers into *out, freed by cbm_store_traverse_free. */static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, int node_count,const char *direction, const char **edge_types, int edge_type_count,- int depth, cbm_traverse_result_t *out) {+ int depth, int limit, cbm_traverse_result_t *out) {memset(out, 0, sizeof(*out));int vcap = 0, ecap = 0;for (int k = 0; k < node_count; k++) {cbm_traverse_result_t tr = {0};- cbm_store_bfs(store, nodes[k].id, direction, edge_types, edge_type_count, depth,- MCP_BFS_LIMIT, &tr);+ cbm_store_bfs(store, nodes[k].id, direction, edge_types, edge_type_count, depth, limit,+ &tr);for (int i = 0; i < tr.visited_count; i++) {bool dup = false;for (int j = 0; j < out->visited_count; j++) {if (out->visited[j].node.id == tr.visited[i].node.id) {+ /* Min-hop across seeds: keep-first recorded the EARLIER+ * seed's (possibly longer) distance; hop feeds risk_labels+ * and pagination watermarks, so it must match the+ * single-BFS MIN(hop) semantics (#797). */+ if (tr.visited[i].hop < out->visited[j].hop) {+ out->visited[j].hop = tr.visited[i].hop;+ }dup = true;break;}@@ -4655,6 +4862,20 @@ static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, intmemset(&tr.visited[i], 0, sizeof(tr.visited[i])); /* ownership moved */}for (int i = 0; i < tr.edge_count; i++) {+ /* Overlapping seed neighborhoods yield the same edge from more+ * than one BFS — dedup by (source, target, type). */+ bool edup = false;+ for (int j = 0; j < out->edge_count; j++) {+ if (out->edges[j].source_id == tr.edges[i].source_id &&+ out->edges[j].target_id == tr.edges[i].target_id && out->edges[j].type &&+ tr.edges[i].type && strcmp(out->edges[j].type, tr.edges[i].type) == 0) {+ edup = true;+ break;+ }+ }+ if (edup) {+ continue;+ }if (out->edge_count >= ecap) {ecap = ecap ? ecap * 2 : 8;out->edges = safe_realloc(out->edges, ecap * sizeof(cbm_edge_info_t));@@ -4664,6 +4885,166 @@ static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, int}cbm_store_traverse_free(&tr); /* frees only the un-moved (root + dup) fields */}+ /* Canonical (hop, id) order — a pure function of the graph, independent of+ * seed iteration order; required for deterministic output and watermarks. */+ if (out->visited_count > 1) {+ qsort(out->visited, (size_t)out->visited_count, sizeof(cbm_node_hop_t),+ node_hop_cmp_hop_id);+ }+}++/* ── Pagination cursors (stateless, exactly-once) ────────────────────+ * Token: "c1.<leg>.<generation>.<qhash>.<hop>.<id>" — version, trace leg+ * (o=callees, i=callers), the store generation (per-DB uid + mutation+ * counter), an FNV-1a-64 hash of the canonical query params, and the+ * (hop, node_id) watermark of the last emitted row in canonical order.+ * Stateless by design: the server re-traverses (the recursive CTE pays the+ * full reachable-set cost regardless of LIMIT, so a page costs what one+ * call costs today) and skips to the watermark. The generation stamp turns+ * every post-reindex cursor into a loud, actionable error — node ids are+ * never reused across rebuilds, so silently resuming would be wrong. */++static uint64_t cursor_fnv1a64(const char *s, uint64_t h) {+ while (s && *s) {+ h ^= (uint64_t)(unsigned char)*s++;+ h *= 0x100000001b3ULL;+ }+ return h;+}++typedef struct {+ char leg; /* 'o' callees, 'i' callers */+ char generation[96]; /* store generation at mint time */+ uint64_t qhash; /* canonical-params hash */+ int hop; /* watermark: last emitted row */+ int64_t node_id;+} trace_cursor_t;++/* Hash the params that define the traversal identity. A cursor replayed with+ * different params must fail loudly, never silently mis-skip. */+static uint64_t trace_params_hash(const char *project, const char *func_name, const char *direction,+ const char *mode, int depth, bool include_tests, int limit) {+ uint64_t h = 0xcbf29ce484222325ULL;+ h = cursor_fnv1a64(project ? project : "", h);+ h = cursor_fnv1a64("|", h);+ h = cursor_fnv1a64(func_name ? func_name : "", h);+ h = cursor_fnv1a64("|", h);+ h = cursor_fnv1a64(direction ? direction : "", h);+ h = cursor_fnv1a64("|", h);+ h = cursor_fnv1a64(mode ? mode : "", h);+ char nums[64];+ snprintf(nums, sizeof(nums), "|%d|%d|%d", depth, include_tests ? 1 : 0, limit);+ h = cursor_fnv1a64(nums, h);+ return h;+}++static void trace_cursor_encode(const trace_cursor_t *c, char *buf, size_t bufsz) {+ snprintf(buf, bufsz, "c1.%c.%s.%016llx.%d.%lld", c->leg, c->generation,+ (unsigned long long)c->qhash, c->hop, (long long)c->node_id);+}++/* Decode + validate. Returns NULL on success, else a static teaching error. */+static const char *trace_cursor_decode(const char *token, const char *current_generation,+ uint64_t expected_qhash, trace_cursor_t *out) {+ memset(out, 0, sizeof(*out));+ if (!token || strncmp(token, "c1.", 3) != 0) {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ const char *p = token + 3;+ if (*p != 'o' && *p != 'i') {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ out->leg = *p;+ p += 2; /* leg + '.' */+ const char *gen_end = strchr(p, '.');+ if (!gen_end || (size_t)(gen_end - p) >= sizeof(out->generation)) {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ memcpy(out->generation, p, (size_t)(gen_end - p));+ out->generation[gen_end - p] = '\0';+ unsigned long long qh = 0;+ long long nid = 0;+ if (sscanf(gen_end + 1, "%16llx.%d.%lld", &qh, &out->hop, &nid) != 3) {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ out->qhash = qh;+ out->node_id = nid;+ if (out->qhash != expected_qhash) {+ return "cursor_params_mismatch: this cursor was issued for different arguments — "+ "pass the cursor back with ALL other arguments identical";+ }+ if (strcmp(out->generation, current_generation) != 0) {+ return "stale_cursor: the project was reindexed since this cursor was issued — "+ "re-run the original query without 'cursor' (node identities changed)";+ }+ return NULL;+}++/* Slice a canonically-ordered traversal at the watermark: index of the first+ * row strictly AFTER (hop, id). */+static int trace_watermark_index(const cbm_traverse_result_t *tr, int hop, int64_t node_id) {+ for (int i = 0; i < tr->visited_count; i++) {+ if (tr->visited[i].hop > hop ||+ (tr->visited[i].hop == hop && tr->visited[i].node.id > node_id)) {+ return i;+ }+ }+ return tr->visited_count;+}++/* Tree-format trace leg: rows grouped by qn-prefix (printed once), each row+ * `name hop` — same data as the TOON table, prefix-factored. Test-file rows+ * honor include_tests exactly like bfs_to_toon_table. Rows arrive in+ * canonical (hop,id) order; grouping re-sorts by (prefix, hop, id) so+ * same-module rows are adjacent (Lost-in-Distance) while hop stays visible. */+static int tree_hop_cmp_qn(const void *pa, const void *pb) {+ const cbm_node_hop_t *a = (const cbm_node_hop_t *)pa;+ const cbm_node_hop_t *b = (const cbm_node_hop_t *)pb;+ const char *qa = a->node.qualified_name ? a->node.qualified_name : "";+ const char *qb = b->node.qualified_name ? b->node.qualified_name : "";+ int c = strcmp(qa, qb);+ if (c != 0) {+ return c;+ }+ return a->hop - b->hop;+}++static void bfs_to_tree_table(cbm_sb_t *sb, const char *key, cbm_traverse_result_t *tr,+ bool include_tests) {+ int visible = 0;+ for (int i = 0; i < tr->visited_count; i++) {+ if (!include_tests && is_test_file(tr->visited[i].node.file_path)) {+ continue;+ }+ visible++;+ }+ char buf[CBM_SZ_256];+ snprintf(buf, sizeof(buf), "%s: %d (rows: name hop; qn = group prefix + \".\" + name)\n", key,+ visible);+ cbm_sb_append(sb, buf);+ if (tr->visited_count > 1) {+ qsort(tr->visited, (size_t)tr->visited_count, sizeof(cbm_node_hop_t), tree_hop_cmp_qn);+ }+ char cur_group[CBM_SZ_1K] = "";+ for (int i = 0; i < tr->visited_count; i++) {+ if (!include_tests && is_test_file(tr->visited[i].node.file_path)) {+ continue;+ }+ const char *qn =+ tr->visited[i].node.qualified_name ? tr->visited[i].node.qualified_name : "";+ size_t plen = sg_qn_prefix_len(qn);+ if (plen >= sizeof(cur_group)) {+ plen = 0;+ }+ if (strncmp(cur_group, qn, plen) != 0 || cur_group[plen] != '\0') {+ snprintf(cur_group, sizeof(cur_group), "%.*s", (int)plen, qn);+ cbm_sb_append(sb, cur_group);+ cbm_sb_append(sb, ":\n");+ }+ char row[CBM_SZ_512];+ snprintf(row, sizeof(row), " %s %d\n", plen ? qn + plen + 1 : qn, tr->visited[i].hop);+ cbm_sb_append(sb, row);+ }}/* Clamp a client-supplied traversal depth to the MCP ceiling (cbm_mcp_max_depth),@@ -4691,6 +5072,18 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {char *param_name = cbm_mcp_get_string_arg(args, "parameter_name");int depth = cbm_mcp_get_int_arg(args, "depth", MCP_DEFAULT_DEPTH);depth = clamp_mcp_depth(depth, "trace_call_path");+ /* Per-direction node budget for the BFS working set. The old fixed+ * MCP_BFS_LIMIT silently truncated hub traces at 100 nodes with no+ * signal; now the limit is a documented parameter and hitting it emits+ * `truncated: true` (never a silent truncation — same policy as the+ * depth clamp, #887). */+ int trace_limit = cbm_mcp_get_int_arg(args, "limit", MCP_BFS_LIMIT);+ if (trace_limit < 1) {+ trace_limit = 1;+ }+ if (trace_limit > MCP_BFS_LIMIT_MAX) {+ trace_limit = MCP_BFS_LIMIT_MAX;+ }bool risk_labels = cbm_mcp_get_bool_arg(args, "risk_labels");bool include_tests = cbm_mcp_get_bool_arg(args, "include_tests");@@ -4723,9 +5116,52 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {return not_indexed;}+ /* Pagination: decode + validate the resume cursor (if any) against the+ * current store generation and the canonical params. Errors teach the+ * recovery action instead of silently restarting from page 1. */+ char generation[96];+ (void)cbm_store_generation(store, generation, sizeof(generation));+ char *cursor_arg = cbm_mcp_get_string_arg(args, "cursor");+ trace_cursor_t cur = {0};+ bool have_cursor = false;+ if (cursor_arg && cursor_arg[0]) {+ uint64_t qh =+ trace_params_hash(project, func_name, direction ? direction : "both", mode,+ cbm_mcp_get_int_arg(args, "depth", MCP_DEFAULT_DEPTH), include_tests,+ cbm_mcp_get_int_arg(args, "limit", MCP_BFS_LIMIT));+ const char *cerr = trace_cursor_decode(cursor_arg, generation, qh, &cur);+ if (cerr) {+ free(cursor_arg);+ free(func_name);+ free(project);+ free(direction);+ free(mode);+ free(param_name);+ return cbm_mcp_text_result(cerr, true);+ }+ have_cursor = true;+ }+ free(cursor_arg);if (!direction) {direction = heap_strdup("both");}+ /* Teaching error: an unknown direction used to silently produce an empty+ * trace (both leg flags false) — a field-eval agent burned four calls on+ * "callers"/"callees" before falling back to Cypher. */+ if (strcmp(direction, "inbound") != 0 && strcmp(direction, "outbound") != 0 &&+ strcmp(direction, "both") != 0) {+ char errbuf[CBM_SZ_256];+ snprintf(errbuf, sizeof(errbuf),+ "invalid direction \"%s\" — use \"inbound\" (callers), \"outbound\" (callees), "+ "or \"both\"",+ direction);+ free(func_name);+ free(project);+ free(direction);+ free(mode);+ free(param_name);+ return cbm_mcp_text_result(errbuf, true);+ }/* Find the node by name. If the bare-name lookup misses, fall back to* qualified_name so callers passing a fully-qualified identifier (which@@ -4784,9 +5220,11 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {}/* Response encoding: TOON tables by default; format:"json" restores the- * legacy verbose per-hop objects. */+ * legacy verbose per-hop objects; format:"tree" = Phase-2 A/B candidate+ * (qn-prefix-grouped rows). */char *trace_format = cbm_mcp_get_string_arg(args, "format");bool trace_legacy_json = trace_format && strcmp(trace_format, "json") == 0;+ bool trace_tree = trace_format && strcmp(trace_format, "tree") == 0;free(trace_format);/* Edge types: explicit > mode-based > default */@@ -4807,14 +5245,79 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {(void)sel; /* union across all same-name nodes — see bfs_union_same_name (#546) */+ /* Traverse with the SAFETY ceiling (not the page size): the recursive CTE+ * enumerates the full depth-bounded reachable set regardless of LIMIT, so+ * materializing up to MCP_BFS_LIMIT_MAX rows costs the same traversal —+ * and gives exact totals plus the rows every later page needs. The page+ * size (trace_limit) only bounds what THIS response emits. */if (do_outbound) {bfs_union_same_name(store, nodes, node_count, "outbound", edge_types, edge_type_count,- depth, &tr_out);+ depth, MCP_BFS_LIMIT_MAX, &tr_out);}if (do_inbound) {bfs_union_same_name(store, nodes, node_count, "inbound", edge_types, edge_type_count, depth,- &tr_in);+ MCP_BFS_LIMIT_MAX, &tr_in);+ }++ /* Page windows in canonical (hop,id) order. Legs drain in a fixed order+ * (callees, then callers); a resume cursor starts its leg at the row+ * after the watermark, and a page that finishes one leg with budget to+ * spare continues into the next. */+ int out_start = 0;+ int in_start = 0;+ if (have_cursor) {+ if (cur.leg == 'o') {+ out_start = trace_watermark_index(&tr_out, cur.hop, cur.node_id);+ } else {+ out_start = tr_out.visited_count; /* callees leg already drained */+ in_start = trace_watermark_index(&tr_in, cur.hop, cur.node_id);+ }+ }+ int budget = trace_limit;+ int out_len = 0;+ int in_len = 0;+ if (do_outbound) {+ out_len = tr_out.visited_count - out_start;+ if (out_len > budget) {+ out_len = budget;+ }+ budget -= out_len;}+ if (do_inbound) {+ in_len = tr_in.visited_count - in_start;+ if (in_len > budget) {+ in_len = budget;+ }+ }+ bool out_more = do_outbound && out_start + out_len < tr_out.visited_count;+ bool in_more = do_inbound && in_start + in_len < tr_in.visited_count;+ char next_tok[192] = "";+ if (out_more || in_more) {+ trace_cursor_t nc = {0};+ snprintf(nc.generation, sizeof(nc.generation), "%s", generation);+ nc.qhash = trace_params_hash(project, func_name, direction, mode, depth, include_tests,+ trace_limit);+ if (out_more) {+ nc.leg = 'o';+ nc.hop = tr_out.visited[out_start + out_len - 1].hop;+ nc.node_id = tr_out.visited[out_start + out_len - 1].node.id;+ } else {+ nc.leg = 'i';+ nc.hop = tr_in.visited[in_start + in_len - 1].hop;+ nc.node_id = tr_in.visited[in_start + in_len - 1].node.id;+ }+ trace_cursor_encode(&nc, next_tok, sizeof(next_tok));+ }++ /* Window views: visited offset + count; the full edges array stays+ * attached so data_flow args resolve for boundary nodes whose incoming+ * edge originated on an earlier page. */+ cbm_traverse_result_t view_out = tr_out;+ view_out.visited += out_start;+ view_out.visited_count = out_len;+ cbm_traverse_result_t view_in = tr_in;+ view_in.visited += in_start;+ view_in.visited_count = in_len;char *json = NULL;if (!trace_legacy_json) {@@ -4825,11 +5328,33 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {if (mode) {cbm_toon_scalar_str(&sb, "mode", mode);}+ /* Grouped tree is THE default; risk_labels/data_flow keep the flat+ * table (extra columns) in the same tree syntax. */+ (void)trace_tree;+ bool flat_trace = risk_labels || data_flow;if (do_outbound) {- bfs_to_toon_table(&sb, "callees", &tr_out, risk_labels, include_tests, data_flow);+ cbm_toon_scalar_int(&sb, "callees_total", tr_out.visited_count);+ if (flat_trace) {+ bfs_to_toon_table(&sb, "callees", &view_out, risk_labels, include_tests, data_flow);+ } else {+ bfs_to_tree_table(&sb, "callees", &view_out, include_tests);+ }}if (do_inbound) {- bfs_to_toon_table(&sb, "callers", &tr_in, risk_labels, include_tests, data_flow);+ cbm_toon_scalar_int(&sb, "callers_total", tr_in.visited_count);+ if (flat_trace) {+ bfs_to_toon_table(&sb, "callers", &view_in, risk_labels, include_tests, data_flow);+ } else {+ bfs_to_tree_table(&sb, "callers", &view_in, include_tests);+ }+ }+ if (next_tok[0]) {+ cbm_toon_scalar_bool(&sb, "truncated", true);+ cbm_toon_scalar_str(&sb, "next", next_tok);+ cbm_toon_scalar_str(&sb, "hint",+ "more rows exist — re-call with cursor set to 'next' and ALL "+ "other arguments identical (no duplicates), or narrow with "+ "depth/edge_types");}json = cbm_sb_finish(&sb);} else {@@ -4843,14 +5368,20 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_obj_add_str(doc, root, "mode", mode);}if (do_outbound) {+ yyjson_mut_obj_add_int(doc, root, "callees_total", tr_out.visited_count);yyjson_mut_obj_add_val(doc, root, "callees",- bfs_to_json_array(doc, &tr_out, risk_labels, include_tests, data_flow));+ bfs_to_json_array(doc, &view_out, risk_labels, include_tests, data_flow));}if (do_inbound) {+ yyjson_mut_obj_add_int(doc, root, "callers_total", tr_in.visited_count);yyjson_mut_obj_add_val(doc, root, "callers",- bfs_to_json_array(doc, &tr_in, risk_labels, include_tests, data_flow));+ bfs_to_json_array(doc, &view_in, risk_labels, include_tests, data_flow));+ }+ if (next_tok[0]) {+ yyjson_mut_obj_add_bool(doc, root, "truncated", true);+ yyjson_mut_obj_add_strcpy(doc, root, "next_cursor", next_tok);}/* Serialize BEFORE freeing traversal results (yyjson borrows strings) */json = yy_doc_to_str(doc);@@ -5029,7 +5560,7 @@ static void try_artifact_bootstrap(const char *project_name, const char *repo_pa/* Cap on excluded dir paths listed in the response — keep it compact on large* repos (node_modules / vendor / etc. can produce many skip points). The full* count is still reported via "count" + "truncated". */-enum { INDEX_EXCLUDED_DIR_CAP = 25 };+enum { INDEX_EXCLUDED_DIR_CAP = 5 }; /* examples only — see INDEX_SKIPPED_FILE_CAP note *//* Attach a compact summary of directory subtrees skipped during discovery (#411).* Shape: "excluded": {"dirs": [up to 25 rel-paths], "count": <total>, "truncated": <bool>}.@@ -5056,7 +5587,12 @@ static void add_excluded_summary(yyjson_mut_doc *doc, yyjson_mut_val *root, char/* Cap on per-file skips embedded in the JSON response — keep it compact on* large repos. The FULL, uncapped list always goes to the per-run logfile;* the JSON carries "count" + "truncated" so nothing is silently hidden. */-enum { INDEX_SKIPPED_FILE_CAP = 50 };+/* In-response coverage lists are EXAMPLES, not the record: the full uncapped+ * lists live in the per-run logfile (path in the same response) and are+ * queryable via index_status (scope_limit) / query_graph(graph="missed").+ * Five examples orient the agent; anything more duplicates the logfile into+ * every index response (53 KB observed on a large repo). */+enum { INDEX_SKIPPED_FILE_CAP = 5 };/* Attach the by-design ignored-FILES summary (#963 "purposely not indexed").* Individual files dropped by ignore rules — deliberate, not failures; whole@@ -5086,10 +5622,8 @@ static void add_not_indexed_files_summary(yyjson_mut_doc *doc, yyjson_mut_val *ryyjson_mut_obj_add_int(doc, ni, "count", total);yyjson_mut_obj_add_bool(doc, ni, "truncated", total > shown);yyjson_mut_obj_add_str(doc, ni, "note",- "Purposely not indexed — excluded BY DESIGN via "- "gitignore/.cbmignore/skip-lists (see each file's reason). Not an "- "error: change the ignore rules and re-index to include them. Whole "- "excluded subtrees are listed separately under \"excluded\".");+ "Excluded by design (gitignore/.cbmignore/skip-lists); examples only — "+ "full list in 'logfile'.");yyjson_mut_obj_add_val(doc, root, "not_indexed_files", ni);}@@ -5181,12 +5715,9 @@ static void add_parse_partial_summary(yyjson_mut_doc *doc, yyjson_mut_val *root,yyjson_mut_obj_add_int(doc, pp, "count", partials);yyjson_mut_obj_add_bool(doc, pp, "truncated", partials > INDEX_SKIPPED_FILE_CAP);yyjson_mut_obj_add_str(doc, pp, "note",- "Best-effort signal, not a completeness guarantee: these files WERE "- "indexed, but constructs inside the listed line ranges (1-based) could "- "not be parsed and MAY be missing from the graph (tree-sitter error "- "recovery still salvages some). Prefer text search (grep) for those "- "regions. Files absent from this list are NOT guaranteed to be fully "- "indexed. Query the persisted signal via index_status.");+ "Indexed, but constructs in these line ranges may be missing (best-"+ "effort signal); examples only — full list via index_status or "+ "'logfile'.");yyjson_mut_obj_add_val(doc, root, "parse_partial", pp);}diff --git a/src/store/store.c b/src/store/store.cindex efd56f531..a9e86cb34 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -1226,6 +1226,51 @@ int cbm_store_upsert_project(cbm_store_t *s, const char *name, const char *root_store_set_error_sqlite(s, "upsert_project");return CBM_STORE_ERR;}++ /* Store generation for cursor staleness (pagination): db_uid is a random+ * identity minted once per DB FILE (a full reindex publishes a fresh file+ * via the writer, which carries no store_meta — the first upsert_project+ * on the opened store seeds a NEW uid, so cursors minted against the old+ * file can never validate against the rebuilt one, whose node ids all+ * differ). mutation_gen increments on every project upsert — the choke+ * point every index run (full, incremental, watcher) passes through.+ * Created here rather than in the byte-level writer: adding a table to+ * its hand-built sqlite_master is rootpage surgery for zero benefit. */+ (void)sqlite3_exec(s->db,+ "CREATE TABLE IF NOT EXISTS store_meta (k TEXT PRIMARY KEY, v TEXT);"+ "INSERT OR IGNORE INTO store_meta VALUES"+ "('db_uid', lower(hex(randomblob(8))));"+ "INSERT OR IGNORE INTO store_meta VALUES('mutation_gen','0');"+ "UPDATE store_meta SET v = CAST(CAST(v AS INTEGER)+1 AS TEXT) "+ "WHERE k='mutation_gen';",+ NULL, NULL, NULL);+ return CBM_STORE_OK;+}++/* Opaque store generation for pagination cursors: "u<db_uid>g<mutation_gen>",+ * or "legacy" when the DB predates store_meta (read-only opens never create+ * it). A cursor whose embedded generation mismatches the store's current one+ * is stale — the graph may have changed under it. */+int cbm_store_generation(cbm_store_t *s, char *buf, size_t bufsz) {+ if (!s || !s->db || !buf || bufsz == 0) {+ return CBM_STORE_ERR;+ }+ snprintf(buf, bufsz, "legacy");+ sqlite3_stmt *stmt = NULL;+ if (sqlite3_prepare_v2(s->db,+ "SELECT (SELECT v FROM store_meta WHERE k='db_uid'),"+ " (SELECT v FROM store_meta WHERE k='mutation_gen');",+ CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {+ return CBM_STORE_OK; /* pre-migration DB: stable "legacy" generation */+ }+ if (sqlite3_step(stmt) == SQLITE_ROW) {+ const char *uid = (const char *)sqlite3_column_text(stmt, 0);+ const char *gen = (const char *)sqlite3_column_text(stmt, SKIP_ONE);+ if (uid && gen) {+ snprintf(buf, bufsz, "u%sg%s", uid, gen);+ }+ }+ sqlite3_finalize(stmt);return CBM_STORE_OK;}@@ -3474,9 +3519,12 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_searint limit = params->limit > 0 ? params->limit : CBM_DEFAULT_SEARCH_LIMIT;int offset = params->offset;const char *name_col = has_degree_filter ? "name" : "n.name";+ const char *id_col = has_degree_filter ? "id" : "n.id";char order_limit[CBM_SZ_128];- snprintf(order_limit, sizeof(order_limit), " ORDER BY %s LIMIT %d OFFSET %d", name_col, limit,- offset);+ /* (name, id) is a unique total order — names are non-unique, and without+ * the tie-break offset pages are not contractually stable across calls. */+ snprintf(order_limit, sizeof(order_limit), " ORDER BY %s, %s LIMIT %d OFFSET %d", name_col,+ id_col, limit, offset);strncat(sql, order_limit, sizeof(sql) - strlen(sql) - 1);/* Execute count query */@@ -3565,19 +3613,34 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_hoint visited_count, const char *types_clause, const char **edge_types,int edge_type_count, cbm_edge_info_t **out_edges,int *out_edge_count) {- /* Build ID set: root + all visited */- char id_set[CBM_SZ_4K];- int ilen = snprintf(id_set, sizeof(id_set), "%lld", (long long)start_id);- if (ilen >= (int)sizeof(id_set)) {- ilen = (int)sizeof(id_set) - SKIP_ONE;+ *out_edges = NULL;+ *out_edge_count = 0;++ /* Visited-ID set via a per-connection TEMP table. The previous approach+ * interpolated the ids into a fixed 4KB SQL string: past ~1000 visited+ * nodes the list was cut MID-NUMBER, the SQL failed to prepare, and every+ * trace edge silently vanished (and a luckier cut could match an+ * unrelated node). TEMP tables live in the connection's temp db, so this+ * works on read-only query connections too. */+ if (sqlite3_exec(s->db,+ "CREATE TEMP TABLE IF NOT EXISTS bfs_ids (id INTEGER PRIMARY KEY);"+ "DELETE FROM bfs_ids;",+ NULL, NULL, NULL) != SQLITE_OK) {+ return CBM_STORE_OK; /* best-effort: nodes without edges beat an error */+ }+ sqlite3_stmt *ins = NULL;+ if (sqlite3_prepare_v2(s->db, "INSERT OR IGNORE INTO bfs_ids(id) VALUES (?1)", CBM_NOT_FOUND,+ &ins, NULL) != SQLITE_OK) {+ return CBM_STORE_OK;}+ sqlite3_bind_int64(ins, SKIP_ONE, start_id);+ (void)sqlite3_step(ins);for (int i = 0; i < visited_count; i++) {- ilen += snprintf(id_set + ilen, sizeof(id_set) - (size_t)ilen, ",%lld",- (long long)visited[i].node.id);- if (ilen >= (int)sizeof(id_set)) {- ilen = (int)sizeof(id_set) - SKIP_ONE;- }+ sqlite3_reset(ins);+ sqlite3_bind_int64(ins, SKIP_ONE, visited[i].node.id);+ (void)sqlite3_step(ins);}+ sqlite3_finalize(ins);char edge_sql[ST_SQL_BUF];snprintf(edge_sql, sizeof(edge_sql),@@ -3585,9 +3648,10 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho"FROM edges e ""JOIN nodes n1 ON n1.id = e.source_id ""JOIN nodes n2 ON n2.id = e.target_id "- "WHERE e.source_id IN (%s) AND e.target_id IN (%s) "+ "WHERE e.source_id IN (SELECT id FROM bfs_ids) "+ "AND e.target_id IN (SELECT id FROM bfs_ids) ""AND e.type IN (%s)",- id_set, id_set, types_clause);+ types_clause);sqlite3_stmt *estmt = NULL;int rc = sqlite3_prepare_v2(s->db, edge_sql, CBM_NOT_FOUND, &estmt, NULL);@@ -3708,7 +3772,9 @@ int cbm_store_bfs(cbm_store_t *s, int64_t start_id, const char *direction, const"JOIN nodes n ON n.id = bfs.node_id ""WHERE bfs.hop > 0 " /* exclude root at hop 0 (self via a loop still appears) */"GROUP BY n.id "- "ORDER BY hop "+ /* (hop, id) is a unique total order — deterministic pagination+ * watermarks and reproducible trace output depend on it. */+ "ORDER BY hop, n.id ""LIMIT %d;",(long long)start_id, next_id, join_cond, types_clause, max_depth, max_results);diff --git a/src/store/store.h b/src/store/store.hindex a07facbc4..d088139ea 100644--- a/src/store/store.h+++ b/src/store/store.h@@ -266,6 +266,11 @@ int cbm_store_checkpoint(cbm_store_t *s);* connection, in bytes; -1 = unlimited (SQLite default / pre-fix). */int64_t cbm_store_journal_size_limit(cbm_store_t *s);+/* Opaque store generation for pagination-cursor staleness detection:+ * "u<db_uid>g<mutation_gen>" — db_uid is minted per DB file, mutation_gen+ * bumps on every index run. "legacy" for DBs predating store_meta. */+int cbm_store_generation(cbm_store_t *s, char *buf, size_t bufsz);+/* Resolve the mmap_size pragma value applied to on-disk stores from the* CBM_SQLITE_MMAP_SIZE environment variable. Defaults to 67108864 (64 MB)* when the variable is unset, malformed, or partially numeric. Negativediff --git a/tests/test_index_resilience.c b/tests/test_index_resilience.cindex 29d316942..8d8a601a6 100644--- a/tests/test_index_resilience.c+++ b/tests/test_index_resilience.c@@ -359,7 +359,9 @@ TEST(index_parse_partial_reported) {ASSERT_TRUE(found_split);const char *note = yyjson_get_str(yyjson_obj_get(pp, "note"));ASSERT_NOT_NULL(note);- ASSERT_NOT_NULL(strstr(note, "guarantee"));+ /* Lean-note contract: best-effort framing + pointer to the full record. */+ ASSERT_NOT_NULL(strstr(note, "best-effort"));+ ASSERT_NOT_NULL(strstr(note, "logfile"));/* Logfile lists it under the distinct phase. */const char *logfile = yyjson_get_str(yyjson_obj_get(sc, "logfile"));@@ -591,7 +593,9 @@ TEST(index_not_indexed_by_design_reported) {ASSERT_TRUE(found_secret);const char *note = yyjson_get_str(yyjson_obj_get(ni, "note"));ASSERT_NOT_NULL(note);- ASSERT_NOT_NULL(strstr(note, "BY DESIGN"));+ /* Lean-note contract: deliberate-exclusion framing + pointer to the record. */+ ASSERT_NOT_NULL(strstr(note, "by design"));+ ASSERT_NOT_NULL(strstr(note, "logfile"));/* The gitignored DIR is in the excluded subtrees list. */yyjson_val *excluded = yyjson_obj_get(sc, "excluded");diff --git a/tests/test_integration.c b/tests/test_integration.cindex b81ac378b..a63f9e5d4 100644--- a/tests/test_integration.c+++ b/tests/test_integration.c@@ -580,6 +580,59 @@ TEST(integ_store_bfs_traversal) {PASS();}+/* bfs_collect_edges built its visited-ID set into a fixed 4KB string: past+ * ~340-1100 visited nodes (id-width dependent) the id list was SILENTLY cut,+ * so trace edges (and data_flow args) vanished — and a partially-written id+ * could even match an UNRELATED node, admitting wrong edges. GUARD: a star of+ * 1200 callers (id string ≈ 4.6KB) must surface every edge. RED on the fixed+ * buffer, GREEN with the temp-table join. */+TEST(store_bfs_edges_survive_large_visited_set) {+ cbm_store_t *s = cbm_store_open_memory();+ ASSERT_NOT_NULL(s);+ ASSERT_EQ(cbm_store_upsert_project(s, "star", "/tmp/star"), CBM_STORE_OK);++ cbm_node_t hub = {0};+ hub.project = "star";+ hub.label = "Function";+ hub.name = "hub";+ hub.qualified_name = "star.hub";+ hub.file_path = "hub.c";+ int64_t hub_id = cbm_store_upsert_node(s, &hub);+ ASSERT_GT(hub_id, 0);++ enum { SPOKES = 1200 };+ for (int i = 0; i < SPOKES; i++) {+ char nm[32];+ char qn[64];+ snprintf(nm, sizeof(nm), "caller_%04d", i);+ snprintf(qn, sizeof(qn), "star.caller_%04d", i);+ cbm_node_t sp = {0};+ sp.project = "star";+ sp.label = "Function";+ sp.name = nm;+ sp.qualified_name = qn;+ sp.file_path = "spokes.c";+ int64_t sid = cbm_store_upsert_node(s, &sp);+ ASSERT_GT(sid, 0);+ cbm_edge_t e = {0};+ e.project = "star";+ e.source_id = sid;+ e.target_id = hub_id;+ e.type = "CALLS";+ ASSERT_GT(cbm_store_insert_edge(s, &e), 0); /* returns the edge id */+ }++ cbm_traverse_result_t tr = {0};+ ASSERT_EQ(cbm_store_bfs(s, hub_id, "inbound", NULL, 0, 1, SPOKES + 10, &tr), CBM_STORE_OK);+ ASSERT_EQ(tr.visited_count, SPOKES);+ /* Every caller->hub edge must be collected — none silently dropped. */+ ASSERT_EQ(tr.edge_count, SPOKES);++ cbm_store_traverse_free(&tr);+ cbm_store_close(s);+ PASS();+}+/* #411: index_repository silently drops entire subtrees with no record.* Moderate/fast mode applies FAST_SKIP_DIRS (tools/scripts/bin/docs/...) and ALL* modes apply ALWAYS_SKIP_DIRS (node_modules/...), so files are excluded from the@@ -667,6 +720,7 @@ SUITE(integration) {RUN_TEST(integ_store_search_by_degree);RUN_TEST(integ_store_find_by_file);RUN_TEST(integ_store_bfs_traversal);+ RUN_TEST(store_bfs_edges_survive_large_visited_set);/* Pipeline API tests (no db needed) */RUN_TEST(integ_pipeline_fqn_compute);diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex 4e1d5eeb3..0fdfa5e20 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -1110,8 +1110,8 @@ TEST(tool_search_graph_includes_node_properties) {ASSERT_NOT_NULL(strstr(resp, "\"structuredContent\":{\"text\":"));char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "results[")); /* TOON table header */- ASSERT_NOT_NULL(strstr(inner, "{qn,label,file,lines,in,out}"));+ ASSERT_NOT_NULL(strstr(inner, "results:")); /* TOON table header */+ ASSERT_NOT_NULL(strstr(inner, "(rows: name label lines in out;"));ASSERT_NOT_NULL(strstr(inner, "HandleRequest"));ASSERT_NULL(strstr(inner, "func HandleRequest")); /* signature not spilled */ASSERT_NULL(strstr(inner, "is_exported"));@@ -1127,7 +1127,7 @@ TEST(tool_search_graph_includes_node_properties) {ASSERT_NOT_NULL(resp);inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "{qn,label,file,lines,in,out,signature}"));+ ASSERT_NOT_NULL(strstr(inner, "(rows: name label lines in out signature;"));ASSERT_NOT_NULL(strstr(inner, "func HandleRequest"));free(inner);free(resp);@@ -1185,7 +1185,7 @@ TEST(tool_output_byte_budgets) {ASSERT_NOT_NULL(resp);inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "callees["));+ ASSERT_NOT_NULL(strstr(inner, "callees:"));ASSERT_LT((int)strlen(inner), 800);free(inner);free(resp);@@ -1242,6 +1242,187 @@ TEST(tool_search_graph_toon_never_leaks_internal_fields) {PASS();}+TEST(tool_lean_defaults_schema_and_status) {+ /* GUARDS for the lean-default contract (TOON round 2):+ * 1. get_graph_schema must not advertise the blocked internal fields+ * (fp/sp/bt) — the server refuses to emit them, so listing them in the+ * schema invited agents to request fields they can never get.+ * 2. index_status omits the git context block unless verbose:true — the+ * worktree/shadow path variants only matter when debugging where an+ * index lives. */+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);++ cbm_node_t n = {0};+ n.project = "test-project";+ n.label = "Function";+ n.name = "schemaCarrier";+ n.qualified_name = "test-project.src.schemaCarrier";+ n.file_path = "src/sc.go";+ n.start_line = 1;+ n.end_line = 2;+ n.properties_json = "{\"fp\":\"x\",\"sp\":\"y\",\"bt\":\"z\",\"complexity\":3}";+ ASSERT_GT(cbm_store_upsert_node(st, &n), 0);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":48,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"get_graph_schema\","+ "\"arguments\":{\"project\":\"test-project\"}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "Function")); /* non-vacuous: label present */+ ASSERT_NOT_NULL(strstr(inner, "complexity")); /* obtainable property listed */+ ASSERT_NULL(strstr(inner, "\"fp\"")); /* blocked fields not advertised */+ ASSERT_NULL(strstr(inner, "\"sp\""));+ ASSERT_NULL(strstr(inner, "\"bt\""));+ free(inner);+ free(resp);++ /* index_status: no git block by default... */+ resp = cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":49,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\"}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"status\""));+ ASSERT_NULL(strstr(inner, "\"git\""));+ free(inner);+ free(resp);++ /* ...and present with verbose:true. */+ resp = cbm_mcp_server_handle(srv,+ "{\"jsonrpc\":\"2.0\",\"id\":50,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\",\"verbose\":true}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"git\""));+ free(inner);+ free(resp);++ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+}++/* ── Tool-output regression suite (gating) ──────────────────────────+ * Context-explosion detector: flags the measured smells that re-introduce+ * token bloat into default outputs, independent of any specific tool:+ * 1. blocked internal fields (fp/sp/bt) appearing anywhere;+ * 2. repeated-key JSON envelopes — the same key emitted per row instead of+ * a header-once table (the un-TOONed enumeration smell; detect_changes+ * shipped 4,787x3 of these = 416KB);+ * 3. embedded prose notes/hints beyond one line (~220 chars) — long prose+ * belongs in tool descriptions or docs, not repeated per response.+ * Returns NULL when clean, else a static description of the violation. */+static const char *output_explosion_smell(const char *inner) {+ static const char *row_keys[] = {+ "\"name\":", "\"label\":", "\"file\":", "\"path\":", "\"qualified_name\":", "\"qn\":"};+ if (strstr(inner, "\"fp\":") || strstr(inner, "\"sp\":") || strstr(inner, "\"bt\":")) {+ return "blocked internal field (fp/sp/bt) leaked into output";+ }+ for (size_t k = 0; k < sizeof(row_keys) / sizeof(row_keys[0]); k++) {+ int n = 0;+ for (const char *p = strstr(inner, row_keys[k]); p && n <= 32;+ p = strstr(p + 1, row_keys[k])) {+ n++;+ }+ if (n > 32) {+ return "repeated-key envelope (>32x same JSON key) — emit a header-once table";+ }+ }+ for (const char *p = strstr(inner, "\"note\":\""); p; p = strstr(p + 1, "\"note\":\"")) {+ const char *end = strchr(p + 9, '"');+ while (end && end[-1] == '\\') {+ end = strchr(end + 1, '"');+ }+ if (end && end - (p + 9) > 220) {+ return "embedded note exceeds one line (~220 chars)";+ }+ }+ return NULL;+}++/* Run one tool call on the fixture server, apply the explosion detector and+ * an absolute byte ceiling, and require a semantic-floor marker so trimming+ * can never hollow the response out either. */+static const char *check_tool_output(cbm_mcp_server_t *srv, const char *req, int ceiling,+ const char *floor_marker) {+ char *resp = cbm_mcp_server_handle(srv, req);+ if (!resp) {+ return "no response";+ }+ char *inner = extract_text_content(resp);+ free(resp);+ if (!inner) {+ return "no text content";+ }+ static char why[256];+ const char *smell = output_explosion_smell(inner);+ if (smell) {+ snprintf(why, sizeof(why), "%s", smell);+ free(inner);+ return why;+ }+ if ((int)strlen(inner) >= ceiling) {+ snprintf(why, sizeof(why), "output %d B >= ceiling %d B", (int)strlen(inner), ceiling);+ free(inner);+ return why;+ }+ if (floor_marker && !strstr(inner, floor_marker)) {+ snprintf(why, sizeof(why), "semantic floor missing: %s", floor_marker);+ free(inner);+ return why;+ }+ free(inner);+ return NULL;+}++TEST(tool_output_regression_gate) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);++ struct {+ const char *req;+ int ceiling;+ const char *floor;+ } cases[] = {+ {"{\"jsonrpc\":\"2.0\",\"id\":70,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"search_graph\",\"arguments\":{\"project\":\"test-project\","+ "\"name_pattern\":\".*\",\"limit\":50}}}",+ 6000, "results:"},+ {"{\"jsonrpc\":\"2.0\",\"id\":71,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"get_graph_schema\",\"arguments\":{\"project\":\"test-project\"}}}",+ 6000, "node_labels"},+ {"{\"jsonrpc\":\"2.0\",\"id\":72,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"index_status\",\"arguments\":{\"project\":\"test-project\"}}}",+ 7000, "\"status\""},+ {"{\"jsonrpc\":\"2.0\",\"id\":73,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"test-project\","+ "\"function_name\":\"HandleRequest\",\"direction\":\"both\"}}}",+ 1500, "callees:"},+ };+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ const char *why = check_tool_output(srv, cases[i].req, cases[i].ceiling, cases[i].floor);+ if (why) {+ char msg[320];+ snprintf(msg, sizeof(msg), "case %d: %s", (int)i, why);+ FAIL(msg);+ }+ }++ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+}+TEST(tool_search_graph_query_honors_file_pattern_issue552) {cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);ASSERT_NOT_NULL(srv);@@ -1558,14 +1739,17 @@ TEST(tool_check_index_coverage_surfaces_lookup_errors) {}TEST(tool_index_status_includes_git_metadata) {+ /* The git context block moved behind verbose:true (lean-default contract,+ * TOON round 2) — this test pins the verbose path's content; the default-+ * omission guard lives in tool_lean_defaults_schema_and_status. */char tmp[256];cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));ASSERT_NOT_NULL(srv);- char *resp =- cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":16,\"method\":\"tools/call\","- "\"params\":{\"name\":\"index_status\","- "\"arguments\":{\"project\":\"test-project\"}}}");+ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":16,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\",\"verbose\":true}}}");ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);@@ -1658,6 +1842,223 @@ TEST(tool_trace_call_path_ambiguous) {PASS();}+/* Multi-seed union hop semantics: bfs_union_same_name deduped visited nodes+ * keep-FIRST-seen, so a node reached at hop 2 from the first seed kept hop 2+ * even when the second seed reaches it at hop 1. hop feeds risk_labels and+ * (soon) pagination watermarks — it must be the MINIMUM across seeds, matching+ * the single-BFS MIN(hop) semantics (#797). */+TEST(tool_trace_union_records_min_hop_across_seeds) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ const char *proj = "dualproj";+ cbm_mcp_server_set_project(srv, proj);+ cbm_store_upsert_project(st, proj, "/tmp/dual");++ /* One real definition + one body-less stub (start==end) — the #546/#650+ * shape pick_resolved_node resolves WITHOUT ambiguity while+ * bfs_union_same_name still traverses both. Seed A (real def, lower id,+ * traversed first) reaches tgt only via mid (hop 2); the stub seed B+ * reaches tgt directly (hop 1). */+ cbm_node_t sa = {.project = proj,+ .label = "Function",+ .name = "dual",+ .qualified_name = "dualproj.a.dual",+ .file_path = "a.c",+ .start_line = 1,+ .end_line = 50};+ cbm_node_t sb = {.project = proj,+ .label = "Function",+ .name = "dual",+ .qualified_name = "dualproj.b.dual",+ .file_path = "b.d.ts",+ .start_line = 1,+ .end_line = 1};+ cbm_node_t mid = {.project = proj,+ .label = "Function",+ .name = "mid",+ .qualified_name = "dualproj.c.mid",+ .file_path = "c.c",+ .start_line = 1,+ .end_line = 5};+ cbm_node_t tgt = {.project = proj,+ .label = "Function",+ .name = "tgt",+ .qualified_name = "dualproj.c.tgt",+ .file_path = "c.c",+ .start_line = 10,+ .end_line = 15};+ int64_t ida = cbm_store_upsert_node(st, &sa);+ int64_t idb = cbm_store_upsert_node(st, &sb);+ int64_t idm = cbm_store_upsert_node(st, &mid);+ int64_t idt = cbm_store_upsert_node(st, &tgt);+ ASSERT_GT(ida, 0);+ ASSERT_GT(idb, 0);+ ASSERT_GT(idm, 0);+ ASSERT_GT(idt, 0);+ cbm_edge_t e1 = {.project = proj, .source_id = ida, .target_id = idm, .type = "CALLS"};+ cbm_edge_t e2 = {.project = proj, .source_id = idm, .target_id = idt, .type = "CALLS"};+ cbm_edge_t e3 = {.project = proj, .source_id = idb, .target_id = idt, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(st, &e1), 0);+ ASSERT_GT(cbm_store_insert_edge(st, &e2), 0);+ ASSERT_GT(cbm_store_insert_edge(st, &e3), 0);++ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":62,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"trace_call_path\","+ "\"arguments\":{\"function_name\":\"dual\",\"project\":\"dualproj\","+ "\"direction\":\"outbound\",\"depth\":3}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ /* tgt is one hop from seed B — the union must record hop 1, not seed A's 2. */+ ASSERT_NOT_NULL(strstr(inner, " tgt 1"));+ ASSERT_NULL(strstr(inner, " tgt 2"));+ free(inner);+ free(resp);+ cbm_mcp_server_free(srv);+ PASS();+}++/* Exactly-once trace pagination: 12 callees paged at limit=5 must yield+ * 5+5+2 rows with every callee appearing on exactly one page, exact totals+ * on every page, and a final page without a cursor. Stale and mismatched+ * cursors must fail with teaching errors, never silently restart. */+TEST(tool_trace_pagination_exactly_once) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ const char *proj = "pageproj";+ cbm_mcp_server_set_project(srv, proj);+ cbm_store_upsert_project(st, proj, "/tmp/page");++ cbm_node_t hub = {.project = proj,+ .label = "Function",+ .name = "hub",+ .qualified_name = "pageproj.h.hub",+ .file_path = "h.c",+ .start_line = 1,+ .end_line = 9};+ int64_t hid = cbm_store_upsert_node(st, &hub);+ ASSERT_GT(hid, 0);+ enum { CALLEES = 12 };+ for (int i = 0; i < CALLEES; i++) {+ char nm[16];+ char qn[48];+ snprintf(nm, sizeof(nm), "c%02d", i);+ snprintf(qn, sizeof(qn), "pageproj.m.c%02d", i);+ cbm_node_t n = {.project = proj,+ .label = "Function",+ .name = nm,+ .qualified_name = qn,+ .file_path = "m.c",+ .start_line = 1,+ .end_line = 3};+ int64_t nid = cbm_store_upsert_node(st, &n);+ ASSERT_GT(nid, 0);+ cbm_edge_t e = {.project = proj, .source_id = hid, .target_id = nid, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(st, &e), 0);+ }++ char pages[3][4096];+ char tok[192] = "";+ int npages = 0;+ for (; npages < 3; npages++) {+ char req[640];+ if (tok[0]) {+ snprintf(req, sizeof(req),+ "{\"jsonrpc\":\"2.0\",\"id\":80,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"+ "\"cursor\":\"%s\"}}}",+ tok);+ } else {+ snprintf(req, sizeof(req),+ "{\"jsonrpc\":\"2.0\",\"id\":80,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5}}}");+ }+ char *resp = cbm_mcp_server_handle(srv, req);+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ snprintf(pages[npages], sizeof(pages[npages]), "%s", inner);+ ASSERT_NOT_NULL(strstr(inner, "callees_total: 12")); /* exact total, every page */+ const char *nx = strstr(inner, "next: ");+ if (nx) {+ const char *e = strchr(nx + 6, '\n');+ size_t tl = e ? (size_t)(e - (nx + 6)) : strlen(nx + 6);+ ASSERT_TRUE(tl < sizeof(tok));+ memcpy(tok, nx + 6, tl);+ tok[tl] = '\0';+ } else {+ tok[0] = '\0';+ }+ free(inner);+ if (!tok[0]) {+ npages++;+ break;+ }+ }+ ASSERT_EQ(npages, 3); /* 5 + 5 + 2 */+ /* Exactly-once: every callee appears on exactly ONE page. */+ for (int i = 0; i < CALLEES; i++) {+ char qn[48];+ snprintf(qn, sizeof(qn), " c%02d 1\n", i);+ int seen = 0;+ for (int p = 0; p < 3; p++) {+ if (strstr(pages[p], qn)) {+ seen++;+ }+ }+ ASSERT_EQ(seen, 1);+ }+ /* Final page carries no cursor. */+ ASSERT_NULL(strstr(pages[2], "next: "));++ /* Params mismatch: replay a page-2-era cursor with a different depth. */+ const char *nx1 = strstr(pages[0], "next: ");+ ASSERT_NOT_NULL(nx1);+ char tok1[192];+ const char *e1 = strchr(nx1 + 6, '\n');+ size_t tl1 = e1 ? (size_t)(e1 - (nx1 + 6)) : strlen(nx1 + 6);+ memcpy(tok1, nx1 + 6, tl1);+ tok1[tl1] = '\0';+ char req2[640];+ snprintf(req2, sizeof(req2),+ "{\"jsonrpc\":\"2.0\",\"id\":81,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,\"depth\":2,"+ "\"cursor\":\"%s\"}}}",+ tok1);+ char *resp = cbm_mcp_server_handle(srv, req2);+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "cursor_params_mismatch"));+ free(inner);++ /* Stale: an index run (upsert_project bumps the generation) invalidates+ * outstanding cursors with a loud, actionable error. */+ cbm_store_upsert_project(st, proj, "/tmp/page");+ snprintf(req2, sizeof(req2),+ "{\"jsonrpc\":\"2.0\",\"id\":82,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"+ "\"cursor\":\"%s\"}}}",+ tok1);+ resp = cbm_mcp_server_handle(srv, req2);+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "stale_cursor"));+ free(inner);++ cbm_mcp_server_free(srv);+ PASS();+}+/* Regression: when same-named nodes differ in rank, trace must pick the real* definition (callable, larger body) — NOT nodes[0]. The Module is inserted* first; if trace took nodes[0] the outbound trace would be empty. */@@ -1985,7 +2386,7 @@ TEST(tool_get_architecture_emits_populated_sections) {* those existed before #281. The "entry_points" array only appears* when cbm_store_get_architecture is actually called and its result* is serialized — which is exactly what #281 wires up. */- ASSERT_NOT_NULL(strstr(inner, "entry_points["));+ ASSERT_NOT_NULL(strstr(inner, "entry_points:"));ASSERT_NOT_NULL(strstr(inner, "main"));free(inner);@@ -2038,8 +2439,8 @@ TEST(tool_get_architecture_overview_compact_subset_pr560) {ASSERT_NOT_NULL(resp_all);char *inner_all = extract_text_content(resp_all);ASSERT_NOT_NULL(inner_all);- ASSERT_NOT_NULL(strstr(inner_all, "entry_points["));- ASSERT_NOT_NULL(strstr(inner_all, "file_tree["));+ ASSERT_NOT_NULL(strstr(inner_all, "entry_points:"));+ ASSERT_NOT_NULL(strstr(inner_all, "file_tree:"));free(inner_all);free(resp_all);@@ -2052,9 +2453,9 @@ TEST(tool_get_architecture_overview_compact_subset_pr560) {ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "entry_points["));- ASSERT_NOT_NULL(strstr(inner, "node_labels["));- ASSERT_NULL(strstr(inner, "file_tree["));+ ASSERT_NOT_NULL(strstr(inner, "entry_points:"));+ ASSERT_NOT_NULL(strstr(inner, "node_labels:"));+ ASSERT_NULL(strstr(inner, "file_tree:"));free(inner);free(resp);@@ -2135,7 +2536,7 @@ TEST(tool_get_architecture_accepts_project_name_alias_issue640) {/* RED before the alias: inner is the "project not found" error.* GREEN after: the alias resolves and architecture sections surface. */ASSERT_NULL(strstr(inner, "project not found"));- ASSERT_NOT_NULL(strstr(inner, "entry_points["));+ ASSERT_NOT_NULL(strstr(inner, "entry_points:"));free(inner);free(resp);@@ -6404,6 +6805,8 @@ SUITE(mcp) {RUN_TEST(tool_search_graph_basic);RUN_TEST(tool_search_graph_includes_node_properties);RUN_TEST(tool_search_graph_toon_never_leaks_internal_fields);+ RUN_TEST(tool_lean_defaults_schema_and_status);+ RUN_TEST(tool_output_regression_gate);RUN_TEST(tool_output_byte_budgets);RUN_TEST(tool_search_graph_query_honors_file_pattern_issue552);RUN_TEST(mcp_resource_discovery_methods_return_empty_lists);@@ -6420,6 +6823,8 @@ SUITE(mcp) {RUN_TEST(tool_trace_call_path_not_found);RUN_TEST(tool_trace_missing_function_name);RUN_TEST(tool_trace_call_path_ambiguous);+ RUN_TEST(tool_trace_union_records_min_hop_across_seeds);+ RUN_TEST(tool_trace_pagination_exactly_once);RUN_TEST(tool_trace_call_path_prefers_definition);RUN_TEST(tool_trace_call_path_depth_clamped);RUN_TEST(tool_trace_call_path_distinct_defs_not_over_unioned);diff --git a/tests/test_store_pragmas.c b/tests/test_store_pragmas.cindex 5aff16235..0d093589c 100644--- a/tests/test_store_pragmas.c+++ b/tests/test_store_pragmas.c@@ -113,6 +113,35 @@ TEST(journal_size_limit_bounds_wal_issue1083) {PASS();}+/* Pagination-cursor generation: minted per DB file, bumped per index run.+ * Same store + reads only -> stable; upsert_project (every index run's choke+ * point) -> changes; two distinct DB files can never share a generation even+ * at the same counter value (random db_uid). */+TEST(store_generation_tracks_mutations) {+ char g1[128];+ char g2[128];+ char g3[128];+ cbm_store_t *a = cbm_store_open_memory();+ ASSERT(a != NULL);+ ASSERT_EQ(cbm_store_upsert_project(a, "p", "/tmp/p"), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_generation(a, g1, sizeof(g1)), CBM_STORE_OK);+ ASSERT(strncmp(g1, "u", 1) == 0); /* seeded, not legacy */+ ASSERT_EQ(cbm_store_generation(a, g2, sizeof(g2)), CBM_STORE_OK);+ ASSERT(strcmp(g1, g2) == 0); /* reads are stable */+ ASSERT_EQ(cbm_store_upsert_project(a, "p", "/tmp/p"), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_generation(a, g3, sizeof(g3)), CBM_STORE_OK);+ ASSERT(strcmp(g1, g3) != 0); /* index run bumps */++ cbm_store_t *b = cbm_store_open_memory();+ ASSERT(b != NULL);+ ASSERT_EQ(cbm_store_upsert_project(b, "p", "/tmp/p"), CBM_STORE_OK);+ char gb[128];+ ASSERT_EQ(cbm_store_generation(b, gb, sizeof(gb)), CBM_STORE_OK);+ ASSERT(strcmp(g1, gb) != 0); /* distinct DBs never alias (random uid) */+ cbm_store_close(a);+ cbm_store_close(b);+ PASS();+}/* #896: a row-scan that dies mid-stream (SQLITE_CORRUPT) must surface a* loud store error, not masquerade as a clean end of results. Counts are@@ -134,8 +163,7 @@ TEST(corrupt_page_scan_returns_error_not_truncation) {char qn[256];snprintf(name, sizeof(name), "corrupt_probe_fn_%04d", i);snprintf(qn, sizeof(qn),- "corr.some.rather.long.module.path.to.fill.table.pages.%s_padding_padding",- name);+ "corr.some.rather.long.module.path.to.fill.table.pages.%s_padding_padding", name);cbm_node_t n = {.project = "corr",.label = "Function",.name = name,@@ -174,8 +202,8 @@ TEST(corrupt_page_scan_returns_error_not_truncation) {cbm_store_t *s2 = cbm_store_open_path(db_path);ASSERT_NOT_NULL(s2);/* The scan must CROSS the corrupt band: request every row. */- cbm_search_params_t all_params = {.project = "corr", .label = "Function",- .limit = CORRUPT_NODES};+ cbm_search_params_t all_params = {+ .project = "corr", .label = "Function", .limit = CORRUPT_NODES};cbm_search_output_t out2 = {0};int rc_search = cbm_store_search(s2, &all_params, &out2);if (rc_search == CBM_STORE_OK && out2.count == CORRUPT_NODES) {@@ -207,6 +235,7 @@ TEST(corrupt_page_scan_returns_error_not_truncation) {SUITE(store_pragmas) {RUN_TEST(journal_size_limit_bounds_wal_issue1083);+ RUN_TEST(store_generation_tracks_mutations);RUN_TEST(corrupt_page_scan_returns_error_not_truncation);RUN_TEST(mmap_size_default_when_unset);RUN_TEST(mmap_size_zero_disables_mmap);