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.

fix(mcp): keep compact pagination lossless

Martin Vogel0735fdccb7d4
diff --git a/src/mcp/compact_out.c b/src/mcp/compact_out.c
index 7a7e415a7..2fbbb8314 100644
--- a/src/mcp/compact_out.c
+++ b/src/mcp/compact_out.c
@@ -76,20 +76,20 @@ void cbm_sb_free(cbm_sb_t *sb) {
/* ── Tree quoting ────────────────────────────────────────────────── */
/* True when `s` parses as an integer or real literal (sign, digits, one dot). */
-static bool looks_numeric(const char *s) {
- if (!s || !*s) {
+static bool looks_numeric_n(const char *s, size_t len) {
+ if (!s || len == 0) {
return false;
}
- const char *p = s;
- if (*p == '-' || *p == '+') {
- p++;
+ size_t offset = 0;
+ if (s[offset] == '-' || s[offset] == '+') {
+ offset++;
}
bool digit = false;
bool dot = false;
- for (; *p; p++) {
- if (isdigit((unsigned char)*p)) {
+ for (; offset < len; offset++) {
+ if (isdigit((unsigned char)s[offset])) {
digit = true;
- } else if (*p == '.' && !dot) {
+ } else if (s[offset] == '.' && !dot) {
dot = true;
} else {
return false;
@@ -178,7 +178,7 @@ bool cbm_output_encode_text(const char *data, size_t len, char **encoded, size_t
bool valid_utf8 = true;
size_t offset = 0;
- while (offset < len) {
+ while (valid_utf8 && offset < len) {
size_t sequence = utf8_sequence_length((const unsigned char *)data + offset, len - offset);
if (!sequence) {
valid_utf8 = false;
@@ -219,41 +219,47 @@ bool cbm_output_encode_text(const char *data, size_t len, char **encoded, size_t
return true;
}
-static bool needs_quotes(const char *s) {
- if (!s || !*s) {
+static bool needs_quotes_n(const char *s, size_t len) {
+ if (!s || len == 0) {
return false; /* empty cells emit as the "-" placeholder, not quotes */
}
- size_t remaining = strlen(s);
- for (const char *p = s; *p; p++, remaining--) {
- unsigned char c = (unsigned char)*p;
+ size_t offset = 0;
+ while (offset < len) {
+ unsigned char c = (unsigned char)s[offset];
/* Space-delimited rows: any internal whitespace or quote forces
* quoting so column positions stay parseable. Control bytes and
* invalid UTF-8 force the quoted path too, which sanitizes them —
* one raw byte otherwise makes line-oriented consumers (BSD grep)
* treat the ENTIRE tool output as unmatchable binary. */
- if (isspace(c) || *p == '"' || *p == '\r' || c < 0x20 || c == 0x7f) {
+ if (isspace(c) || s[offset] == '"' || s[offset] == '\r' || c < 0x20 || c == 0x7f) {
return true;
}
if (c >= 0x80) {
- size_t len = utf8_sequence_length((const unsigned char *)p, remaining);
- if (!len) {
+ size_t sequence = utf8_sequence_length((const unsigned char *)s + offset, len - offset);
+ if (!sequence) {
return true;
}
- p += len - 1;
- remaining -= len - 1;
+ offset += sequence;
+ } else {
+ offset++;
}
}
- if (strcmp(s, "true") == 0 || strcmp(s, "false") == 0 || strcmp(s, "null") == 0 ||
- strcmp(s, "-") == 0) {
+ if ((len == 4 && memcmp(s, "true", 4) == 0) || (len == 5 && memcmp(s, "false", 5) == 0) ||
+ (len == 4 && memcmp(s, "null", 4) == 0) || (len == 1 && s[0] == '-')) {
return true;
}
- return looks_numeric(s);
+ return looks_numeric_n(s, len);
}
-static void append_quoted(cbm_sb_t *sb, const char *s) {
+static bool needs_quotes(const char *s) {
+ return needs_quotes_n(s, s ? strlen(s) : 0);
+}
+
+static void append_quoted_n(cbm_sb_t *sb, const char *s, size_t len) {
cbm_sb_append_n(sb, "\"", 1);
- size_t remaining = s ? strlen(s) : 0;
- for (const char *p = s ? s : ""; *p; p++, remaining--) {
+ size_t offset = 0;
+ while (s && offset < len) {
+ const char *p = s + offset;
switch (*p) {
case '"':
cbm_sb_append_n(sb, "\\\"", 2);
@@ -277,11 +283,11 @@ static void append_quoted(cbm_sb_t *sb, const char *s) {
snprintf(esc, sizeof(esc), "\\u%04x", (unsigned)c);
cbm_sb_append(sb, esc);
} else {
- size_t len = utf8_sequence_length((const unsigned char *)p, remaining);
- if (len) {
- cbm_sb_append_n(sb, p, len);
- p += len - 1;
- remaining -= len - 1;
+ size_t sequence = utf8_sequence_length((const unsigned char *)p, len - offset);
+ if (sequence) {
+ cbm_sb_append_n(sb, p, sequence);
+ offset += sequence;
+ continue;
} else {
/* Callers normalize first; retain a defensive printable
* escape if an internal caller ever violates that rule. */
@@ -293,52 +299,69 @@ static void append_quoted(cbm_sb_t *sb, const char *s) {
break;
}
}
+ offset++;
}
cbm_sb_append_n(sb, "\"", 1);
}
-static void append_value(cbm_sb_t *sb, const char *s) {
- if (!s || !*s) {
+static void append_quoted(cbm_sb_t *sb, const char *s) {
+ append_quoted_n(sb, s, s ? strlen(s) : 0);
+}
+
+static void append_value_n(cbm_sb_t *sb, const char *s, size_t len) {
+ if (!s || len == 0) {
cbm_sb_append_n(sb, "-", 1); /* stable column positions for empties */
return;
}
char *encoded = NULL;
size_t encoded_len = 0;
- if (!cbm_output_encode_text(s, strlen(s), &encoded, &encoded_len)) {
+ if (!cbm_output_encode_text(s, len, &encoded, &encoded_len)) {
sb->oom = true;
return;
}
const char *safe = encoded ? encoded : s;
- if (needs_quotes(safe)) {
- append_quoted(sb, safe);
+ size_t safe_len = encoded ? encoded_len : len;
+ if (needs_quotes_n(safe, safe_len)) {
+ append_quoted_n(sb, safe, safe_len);
} else {
- cbm_sb_append_n(sb, safe, encoded ? encoded_len : strlen(safe));
+ cbm_sb_append_n(sb, safe, safe_len);
}
free(encoded);
}
+static void append_value(cbm_sb_t *sb, const char *s) {
+ append_value_n(sb, s, s ? strlen(s) : 0);
+}
+
/* Object keys and table column names share the compact tree's structural
* line. Keep common identifier-like names bare, but quote anything that can
* be confused with a delimiter or escape sequence. Unlike a value cell, an
* empty key must remain the lossless string "" rather than the missing-value
* placeholder "-". */
-static void append_key(cbm_sb_t *sb, const char *s) {
+static void append_key_n(cbm_sb_t *sb, const char *s, size_t len) {
const char *raw = s ? s : "";
char *encoded = NULL;
size_t encoded_len = 0;
- if (!cbm_output_encode_text(raw, strlen(raw), &encoded, &encoded_len)) {
+ if (!cbm_output_encode_text(raw, len, &encoded, &encoded_len)) {
sb->oom = true;
return;
}
const char *safe = encoded ? encoded : raw;
- if (!*safe || needs_quotes(safe) || strpbrk(safe, ":()\\")) {
- append_quoted(sb, safe);
+ size_t safe_len = encoded ? encoded_len : len;
+ if (safe_len == 0 || needs_quotes_n(safe, safe_len) || memchr(safe, ':', safe_len) ||
+ memchr(safe, '(', safe_len) || memchr(safe, ')', safe_len) ||
+ memchr(safe, '\\', safe_len)) {
+ append_quoted_n(sb, safe, safe_len);
} else {
- cbm_sb_append_n(sb, safe, encoded ? encoded_len : strlen(safe));
+ cbm_sb_append_n(sb, safe, safe_len);
}
free(encoded);
}
+static void append_key(cbm_sb_t *sb, const char *s) {
+ append_key_n(sb, s, s ? strlen(s) : 0);
+}
+
/* ── Scalars ────────────────────────────────────────────────────── */
void cbm_tree_scalar_str(cbm_sb_t *sb, const char *key, const char *val) {
@@ -878,13 +901,12 @@ static void tree_table_rows_impl(cbm_sb_t *sb, const char *key, int nrows, const
size_t saving = plain_len > compact_len ? plain_len - compact_len : 0;
size_t plain_token_shape = tree_token_shape_units(plain_text);
size_t compact_token_shape = tree_token_shape_units(compact_text);
- size_t token_shape_saving = plain_token_shape > compact_token_shape
- ? plain_token_shape - compact_token_shape
- : 0;
- use_compact = saving >= TREE_PREFIX_MIN_SAVING &&
- saving * 100 >= plain_len * TREE_PREFIX_MIN_PERCENT &&
- token_shape_saving * 100 >=
- plain_token_shape * TREE_PREFIX_MIN_TOKEN_SHAPE_PERCENT;
+ size_t token_shape_saving =
+ plain_token_shape > compact_token_shape ? plain_token_shape - compact_token_shape : 0;
+ use_compact =
+ saving >= TREE_PREFIX_MIN_SAVING &&
+ saving * 100 >= plain_len * TREE_PREFIX_MIN_PERCENT &&
+ token_shape_saving * 100 >= plain_token_shape * TREE_PREFIX_MIN_TOKEN_SHAPE_PERCENT;
}
if (use_compact) {
cbm_sb_append(sb, compact_text);
@@ -933,18 +955,18 @@ static void json_tree_indent(cbm_sb_t *sb, int depth) {
* escaped into one long quoted scalar. Use the familiar YAML block markers:
* `|-` means no trailing newline, `|` means one, and `|+` preserves several.
* The content remains readable/copyable and valid UTF-8. */
-static void json_tree_block_string(cbm_sb_t *sb, const char *text, int depth) {
- size_t len = strlen(text);
+static void json_tree_block_string(cbm_sb_t *sb, const char *text, size_t len, int depth) {
size_t trailing_newlines = 0;
while (trailing_newlines < len && text[len - trailing_newlines - 1] == '\n') {
trailing_newlines++;
}
cbm_sb_append(sb, trailing_newlines == 0 ? "|-\n" : trailing_newlines == 1 ? "|\n" : "|+\n");
- const char *line = text;
+ size_t line_offset = 0;
for (;;) {
- const char *newline = strchr(line, '\n');
- const char *end = newline ? newline : line + strlen(line);
+ const char *line = text + line_offset;
+ const char *newline = memchr(line, '\n', len - line_offset);
+ const char *end = newline ? newline : text + len;
json_tree_indent(sb, depth + 1);
for (const char *p = line; p < end; p++) {
unsigned char c = (unsigned char)*p;
@@ -968,8 +990,8 @@ static void json_tree_block_string(cbm_sb_t *sb, const char *text, int depth) {
if (!newline) {
break;
}
- line = newline + 1;
- if (*line == '\0') {
+ line_offset = (size_t)(newline - text) + 1;
+ if (line_offset == len) {
break;
}
}
@@ -977,7 +999,7 @@ static void json_tree_block_string(cbm_sb_t *sb, const char *text, int depth) {
static void json_tree_scalar(cbm_sb_t *sb, yyjson_val *value) {
if (yyjson_is_str(value)) {
- append_value(sb, yyjson_get_str(value));
+ append_value_n(sb, yyjson_get_str(value), yyjson_get_len(value));
} else if (yyjson_is_bool(value)) {
cbm_sb_append(sb, yyjson_get_bool(value) ? "true" : "false");
} else if (yyjson_is_null(value)) {
@@ -1018,7 +1040,7 @@ static bool json_tree_array_is_object_table(yyjson_val *array, yyjson_val **firs
yyjson_val *key;
yyjson_val *unused;
yyjson_obj_foreach(first, key_index, key_maximum, key, unused) {
- if (!yyjson_obj_get(item, yyjson_get_str(key))) {
+ if (!yyjson_obj_getn(item, yyjson_get_str(key), yyjson_get_len(key))) {
return false;
}
}
@@ -1027,15 +1049,16 @@ static bool json_tree_array_is_object_table(yyjson_val *array, yyjson_val **firs
return true;
}
-static void json_tree_value(cbm_sb_t *sb, const char *key_name, yyjson_val *value, int depth);
+static void json_tree_value(cbm_sb_t *sb, const char *key_name, size_t key_len, yyjson_val *value,
+ int depth);
-static void json_tree_object_table(cbm_sb_t *sb, const char *key_name, yyjson_val *array,
- yyjson_val *first, int depth) {
+static void json_tree_object_table(cbm_sb_t *sb, const char *key_name, size_t key_len,
+ yyjson_val *array, yyjson_val *first, int depth) {
if (!sb || !key_name || !array || !first) {
return;
}
json_tree_indent(sb, depth);
- append_key(sb, key_name);
+ append_key_n(sb, key_name, key_len);
char count[48];
snprintf(count, sizeof(count), ": %zu (cols:", yyjson_arr_size(array));
cbm_sb_append(sb, count);
@@ -1046,7 +1069,7 @@ static void json_tree_object_table(cbm_sb_t *sb, const char *key_name, yyjson_va
yyjson_val *unused;
yyjson_obj_foreach(first, key_index, key_maximum, column, unused) {
cbm_sb_append_n(sb, " ", 1);
- append_key(sb, yyjson_get_str(column));
+ append_key_n(sb, yyjson_get_str(column), yyjson_get_len(column));
}
cbm_sb_append_n(sb, ")\n", 2);
@@ -1060,7 +1083,7 @@ static void json_tree_object_table(cbm_sb_t *sb, const char *key_name, yyjson_va
if (!first_cell) {
cbm_sb_append_n(sb, " ", 1);
}
- yyjson_val *cell = yyjson_obj_get(row, yyjson_get_str(column));
+ yyjson_val *cell = yyjson_obj_getn(row, yyjson_get_str(column), yyjson_get_len(column));
json_tree_scalar(sb, cell);
first_cell = false;
}
@@ -1068,15 +1091,16 @@ static void json_tree_object_table(cbm_sb_t *sb, const char *key_name, yyjson_va
}
}
-static void json_tree_array(cbm_sb_t *sb, const char *key_name, yyjson_val *array, int depth) {
+static void json_tree_array(cbm_sb_t *sb, const char *key_name, size_t key_len, yyjson_val *array,
+ int depth) {
yyjson_val *first = NULL;
if (json_tree_array_is_object_table(array, &first)) {
- json_tree_object_table(sb, key_name, array, first, depth);
+ json_tree_object_table(sb, key_name, key_len, array, first, depth);
return;
}
json_tree_indent(sb, depth);
- append_key(sb, key_name);
+ append_key_n(sb, key_name, key_len);
char count[48];
snprintf(count, sizeof(count), ": %zu\n", yyjson_arr_size(array));
cbm_sb_append(sb, count);
@@ -1092,10 +1116,11 @@ static void json_tree_array(cbm_sb_t *sb, const char *key_name, yyjson_val *arra
yyjson_val *field;
yyjson_val *field_value;
yyjson_obj_foreach(item, field_index, field_maximum, field, field_value) {
- json_tree_value(sb, yyjson_get_str(field), field_value, depth + 2);
+ json_tree_value(sb, yyjson_get_str(field), yyjson_get_len(field), field_value,
+ depth + 2);
}
} else if (yyjson_is_arr(item)) {
- json_tree_value(sb, "-", item, depth + 1);
+ json_tree_value(sb, "-", 1, item, depth + 1);
} else {
json_tree_indent(sb, depth + 1);
cbm_sb_append(sb, "- ");
@@ -1105,10 +1130,11 @@ static void json_tree_array(cbm_sb_t *sb, const char *key_name, yyjson_val *arra
}
}
-static void json_tree_value(cbm_sb_t *sb, const char *key_name, yyjson_val *value, int depth) {
+static void json_tree_value(cbm_sb_t *sb, const char *key_name, size_t key_len, yyjson_val *value,
+ int depth) {
if (depth >= JSON_TREE_MAX_DEPTH) {
json_tree_indent(sb, depth);
- append_key(sb, key_name);
+ append_key_n(sb, key_name, key_len);
cbm_sb_append(sb, ": ");
char *encoded = yyjson_val_write(value, 0, NULL);
append_value(sb, encoded ? encoded : "null");
@@ -1118,26 +1144,28 @@ static void json_tree_value(cbm_sb_t *sb, const char *key_name, yyjson_val *valu
}
if (yyjson_is_obj(value)) {
json_tree_indent(sb, depth);
- append_key(sb, key_name);
+ append_key_n(sb, key_name, key_len);
cbm_sb_append(sb, ":\n");
size_t index;
size_t maximum;
yyjson_val *key;
yyjson_val *child;
yyjson_obj_foreach(value, index, maximum, key, child) {
- json_tree_value(sb, yyjson_get_str(key), child, depth + 1);
+ json_tree_value(sb, yyjson_get_str(key), yyjson_get_len(key), child, depth + 1);
}
} else if (yyjson_is_arr(value)) {
- json_tree_array(sb, key_name, value, depth);
+ json_tree_array(sb, key_name, key_len, value, depth);
} else if (yyjson_is_str(value) &&
- (strchr(yyjson_get_str(value), '\n') || strchr(yyjson_get_str(value), '\r'))) {
+ !memchr(yyjson_get_str(value), '\0', yyjson_get_len(value)) &&
+ (memchr(yyjson_get_str(value), '\n', yyjson_get_len(value)) ||
+ memchr(yyjson_get_str(value), '\r', yyjson_get_len(value)))) {
json_tree_indent(sb, depth);
- append_key(sb, key_name);
+ append_key_n(sb, key_name, key_len);
cbm_sb_append(sb, ": ");
- json_tree_block_string(sb, yyjson_get_str(value), depth);
+ json_tree_block_string(sb, yyjson_get_str(value), yyjson_get_len(value), depth);
} else {
json_tree_indent(sb, depth);
- append_key(sb, key_name);
+ append_key_n(sb, key_name, key_len);
cbm_sb_append(sb, ": ");
json_tree_scalar(sb, value);
cbm_sb_append_n(sb, "\n", 1);
@@ -1161,10 +1189,10 @@ char *cbm_json_to_tree(const char *json) {
yyjson_val *key;
yyjson_val *value;
yyjson_obj_foreach(root, index, maximum, key, value) {
- json_tree_value(&sb, yyjson_get_str(key), value, 0);
+ json_tree_value(&sb, yyjson_get_str(key), yyjson_get_len(key), value, 0);
}
} else if (yyjson_is_arr(root)) {
- json_tree_array(&sb, "items", root, 0);
+ json_tree_array(&sb, "items", sizeof("items") - 1, root, 0);
} else {
cbm_sb_append(&sb, "value: ");
json_tree_scalar(&sb, root);
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 603818bf0..218c10213 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -457,31 +457,29 @@ bool cbm_mcp_cancel_request_matches(const char *params_json, int64_t active_id,
typedef struct {
const char *name;
- const char *title;
const char *description;
const char *input_schema; /* JSON string */
} tool_def_t;
static const tool_def_t TOOLS[] = {
- {"index_repository", "Index repository",
- "Index a repository. full/moderate add semantic edges; fast omits them; "
- "cross-repo-intelligence links indexed services. Results summarize coverage gaps.",
+ {"index_repository",
+ "Index a repository. full/moderate add semantics; fast omits them; cross-repo-intelligence "
+ "links services. Reports coverage gaps.",
"{\"type\":\"object\",\"properties\":{\"repo_path\":{\"type\":\"string\",\"description\":"
"\"Repository path\"},"
"\"mode\":{\"type\":\"string\","
"\"enum\":[\"full\",\"moderate\",\"fast\",\"cross-repo-intelligence\"],"
- "\"default\":\"full\",\"description\":\"full: all files+semantic; moderate: "
- "filtered+semantic; "
- "fast: filtered without semantic; cross-repo-intelligence: link services.\"},"
+ "\"default\":\"full\",\"description\":\"full: all+semantic; moderate: "
+ "filtered+semantic; fast: filtered only; cross-repo-intelligence: link services.\"},"
"\"target_projects\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
"\"description\":\"Cross-repo targets; [\\\"*\\\"] means all.\"},"
"\"name\":{\"type\":\"string\",\"description\":"
- "\"Project-name override; Non-ASCII bytes are encoded and unsafe characters normalized.\"},"
+ "\"Name override; Non-ASCII bytes are encoded; unsafe characters normalized.\"},"
"\"persistence\":{\"type\":\"boolean\",\"default\":false,\"description\":"
"\"Write .codebase-memory/graph.db.zst.\"}"
"},\"required\":[\"repo_path\"]}"},
- {"search_graph", "Search graph",
+ {"search_graph",
"Find symbols via BM25 query, regex name/qn filters, or semantic_query. Rows keep "
"qn/file/lines and in/out over CALLS/USAGE/CALL_REFERENCE/INHERITS/IMPLEMENTS.",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},"
@@ -506,86 +504,81 @@ static const tool_def_t TOOLS[] = {
"\"detail\":{\"type\":\"string\",\"enum\":[\"ids\",\"default\"],\"default\":\"default\"}},"
"\"required\":[\"project\"]}"},
- {"query_graph", "Query graph",
- "Run read-only Cypher for multi-hop patterns, aggregation, complexity, or cross-service "
- "analysis. Defaults to 200 visible rows and reports exact or lower-bound totals plus "
- "truncation. Use max_rows or Cypher SKIP/LIMIT to continue. graph=missed queries flagged "
- "coverage files; absence there is not proof of completeness. Call get_graph_schema with "
- "diagnostics=full to discover queryable property names.",
+ {"query_graph",
+ "Read-only Cypher for multi-hop, aggregation, complexity, or cross-service analysis. "
+ "Default: 200 visible rows with "
+ "exact/lower-bound totals and truncation; continue safely with next_cursor. "
+ "graph=missed is a file tree of flagged coverage gaps; absence is not proof of completeness. "
+ "Use get_graph_schema(diagnostics=full) for properties.",
"{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"Cypher "
"query\"},\"project\":{\"type\":\"string\"},"
"\"graph\":{\"type\":\"string\",\"enum\":[\"code\",\"missed\"],\"default\":\"code\","
- "\"description\":\"Which graph to query: the code knowledge graph (default) or the "
- "missed graph (only files not fully indexed, laid out as their file structure).\"},"
+ "\"description\":\"code graph (default) or missed coverage-gap file tree.\"},"
"\"max_rows\":{\"type\":\"integer\","
"\"description\":"
- "\"Visible row budget (default 200; max 99998). Zero preserves the legacy maximum "
- "window. This never changes query evaluation.\",\"minimum\":0,\"default\":200},"
+ "\"Visible rows (default 200; max 99998); 0 uses the legacy maximum. Evaluation is "
+ "unchanged.\",\"minimum\":0,\"default\":200},"
"\"offset\":{\"type\":\"integer\",\"minimum\":0,\"default\":0,"
- "\"description\":\"Skip materialized result rows for response paging; unlike Cypher "
- "SKIP, this does not change query evaluation.\"},"
+ "\"description\":\"Live compatibility paging; cannot be combined with cursor.\"},"
+ "\"cursor\":{\"type\":\"string\",\"description\":\"Snapshot continuation; keep "
+ "query/project/graph. Format, budget, and max_rows may change.\"},"
"\"max_output_tokens\":{\"type\":\"integer\",\"minimum\":128,\"maximum\":1000000,"
- "\"description\":\"Approximate token sizing; deterministic ceiling is 4 UTF-8 bytes per "
- "requested token. Rows are omitted only whole.\"},"
+ "\"description\":\"Sizing hint; hard ceiling is 4 UTF-8 bytes/token. Rows stay whole.\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\","
- "\"description\":\"tree may encode repeated prefixes with a local @N+suffix directory; "
- "json keeps direct strings.\"}},"
+ "\"description\":\"tree may use local @N+suffix prefix refs; json uses direct strings.\"}},"
"\"required\":[\"query\",\"project\"]}"},
- {"trace_path", "Trace path",
+ {"trace_path",
"Trace callers/callees, data flow, or cross-service paths. Defaults exclude tests and "
- "resolver evidence. Rows retain qn/hop; totals, relations, and continuations are explicit.",
+ "resolver evidence. Rows keep qn/hop with explicit totals, relations, and continuations.",
"{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"project\":{"
"\"type\":\"string\"},\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\","
"\"both\"],\"default\":\"both\"},\"depth\":{\"type\":\"integer\",\"default\":3,"
"\"minimum\":1,\"maximum\":15},"
"\"limit\":{\"type\":\"integer\",\"default\":100,\"minimum\":1,\"maximum\":5000,"
- "\"description\":\"Visible rows per page; a gte relation flags the 5000-node engine "
- "ceiling.\"},"
+ "\"description\":\"Rows/page; gte flags the 5000-node engine ceiling.\"},"
"\"max_output_tokens\":{\"type\":\"integer\",\"default\":3200,\"minimum\":128,"
- "\"maximum\":1000000,\"description\":\"Approximate token sizing; deterministic ceiling "
- "is 4 UTF-8 bytes per requested token. Optional evidence/args yield before nearest graph "
- "rows.\"},"
- "\"cursor\":{\"type\":\"string\",\"description\":\"Pass tree next or JSON next_cursor back "
- "with traversal args unchanged; max_output_tokens may be raised.\"},"
+ "\"maximum\":1000000,\"description\":\"Sizing hint; hard ceiling is 4 UTF-8 bytes/token. "
+ "Evidence/args yield before nearest graph rows.\"},"
+ "\"cursor\":{\"type\":\"string\",\"description\":\"Pass next/next_cursor with traversal "
+ "args unchanged; budget may increase.\"},"
"\"mode\":{"
"\"type\":\"string\",\"enum\":[\"calls\",\"data_flow\",\"cross_service\"],\"default\":"
- "\"calls\",\"description\":\"calls, argument-aware data_flow, or service-boundary edges.\"},"
+ "\"calls\",\"description\":\"calls, argument-aware data_flow, or service edges.\"},"
"\"parameter_name\":{\"type\":\"string\",\"description\":\"data_flow parameter filter.\"},"
"\"edge_types\":{\"type\":\"array\",\"items\":{"
"\"type\":\"string\"}},\"risk_labels\":{\"type\":\"boolean\",\"default\":false,"
"\"description\":\"Add hop-risk labels.\"},\"include_tests\":{\"type\":\"boolean\","
"\"default\":false},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\","
- "\"description\":\"tree chooses the smaller complete direct/grouped shape; json preserves "
- "a stable grouped table model.\"},"
+ "\"description\":\"tree chooses smaller complete direct/grouped output; json uses stable "
+ "grouped tables.\"},"
"\"include_evidence\":{\"type\":\"boolean\",\"default\":false,"
"\"description\":\"Add resolver class and confidence.\"}},"
"\"required\":[\"function_name\",\"project\"]}"},
- {"get_code_snippet", "Get code snippet",
- "Read a symbol found by search_graph. auto returns bounded source, but outlines large "
- "containers; full restores up to 500 lines; outline and source pages carry continuations. "
- "coverage_note marks partial indexing.",
+ {"get_code_snippet",
+ "Read a search_graph symbol. auto bounds source and outlines large containers; full "
+ "restores up to 500 lines. Source/outline pages continue; coverage_note marks gaps.",
"{\"type\":\"object\",\"properties\":{\"qualified_name\":{\"type\":\"string\",\"description\":"
- "\"Qualified name from search_graph, or short name.\"},\"project\":{"
+ "\"search_graph qn, or short name.\"},\"project\":{"
"\"type\":\"string\"},\"include_neighbors\":{"
"\"type\":\"boolean\",\"default\":false},"
"\"source_mode\":{\"type\":\"string\",\"enum\":[\"auto\",\"full\",\"outline\"],"
"\"default\":\"auto\",\"description\":\"auto outlines 200+ line containers; full returns "
- "source; outline lists members.\"},"
+ "source; "
+ "outline lists members.\"},"
"\"member_limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"
"\"member_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
"\"start_line\":{\"type\":\"integer\",\"minimum\":1},"
"\"max_lines\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":500},"
"\"max_output_tokens\":{\"type\":\"integer\",\"minimum\":128,"
- "\"maximum\":1000000,\"description\":\"Approximate token sizing for auto/outline "
- "(default 2500); deterministic ceiling is 4 UTF-8 bytes per requested token. Source is "
- "reduced only at whole-line boundaries. Explicit full is uncapped unless this is set.\"},"
+ "\"maximum\":1000000,\"description\":\"auto/outline sizing hint (default 2500), hard "
+ "ceiling 4 UTF-8 bytes/token. Lines stay whole; explicit full is uncapped unless set.\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"
"\"required\":[\"qualified_name\",\"project\"]}"},
- {"get_file_outline", "Get file outline",
+ {"get_file_outline",
"Return a compact declaration outline for one exact repository-relative file. Results are "
"filtered by optional exact labels, ordered deterministically by source position, and "
"bounded with exact total/offset/limit pagination metadata. File/folder/container nodes "
@@ -600,7 +593,7 @@ static const tool_def_t TOOLS[] = {
"\"default\":\"tree\"}},\"additionalProperties\":false,"
"\"required\":[\"project\",\"file_path\"]}"},
- {"get_graph_schema", "Get graph schema",
+ {"get_graph_schema",
"Get node-label and edge-type counts. diagnostics=full also lists queryable properties.",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"},"
@@ -609,7 +602,7 @@ static const tool_def_t TOOLS[] = {
"\"offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0}},\"required\":["
"\"project\"]}"},
- {"compare_graphs", "Compare graphs",
+ {"compare_graphs",
"Compare two indexed project snapshots. Returns deterministic target-only additions and "
"base-only removals for stable node and edge identities using a bounded streaming merge. "
"Each result set is independently capped by limit and a fixed 512 KiB encoded-byte budget; "
@@ -622,25 +615,24 @@ static const tool_def_t TOOLS[] = {
"\"default\":2000000}},\"required\":[\"base_project\",\"target_project\"],"
"\"additionalProperties\":false}"},
- {"get_architecture", "Get architecture",
- "Get a compact architecture overview: counts, languages, packages, and entry points. "
- "Request aspects for structure, dependencies, routes, hotspots, boundaries, layers, "
- "clusters, cycles, or file tree; path scopes to a directory.",
+ {"get_architecture",
+ "Compact counts, languages, packages, entry points. Request structure, dependencies, "
+ "routes, hotspots, boundaries, layers, clusters, cycles, or file_tree; path scopes a "
+ "directory.",
/* The aspects enum mirrors VALID_ASPECTS (see aspect_is_valid) — update both together. */
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"path\":{\"type\":"
- "\"string\",\"description\":\"Optional directory prefix to scope architecture (e.g. "
- "apps/hoa)\"},"
+ "\"string\",\"description\":\"Directory prefix (for example apps/hoa).\"},"
"\"aspects\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"all\","
"\"overview\",\"structure\",\"dependencies\",\"routes\",\"languages\",\"packages\","
"\"entry_points\",\"hotspots\",\"boundaries\",\"layers\",\"file_tree\",\"clusters\","
"\"cycles\"]},"
- "\"description\":\"Aspects to include. 'all' = everything; 'overview' = compact summary "
- "except file_tree; omit = languages/packages/entry_points. cycles is always opt-in.\"},"
+ "\"description\":\"all=everything; overview=compact except file_tree; omitted=languages/"
+ "packages/entry_points; cycles is opt-in.\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"
"\"required\":[\"project\"]}"},
- {"search_code", "Search code",
- "Graph-ranked text search. compact returns symbols; full adds bounded source; files paths.",
+ {"search_code",
+ "Graph-ranked text search: compact symbols, full bounded source, or file paths.",
"{\"type\":\"object\",\"properties\":{\"pattern\":{\"type\":\"string\"},\"project\":{\"type\":"
"\"string\"},\"file_pattern\":{\"type\":\"string\"},\"path_filter\":{\"type\":\"string\"},"
"\"mode\":{\"type\":\"string\","
@@ -656,7 +648,7 @@ static const tool_def_t TOOLS[] = {
"\"raw_limit\":{\"type\":\"integer\",\"default\":5,\"minimum\":0,\"maximum\":100},"
"\"raw_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
"\"raw_content_offset\":{\"type\":\"integer\",\"minimum\":0,"
- "\"description\":\"Raw-line byte offset; omit for a match-centered preview.\"},"
+ "\"description\":\"Raw-line byte offset; omit for match-centered preview.\"},"
"\"directory_limit\":{\"type\":\"integer\",\"default\":20,\"minimum\":0,"
"\"maximum\":64},"
"\"directory_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
@@ -668,9 +660,7 @@ static const tool_def_t TOOLS[] = {
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"
"\"required\":[\"pattern\",\"project\"]}"},
- {"list_projects", "List projects",
- "List indexed projects with stable paging. Identity is "
- "the lean default; request stats for graph sizes.",
+ {"list_projects", "List projects with stable paging. Identity is lean; stats adds graph sizes.",
"{\"type\":\"object\",\"properties\":{"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"},"
"\"detail\":{\"type\":\"string\",\"enum\":[\"identity\",\"stats\"],"
@@ -681,29 +671,27 @@ static const tool_def_t TOOLS[] = {
"\"limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"
"\"offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
"\"metadata_only\":{\"type\":\"boolean\",\"default\":false,"
- "\"description\":\"Compatibility mode: omit counts, size, and branch.\"}}}"},
- {"delete_project", "Delete project", "Delete a project from the index",
+ "\"description\":\"Compatibility: omit counts, size, and branch.\"}}}"},
+ {"delete_project", "Delete a project from the index",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
"\"project\"]}"},
- {"index_status", "Index status",
- "Get project readiness, counts, root, and coverage-gap counts. diagnostics=summary/full adds "
- "sample/file rows; verbose adds Git-path diagnostics. Coverage is best-effort, not proof of "
- "completeness; use check_index_coverage for cited paths.",
+ {"index_status",
+ "Project readiness, counts, root, and coverage gaps. diagnostics adds coverage rows; verbose "
+ "adds Git paths. Best-effort only; verify cited paths with check_index_coverage.",
"{\"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.\"},"
+ "\"verbose\":{\"type\":\"boolean\",\"default\":false,\"description\":\"Add worktree/"
+ "shadow Git paths for index-location debugging.\"},"
"\"diagnostics\":{\"type\":\"string\",\"enum\":[\"none\",\"summary\",\"full\"],"
- "\"default\":\"none\",\"description\":\"Coverage rows: counts only, five samples, or up to "
+ "\"default\":\"none\",\"description\":\"Coverage rows: counts, five samples, or up to "
"500.\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"
"\"required\":["
"\"project\"]}"},
- {"check_index_coverage", "Check index coverage",
- "Best-effort coverage/freshness for exact paths or scopes. Paths and scopes page separately; "
- "diagnostics=full adds raw detail. A clean result is not proof of completeness.",
+ {"check_index_coverage",
+ "Best-effort exact-path/scope coverage and freshness, paged separately. full diagnostics "
+ "adds raw detail. Clean is not proof of completeness.",
"{\"type\":\"object\",\"properties\":{"
"\"project\":{\"type\":\"string\"},"
"\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"maxItems\":128},"
@@ -717,8 +705,7 @@ static const tool_def_t TOOLS[] = {
"\"required\":[\"project\"]"
"}"},
- {"detect_changes", "Detect changes",
- "Map a Git diff to files and impact. Page with snapshot cursors.",
+ {"detect_changes", "Map a Git diff to files and impact. Page with snapshot cursors.",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"scope\":{\"type\":"
"\"string\",\"enum\":[\"files\",\"impact\"],\"default\":\"impact\"},"
"\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\",\"both\"],\"default\":"
@@ -734,28 +721,23 @@ static const tool_def_t TOOLS[] = {
"\"module_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
"\"module_cursor\":{\"type\":\"string\"},"
"\"max_output_tokens\":{\"type\":\"integer\",\"default\":3200,\"minimum\":128,"
- "\"maximum\":1000000,\"description\":\"Approximate token sizing; deterministic ceiling "
- "is 4 UTF-8 bytes per requested token.\"},"
+ "\"maximum\":1000000,\"description\":\"Sizing hint; hard ceiling is 4 UTF-8 bytes/token.\"},"
"\"base_branch\":{\"type\":"
"\"string\",\"default\":\"main\"},\"since\":{\"type\":\"string\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"
"\"required\":"
"[\"project\"]}"},
- {"manage_adr", "Manage ADR", "Outline an ADR by default; get reads it; update replaces it",
+ {"manage_adr", "Outline an ADR by default; get reads it; update replaces it",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"mode\":{\"type\":"
"\"string\",\"enum\":[\"outline\",\"get\",\"update\",\"set_sections\",\"sections\"],"
- "\"default\":\"outline\",\"description\":\"outline pages heading rows (default); get returns "
- "content; update REPLACES the entire ADR document; set_sections rewrites only the named sections "
- "and leaves every other byte of the stored document untouched, so adding one entry does not "
- "mean re-sending the whole ADR (setting the same section to the same body twice leaves the "
- "document byte-identical, so retrying after a lost response is safe); sections is the legacy "
- "heading list\"},\"content\":{\"type\":\"string\",\"description\":\"Complete replacement "
- "document required by update\"},\"section_updates\":{\"type\":\"object\",\"description\":"
- "\"Required by set_sections: section name -> new body for that section. Any heading name "
- "works, so a new entry can be added under its own heading; PURPOSE, STACK, ARCHITECTURE, "
- "PATTERNS, TRADEOFFS and PHILOSOPHY are the conventional ones. Names match exactly, "
- "including case, so 'Purpose' and 'PURPOSE' are different sections.\","
+ "\"default\":\"outline\",\"description\":\"outline pages headings; get reads; update replaces "
+ "the whole document; set_sections rewrites only the named sections and leaves every other "
+ "byte untouched (an identical repeated write is byte-identical, so retrying is safe); "
+ "sections is legacy.\"},"
+ "\"content\":{\"type\":\"string\",\"description\":\"Whole document for update\"},"
+ "\"section_updates\":{\"type\":\"object\",\"description\":\"set_sections: section name -> "
+ "new body. Any heading name works; names match exactly, including case.\","
"\"additionalProperties\":{\"type\":\"string\"}},"
"\"section_limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"
"\"section_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
@@ -763,8 +745,7 @@ static const tool_def_t TOOLS[] = {
"\"additionalProperties\":false,"
"\"required\":[\"project\"]}"},
- {"ingest_traces", "Ingest traces",
- "Validate and count traces; graph edge creation is not implemented",
+ {"ingest_traces", "Validate and count traces; graph edge creation is not implemented",
"{\"type\":\"object\",\"properties\":{\"traces\":{\"type\":\"array\",\"items\":{\"type\":"
"\"object\",\"properties\":{\"caller\":{\"type\":\"string\"},\"callee\":{\"type\":\"string\"},"
"\"count\":{\"type\":\"integer\"}},\"additionalProperties\":false}},\"project\":{\"type\":"
@@ -835,7 +816,9 @@ static void mcp_add_json_schema(yyjson_mut_doc *doc, yyjson_mut_val *obj, const
static void mcp_add_tool_def(yyjson_mut_doc *doc, yyjson_mut_val *tools, int i) {
yyjson_mut_val *tool = yyjson_mut_obj(doc);
yyjson_mut_obj_add_str(doc, tool, "name", TOOLS[i].name);
- yyjson_mut_obj_add_str(doc, tool, "title", TOOLS[i].title);
+ /* MCP title is optional and clients fall back to name. These titles only
+ * repeated the snake_case name with spaces, so omit their recurring
+ * discovery cost and retain the behavioral description instead. */
yyjson_mut_obj_add_str(doc, tool, "description", TOOLS[i].description);
mcp_add_json_schema(doc, tool, "inputSchema", TOOLS[i].input_schema);
@@ -5289,6 +5272,230 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
return result;
}
+/* query_graph response cursors bind one fully materialized result, not merely
+ * an integer offset. Re-executing an unordered query may otherwise produce a
+ * different order even while the store's coarse generation is unchanged.
+ *
+ * Token: q1.<generation>.<params-hash>.<result-digest>.<offset>.<seal>
+ *
+ * The SHA-256 materialization digest covers ordered columns and rows, explicit
+ * NULL markers, engine truncation, and the warning. The short seal makes an
+ * edited offset or token field fail closed instead of silently skipping rows.
+ * It is an integrity checksum for an opaque token, not an authentication MAC.
+ */
+enum {
+ QUERY_GRAPH_CURSOR_TOKEN_CAP = 224,
+ QUERY_GRAPH_GENERATION_CAP = 96,
+ QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN = 32
+};
+
+typedef struct {
+ char generation[QUERY_GRAPH_GENERATION_CAP];
+ uint64_t params_hash;
+ char result_digest[QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN + 1];
+ int offset;
+} query_graph_cursor_t;
+
+typedef struct {
+ const char *generation;
+ uint64_t params_hash;
+ const char *result_digest;
+ bool can_mint;
+} query_graph_cursor_context_t;
+
+static void query_graph_sha_u64(cbm_sha256_ctx *sha, uint64_t value) {
+ uint8_t bytes[8];
+ for (int index = 7; index >= 0; index--) {
+ bytes[index] = (uint8_t)(value & 0xffU);
+ value >>= 8U;
+ }
+ cbm_sha256_update(sha, bytes, sizeof(bytes));
+}
+
+static void query_graph_sha_field(cbm_sha256_ctx *sha, const char *value) {
+ const uint8_t present = value ? 1U : 0U;
+ cbm_sha256_update(sha, &present, sizeof(present));
+ if (!value) {
+ return;
+ }
+ size_t length = strlen(value);
+ query_graph_sha_u64(sha, (uint64_t)length);
+ cbm_sha256_update(sha, value, length);
+}
+
+static void query_graph_digest_hex(const uint8_t digest[CBM_SHA256_DIGEST_LEN],
+ char out[CBM_SHA256_HEX_LEN + 1]) {
+ static const char hex[] = "0123456789abcdef";
+ for (int index = 0; index < CBM_SHA256_DIGEST_LEN; index++) {
+ out[index * 2] = hex[digest[index] >> 4U];
+ out[index * 2 + 1] = hex[digest[index] & 0x0fU];
+ }
+ out[CBM_SHA256_HEX_LEN] = '\0';
+}
+
+static uint64_t query_graph_params_hash(const char *project, const char *query, const char *graph) {
+ static const char domain[] = "cbm.query_graph.params.v1";
+ cbm_sha256_ctx sha;
+ cbm_sha256_init(&sha);
+ cbm_sha256_update(&sha, domain, sizeof(domain));
+ query_graph_sha_field(&sha, project);
+ query_graph_sha_field(&sha, query);
+ query_graph_sha_field(&sha, graph);
+ uint8_t digest[CBM_SHA256_DIGEST_LEN];
+ cbm_sha256_final(&sha, digest);
+ uint64_t hash = 0;
+ for (int index = 0; index < 8; index++) {
+ hash = (hash << 8U) | digest[index];
+ }
+ return hash;
+}
+
+static void query_graph_result_digest(const cbm_cypher_result_t *result,
+ char out[CBM_SHA256_HEX_LEN + 1]) {
+ static const char domain[] = "cbm.query_graph.materialization.v1";
+ cbm_sha256_ctx sha;
+ cbm_sha256_init(&sha);
+ cbm_sha256_update(&sha, domain, sizeof(domain));
+ query_graph_sha_u64(&sha, (uint64_t)result->col_count);
+ query_graph_sha_u64(&sha, (uint64_t)result->row_count);
+ const uint8_t truncated = result->truncated ? 1U : 0U;
+ cbm_sha256_update(&sha, &truncated, sizeof(truncated));
+ query_graph_sha_field(&sha, result->warning);
+ for (int column = 0; column < result->col_count; column++) {
+ query_graph_sha_field(&sha, result->columns ? result->columns[column] : NULL);
+ }
+ for (int row = 0; row < result->row_count; row++) {
+ const char **cells = result->rows ? result->rows[row] : NULL;
+ for (int column = 0; column < result->col_count; column++) {
+ query_graph_sha_field(&sha, cells ? cells[column] : NULL);
+ }
+ }
+ uint8_t digest[CBM_SHA256_DIGEST_LEN];
+ cbm_sha256_final(&sha, digest);
+ query_graph_digest_hex(digest, out);
+}
+
+static void query_graph_cursor_seal(const query_graph_cursor_t *cursor, char out[17]) {
+ static const char domain[] = "cbm.query_graph.cursor.v1";
+ cbm_sha256_ctx sha;
+ cbm_sha256_init(&sha);
+ cbm_sha256_update(&sha, domain, sizeof(domain));
+ query_graph_sha_field(&sha, cursor->generation);
+ query_graph_sha_u64(&sha, cursor->params_hash);
+ query_graph_sha_field(&sha, cursor->result_digest);
+ query_graph_sha_u64(&sha, (uint64_t)cursor->offset);
+ uint8_t digest[CBM_SHA256_DIGEST_LEN];
+ cbm_sha256_final(&sha, digest);
+ char full_hex[CBM_SHA256_HEX_LEN + 1];
+ query_graph_digest_hex(digest, full_hex);
+ memcpy(out, full_hex, 16);
+ out[16] = '\0';
+}
+
+static bool query_graph_cursor_encode(const query_graph_cursor_context_t *context, int offset,
+ char out[QUERY_GRAPH_CURSOR_TOKEN_CAP]) {
+ if (!context || !context->can_mint || !context->generation || !context->result_digest ||
+ offset <= 0) {
+ return false;
+ }
+ query_graph_cursor_t cursor = {.params_hash = context->params_hash, .offset = offset};
+ snprintf(cursor.generation, sizeof(cursor.generation), "%s", context->generation);
+ snprintf(cursor.result_digest, sizeof(cursor.result_digest), "%.*s",
+ QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN, context->result_digest);
+ char seal[17];
+ query_graph_cursor_seal(&cursor, seal);
+ int written =
+ snprintf(out, QUERY_GRAPH_CURSOR_TOKEN_CAP, "q1.%s.%016llx.%s.%d.%s", cursor.generation,
+ (unsigned long long)cursor.params_hash, cursor.result_digest, cursor.offset, seal);
+ return written > 0 && written < QUERY_GRAPH_CURSOR_TOKEN_CAP;
+}
+
+static bool query_graph_hex_span(const char *begin, const char *end, size_t expected) {
+ if (!begin || !end || end < begin || (size_t)(end - begin) != expected) {
+ return false;
+ }
+ for (const char *digit = begin; digit < end; digit++) {
+ if (!isxdigit((unsigned char)*digit)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* Decode and validate every token field that does not require executing the
+ * query. The materialization digest itself is checked immediately after the
+ * full query has been re-executed. */
+static const char *query_graph_cursor_decode(const char *token, const char *current_generation,
+ uint64_t expected_params_hash,
+ query_graph_cursor_t *out) {
+ static const char invalid[] =
+ "invalid_cursor: unrecognized or modified token — re-run the original query without "
+ "'cursor'";
+ memset(out, 0, sizeof(*out));
+ if (!token || strncmp(token, "q1.", 3) != 0) {
+ return invalid;
+ }
+ const char *generation_start = token + 3;
+ const char *generation_end = strchr(generation_start, '.');
+ if (!generation_end || generation_end == generation_start ||
+ (size_t)(generation_end - generation_start) >= sizeof(out->generation)) {
+ return invalid;
+ }
+ memcpy(out->generation, generation_start, (size_t)(generation_end - generation_start));
+ out->generation[generation_end - generation_start] = '\0';
+
+ const char *hash_start = generation_end + 1;
+ const char *hash_end = strchr(hash_start, '.');
+ if (!query_graph_hex_span(hash_start, hash_end, 16)) {
+ return invalid;
+ }
+ errno = 0;
+ char *parsed_end = NULL;
+ unsigned long long parsed_hash = strtoull(hash_start, &parsed_end, 16);
+ if (errno == ERANGE || parsed_end != hash_end) {
+ return invalid;
+ }
+ out->params_hash = (uint64_t)parsed_hash;
+
+ const char *digest_start = hash_end + 1;
+ const char *digest_end = strchr(digest_start, '.');
+ if (!query_graph_hex_span(digest_start, digest_end, QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN)) {
+ return invalid;
+ }
+ memcpy(out->result_digest, digest_start, QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN);
+ out->result_digest[QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN] = '\0';
+
+ const char *offset_start = digest_end + 1;
+ const char *offset_end = strchr(offset_start, '.');
+ errno = 0;
+ long parsed_offset = offset_end ? strtol(offset_start, &parsed_end, 10) : -1;
+ if (!offset_end || offset_end == offset_start || errno == ERANGE || parsed_end != offset_end ||
+ parsed_offset <= 0 || parsed_offset > INT_MAX) {
+ return invalid;
+ }
+ out->offset = (int)parsed_offset;
+
+ const char *seal_start = offset_end + 1;
+ const char *seal_end = token + strlen(token);
+ if (!query_graph_hex_span(seal_start, seal_end, 16)) {
+ return invalid;
+ }
+ char expected_seal[17];
+ query_graph_cursor_seal(out, expected_seal);
+ if (memcmp(seal_start, expected_seal, 16) != 0) {
+ return invalid;
+ }
+ if (out->params_hash != expected_params_hash) {
+ return "cursor_params_mismatch: this cursor was issued for a different "
+ "query/project/graph — pass those arguments unchanged";
+ }
+ 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'";
+ }
+ return NULL;
+}
+
static bool query_graph_semantic_prefix_column(const char *column) {
if (!column) {
return false;
@@ -5376,7 +5583,8 @@ static const char *query_graph_truncation_reason(const cbm_cypher_result_t *resu
static char *query_graph_tree_response_text(const cbm_cypher_result_t *result, int row_offset,
int row_count, int visible_count, bool exact_total,
- bool allow_directory) {
+ bool allow_directory,
+ const query_graph_cursor_context_t *cursor_context) {
bool budget_hit = row_count < visible_count;
bool materialized_more = row_offset + row_count < result->row_count;
bool page_limit_hit = !budget_hit && materialized_more;
@@ -5403,6 +5611,10 @@ static char *query_graph_tree_response_text(const cbm_cypher_result_t *result, i
cbm_tree_scalar_str(&sb, "truncation_reason", reason);
}
if (row_count > 0 && materialized_more) {
+ char next_cursor[QUERY_GRAPH_CURSOR_TOKEN_CAP];
+ if (query_graph_cursor_encode(cursor_context, row_offset + row_count, next_cursor)) {
+ cbm_tree_scalar_str(&sb, "next_cursor", next_cursor);
+ }
cbm_tree_scalar_int(&sb, "next_offset", row_offset + row_count);
} else if (budget_hit && row_count == 0) {
cbm_tree_scalar_str(&sb, "hint",
@@ -5420,7 +5632,8 @@ static char *query_graph_tree_response_text(const cbm_cypher_result_t *result, i
}
static char *query_graph_json_response_text(const cbm_cypher_result_t *result, int row_offset,
- int row_count, int visible_count, bool exact_total) {
+ int row_count, int visible_count, bool exact_total,
+ const query_graph_cursor_context_t *cursor_context) {
bool budget_hit = row_count < visible_count;
bool materialized_more = row_offset + row_count < result->row_count;
bool page_limit_hit = !budget_hit && materialized_more;
@@ -5456,6 +5669,10 @@ static char *query_graph_json_response_text(const cbm_cypher_result_t *result, i
yyjson_mut_obj_add_str(doc, root, "truncation_reason", reason);
}
if (row_count > 0 && materialized_more) {
+ char next_cursor[QUERY_GRAPH_CURSOR_TOKEN_CAP];
+ if (query_graph_cursor_encode(cursor_context, row_offset + row_count, next_cursor)) {
+ yyjson_mut_obj_add_strcpy(doc, root, "next_cursor", next_cursor);
+ }
yyjson_mut_obj_add_int(doc, root, "next_offset", row_offset + row_count);
} else if (budget_hit && row_count == 0) {
yyjson_mut_obj_add_str(doc, root, "hint",
@@ -5535,10 +5752,12 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
} else if (visible_limit < 0) {
visible_limit = 1;
}
- int row_offset = cbm_mcp_get_int_arg(args, "offset", 0);
+ int requested_offset = cbm_mcp_get_int_arg(args, "offset", 0);
+ int row_offset = requested_offset;
if (row_offset < 0) {
row_offset = 0;
}
+ char *cursor_arg = cbm_mcp_get_string_arg(args, "cursor");
/* graph="missed" (#963): run the SAME cypher against the derived
* miss-graph view (shadow project "<project>::missed") instead of the
@@ -5548,10 +5767,12 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
free(graph_arg);
if (!query) {
+ free(cursor_arg);
free(project);
return cbm_mcp_text_result("query is required", true);
}
if (missed_graph && !project) {
+ free(cursor_arg);
free(query);
return cbm_mcp_text_result("project is required when graph=\"missed\"", true);
}
@@ -5559,6 +5780,7 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
char *_err = build_project_list_error("project not found or not indexed");
char *_res = cbm_mcp_text_result(_err, true);
free(_err);
+ free(cursor_arg);
free(project);
free(query);
return _res;
@@ -5566,6 +5788,7 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
char *not_indexed = verify_project_indexed(store, project);
if (not_indexed) {
+ free(cursor_arg);
free(project);
free(query);
return not_indexed;
@@ -5578,6 +5801,49 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
cypher_project = covproj;
}
+ char generation[QUERY_GRAPH_GENERATION_CAP] = "";
+ int generation_rc = cbm_store_generation(store, generation, sizeof(generation));
+ if (generation_rc != CBM_STORE_OK) {
+ free(cursor_arg);
+ free(project);
+ free(query);
+ return cbm_mcp_text_result(
+ "index_metadata_error: generation metadata is unreadable; reindex before querying",
+ true);
+ }
+ bool generation_available = generation[0] != '\0';
+ const char *effective_project = project ? project : srv->current_project;
+ uint64_t params_hash =
+ query_graph_params_hash(effective_project, query, missed_graph ? "missed" : "code");
+ query_graph_cursor_t cursor = {0};
+ if (cursor_arg) {
+ if (requested_offset != 0) {
+ free(cursor_arg);
+ free(project);
+ free(query);
+ return cbm_mcp_text_result(
+ "invalid_params: cursor cannot be combined with a nonzero offset", true);
+ }
+ if (!generation_available || strcmp(generation, "legacy") == 0) {
+ free(cursor_arg);
+ free(project);
+ free(query);
+ return cbm_mcp_text_result(
+ "cursor_unsupported: this index predates generation tracking; reindex before "
+ "using snapshot pagination",
+ true);
+ }
+ const char *cursor_error =
+ query_graph_cursor_decode(cursor_arg, generation, params_hash, &cursor);
+ if (cursor_error) {
+ free(cursor_arg);
+ free(project);
+ free(query);
+ return cbm_mcp_text_result(cursor_error, true);
+ }
+ row_offset = cursor.offset;
+ }
+
cbm_cypher_result_t result = {0};
/* `max_rows` is a presentation budget, never an evaluation budget.
* Executing at visible_limit+1 corrupts ORDER BY, DISTINCT, aggregation,
@@ -5589,10 +5855,32 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
char *err_msg = result.error ? result.error : "query execution failed";
char *resp = cbm_mcp_text_result(err_msg, true);
cbm_cypher_result_free(&result);
+ free(cursor_arg);
+ free(query);
+ free(project);
+ return resp;
+ }
+
+ char result_digest[CBM_SHA256_HEX_LEN + 1];
+ query_graph_result_digest(&result, result_digest);
+ if (cursor_arg &&
+ strncmp(cursor.result_digest, result_digest, QUERY_GRAPH_CURSOR_DIGEST_HEX_LEN) != 0) {
+ char *resp = cbm_mcp_text_result(
+ "stale_cursor: the complete query materialization changed since this cursor was "
+ "issued; re-run the original query without 'cursor'",
+ true);
+ cbm_cypher_result_free(&result);
+ free(cursor_arg);
free(query);
free(project);
return resp;
}
+ query_graph_cursor_context_t cursor_context = {
+ .generation = generation,
+ .params_hash = params_hash,
+ .result_digest = result_digest,
+ .can_mint = generation_available && strcmp(generation, "legacy") != 0,
+ };
/* Response encoding: TOON table by default (the columns double as the
* table header); format:"json" restores the legacy columns/rows arrays. */
@@ -5646,8 +5934,8 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
int high = exact_upper;
while (low <= high) {
int middle = low + (high - low) / 2;
- char *candidate = query_graph_json_response_text(&result, row_offset, middle,
- available_rows, exact_total);
+ char *candidate = query_graph_json_response_text(
+ &result, row_offset, middle, available_rows, exact_total, &cursor_context);
bool fits = candidate && strlen(candidate) <= byte_budget;
free(candidate);
if (fits) {
@@ -5658,7 +5946,7 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
}
}
json = query_graph_json_response_text(&result, row_offset, output_rows, available_rows,
- exact_total);
+ exact_total, &cursor_context);
} else {
/* A repeated multi-KiB path/QN prefix can make the complete compact
* page tiny even when the raw estimate is enormous. Probe that common
@@ -5666,8 +5954,9 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
* using the conservative raw estimate. */
enum { QUERY_COMPACT_FULL_PROBE_MAX_BYTES = 16 * 1024 * 1024 };
if (available_rows <= 512 && estimated <= QUERY_COMPACT_FULL_PROBE_MAX_BYTES) {
- char *candidate = query_graph_tree_response_text(&result, row_offset, available_rows,
- available_rows, exact_total, true);
+ char *candidate =
+ query_graph_tree_response_text(&result, row_offset, available_rows, available_rows,
+ exact_total, true, &cursor_context);
if (candidate && strlen(candidate) <= byte_budget) {
output_rows = available_rows;
json = candidate;
@@ -5682,8 +5971,9 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
int high = exact_upper;
while (low <= high) {
int middle = low + (high - low) / 2;
- char *candidate = query_graph_tree_response_text(
- &result, row_offset, middle, available_rows, exact_total, false);
+ char *candidate =
+ query_graph_tree_response_text(&result, row_offset, middle, available_rows,
+ exact_total, false, &cursor_context);
bool fits = candidate && strlen(candidate) <= byte_budget;
free(candidate);
if (fits) {
@@ -5707,7 +5997,8 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
for (int candidate_rows = compact_upper; candidate_rows > output_rows;
candidate_rows--) {
char *candidate = query_graph_tree_response_text(
- &result, row_offset, candidate_rows, available_rows, exact_total, true);
+ &result, row_offset, candidate_rows, available_rows, exact_total, true,
+ &cursor_context);
bool fits = candidate && strlen(candidate) <= byte_budget;
if (fits) {
output_rows = candidate_rows;
@@ -5717,8 +6008,9 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
free(candidate);
}
if (!json) {
- json = query_graph_tree_response_text(&result, row_offset, output_rows,
- available_rows, exact_total, true);
+ json =
+ query_graph_tree_response_text(&result, row_offset, output_rows, available_rows,
+ exact_total, true, &cursor_context);
}
}
}
@@ -5727,6 +6019,7 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {
json = query_graph_budget_floor_text(&result, row_offset, exact_total, qg_legacy_json);
}
cbm_cypher_result_free(&result);
+ free(cursor_arg);
free(query);
free(project);
@@ -12141,29 +12434,27 @@ void cbm_search_code_build_grep_cmd(char *cmd, size_t cmd_sz, bool use_regex, bo
* The xargs wrapper's zero-argument guard also makes empty discovery
* succeed on both GNU (runs once) and BSD (runs zero times) xargs. */
if (file_pattern) {
- snprintf(
- cmd, cmd_sz,
- "fl='%s'; find '%s' -type f -name '%s' -print0 > \"$fl\" 2>/dev/null; "
- "rc=$?; if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
- "LC_ALL=C sort -z -o \"$fl\" \"$fl\" 2>/dev/null; rc=$?; "
- "if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
- "xargs -0 sh -c 'pat=$1; shift; if [ \"$#\" -eq 0 ]; then exit 0; fi; "
- "grep -Hn %s -f \"$pat\" -- \"$@\"; rc=$?; if [ \"$rc\" -eq 1 ]; then "
- "exit 0; fi; if [ \"$rc\" -ne 0 ]; then exit 255; fi; exit 0' sh '%s' "
- "< \"$fl\" 2>/dev/null",
- filelist, root_path, file_pattern, flag, tmpfile);
+ snprintf(cmd, cmd_sz,
+ "fl='%s'; find '%s' -type f -name '%s' -print0 > \"$fl\" 2>/dev/null; "
+ "rc=$?; if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
+ "LC_ALL=C sort -z -o \"$fl\" \"$fl\" 2>/dev/null; rc=$?; "
+ "if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
+ "xargs -0 sh -c 'pat=$1; shift; if [ \"$#\" -eq 0 ]; then exit 0; fi; "
+ "grep -Hn %s -f \"$pat\" -- \"$@\"; rc=$?; if [ \"$rc\" -eq 1 ]; then "
+ "exit 0; fi; if [ \"$rc\" -ne 0 ]; then exit 255; fi; exit 0' sh '%s' "
+ "< \"$fl\" 2>/dev/null",
+ filelist, root_path, file_pattern, flag, tmpfile);
} else {
- snprintf(
- cmd, cmd_sz,
- "fl='%s'; find '%s' -type f -print0 > \"$fl\" 2>/dev/null; rc=$?; "
- "if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
- "LC_ALL=C sort -z -o \"$fl\" \"$fl\" 2>/dev/null; rc=$?; "
- "if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
- "xargs -0 sh -c 'pat=$1; shift; if [ \"$#\" -eq 0 ]; then exit 0; fi; "
- "grep -Hn %s -f \"$pat\" -- \"$@\"; rc=$?; if [ \"$rc\" -eq 1 ]; then "
- "exit 0; fi; if [ \"$rc\" -ne 0 ]; then exit 255; fi; exit 0' sh '%s' "
- "< \"$fl\" 2>/dev/null",
- filelist, root_path, flag, tmpfile);
+ snprintf(cmd, cmd_sz,
+ "fl='%s'; find '%s' -type f -print0 > \"$fl\" 2>/dev/null; rc=$?; "
+ "if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
+ "LC_ALL=C sort -z -o \"$fl\" \"$fl\" 2>/dev/null; rc=$?; "
+ "if [ \"$rc\" -ne 0 ]; then exit \"$rc\"; fi; "
+ "xargs -0 sh -c 'pat=$1; shift; if [ \"$#\" -eq 0 ]; then exit 0; fi; "
+ "grep -Hn %s -f \"$pat\" -- \"$@\"; rc=$?; if [ \"$rc\" -eq 1 ]; then "
+ "exit 0; fi; if [ \"$rc\" -ne 0 ]; then exit 255; fi; exit 0' sh '%s' "
+ "< \"$fl\" 2>/dev/null",
+ filelist, root_path, flag, tmpfile);
}
}
#endif
@@ -12386,13 +12677,12 @@ static char *search_match_lines_text(const search_result_t *result, int match_li
* distribution table, and the summary scalars. */
static char *assemble_search_output_toon(search_result_t *sr, int sr_count, grep_match_t *raw,
int raw_count, int raw_content_truncated, int gm_count,
- int result_start,
- int result_limit, int output_count, int raw_start,
- int raw_output, int directory_start, int directory_output,
- int raw_limit, int directory_limit, int match_limit,
- bool scan_saturated, bool warn_literal_pipe,
- const search_metrics_t *metrics, bool budget_hit,
- int source_lines_returned) {
+ int result_start, int result_limit, int output_count,
+ int raw_start, int raw_output, int directory_start,
+ int directory_output, int raw_limit, int directory_limit,
+ int match_limit, bool scan_saturated,
+ bool warn_literal_pipe, const search_metrics_t *metrics,
+ bool budget_hit, int source_lines_returned) {
enum { SEARCH_SLOW_MS = 5000 };
cbm_sb_t sb;
cbm_sb_init(&sb);
@@ -12633,15 +12923,12 @@ static char *assemble_search_output_toon(search_result_t *sr, int sr_count, grep
}
/* Phase 4: assemble JSON output from search results */
-static char *assemble_search_output(search_result_t *sr, int sr_count, grep_match_t *raw,
- int raw_count, int raw_content_truncated, int gm_count,
- int result_start, int result_limit,
- int output_count, int raw_start, int raw_output,
- int directory_start, int directory_output, int raw_limit,
- int directory_limit, int match_limit, int mode,
- int context_lines, int source_max_lines, const char *root_path,
- bool scan_saturated, bool warn_literal_pipe,
- const search_metrics_t *metrics, bool budget_hit) {
+static char *assemble_search_output(
+ search_result_t *sr, int sr_count, grep_match_t *raw, int raw_count, int raw_content_truncated,
+ int gm_count, int result_start, int result_limit, int output_count, int raw_start,
+ int raw_output, int directory_start, int directory_output, int raw_limit, int directory_limit,
+ int match_limit, int mode, int context_lines, int source_max_lines, const char *root_path,
+ bool scan_saturated, bool warn_literal_pipe, const search_metrics_t *metrics, bool budget_hit) {
enum { MODE_COMPACT = 0, MODE_FULL = 1, MODE_FILES = 2, SEARCH_SLOW_MS = 5000 };
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
@@ -12881,19 +13168,18 @@ static char *assemble_search_output(search_result_t *sr, int sr_count, grep_matc
static char *render_search_payload(search_result_t *sr, int sr_count, grep_match_t *raw,
int raw_count, int raw_content_truncated, int gm_count,
int result_start, int result_limit, int output_count,
- int raw_start, int raw_output,
- int directory_start, int directory_output, int raw_limit,
- int directory_limit, int match_limit, int mode,
- int context_lines, int source_max_lines, const char *root_path,
- bool scan_saturated, bool warn_literal_pipe,
- const search_metrics_t *metrics, bool budget_hit,
+ int raw_start, int raw_output, int directory_start,
+ int directory_output, int raw_limit, int directory_limit,
+ int match_limit, int mode, int context_lines,
+ int source_max_lines, const char *root_path, bool scan_saturated,
+ bool warn_literal_pipe, const search_metrics_t *metrics, bool budget_hit,
bool json_format) {
if (mode == 0 && !json_format) {
- return assemble_search_output_toon(
- sr, sr_count, raw, raw_count, raw_content_truncated, gm_count, result_start,
- result_limit, output_count, raw_start, raw_output, directory_start, directory_output,
- raw_limit, directory_limit, match_limit, scan_saturated, warn_literal_pipe, metrics,
- budget_hit, -1);
+ return assemble_search_output_toon(sr, sr_count, raw, raw_count, raw_content_truncated,
+ gm_count, result_start, result_limit, output_count,
+ raw_start, raw_output, directory_start, directory_output,
+ raw_limit, directory_limit, match_limit, scan_saturated,
+ warn_literal_pipe, metrics, budget_hit, -1);
}
char *json = assemble_search_output(
@@ -12941,9 +13227,8 @@ char *cbm_mcp_render_search_rows_for_testing(const char *const *qualified_names,
}
char *payload =
render_search_payload(results, row_count, NULL, 0, 0, row_count, 0, row_count, row_count, 0,
- 0, 0, row_count, 0, row_count > 0 ? 1 : 0,
- row_count > 0 ? 1 : 0, 0, 0, 0, "", false, false, &zero_metrics, false,
- json_format);
+ 0, 0, row_count, 0, row_count > 0 ? 1 : 0, row_count > 0 ? 1 : 0, 0,
+ 0, 0, "", false, false, &zero_metrics, false, json_format);
free_search_results(results, initialized);
return payload;
}
@@ -13083,8 +13368,7 @@ static bool search_utf8_continuation_byte(unsigned char byte) {
* paging only when a complete sequence actually spans the requested boundary;
* malformed bytes remain independently addressable original source bytes. */
static size_t search_utf8_page_start(const char *content, size_t total, size_t start) {
- if (start >= total ||
- !search_utf8_continuation_byte((unsigned char)content[start])) {
+ if (start >= total || !search_utf8_continuation_byte((unsigned char)content[start])) {
return start;
}
size_t earliest = start > 3U ? start - 3U : 0U;
@@ -13176,9 +13460,8 @@ char *cbm_mcp_render_raw_preview_for_testing(const char *content, bool content_o
}
grep_match_t raw = {.file = "fixture.raw", .line = 7};
search_raw_preview(&raw, content, content_offset_set, content_offset, false, 0, 0);
- return render_search_payload(NULL, 0, &raw, 1, raw.content_truncated ? 1 : 0, 1, 0, 0, 0,
- 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, "", false, false, &zero_metrics, false,
- json_format);
+ return render_search_payload(NULL, 0, &raw, 1, raw.content_truncated ? 1 : 0, 1, 0, 0, 0, 0, 1,
+ 0, 0, 1, 0, 0, 0, 0, 0, "", false, false, &zero_metrics, false, json_format);
}
#endif
@@ -13288,9 +13571,8 @@ static bool add_to_search_results(search_result_t **sr, int *sr_count, int *sr_c
/* Match a single grep hit to the tightest containing node, then add to sr or raw. */
static bool classify_grep_hit(grep_match_t *hit, cbm_node_t *file_nodes, int file_node_count,
search_result_t **sr, int *sr_count, int *sr_cap, grep_match_t **raw,
- int raw_offset, int raw_limit, int *raw_count,
- int *raw_stored_count, int *raw_cap,
- int *raw_content_truncated) {
+ int raw_offset, int raw_limit, int *raw_count, int *raw_stored_count,
+ int *raw_cap, int *raw_content_truncated) {
int best = find_tightest_node(file_nodes, file_node_count, hit->line);
if (best >= 0) {
return add_to_search_results(sr, sr_count, sr_cap, &file_nodes[best], hit->line);
@@ -13305,8 +13587,8 @@ static bool classify_grep_hit(grep_match_t *hit, cbm_node_t *file_nodes, int fil
}
(*raw_content_truncated)++;
}
- bool retain = raw_limit > 0 && raw_index >= raw_offset &&
- raw_index - raw_offset < raw_limit;
+ bool retain =
+ raw_limit > 0 && raw_index >= raw_offset && raw_index - raw_offset < raw_limit;
if (!retain) {
return true;
}
@@ -13347,21 +13629,19 @@ static void free_file_nodes(cbm_node_t *nodes, int count) {
* line numbers each; raw matches retain only the caller's requested page.
* Exact totals are counted while the stream is consumed to EOF. */
static bool scan_and_classify_grep_matches(
- FILE *fp, const char *root_path, size_t root_len, bool has_path_filter,
- cbm_regex_t *path_regex, const char *pattern, bool use_regex,
- bool raw_content_offset_set, size_t raw_content_offset, cbm_store_t *store,
- const char *project, search_result_t **sr, int *sr_count, int *sr_cap, grep_match_t **raw,
- int raw_offset, int raw_limit, int *raw_count, int *raw_stored_count, int *raw_cap,
- int *raw_content_truncated, int *grep_count) {
+ FILE *fp, const char *root_path, size_t root_len, bool has_path_filter, cbm_regex_t *path_regex,
+ const char *pattern, bool use_regex, bool raw_content_offset_set, size_t raw_content_offset,
+ cbm_store_t *store, const char *project, search_result_t **sr, int *sr_count, int *sr_cap,
+ grep_match_t **raw, int raw_offset, int raw_limit, int *raw_count, int *raw_stored_count,
+ int *raw_cap, int *raw_content_truncated, int *grep_count) {
char *line = NULL;
size_t line_capacity = 0;
char *current_file = NULL;
cbm_node_t *file_nodes = NULL;
int file_node_count = 0;
cbm_regex_t content_regex;
- bool content_regex_ready =
- use_regex && pattern &&
- cbm_regcomp(&content_regex, pattern, CBM_REG_EXTENDED) == CBM_REG_OK;
+ bool content_regex_ready = use_regex && pattern &&
+ cbm_regcomp(&content_regex, pattern, CBM_REG_EXTENDED) == CBM_REG_OK;
bool ok = true;
for (;;) {
@@ -15048,15 +15328,17 @@ static bool detect_snapshot_add_changed_file(cbm_mcp_server_t *srv, cbm_sha256_c
detect_snapshot_add_field(hash, metadata);
bool complete = true;
if (info.is_regular) {
- bool allow_open = true;
+ FILE *file = NULL;
#ifdef CBM_ENABLE_TEST_SEAMS
- if (srv && srv->snapshot_read_test_hook) {
- allow_open = srv->snapshot_read_test_hook(srv->snapshot_read_test_context, absolute);
+ bool allow_open = !srv || !srv->snapshot_read_test_hook ||
+ srv->snapshot_read_test_hook(srv->snapshot_read_test_context, absolute);
+ if (allow_open) {
+ file = cbm_fopen(absolute, "rb");
}
#else
(void)srv;
+ file = cbm_fopen(absolute, "rb");
#endif
- FILE *file = allow_open ? cbm_fopen(absolute, "rb") : NULL;
if (file) {
unsigned char buffer[64 * 1024];
size_t count;
@@ -15084,9 +15366,9 @@ static bool detect_snapshot_add_changed_file(cbm_mcp_server_t *srv, cbm_sha256_c
}
static bool detect_snapshot_fingerprint(cbm_mcp_server_t *srv, const char *root_path,
- const char *head_oid,
- const char *base_oid, const char *merge_base,
- const char *generation, char **files, int file_count,
+ const char *head_oid, const char *base_oid,
+ const char *merge_base, const char *generation,
+ char **files, int file_count,
const cbm_traverse_result_t *impact,
const detect_module_row_t *modules, int module_count,
int module_overflow, char out[33]) {
@@ -15196,6 +15478,22 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
return cbm_mcp_text_result("project path contains invalid characters", true);
}
+ /* Every detect snapshot and cursor is generation-bound. Validate the
+ * metadata immediately after store resolution so fresh requests and
+ * cursor replays fail identically before Git work or cursor minting. */
+ cbm_store_t *store = srv->store;
+ char generation[96] = "";
+ if (cbm_store_generation(store, generation, sizeof(generation)) != CBM_STORE_OK) {
+ free(root_path);
+ free(project);
+ free(base_branch);
+ free(scope);
+ return cbm_mcp_text_result(
+ "index_metadata_error: generation metadata is unreadable; reindex before detecting "
+ "changes",
+ true);
+ }
+
/* Direction of impact. Default inbound = the BLAST RADIUS: the transitive
* CALLERS of the changed symbols, which may need review. outbound = what
* the changed code depends on; both = union. */
@@ -15519,9 +15817,6 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
qsort(files, (size_t)file_count, sizeof(*files), detect_changed_path_compare);
}
- /* resolve_store already called via get_project_root above */
- cbm_store_t *store = srv->store;
-
/* Per-symbol impact page size. Engine saturation makes the reported total
* an explicit lower bound, while impact_offset continues every materialized
* row without identifier truncation. */
@@ -15654,10 +15949,10 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
/* The impact traversal: ONE multi-source BFS over all seeds. */
cbm_traverse_result_t impact = {0};
- bool truncated = false;
+ bool engine_saturated = false;
if (want_symbols && seed_count > 0) {
(void)cbm_store_bfs_multi(store, seeds, seed_count, direction, NULL, 0, depth,
- MCP_BFS_LIMIT_MAX, &impact, &truncated);
+ MCP_BFS_LIMIT_MAX, &impact, &engine_saturated);
}
detect_module_row_t *modules = NULL;
@@ -15673,14 +15968,12 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
* number of pageable rollup rows for the materialized impact set; its
* relation becomes `gte` if traversal hit the engine ceiling. */
int module_total = nmods + (module_overflow > 0 ? 1 : 0);
- char generation[96] = "unknown";
- (void)cbm_store_generation(store, generation, sizeof(generation));
- char detect_snapshot[33];
+ const char *cursor_error = NULL;
+ char detect_snapshot[33] = "";
bool detect_snapshot_complete = detect_snapshot_fingerprint(
srv, root_path, head_oid, base_oid, merge_base, generation, files, file_count, &impact,
modules, nmods, module_overflow, detect_snapshot);
- const char *cursor_error = NULL;
detect_cursor_t decoded_cursor = {0};
bool cursor_supplied = (changed_cursor_arg && changed_cursor_arg[0]) ||
(impact_cursor_arg && impact_cursor_arg[0]) ||
@@ -15766,7 +16059,12 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
bool output_budget_floor_exceeded = false;
char *out_str = NULL;
-render_detect_output:
+render_detect_output:;
+ bool changed_has_more = changed_start + changed_returned < file_count;
+ bool impacted_has_more = want_symbols && imp_start + imp_returned < impact.visited_count;
+ bool module_has_more = want_symbols && module_start + module_returned < module_total;
+ bool response_truncated = engine_saturated || output_budget_hit || changed_has_more ||
+ impacted_has_more || module_has_more;
if (!legacy_json) {
cbm_sb_t sb;
cbm_sb_init(&sb);
@@ -15782,6 +16080,9 @@ render_detect_output:
if (output_budget_floor_exceeded) {
cbm_tree_scalar_bool(&sb, "output_budget_floor_exceeded", true);
}
+ if (engine_saturated) {
+ cbm_tree_scalar_bool(&sb, "engine_saturated", true);
+ }
if (!detect_snapshot_complete) {
cbm_tree_scalar_bool(&sb, "snapshot_cursor_unavailable", true);
}
@@ -15789,12 +16090,11 @@ render_detect_output:
* file, so paging affects presentation only, never the graph answer. */
cbm_tree_scalar_int(&sb, "changed_total", file_count);
cbm_tree_scalar_int(&sb, "changed_returned", changed_returned);
- bool changed_has_more = changed_start + changed_returned < file_count;
cbm_tree_scalar_bool(&sb, "changed_has_more", changed_has_more);
if (changed_has_more && changed_returned > 0) {
cbm_tree_scalar_int(&sb, "changed_next_offset", changed_start + changed_returned);
- char cursor[80];
if (detect_snapshot_complete) {
+ char cursor[80];
detect_cursor_encode('c', detect_snapshot, detect_qhash,
changed_start + changed_returned, cursor);
cbm_tree_scalar_str(&sb, "changed_next_cursor", cursor);
@@ -15824,7 +16124,7 @@ render_detect_output:
free(changed_cells);
cbm_tree_scalar_int(&sb, "seed_symbols", seed_count);
if (want_symbols) {
- detect_emit_impacted_tree(&sb, &impact, imp_start, imp_returned, truncated);
+ detect_emit_impacted_tree(&sb, &impact, imp_start, imp_returned, engine_saturated);
if (detect_snapshot_complete && imp_start + imp_returned < impact.visited_count &&
imp_returned > 0) {
char cursor[80];
@@ -15835,14 +16135,13 @@ render_detect_output:
/* module rollup: independently pageable, while counts are still
* computed from the complete impact set. */
cbm_tree_scalar_int(&sb, "module_total", module_total);
- cbm_tree_scalar_str(&sb, "module_total_relation", truncated ? "gte" : "eq");
+ cbm_tree_scalar_str(&sb, "module_total_relation", engine_saturated ? "gte" : "eq");
cbm_tree_scalar_int(&sb, "module_returned", module_returned);
- bool module_has_more = module_start + module_returned < module_total;
cbm_tree_scalar_bool(&sb, "module_has_more", module_has_more);
if (module_has_more && module_returned > 0) {
cbm_tree_scalar_int(&sb, "module_next_offset", module_start + module_returned);
- char cursor[80];
if (detect_snapshot_complete) {
+ char cursor[80];
detect_cursor_encode('m', detect_snapshot, detect_qhash,
module_start + module_returned, cursor);
cbm_tree_scalar_str(&sb, "module_next_cursor", cursor);
@@ -15877,13 +16176,13 @@ render_detect_output:
}
free(count_text);
free(cells);
- if (truncated) {
+ if (engine_saturated) {
cbm_tree_scalar_str(&sb, "hint",
"impact hit the safety ceiling — narrow with a lower "
"'depth' or a smaller diff");
}
}
- if (truncated || output_budget_hit) {
+ if (response_truncated) {
cbm_tree_scalar_bool(&sb, "truncated", true);
}
out_str = cbm_sb_finish(&sb);
@@ -15904,18 +16203,20 @@ render_detect_output:
if (output_budget_floor_exceeded) {
yyjson_mut_obj_add_bool(doc, root_obj, "output_budget_floor_exceeded", true);
}
+ if (engine_saturated) {
+ yyjson_mut_obj_add_bool(doc, root_obj, "engine_saturated", true);
+ }
if (!detect_snapshot_complete) {
yyjson_mut_obj_add_bool(doc, root_obj, "snapshot_cursor_unavailable", true);
}
yyjson_mut_obj_add_int(doc, root_obj, "changed_total", file_count);
yyjson_mut_obj_add_int(doc, root_obj, "changed_returned", changed_returned);
- bool changed_has_more = changed_start + changed_returned < file_count;
yyjson_mut_obj_add_bool(doc, root_obj, "changed_has_more", changed_has_more);
if (changed_has_more && changed_returned > 0) {
yyjson_mut_obj_add_int(doc, root_obj, "changed_next_offset",
changed_start + changed_returned);
- char cursor[80];
if (detect_snapshot_complete) {
+ char cursor[80];
detect_cursor_encode('c', detect_snapshot, detect_qhash,
changed_start + changed_returned, cursor);
yyjson_mut_obj_add_strcpy(doc, root_obj, "changed_next_cursor", cursor);
@@ -15934,7 +16235,8 @@ render_detect_output:
yyjson_mut_obj_add_val(doc, root_obj, "changed_files", cf);
yyjson_mut_obj_add_int(doc, root_obj, "seed_symbols", seed_count);
yyjson_mut_obj_add_int(doc, root_obj, "impacted_total", impact.visited_count);
- yyjson_mut_obj_add_str(doc, root_obj, "impacted_total_relation", truncated ? "gte" : "eq");
+ yyjson_mut_obj_add_str(doc, root_obj, "impacted_total_relation",
+ engine_saturated ? "gte" : "eq");
yyjson_mut_obj_add_int(doc, root_obj, "impacted_shown", imp_returned);
yyjson_mut_val *imp = yyjson_mut_arr(doc);
for (int i = imp_start; i < imp_start + imp_returned; i++) {
@@ -15951,7 +16253,6 @@ render_detect_output:
yyjson_mut_arr_add_val(imp, o);
}
yyjson_mut_obj_add_val(doc, root_obj, "impacted", imp);
- bool impacted_has_more = imp_start + imp_returned < impact.visited_count;
yyjson_mut_obj_add_bool(doc, root_obj, "impacted_has_more", impacted_has_more);
if (impacted_has_more && imp_returned > 0) {
yyjson_mut_obj_add_int(doc, root_obj, "impacted_next_offset", imp_start + imp_returned);
@@ -15969,9 +16270,8 @@ render_detect_output:
if (want_symbols) {
yyjson_mut_obj_add_int(doc, root_obj, "module_total", module_total);
yyjson_mut_obj_add_str(doc, root_obj, "module_total_relation",
- truncated ? "gte" : "eq");
+ engine_saturated ? "gte" : "eq");
yyjson_mut_obj_add_int(doc, root_obj, "module_returned", module_returned);
- bool module_has_more = module_start + module_returned < module_total;
yyjson_mut_obj_add_bool(doc, root_obj, "module_has_more", module_has_more);
if (module_has_more && module_returned > 0) {
yyjson_mut_obj_add_int(doc, root_obj, "module_next_offset",
@@ -16003,7 +16303,7 @@ render_detect_output:
}
yyjson_mut_obj_add_val(doc, root_obj, "impacted_modules", rollup);
}
- yyjson_mut_obj_add_bool(doc, root_obj, "truncated", truncated || output_budget_hit);
+ yyjson_mut_obj_add_bool(doc, root_obj, "truncated", response_truncated);
out_str = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
}
@@ -16034,6 +16334,9 @@ render_detect_output:
cbm_tree_scalar_str(&floor, "truncation_reason", "output_budget");
cbm_tree_scalar_bool(&floor, "truncated", true);
cbm_tree_scalar_bool(&floor, "output_budget_floor_exceeded", true);
+ if (engine_saturated) {
+ cbm_tree_scalar_bool(&floor, "engine_saturated", true);
+ }
cbm_tree_scalar_int(&floor, "max_output_bytes", (long long)output_budget_bytes);
cbm_tree_scalar_str(&floor, "hint",
"mandatory detect_changes metadata exceeds the budget; raise "
@@ -16046,6 +16349,9 @@ render_detect_output:
yyjson_mut_obj_add_str(floor_doc, floor, "truncation_reason", "output_budget");
yyjson_mut_obj_add_bool(floor_doc, floor, "truncated", true);
yyjson_mut_obj_add_bool(floor_doc, floor, "output_budget_floor_exceeded", true);
+ if (engine_saturated) {
+ yyjson_mut_obj_add_bool(floor_doc, floor, "engine_saturated", true);
+ }
yyjson_mut_obj_add_uint(floor_doc, floor, "max_output_bytes", output_budget_bytes);
yyjson_mut_obj_add_str(
floor_doc, floor, "hint",
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 0aa4806ac..cdab338dc 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -693,6 +693,17 @@ TEST(tree_cell_reversibly_encodes_invalid_utf8) {
PASS();
}
+TEST(output_text_accepts_embedded_nul_as_valid_utf8) {
+ const char raw[] = {'a', '\0', 'b'};
+ char *encoded = NULL;
+ size_t encoded_len = 0;
+ ASSERT_TRUE(cbm_output_encode_text(raw, sizeof(raw), &encoded, &encoded_len));
+ ASSERT_NULL(encoded); /* U+0000 is valid UTF-8; the length-aware renderer escapes it. */
+ ASSERT_EQ(encoded_len, sizeof(raw));
+ free(encoded);
+ PASS();
+}
+
TEST(json_to_tree_uses_header_once_rows_without_losing_metadata) {
const char *json =
"{\"projects\":[{\"name\":\"alpha\",\"nodes\":10},{\"name\":\"beta\",\"nodes\":20}],"
@@ -729,9 +740,8 @@ TEST(json_to_tree_keeps_multiline_source_readable) {
}
TEST(json_to_tree_quotes_dynamic_keys_without_line_injection) {
- const char *json =
- "{\"bad\\nkey\":{\"colon:key\":1,\"\":2},"
- "\"rows\":[{\"col\\tname\":\"x\",\"close)\":\"y\"}]}";
+ const char *json = "{\"bad\\nkey\":{\"colon:key\":1,\"\":2},"
+ "\"rows\":[{\"col\\tname\":\"x\",\"close)\":\"y\"}]}";
char *tree = cbm_json_to_tree(json);
ASSERT_NOT_NULL(tree);
ASSERT_STR_EQ(tree, "\"bad\\nkey\":\n"
@@ -743,6 +753,23 @@ TEST(json_to_tree_quotes_dynamic_keys_without_line_injection) {
PASS();
}
+TEST(json_to_tree_preserves_embedded_nul_keys_values_and_table_cells) {
+ const char *json = "{\"a\\u0000b\":\"x\\u0000y\",\"multiline\":\"x\\u0000\\ny\","
+ "\"reserved\":\"@bytes:x\\u0000y\","
+ "\"rows\":[{\"k\\u0000x\":\"v\\u0000one\",\"k\\u0000y\":\"left\"},"
+ "{\"k\\u0000x\":\"two\",\"k\\u0000y\":\"q\\u0000right\"}]}";
+ char *tree = cbm_json_to_tree(json);
+ ASSERT_NOT_NULL(tree);
+ ASSERT_STR_EQ(tree, "\"a\\u0000b\": \"x\\u0000y\"\n"
+ "multiline: \"x\\u0000\\ny\"\n"
+ "reserved: \"@utf8:@bytes:x\\u0000y\"\n"
+ "rows: 2 (cols: \"k\\u0000x\" \"k\\u0000y\")\n"
+ " \"v\\u0000one\" left\n"
+ " two \"q\\u0000right\"\n");
+ free(tree);
+ PASS();
+}
+
/* Decode the intentionally tiny one-column subset used by the prefix-directory
* round-trip test. Its values need no tree quoting, so any mismatch is an
* encoder/reference bug rather than a second parser implementation. */
@@ -998,14 +1025,13 @@ TEST(tree_table_uses_prefix_dictionary_only_when_it_materially_wins) {
char token_cheap_values[TOKEN_CHEAP_ROWS][64];
const char *token_cheap_cells[TOKEN_CHEAP_ROWS];
for (int i = 0; i < TOKEN_CHEAP_ROWS; i++) {
- snprintf(token_cheap_values[i], sizeof(token_cheap_values[i]),
- "establishment.handler_%04d", i);
+ snprintf(token_cheap_values[i], sizeof(token_cheap_values[i]), "establishment.handler_%04d",
+ i);
token_cheap_cells[i] = token_cheap_values[i];
}
cbm_sb_init(&sb);
cbm_tree_table_rows_profiled(&sb, "token_cheap", TOKEN_CHEAP_ROWS, roundtrip_cols, 1,
- token_cheap_cells, roundtrip_string_cols,
- roundtrip_prefix_cols);
+ token_cheap_cells, roundtrip_string_cols, roundtrip_prefix_cols);
out = cbm_sb_finish(&sb);
ASSERT_NOT_NULL(out);
ASSERT_NULL(strstr(out, "token_cheap_refs:"));
@@ -1236,10 +1262,9 @@ TEST(mcp_tools_help_list_matches_registry) {
TEST(mcp_tools_list_latest_metadata) {
char *json = cbm_mcp_tools_list();
ASSERT_NOT_NULL(json);
- ASSERT_NOT_NULL(strstr(json, "\"title\":\"Search graph\""));
- ASSERT_NOT_NULL(strstr(json, "\"title\":\"Index repository\""));
- ASSERT_NOT_NULL(strstr(json, "\"title\":\"Check index coverage\""));
- ASSERT_NOT_NULL(strstr(json, "\"title\":\"Get file outline\""));
+ /* MCP tool titles are optional; name is the specified display fallback.
+ * Avoid paying for space-cased duplicates on every discovery response. */
+ ASSERT_NULL(strstr(json, "\"title\":"));
/* No tool may declare an outputSchema. The blanket permissive schema
* ({"type":"object","additionalProperties":true}) carried zero information
* for clients, but its presence made spec-compliant clients read
@@ -1333,7 +1358,7 @@ TEST(mcp_metadata_byte_budget) {
char *json = cbm_mcp_tools_list();
ASSERT_NOT_NULL(json);
- ASSERT_LT((int)strlen(json), 16 * 1024);
+ ASSERT_LT((int)strlen(json), 15 * 1024);
yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
ASSERT_NOT_NULL(doc);
@@ -3785,10 +3810,10 @@ TEST(tool_search_graph_rejects_bm25_and_semantic_query_together) {
"label, file_path FROM nodes;"),
CBM_STORE_OK);
- char *response = cbm_mcp_handle_tool(
- srv, "search_graph",
- "{\"project\":\"mixed-search-modes\",\"query\":\"mixedneedle\","
- "\"semantic_query\":[\"meaning\"],\"format\":\"json\"}");
+ char *response =
+ cbm_mcp_handle_tool(srv, "search_graph",
+ "{\"project\":\"mixed-search-modes\",\"query\":\"mixedneedle\","
+ "\"semantic_query\":[\"meaning\"],\"format\":\"json\"}");
ASSERT_NOT_NULL(response);
ASSERT_NOT_NULL(strstr(response, "\"isError\":true"));
ASSERT_NOT_NULL(strstr(response, "query and semantic_query are mutually exclusive"));
@@ -3873,10 +3898,10 @@ TEST(tool_search_graph_semantic_ceiling_never_emits_unusable_continuation) {
cbm_mcp_server_set_project(srv, "semantic-ceiling");
ASSERT_EQ(cbm_store_upsert_project(store, "semantic-ceiling", "/tmp/semantic-ceiling"),
CBM_STORE_OK);
- char *response = cbm_mcp_handle_tool(
- srv, "search_graph",
- "{\"project\":\"semantic-ceiling\",\"semantic_query\":[\"x\"],"
- "\"semantic_offset\":99999,\"format\":\"json\"}");
+ char *response =
+ cbm_mcp_handle_tool(srv, "search_graph",
+ "{\"project\":\"semantic-ceiling\",\"semantic_query\":[\"x\"],"
+ "\"semantic_offset\":99999,\"format\":\"json\"}");
ASSERT_NOT_NULL(response);
ASSERT_NOT_NULL(strstr(response, "\"isError\":true"));
ASSERT_NOT_NULL(strstr(response, "semantic_offset maximum is 99998"));
@@ -4609,6 +4634,219 @@ TEST(tool_query_graph_default_budget_is_truthful_and_expandable) {
PASS();
}
+/* Snapshot pagination binds the effective query identity, store generation,
+ * and the complete ordered materialization. Presentation knobs can change;
+ * graph/query identity and result bytes cannot. */
+TEST(tool_query_graph_cursor_is_lossless_and_snapshot_bound) {
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(srv);
+ cbm_store_t *store = cbm_mcp_server_store(srv);
+ ASSERT_NOT_NULL(store);
+ const char *project = "query-cursor";
+ cbm_mcp_server_set_project(srv, project);
+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/query-cursor"), CBM_STORE_OK);
+
+ char *long_file = malloc(3001U);
+ ASSERT_NOT_NULL(long_file);
+ memset(long_file, 'p', 3000U);
+ long_file[3000] = '\0';
+ for (int index = 0; index < 5; index++) {
+ char name[16];
+ char qn[48];
+ snprintf(name, sizeof(name), "row_%d", index);
+ snprintf(qn, sizeof(qn), "query-cursor.row_%d", index);
+ cbm_node_t node = {.project = project,
+ .label = "Function",
+ .name = name,
+ .qualified_name = qn,
+ .file_path = index == 4 ? long_file : "src/short.c",
+ .start_line = index + 1,
+ .end_line = index + 1};
+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);
+ }
+ const char *query = "MATCH (n:Function) RETURN n.qualified_name AS qn, n.file_path AS file "
+ "ORDER BY qn";
+
+ char first_args[512];
+ snprintf(first_args, sizeof(first_args),
+ "{\"project\":\"%s\",\"query\":\"%s\",\"max_rows\":2,"
+ "\"max_output_tokens\":2000,\"format\":\"json\"}",
+ project, query);
+ char *response = cbm_mcp_handle_tool(srv, "query_graph", first_args);
+ char *inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *root = yyjson_doc_get_root(doc);
+ yyjson_val *next_value = yyjson_obj_get(root, "next_cursor");
+ ASSERT_TRUE(yyjson_is_str(next_value));
+ char *first_cursor = strdup(yyjson_get_str(next_value));
+ ASSERT_NOT_NULL(first_cursor);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "next_offset")), 2);
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_arr_get(yyjson_arr_get(yyjson_obj_get(root, "rows"), 0), 0)),
+ "query-cursor.row_0");
+ yyjson_doc_free(doc);
+ free(inner);
+ free(response);
+
+ /* max_rows, output budget, and format are presentation only. */
+ char args[1024];
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"query\":\"%s\",\"max_rows\":2,"
+ "\"max_output_tokens\":1000,\"format\":\"tree\",\"cursor\":\"%s\"}",
+ project, query, first_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NOT_NULL(strstr(inner, "query-cursor.row_2"));
+ ASSERT_NOT_NULL(strstr(inner, "query-cursor.row_3"));
+ ASSERT_NULL(strstr(inner, "query-cursor.row_0"));
+ const char *cursor_line = strstr(inner, "next_cursor: ");
+ ASSERT_NOT_NULL(cursor_line);
+ cursor_line += strlen("next_cursor: ");
+ size_t second_cursor_len = strcspn(cursor_line, "\r\n");
+ ASSERT_TRUE(second_cursor_len > 0 && second_cursor_len < 224U);
+ char second_cursor[224];
+ memcpy(second_cursor, cursor_line, second_cursor_len);
+ second_cursor[second_cursor_len] = '\0';
+ free(inner);
+ free(response);
+
+ /* The next row exists but cannot fit at the floor. No advancing cursor is
+ * fabricated; retrying the same cursor at a higher budget resumes it. */
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"query\":\"%s\",\"max_rows\":9,"
+ "\"max_output_tokens\":128,\"format\":\"json\",\"cursor\":\"%s\"}",
+ project, query, second_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ doc = yyjson_read(inner, strlen(inner), 0);
+ ASSERT_NOT_NULL(doc);
+ root = yyjson_doc_get_root(doc);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "returned")), 0);
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));
+ ASSERT_NULL(yyjson_obj_get(root, "next_cursor"));
+ yyjson_doc_free(doc);
+ free(inner);
+ free(response);
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"query\":\"%s\",\"max_rows\":9,"
+ "\"max_output_tokens\":2000,\"format\":\"json\",\"cursor\":\"%s\"}",
+ project, query, second_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ doc = yyjson_read(inner, strlen(inner), 0);
+ ASSERT_NOT_NULL(doc);
+ root = yyjson_doc_get_root(doc);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "returned")), 1);
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_arr_get(yyjson_arr_get(yyjson_obj_get(root, "rows"), 0), 0)),
+ "query-cursor.row_4");
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));
+ yyjson_doc_free(doc);
+ free(inner);
+ free(response);
+
+ /* A changed row without a generation bump is still detected by the full
+ * ordered-materialization digest. */
+ cbm_node_t changed = {.project = project,
+ .label = "Function",
+ .name = "row_3",
+ .qualified_name = "query-cursor.row_3",
+ .file_path = "src/changed.c",
+ .start_line = 4,
+ .end_line = 4};
+ ASSERT_GT(cbm_store_upsert_node(store, &changed), 0);
+ snprintf(args, sizeof(args), "{\"project\":\"%s\",\"query\":\"%s\",\"cursor\":\"%s\"}", project,
+ query, first_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NOT_NULL(strstr(inner, "stale_cursor"));
+ ASSERT_NOT_NULL(strstr(response, "isError"));
+ free(inner);
+ free(response);
+
+ /* Query identity, explicit offsets, cursor bytes, and generation are all
+ * independently fail-closed. */
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"query\":\"MATCH (n) RETURN n.name\","
+ "\"cursor\":\"%s\"}",
+ project, first_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(strstr(inner, "cursor_params_mismatch"));
+ free(inner);
+ free(response);
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"query\":\"%s\",\"offset\":1,"
+ "\"cursor\":\"%s\"}",
+ project, query, first_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(strstr(inner, "cannot be combined"));
+ free(inner);
+ free(response);
+
+ char *tampered = strdup(first_cursor);
+ ASSERT_NOT_NULL(tampered);
+ size_t tampered_len = strlen(tampered);
+ tampered[tampered_len - 1U] = tampered[tampered_len - 1U] == '0' ? '1' : '0';
+ snprintf(args, sizeof(args), "{\"project\":\"%s\",\"query\":\"%s\",\"cursor\":\"%s\"}", project,
+ query, tampered);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(strstr(inner, "invalid_cursor"));
+ free(inner);
+ free(response);
+ free(tampered);
+
+ /* Mint under the changed materialization, then invalidate by generation. */
+ response = cbm_mcp_handle_tool(srv, "query_graph", first_args);
+ inner = extract_text_content(response);
+ doc = yyjson_read(inner, strlen(inner), 0);
+ ASSERT_NOT_NULL(doc);
+ next_value = yyjson_obj_get(yyjson_doc_get_root(doc), "next_cursor");
+ ASSERT_TRUE(yyjson_is_str(next_value));
+ char *generation_cursor = strdup(yyjson_get_str(next_value));
+ yyjson_doc_free(doc);
+ free(inner);
+ free(response);
+ ASSERT_NOT_NULL(generation_cursor);
+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/query-cursor"), CBM_STORE_OK);
+ snprintf(args, sizeof(args), "{\"project\":\"%s\",\"query\":\"%s\",\"cursor\":\"%s\"}", project,
+ query, generation_cursor);
+ response = cbm_mcp_handle_tool(srv, "query_graph", args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(strstr(inner, "stale_cursor"));
+ free(inner);
+ free(response);
+
+ /* Corrupt generation metadata must not silently degrade a fresh request
+ * to mutation-unsafe raw-offset pagination. */
+ ASSERT_EQ(cbm_store_exec(store, "UPDATE store_meta SET v='not-a-number' "
+ "WHERE k='mutation_gen';"),
+ CBM_STORE_OK);
+ response = cbm_mcp_handle_tool(srv, "query_graph", first_args);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NOT_NULL(strstr(inner, "index_metadata_error"));
+ ASSERT_NOT_NULL(strstr(response, "isError"));
+ free(inner);
+ free(response);
+
+ free(generation_cursor);
+ free(first_cursor);
+ free(long_file);
+ cbm_mcp_server_free(srv);
+ PASS();
+}
+
TEST(tool_query_graph_budget_bounds_first_row_and_json_escaping) {
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
ASSERT_NOT_NULL(srv);
@@ -8188,8 +8426,7 @@ TEST(search_code_scans_complete_stream_and_ranks_globally) {
yyjson_val *rows = root ? yyjson_obj_get(root, "rows") : NULL;
yyjson_val *first = rows ? yyjson_arr_get(rows, 0) : NULL;
bool complete_and_globally_ranked =
- root && first &&
- yyjson_get_int(yyjson_obj_get(root, "total_grep_matches")) == 502 &&
+ root && first && yyjson_get_int(yyjson_obj_get(root, "total_grep_matches")) == 502 &&
strcmp(yyjson_get_str(yyjson_obj_get(root, "total_relation")), "eq") == 0 &&
yyjson_obj_get(root, "scan_saturated") == NULL &&
yyjson_get_int(yyjson_obj_get(root, "total_results")) == 2 &&
@@ -8250,10 +8487,10 @@ TEST(search_code_fails_closed_when_complete_scan_is_impossible) {
.end_line = 1};
ASSERT_GT(cbm_store_upsert_node(store, &missing), 0);
- char *response = cbm_mcp_handle_tool(
- srv, "search_code",
- "{\"pattern\":\"NEVER_SCANNED\",\"project\":\"search-incomplete\","
- "\"format\":\"json\"}");
+ char *response =
+ cbm_mcp_handle_tool(srv, "search_code",
+ "{\"pattern\":\"NEVER_SCANNED\",\"project\":\"search-incomplete\","
+ "\"format\":\"json\"}");
ASSERT_NOT_NULL(response);
ASSERT_NOT_NULL(strstr(response, "\"isError\":true"));
ASSERT_NOT_NULL(strstr(response, "complete result set was scanned"));
@@ -8284,10 +8521,9 @@ TEST(search_code_recursive_fallback_propagates_discovery_failures) {
snprintf(victim, sizeof(victim), "%s/victim.c", tmp);
ASSERT_EQ(cbm_mkdir(bin_dir), 0);
ASSERT_EQ(cbm_mkdir(sort_bin_dir), 0);
- ASSERT_EQ(th_write_file(fake_find,
- "#!/bin/sh\n"
- "printf '%s\\000' \"$1/victim.c\"\n"
- "exit 73\n"),
+ ASSERT_EQ(th_write_file(fake_find, "#!/bin/sh\n"
+ "printf '%s\\000' \"$1/victim.c\"\n"
+ "exit 73\n"),
0);
ASSERT_EQ(chmod(fake_find, 0700), 0);
ASSERT_EQ(th_write_file(fake_sort, "#!/bin/sh\nexit 74\n"), 0);
@@ -8308,8 +8544,7 @@ TEST(search_code_recursive_fallback_propagates_discovery_failures) {
path_backup.value = path ? strdup(path) : NULL;
ASSERT_TRUE(!path || path_backup.value != NULL);
char forced_path[CBM_SZ_2K];
- int forced_length =
- snprintf(forced_path, sizeof(forced_path), "%s:/usr/bin:/bin", bin_dir);
+ int forced_length = snprintf(forced_path, sizeof(forced_path), "%s:/usr/bin:/bin", bin_dir);
ASSERT_TRUE(forced_length > 0 && (size_t)forced_length < sizeof(forced_path));
ASSERT_EQ(cbm_setenv("PATH", forced_path, 1), 0);
@@ -8317,9 +8552,9 @@ TEST(search_code_recursive_fallback_propagates_discovery_failures) {
srv, "search_code",
"{\"pattern\":\"FALLBACK_STATUS_NEEDLE\",\"project\":\"search-find-status\","
"\"file_pattern\":\"*.c\",\"format\":\"json\"}");
- bool discovery_failure_propagated =
- failed_response && strstr(failed_response, "\"isError\":true") &&
- strstr(failed_response, "complete result set was scanned");
+ bool discovery_failure_propagated = failed_response &&
+ strstr(failed_response, "\"isError\":true") &&
+ strstr(failed_response, "complete result set was scanned");
free(failed_response);
int forced_sort_length =
@@ -8330,9 +8565,9 @@ TEST(search_code_recursive_fallback_propagates_discovery_failures) {
srv, "search_code",
"{\"pattern\":\"FALLBACK_STATUS_NEEDLE\",\"project\":\"search-find-status\","
"\"file_pattern\":\"*.c\",\"format\":\"json\"}");
- bool sort_failure_propagated =
- sort_failed_response && strstr(sort_failed_response, "\"isError\":true") &&
- strstr(sort_failed_response, "complete result set was scanned");
+ bool sort_failure_propagated = sort_failed_response &&
+ strstr(sort_failed_response, "\"isError\":true") &&
+ strstr(sort_failed_response, "complete result set was scanned");
free(sort_failed_response);
mcp_test_restore_env(&path_backup, 1U);
@@ -8497,33 +8732,31 @@ TEST(search_code_raw_and_directory_remainders_are_independently_pageable) {
ASSERT_GT(cbm_store_upsert_node(store, &nodes[i]), 0);
}
- char *first_response = cbm_mcp_handle_tool(
- srv, "search_code",
- "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
- "\"limit\":2,\"raw_limit\":1,\"directory_limit\":1,"
- "\"max_output_tokens\":10000,\"format\":\"json\"}");
+ char *first_response =
+ cbm_mcp_handle_tool(srv, "search_code",
+ "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
+ "\"limit\":2,\"raw_limit\":1,\"directory_limit\":1,"
+ "\"max_output_tokens\":10000,\"format\":\"json\"}");
char *first_inner = extract_text_content(first_response);
- yyjson_doc *first_doc =
- first_inner ? yyjson_read(first_inner, strlen(first_inner), 0) : NULL;
+ yyjson_doc *first_doc = first_inner ? yyjson_read(first_inner, strlen(first_inner), 0) : NULL;
yyjson_val *first_root = first_doc ? yyjson_doc_get_root(first_doc) : NULL;
yyjson_val *first_raw = first_root ? yyjson_obj_get(first_root, "raw_matches") : NULL;
yyjson_val *first_raw_rows = first_raw ? yyjson_obj_get(first_raw, "rows") : NULL;
yyjson_val *first_raw_row = first_raw_rows ? yyjson_arr_get(first_raw_rows, 0) : NULL;
- yyjson_val *first_directories =
- first_root ? yyjson_obj_get(first_root, "directories") : NULL;
+ yyjson_val *first_directories = first_root ? yyjson_obj_get(first_root, "directories") : NULL;
bool first_page_bound =
first_root && yyjson_get_int(yyjson_obj_get(first_root, "raw_next_offset")) == 1 &&
- yyjson_get_int(yyjson_obj_get(first_root, "directory_next_offset")) == 1 &&
- first_raw_row && strcmp(yyjson_get_str(yyjson_arr_get(first_raw_row, 0)), "raw-a.txt") == 0 &&
+ yyjson_get_int(yyjson_obj_get(first_root, "directory_next_offset")) == 1 && first_raw_row &&
+ strcmp(yyjson_get_str(yyjson_arr_get(first_raw_row, 0)), "raw-a.txt") == 0 &&
yyjson_obj_get(first_directories, "graph-a/") != NULL &&
yyjson_obj_get(first_directories, "graph-b/") == NULL;
- char *second_response = cbm_mcp_handle_tool(
- srv, "search_code",
- "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
- "\"limit\":2,\"raw_limit\":1,\"raw_offset\":1,"
- "\"directory_limit\":1,\"directory_offset\":1,"
- "\"max_output_tokens\":10000,\"format\":\"json\"}");
+ char *second_response =
+ cbm_mcp_handle_tool(srv, "search_code",
+ "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
+ "\"limit\":2,\"raw_limit\":1,\"raw_offset\":1,"
+ "\"directory_limit\":1,\"directory_offset\":1,"
+ "\"max_output_tokens\":10000,\"format\":\"json\"}");
char *second_inner = extract_text_content(second_response);
yyjson_doc *second_doc =
second_inner ? yyjson_read(second_inner, strlen(second_inner), 0) : NULL;
@@ -8541,14 +8774,13 @@ TEST(search_code_raw_and_directory_remainders_are_independently_pageable) {
!yyjson_get_bool(yyjson_obj_get(second_root, "raw_has_more")) &&
!yyjson_get_bool(yyjson_obj_get(second_root, "directories_has_more"));
- char *floor_response = cbm_mcp_handle_tool(
- srv, "search_code",
- "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
- "\"result_limit\":1,\"raw_limit\":1,\"directory_limit\":1,"
- "\"max_output_tokens\":128,\"format\":\"json\"}");
+ char *floor_response =
+ cbm_mcp_handle_tool(srv, "search_code",
+ "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
+ "\"result_limit\":1,\"raw_limit\":1,\"directory_limit\":1,"
+ "\"max_output_tokens\":128,\"format\":\"json\"}");
char *floor_inner = extract_text_content(floor_response);
- yyjson_doc *floor_doc =
- floor_inner ? yyjson_read(floor_inner, strlen(floor_inner), 0) : NULL;
+ yyjson_doc *floor_doc = floor_inner ? yyjson_read(floor_inner, strlen(floor_inner), 0) : NULL;
yyjson_val *floor_root = floor_doc ? yyjson_doc_get_root(floor_doc) : NULL;
bool json_floor_is_bounded_and_resumable =
floor_root && strlen(floor_inner) <= 128U * 4U &&
@@ -8565,11 +8797,11 @@ TEST(search_code_raw_and_directory_remainders_are_independently_pageable) {
free(floor_inner);
free(floor_response);
- floor_response = cbm_mcp_handle_tool(
- srv, "search_code",
- "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
- "\"result_limit\":1,\"raw_limit\":1,\"directory_limit\":1,"
- "\"max_output_tokens\":128}");
+ floor_response =
+ cbm_mcp_handle_tool(srv, "search_code",
+ "{\"pattern\":\"PAGE_NEEDLE\",\"project\":\"search-section-pages\","
+ "\"result_limit\":1,\"raw_limit\":1,\"directory_limit\":1,"
+ "\"max_output_tokens\":128}");
floor_inner = extract_text_content(floor_response);
bool compact_floor_is_bounded_and_resumable =
floor_inner && strlen(floor_inner) <= 128U * 4U &&
@@ -9039,8 +9271,7 @@ TEST(search_code_raw_preview_centers_late_match_and_pages_content_bytes) {
}
TEST(search_code_raw_preview_reversibly_pages_malformed_utf8_bytes) {
- const char malformed[] = {'H', 'E', 'A', 'D', (char)0x80, (char)0xff,
- 'T', 'A', 'I', 'L', '\0'};
+ const char malformed[] = {'H', 'E', 'A', 'D', (char)0x80, (char)0xff, 'T', 'A', 'I', 'L', '\0'};
char *json = cbm_mcp_render_raw_preview_for_testing(malformed, false, 0, true);
ASSERT_NOT_NULL(json);
@@ -9051,8 +9282,7 @@ TEST(search_code_raw_preview_reversibly_pages_malformed_utf8_bytes) {
yyjson_val *rows = raw ? yyjson_obj_get(raw, "rows") : NULL;
yyjson_val *row = rows ? yyjson_arr_get(rows, 0) : NULL;
ASSERT_NOT_NULL(row);
- ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(row, 2)),
- "@bytes:4845414480ff5441494c");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(row, 2)), "@bytes:4845414480ff5441494c");
ASSERT_EQ((int)yyjson_get_uint(yyjson_arr_get(row, 3)), 0);
ASSERT_EQ((int)yyjson_get_uint(yyjson_arr_get(row, 4)), 10);
ASSERT_EQ((int)yyjson_get_uint(yyjson_arr_get(row, 5)), 10);
@@ -13041,11 +13271,11 @@ TEST(tool_detect_changes_invalid_base_is_an_error) {
ASSERT_EQ(cbm_store_upsert_project(store, project, repo), CBM_STORE_OK);
cbm_mcp_server_set_project(srv, project);
- char *response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-invalid-base-project\","
- "\"base_branch\":\"refs/heads/cbm-base-that-does-not-exist\","
- "\"scope\":\"files\",\"format\":\"json\"}");
+ char *response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-invalid-base-project\","
+ "\"base_branch\":\"refs/heads/cbm-base-that-does-not-exist\","
+ "\"scope\":\"files\",\"format\":\"json\"}");
bool errored = response_contains_json_fragment(response, "\"isError\":true");
free(response);
@@ -13067,7 +13297,9 @@ TEST(tool_detect_changes_preserves_utf8_git_path_and_impact_seed) {
snprintf(cache, sizeof(cache), "%s/cbm-detect-utf8-path-cache-XXXXXX", cbm_tmpdir());
ASSERT_NOT_NULL(cbm_mkdtemp(cache));
- static const char utf8_path[] = "caf" "\xC3\xA9" ".c";
+ static const char utf8_path[] = "caf"
+ "\xC3\xA9"
+ ".c";
char source_path[CBM_SZ_4K];
snprintf(source_path, sizeof(source_path), "%s/%s", repo, utf8_path);
ASSERT_EQ(th_write_file(source_path, "int cafe_value = 1;\n"), 0);
@@ -13118,17 +13350,15 @@ TEST(tool_detect_changes_preserves_utf8_git_path_and_impact_seed) {
.end_line = 1};
int64_t caller_id = cbm_store_upsert_node(store, &caller);
ASSERT_GT(caller_id, 0);
- cbm_edge_t edge = {.project = project,
- .source_id = caller_id,
- .target_id = seed_id,
- .type = "CALLS"};
+ cbm_edge_t edge = {
+ .project = project, .source_id = caller_id, .target_id = seed_id, .type = "CALLS"};
ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);
- char *response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-utf8-path-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"impact\",\"depth\":1,\"max_output_tokens\":10000,"
- "\"format\":\"json\"}");
+ char *response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-utf8-path-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"impact\",\"depth\":1,\"max_output_tokens\":10000,"
+ "\"format\":\"json\"}");
char *inner = extract_text_content(response);
yyjson_doc *doc = inner ? yyjson_read(inner, strlen(inner), 0) : NULL;
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
@@ -13139,9 +13369,8 @@ TEST(tool_detect_changes_preserves_utf8_git_path_and_impact_seed) {
bool path_preserved = changed_path && yyjson_is_str(changed_path) &&
strcmp(yyjson_get_str(changed_path), utf8_path) == 0;
bool seed_found = root && yyjson_get_int(yyjson_obj_get(root, "seed_symbols")) == 1;
- bool impact_found =
- first_impact &&
- strcmp(yyjson_get_str(yyjson_obj_get(first_impact, "qn")), "fixture.cafe_caller") == 0;
+ bool impact_found = first_impact && strcmp(yyjson_get_str(yyjson_obj_get(first_impact, "qn")),
+ "fixture.cafe_caller") == 0;
yyjson_doc_free(doc);
free(inner);
@@ -13169,11 +13398,11 @@ TEST(tool_detect_changes_finds_nested_untracked_file_and_impact_seed) {
const char *const init_args[] = {"init", "-q", NULL};
const char *const add_args[] = {"add", "-A", NULL};
const char *const commit_args[] = {
- "-c", "user.name=cbm-test",
- "-c", "commit.gpgsign=false",
- "commit", "-q",
- "-m", "fixture",
+ "-c", "user.name=cbm-test",
+ "-c", "commit.gpgsign=false",
+ "commit", "-q",
+ "-m", "fixture",
NULL,
};
ASSERT_EQ(mcp_test_git(repo, init_args), 0);
@@ -13218,10 +13447,8 @@ TEST(tool_detect_changes_finds_nested_untracked_file_and_impact_seed) {
.end_line = 1};
int64_t caller_id = cbm_store_upsert_node(store, &caller);
ASSERT_GT(caller_id, 0);
- cbm_edge_t edge = {.project = project,
- .source_id = caller_id,
- .target_id = seed_id,
- .type = "CALLS"};
+ cbm_edge_t edge = {
+ .project = project, .source_id = caller_id, .target_id = seed_id, .type = "CALLS"};
ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);
char *response = cbm_mcp_handle_tool(
@@ -13236,14 +13463,12 @@ TEST(tool_detect_changes_finds_nested_untracked_file_and_impact_seed) {
yyjson_val *changed_path = changed_files ? yyjson_arr_get(changed_files, 0) : NULL;
yyjson_val *impacted = root ? yyjson_obj_get(root, "impacted") : NULL;
yyjson_val *first_impact = impacted ? yyjson_arr_get(impacted, 0) : NULL;
- bool exact_nested_path =
- root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 1 && changed_path &&
- strcmp(yyjson_get_str(changed_path), "newdir/new.c") == 0;
+ bool exact_nested_path = root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 1 &&
+ changed_path &&
+ strcmp(yyjson_get_str(changed_path), "newdir/new.c") == 0;
bool seed_found = root && yyjson_get_int(yyjson_obj_get(root, "seed_symbols")) == 1;
- bool impact_found =
- first_impact &&
- strcmp(yyjson_get_str(yyjson_obj_get(first_impact, "qn")),
- "fixture.untracked_caller") == 0;
+ bool impact_found = first_impact && strcmp(yyjson_get_str(yyjson_obj_get(first_impact, "qn")),
+ "fixture.untracked_caller") == 0;
yyjson_doc_free(doc);
free(inner);
@@ -13277,11 +13502,11 @@ TEST(tool_detect_changes_escapes_newline_path_in_tree_and_round_trips_json) {
const char *const init_args[] = {"init", "-q", NULL};
const char *const add_args[] = {"add", "-A", NULL};
const char *const commit_args[] = {
- "-c", "user.name=cbm-test",
- "-c", "commit.gpgsign=false",
- "commit", "-q",
- "-m", "fixture",
+ "-c", "user.name=cbm-test",
+ "-c", "commit.gpgsign=false",
+ "commit", "-q",
+ "-m", "fixture",
NULL,
};
ASSERT_EQ(mcp_test_git(repo, init_args), 0);
@@ -13304,28 +13529,25 @@ TEST(tool_detect_changes_escapes_newline_path_in_tree_and_round_trips_json) {
ASSERT_EQ(cbm_store_upsert_project(store, project, repo), CBM_STORE_OK);
cbm_mcp_server_set_project(srv, project);
- char *tree_response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-newline-path-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"max_output_tokens\":10000}");
+ char *tree_response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-newline-path-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"max_output_tokens\":10000}");
char *tree = extract_text_content(tree_response);
- bool escaped_single_cell =
- tree && strstr(tree, "\"safe.c\\nseed_symbols: 777\"") != NULL;
- bool no_injected_scalar =
- tree && strstr(tree, "\nseed_symbols: 777\n") == NULL;
+ bool escaped_single_cell = tree && strstr(tree, "\"safe.c\\nseed_symbols: 777\"") != NULL;
+ bool no_injected_scalar = tree && strstr(tree, "\nseed_symbols: 777\n") == NULL;
- char *json_response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-newline-path-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"max_output_tokens\":10000,\"format\":\"json\"}");
+ char *json_response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-newline-path-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"max_output_tokens\":10000,\"format\":\"json\"}");
char *json = extract_text_content(json_response);
yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
yyjson_val *changed_files = root ? yyjson_obj_get(root, "changed_files") : NULL;
yyjson_val *changed_path = changed_files ? yyjson_arr_get(changed_files, 0) : NULL;
- bool json_round_trip =
- root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 1 && changed_path &&
- strcmp(yyjson_get_str(changed_path), newline_path) == 0;
+ bool json_round_trip = root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 1 &&
+ changed_path && strcmp(yyjson_get_str(changed_path), newline_path) == 0;
yyjson_doc_free(doc);
free(json);
@@ -13361,11 +13583,11 @@ TEST(tool_detect_changes_staged_rename_uses_exact_destination_record) {
const char *const init_args[] = {"init", "-q", NULL};
const char *const add_args[] = {"add", "-A", NULL};
const char *const commit_args[] = {
- "-c", "user.name=cbm-test",
- "-c", "commit.gpgsign=false",
- "commit", "-q",
- "-m", "fixture",
+ "-c", "user.name=cbm-test",
+ "-c", "commit.gpgsign=false",
+ "commit", "-q",
+ "-m", "fixture",
NULL,
};
ASSERT_EQ(mcp_test_git(repo, init_args), 0);
@@ -13392,19 +13614,18 @@ TEST(tool_detect_changes_staged_rename_uses_exact_destination_record) {
ASSERT_EQ(cbm_store_upsert_project(store, project, repo), CBM_STORE_OK);
cbm_mcp_server_set_project(srv, project);
- char *response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-rename-path-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"max_output_tokens\":10000,\"format\":\"json\"}");
+ char *response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-rename-path-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"max_output_tokens\":10000,\"format\":\"json\"}");
char *inner = extract_text_content(response);
yyjson_doc *doc = inner ? yyjson_read(inner, strlen(inner), 0) : NULL;
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
yyjson_val *changed_files = root ? yyjson_obj_get(root, "changed_files") : NULL;
yyjson_val *changed_path = changed_files ? yyjson_arr_get(changed_files, 0) : NULL;
- bool exact_destination =
- root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 1 && changed_files &&
- yyjson_arr_size(changed_files) == 1 && changed_path &&
- strcmp(yyjson_get_str(changed_path), destination) == 0;
+ bool exact_destination = root && yyjson_get_int(yyjson_obj_get(root, "changed_total")) == 1 &&
+ changed_files && yyjson_arr_size(changed_files) == 1 && changed_path &&
+ strcmp(yyjson_get_str(changed_path), destination) == 0;
yyjson_doc_free(doc);
free(inner);
@@ -13694,6 +13915,7 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_total")), 25);
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_returned")), 20);
ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "changed_has_more")));
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "truncated")));
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_next_offset")), 20);
ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "changed_files")), 20);
yyjson_val *changed_cursor_value = yyjson_obj_get(root, "changed_next_cursor");
@@ -13722,6 +13944,7 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "impacted_total_relation")), "eq");
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "impacted_shown")), 1);
ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "impacted_has_more")));
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "truncated")));
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "impacted_next_offset")), 1);
ASSERT_TRUE(yyjson_is_str(yyjson_obj_get(root, "impacted_next_cursor")));
yyjson_val *first_impacted = yyjson_arr_get_first(yyjson_obj_get(root, "impacted"));
@@ -13750,6 +13973,7 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
ASSERT_NOT_NULL(strstr(inner, long_detect_qn));
ASSERT_NOT_NULL(strstr(inner, long_detect_file));
ASSERT_NOT_NULL(strstr(inner, "module_continuation_requires_positive_limit: true"));
+ ASSERT_NOT_NULL(strstr(inner, "truncated: true"));
ASSERT_NULL(strstr(inner, "module_continuation_requires_higher_budget"));
free(inner);
free(response);
@@ -13804,6 +14028,7 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
root = yyjson_doc_get_root(doc);
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_returned")), 5);
ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "changed_has_more")));
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "truncated")));
ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "changed_files")), 5);
yyjson_doc_free(doc);
free(inner);
@@ -13870,6 +14095,7 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
root = yyjson_doc_get_root(doc);
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_returned")), 5);
ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "changed_has_more")));
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "truncated")));
yyjson_doc_free(doc);
free(inner);
free(response);
@@ -13880,10 +14106,9 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
* and an already-issued cursor must fail closed while the snapshot cannot
* be re-established. */
cbm_mcp_server_set_snapshot_read_test_hook(srv, mcp_snapshot_read_hook_probe, seed_file);
- response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"format\":\"json\"}");
+ response = cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"format\":\"json\"}");
ASSERT_NOT_NULL(response);
inner = extract_text_content(response);
ASSERT_NOT_NULL(inner);
@@ -13926,10 +14151,9 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
char changed_link[CBM_SZ_4K];
snprintf(changed_link, sizeof(changed_link), "%s/changed-link.c", repo);
ASSERT_EQ(symlink("first-target", changed_link), 0);
- response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"format\":\"json\"}");
+ response = cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"format\":\"json\"}");
ASSERT_NOT_NULL(response);
inner = extract_text_content(response);
ASSERT_NOT_NULL(inner);
@@ -13954,10 +14178,9 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
ASSERT_EQ(mcp_test_git(repo, add_deleted_args), 0);
ASSERT_EQ(mcp_test_git(repo, commit_args), 0);
ASSERT_EQ(cbm_unlink(deleted_path), 0);
- response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"format\":\"json\"}");
+ response = cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"format\":\"json\"}");
ASSERT_NOT_NULL(response);
inner = extract_text_content(response);
ASSERT_NOT_NULL(inner);
@@ -13970,6 +14193,32 @@ TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {
yyjson_doc_free(doc);
free(inner);
free(response);
+
+ /* Malformed generation metadata invalidates both a fresh snapshot and
+ * cursor replay. Never mint an empty-generation continuation. */
+ ASSERT_EQ(cbm_store_exec(store, "UPDATE store_meta SET v='not-a-number' "
+ "WHERE k='mutation_gen';"),
+ CBM_STORE_OK);
+ response = cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-pages-project\","
+ "\"base_branch\":\"HEAD\",\"scope\":\"files\","
+ "\"format\":\"json\"}");
+ ASSERT_NOT_NULL(response);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NOT_NULL(strstr(inner, "index_metadata_error"));
+ ASSERT_NOT_NULL(strstr(response, "isError"));
+ free(inner);
+ free(response);
+
+ response = cbm_mcp_handle_tool(srv, "detect_changes", cursor_args);
+ ASSERT_NOT_NULL(response);
+ inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NOT_NULL(strstr(inner, "index_metadata_error"));
+ ASSERT_NOT_NULL(strstr(response, "isError"));
+ free(inner);
+ free(response);
free(changed_cursor);
cbm_mcp_server_free(srv);
@@ -14022,18 +14271,18 @@ TEST(tool_detect_changes_output_budget_sets_truncated_in_tree_and_json) {
ASSERT_EQ(cbm_store_upsert_project(store, project, repo), CBM_STORE_OK);
cbm_mcp_server_set_project(srv, project);
- char *tree_response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-budget-flag-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"max_output_tokens\":128}");
+ char *tree_response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-budget-flag-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"max_output_tokens\":128}");
char *tree = extract_text_content(tree_response);
bool tree_budgeted = tree && strstr(tree, "truncation_reason: output_budget") != NULL;
bool tree_truncated = tree && strstr(tree, "truncated: true") != NULL;
- char *json_response = cbm_mcp_handle_tool(
- srv, "detect_changes",
- "{\"project\":\"detect-budget-flag-project\",\"base_branch\":\"HEAD\","
- "\"scope\":\"files\",\"max_output_tokens\":128,\"format\":\"json\"}");
+ char *json_response =
+ cbm_mcp_handle_tool(srv, "detect_changes",
+ "{\"project\":\"detect-budget-flag-project\",\"base_branch\":\"HEAD\","
+ "\"scope\":\"files\",\"max_output_tokens\":128,\"format\":\"json\"}");
char *json = extract_text_content(json_response);
yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;
yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
@@ -19250,9 +19499,11 @@ SUITE(mcp) {
RUN_TEST(jsonrpc_parse_notification);
RUN_TEST(jsonrpc_parse_invalid);
RUN_TEST(tree_cell_reversibly_encodes_invalid_utf8);
+ RUN_TEST(output_text_accepts_embedded_nul_as_valid_utf8);
RUN_TEST(json_to_tree_uses_header_once_rows_without_losing_metadata);
RUN_TEST(json_to_tree_keeps_multiline_source_readable);
RUN_TEST(json_to_tree_quotes_dynamic_keys_without_line_injection);
+ RUN_TEST(json_to_tree_preserves_embedded_nul_keys_values_and_table_cells);
RUN_TEST(tree_table_uses_prefix_dictionary_only_when_it_materially_wins);
RUN_TEST(jsonrpc_parse_tools_call);
RUN_TEST(jsonrpc_parse_string_id_issue253);
@@ -19376,6 +19627,7 @@ SUITE(mcp) {
RUN_TEST(mcp_resource_discovery_methods_return_empty_lists);
RUN_TEST(tool_query_graph_basic);
RUN_TEST(tool_query_graph_default_budget_is_truthful_and_expandable);
+ RUN_TEST(tool_query_graph_cursor_is_lossless_and_snapshot_bound);
RUN_TEST(tool_query_graph_budget_bounds_first_row_and_json_escaping);
RUN_TEST(tool_query_graph_prefix_directory_is_lossless_and_json_stays_direct);
RUN_TEST(tool_query_graph_prefix_directory_recovers_rows_beyond_raw_estimate);