Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(mcp): make tool output lean and lossless
Martin Vogel3909e5a0e1d5
diff --git a/README.md b/README.mdindex d6d08ae0a..44e1d0e67 100644--- a/README.md+++ b/README.md@@ -629,7 +629,11 @@ Every MCP tool can be invoked as a local, one-shot command. CLI tools neither stCommands that mutate graph data use shared OS-backed, per-project locks. This serializes conflicting work from CLI and MCP sessions on the same project while allowing unrelated projects to proceed independently.-When stderr is an interactive terminal, the CLI automatically shows lifecycle and indexing progress. Pass `--progress` to force the same feedback when stderr is redirected or the command is run non-interactively. Progress is written only to stderr; stdout remains reserved for the command result, so pipes and scripts stay machine-safe. Pass `--json` when the full MCP result envelope is needed.+When stderr is an interactive terminal, the CLI automatically shows lifecycle and indexing progress. Pass `--progress` to force the same feedback when stderr is redirected or the command is run non-interactively. Routine informational logs are quiet by default; pass outer `cli --verbose` to include them. Progress and logs use stderr while stdout remains reserved for the command result. Read tools return a compact tree by default; pass a tool's `--format json` for machine-readable payload JSON, or outer `--json` for the full MCP envelope.++Large compact-tree tables may start with a response-local `<section>_refs` directory and an explicit `<section>_ref_rule`. A cell such as `@0+handler.go` reconstructs to ref `0`'s prefix plus `handler.go`. References are local to that sibling `<section>` table and expansion is non-recursive: entries inside `<section>_refs` are always literal prefixes. This is limited to declared path and qualified-name columns and activates only when that table is at least 15% and 64 bytes smaller. Search and trace likewise render direct and prefix-grouped tree shapes and keep the smaller complete representation, so singleton or scattered answers do not pay directory overhead. Keys are declared once per table but never cryptically abbreviated, and `--format json` keeps stable literal strings for machine consumers. These are deterministic model-neutral byte savings that normally reduce tokens; exact token counts still depend on the caller's tokenizer.++Lean responses truncate semantically, never by cutting arbitrary bytes from code or identifiers. Ranked graph rows are retained ahead of raw grep rows and diagnostic summaries; omitted rows/sections report totals, `has_more`, and a strictly advancing continuation offset or cursor. If even the first whole row cannot fit, CBM asks for a higher budget and emits no self-looping cursor. `max_output_tokens` is model-neutral sizing guidance: CBM enforces a deterministic ceiling of four UTF-8 bytes per requested token, so it is not a tokenizer-exact count. Detail flags such as `diagnostics`, `source_mode`, and `detail` opt into heavier fields. `search_code` additionally exposes `raw_limit`, `directory_limit`, `match_limit`, and `source_max_lines`; its default retains eight match locations per graph result and reports the exact `matches_omitted` remainder. `detect_changes` pages changed files, impacted symbols, and module summaries independently.Use `cli <tool> --help` to see the flags generated from that tool's input schema:@@ -644,7 +648,8 @@ codebase-memory-mcp cli query_graph --project my-project --query 'MATCH (f:Funct# Force human-readable progress without contaminating stdout.codebase-memory-mcp cli --progress index_repository --repo-path /path/to/repo-codebase-memory-mcp cli search_graph --project my-project --label Function | jq '.results[].name'+codebase-memory-mcp cli search_graph --project my-project --label Function --format json+codebase-memory-mcp cli list_projects --format json --detail stats | jq '.projects[].name'```JSON arguments can also be piped on stdin, for tools that take arguments. A tool whose input schema declares none — `list_projects` — never reads stdin, so it stays responsive when it inherits a pipe the caller never closes (the default for `child_process.spawn` and similar wrappers). Inline JSON remains accepted for backward compatibility but is deprecated in favor of flags, `--args-file`, or stdin.diff --git a/graph-ui/src/components/NodeDetailPanel.test.tsx b/graph-ui/src/components/NodeDetailPanel.test.tsxindex 5a9455d09..12c72b1a4 100644--- a/graph-ui/src/components/NodeDetailPanel.test.tsx+++ b/graph-ui/src/components/NodeDetailPanel.test.tsx@@ -68,6 +68,12 @@ describe("NodeDetailPanel code preview + deep-link", () => {/* …but was NOT parsed into a real <script> element, and did not execute. */expect(container.querySelector("script")).toBeNull();expect((window as unknown as { __pwned?: boolean }).__pwned).toBeUndefined();+ expect(callToolMock).toHaveBeenCalledWith("get_code_snippet", {+ qualified_name: "app::render",+ project: "demo",+ format: "json",+ source_mode: "full",+ });});it("builds an https GitHub deep-link with URL-encoded path segments", () => {diff --git a/graph-ui/src/components/NodeDetailPanel.tsx b/graph-ui/src/components/NodeDetailPanel.tsxindex 54be52f36..b75d9083d 100644--- a/graph-ui/src/components/NodeDetailPanel.tsx+++ b/graph-ui/src/components/NodeDetailPanel.tsx@@ -76,6 +76,8 @@ export function NodeDetailPanel({const res = await callTool<SnippetResult>("get_code_snippet", {qualified_name: node.qualified_name,project,+ format: "json",+ source_mode: "full",});setCode(res.source ?? "(source not available)");} catch (e) {diff --git a/graph-ui/src/components/StatsTab.test.tsx b/graph-ui/src/components/StatsTab.test.tsxindex eb17cc715..64c44e977 100644--- a/graph-ui/src/components/StatsTab.test.tsx+++ b/graph-ui/src/components/StatsTab.test.tsx@@ -12,7 +12,7 @@ function mockProjectsFetch(extra?: (url: string, init?: RequestInit) => Responseif (overridden) return overridden;if (url === "/rpc") {return new Response(JSON.stringify({- result: { content: [{ text: JSON.stringify({ projects: [] }) }] },+ result: { content: [{ text: JSON.stringify({ projects: [], has_more: false }) }] },}), { status: 200, headers: { "Content-Type": "application/json" } });}if (url.startsWith("/api/ui-config")) {@@ -221,8 +221,11 @@ describe("StatsTab index modal", () => {root_path: "/repo",indexed_at: "2026-01-01T00:00:00Z",}],+ has_more: false,}- : { node_labels: [], edge_types: [], total_nodes: 0, total_edges: 0 };+ : {+ node_labels: [], edge_types: [], total_nodes: 0, total_edges: 0, has_more: false,+ };return new Response(JSON.stringify({result: { content: [{ text: JSON.stringify(result) }] },}), { status: 200, headers: { "Content-Type": "application/json" } });diff --git a/graph-ui/src/hooks/useProjects.test.tsx b/graph-ui/src/hooks/useProjects.test.tsxnew file mode 100644index 000000000..10d36a97c--- /dev/null+++ b/graph-ui/src/hooks/useProjects.test.tsx@@ -0,0 +1,86 @@+/* @vitest-environment jsdom */+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useProjects } from "./useProjects";++const callToolMock = vi.fn();+vi.mock("../api/rpc", () => ({+ callTool: (...args: unknown[]) => callToolMock(...args),+}));++describe("useProjects machine-readable pagination", () => {+ beforeEach(() => callToolMock.mockReset());++ it("requests JSON and merges every project and schema page", async () => {+ callToolMock.mockImplementation(async (name: string, args: Record<string, unknown>) => {+ if (name === "list_projects") {+ if (args.offset === 0) {+ return {+ projects: [{ name: "alpha", root_path: "/alpha", indexed_at: "now" }],+ has_more: true,+ next_offset: 1,+ };+ }+ return {+ projects: [{ name: "beta", root_path: "/beta", indexed_at: "now" }],+ has_more: false,+ };+ }+ if (name === "get_graph_schema" && args.project === "alpha") {+ if (args.offset === 0) {+ return {+ node_labels: [{ label: "Function", count: 3 }],+ edge_types: [],+ total_nodes: 3,+ total_edges: 2,+ has_more: true,+ next_offset: 1,+ };+ }+ return {+ node_labels: [],+ edge_types: [{ type: "CALLS", count: 2 }],+ total_nodes: 3,+ total_edges: 2,+ has_more: false,+ };+ }+ return {+ node_labels: [{ label: "Class", count: 1 }],+ edge_types: [],+ total_nodes: 1,+ total_edges: 0,+ has_more: false,+ };+ });++ const { result } = renderHook(() => useProjects());+ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.projects).toHaveLength(2);+ expect(result.current.projects[0].schema?.node_labels).toEqual([+ { label: "Function", count: 3 },+ ]);+ expect(result.current.projects[0].schema?.edge_types).toEqual([+ { type: "CALLS", count: 2 },+ ]);+ expect(callToolMock).toHaveBeenCalledWith("list_projects", {+ format: "json",+ detail: "stats",+ limit: 500,+ offset: 0,+ });+ expect(callToolMock).toHaveBeenCalledWith("list_projects", {+ format: "json",+ detail: "stats",+ limit: 500,+ offset: 1,+ });+ expect(callToolMock).toHaveBeenCalledWith("get_graph_schema", {+ project: "alpha",+ format: "json",+ limit: 500,+ offset: 1,+ });+ });+});diff --git a/graph-ui/src/hooks/useProjects.ts b/graph-ui/src/hooks/useProjects.tsindex 5deff5215..7ed5d7511 100644--- a/graph-ui/src/hooks/useProjects.ts+++ b/graph-ui/src/hooks/useProjects.ts@@ -7,6 +7,70 @@ interface ProjectInfo {schema: SchemaInfo | null;}+interface ProjectPage {+ projects?: Project[];+ has_more?: boolean;+ next_offset?: number;+}++interface SchemaPage extends SchemaInfo {+ has_more?: boolean;+ next_offset?: number;+}++const PAGE_LIMIT = 500;++function nextPageOffset(page: { has_more?: boolean; next_offset?: number }, offset: number) {+ if (typeof page.has_more !== "boolean") {+ throw new Error("Invalid pagination response");+ }+ if (!page.has_more) return null;+ if (!Number.isInteger(page.next_offset) || page.next_offset! <= offset) {+ throw new Error("Invalid pagination response");+ }+ return page.next_offset!;+}++async function fetchAllProjects(): Promise<Project[]> {+ const projects: Project[] = [];+ let offset = 0;+ for (;;) {+ const page = await callTool<ProjectPage>("list_projects", {+ format: "json",+ detail: "stats",+ limit: PAGE_LIMIT,+ offset,+ });+ projects.push(...(page.projects ?? []));+ const next = nextPageOffset(page, offset);+ if (next === null) return projects;+ offset = next;+ }+}++async function fetchFullSchema(project: string): Promise<SchemaInfo> {+ const nodeLabels: SchemaInfo["node_labels"] = [];+ const edgeTypes: SchemaInfo["edge_types"] = [];+ let firstPage: SchemaPage | null = null;+ let offset = 0;+ for (;;) {+ const page = await callTool<SchemaPage>("get_graph_schema", {+ project,+ format: "json",+ limit: PAGE_LIMIT,+ offset,+ });+ firstPage ??= page;+ nodeLabels.push(...(page.node_labels ?? []));+ edgeTypes.push(...(page.edge_types ?? []));+ const next = nextPageOffset(page, offset);+ if (next === null) {+ return { ...firstPage, node_labels: nodeLabels, edge_types: edgeTypes };+ }+ offset = next;+ }+}+interface UseProjectsResult {projects: ProjectInfo[];loading: boolean;@@ -23,16 +87,13 @@ export function useProjects(): UseProjectsResult {setLoading(true);setError(null);try {- const result = await callTool<{ projects: Project[] }>("list_projects");- const list = result.projects ?? [];+ const list = await fetchAllProjects();/* Fetch schema for each project */const infos: ProjectInfo[] = await Promise.all(list.map(async (p) => {try {- const schema = await callTool<SchemaInfo>("get_graph_schema", {- project: p.name,- });+ const schema = await fetchFullSchema(p.name);return { project: p, schema };} catch {return { project: p, schema: null };diff --git a/graph-ui/tsconfig.tsbuildinfo b/graph-ui/tsconfig.tsbuildinfoindex 0da71675b..5f1f5e115 100644--- a/graph-ui/tsconfig.tsbuildinfo+++ b/graph-ui/tsconfig.tsbuildinfo@@ -1 +1 @@-{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/rpc.ts","./src/components/controltab.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.tsx","./src/components/graphscene.test.ts","./src/components/graphscene.tsx","./src/components/graphtab.test.ts","./src/components/graphtab.tsx","./src/components/nodecloud.tsx","./src/components/nodedetailpanel.tsx","./src/components/nodelabels.tsx","./src/components/nodetooltip.tsx","./src/components/projectcard.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.tsx","./src/components/tabbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/hooks/usegraphdata.test.ts","./src/hooks/usegraphdata.ts","./src/hooks/useprojects.ts","./src/lib/colors.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/types.ts","./src/lib/utils.ts"],"version":"5.9.3"}\ No newline at end of file+{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/rpc.ts","./src/components/controltab.tsx","./src/components/displaysettingsmenu.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.tsx","./src/components/graphloader.tsx","./src/components/graphscene.test.ts","./src/components/graphscene.tsx","./src/components/graphtab.deadcode.test.tsx","./src/components/graphtab.filters.test.tsx","./src/components/graphtab.test.ts","./src/components/graphtab.tsx","./src/components/missedcallout.tsx","./src/components/nodecloud.tsx","./src/components/nodedetailpanel.test.tsx","./src/components/nodedetailpanel.tsx","./src/components/nodelabels.tsx","./src/components/nodetooltip.tsx","./src/components/projectcard.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.tsx","./src/components/tabbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/hooks/usegraphdata.test.ts","./src/hooks/usegraphdata.ts","./src/hooks/useprojects.test.tsx","./src/hooks/useprojects.ts","./src/lib/colors.ts","./src/lib/density.test.ts","./src/lib/density.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/types.ts","./src/lib/utils.ts"],"version":"5.9.3"}\ No newline at end of filediff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex 415c906ef..094078ebc 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -407,7 +407,7 @@ DUP_CHECKED=0for TOOL_ARGS in "search_graph --project $PROJECT --name-pattern compute" \"search_code --project $PROJECT --query compute" \"get_architecture --project $PROJECT" \- "index_status --project $PROJECT"; do+ "index_status --project $PROJECT --format json"; do# shellcheck disable=SC2086ENVELOPE=$("$BINARY" cli $TOOL_ARGS --json 2>/dev/null || true)[ -z "$ENVELOPE" ] && continue@@ -575,7 +575,7 @@ fiecho "OK: trace_path found $CALLERS caller(s) for 'compute'"# 3c: get_graph_schema — verify labels exist-if ! SCHEMA=$(cli get_graph_schema --project "$PROJECT"); then+if ! SCHEMA=$(cli get_graph_schema --project "$PROJECT" --format json --limit 500); thenecho "FAIL: get_graph_schema (flag form) exited non-zero"; cat "$CLI_STDERR"; exit 1fiLABELS=$(echo "$SCHEMA" | python3 -c "import json,sys; d=json.loads(sys.stdin.read()); print(len(d.get('node_labels',[])))" 2>/dev/null || echo "0")@@ -647,8 +647,10 @@ cyp_first_cell() {# $1 = query; echoes rows[0][0] (or empty). Flag form passes the query as ONE# argv token, so string-literal args (e.g. replace(f.name,"a","A")) and Cypher# metacharacters {}|=~<>" need no JSON escaping.- cli query_graph --project "$PROJECT" --query "$1" |- sed -n '/^rows: /{n;p;}' | sed 's/^ //' | sed 's/^"//;s/"$//;s/\\"/"/g'+ cli query_graph --project "$PROJECT" --query "$1" --format json |+ python3 -c 'import json,sys+d=json.load(sys.stdin); rows=d.get("rows", [])+print(rows[0][0] if rows and rows[0] else "")'}# labels(n) → JSON list like ["Function"]@@ -851,7 +853,7 @@ echo "OK B4: compact STDIN + --json returns a successful schema MCP envelope, no# B5: --args-file — JSON read from a file resolves; must NOT warn deprecated.IM_ARGS_FILE=$(smoke_mktemp_file)-echo "{\"project\":\"$PROJECT\"}" > "$IM_ARGS_FILE"+echo "{\"project\":\"$PROJECT\",\"format\":\"json\",\"limit\":500}" > "$IM_ARGS_FILE"if ! IM_AF=$(cli get_graph_schema --args-file "$IM_ARGS_FILE"); thenecho "FAIL B5: get_graph_schema --args-file exited non-zero"; cat "$CLI_STDERR"; rm -f "$IM_ARGS_FILE"; exit 1fidiff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.cindex ccc94bfa2..1506cbbc3 100644--- a/src/cli/hook_augment.c+++ b/src/cli/hook_augment.c@@ -27,6 +27,7 @@#include <ctype.h>#include <stdbool.h>+#include <stdint.h>#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -45,6 +46,7 @@#define HA_MIN_TOKEN 4 /* skip short/noisy patterns before any work */#define HA_MAX_TOKEN 96#define HA_RESULT_LIMIT 5+#define HA_LIST_PAGE_LIMIT 500#define HA_METADATA_CAP 192#define HA_MAX_WALKUP 8 /* cwd may be a subdir of the indexed root */#define HA_DEADLINE_MS 300 /* hard in-process budget (see also: the */@@ -511,11 +513,45 @@ static char *ha_coverage_context(const char *envelope, const char *rel, bool *isstrcmp(status, "invalid_path") != 0) {const char *kind = NULL;const char *detail = NULL;+ char *range_detail = NULL;yyjson_val *coverage = yyjson_obj_get(item, "coverage");yyjson_val *row = coverage && yyjson_is_arr(coverage) ? yyjson_arr_get(coverage, 0) : NULL;if (row) {kind = ha_obj_str(row, "kind");detail = ha_obj_str(row, "detail");+ yyjson_val *ranges = yyjson_obj_get(row, "ranges");+ size_t range_count = ranges && yyjson_is_arr(ranges) ? yyjson_arr_size(ranges) : 0;+ if ((!detail || !detail[0]) && range_count > 0 && range_count <= SIZE_MAX / 48U) {+ range_detail = calloc(range_count * 48U + 1U, 1U);+ if (range_detail) {+ size_t used = 0;+ size_t index;+ size_t maximum;+ yyjson_val *range;+ yyjson_arr_foreach(ranges, index, maximum, range) {+ yyjson_val *start_value = yyjson_obj_get(range, "start");+ yyjson_val *end_value = yyjson_obj_get(range, "end");+ if (!yyjson_is_int(start_value) || !yyjson_is_int(end_value)) {+ continue;+ }+ long long start = (long long)yyjson_get_sint(start_value);+ long long end = (long long)yyjson_get_sint(end_value);+ int written =+ start == end+ ? snprintf(range_detail + used, range_count * 48U + 1U - used,+ "%s%lld", used ? "," : "", start)+ : snprintf(range_detail + used, range_count * 48U + 1U - used,+ "%s%lld-%lld", used ? "," : "", start, end);+ if (written < 0 || (size_t)written >= range_count * 48U + 1U - used) {+ free(range_detail);+ range_detail = NULL;+ break;+ }+ used += (size_t)written;+ }+ detail = range_detail;+ }+ }}text = malloc(1536);if (text) {@@ -542,6 +578,7 @@ static char *ha_coverage_context(const char *envelope, const char *rel, bool *isstatus, freshness ? freshness : "unavailable");}}+ free(range_detail);}yyjson_doc_free(idoc);yyjson_doc_free(edoc);@@ -611,6 +648,7 @@ static char *ha_resolve_coverage(cbm_mcp_server_t *srv, const char *file_path) {yyjson_mut_obj_add_str(adoc, aroot, "project", project);yyjson_mut_arr_add_strcpy(adoc, paths, rel);yyjson_mut_obj_add_val(adoc, aroot, "paths", paths);+ yyjson_mut_obj_add_str(adoc, aroot, "format", "json");char *args = yyjson_mut_write(adoc, 0, NULL);yyjson_mut_doc_free(adoc);free(project);@@ -811,53 +849,108 @@ static char *ha_registry_project_for_path(cbm_mcp_server_t *srv, const char *cwdif (!ha_canonical_path(cwd, canonical_cwd, sizeof(canonical_cwd))) {return NULL;}- char *envelope = cbm_mcp_handle_tool(srv, "list_projects", "{\"metadata_only\":true}");- yyjson_doc *doc = envelope ? yyjson_read(envelope, strlen(envelope), 0) : NULL;- free(envelope);- if (!doc) {- return NULL;- }- yyjson_val *outer = yyjson_doc_get_root(doc);- yyjson_val *error = yyjson_obj_get(outer, "isError");- yyjson_val *structured = yyjson_obj_get(outer, "structuredContent");- yyjson_val *projects = structured ? yyjson_obj_get(structured, "projects") : NULL;- if ((error && yyjson_is_true(error)) || !projects || !yyjson_is_arr(projects)) {- yyjson_doc_free(doc);- return NULL;- }-- const char *best_name = NULL;+ char *best_name = NULL;char best_root[4096] = {0};size_t best_length = 0U;- size_t index;- size_t maximum;- yyjson_val *project;- yyjson_arr_foreach(projects, index, maximum, project) {- const char *name = ha_obj_str(project, "name");- const char *root = ha_obj_str(project, "root_path");- char canonical_root[4096];- if (!name || !name[0] || !root || !root[0] ||- !ha_canonical_path(root, canonical_root, sizeof(canonical_root)) ||- !ha_path_contains(canonical_root, canonical_cwd)) {- continue;+ int64_t offset = 0;+ bool complete = false;++ for (;;) {+ char args[160];+ int written = snprintf(args, sizeof(args),+ "{\"metadata_only\":true,\"format\":\"json\",\"limit\":%d,"+ "\"offset\":%lld}",+ HA_LIST_PAGE_LIMIT, (long long)offset);+ if (written < 0 || (size_t)written >= sizeof(args)) {+ break;+ }+ char *envelope = cbm_mcp_handle_tool(srv, "list_projects", args);+ yyjson_doc *edoc = envelope ? yyjson_read(envelope, strlen(envelope), 0) : NULL;+ free(envelope);+ if (!edoc) {+ break;+ }+ yyjson_val *outer = yyjson_doc_get_root(edoc);+ yyjson_val *error = yyjson_obj_get(outer, "isError");+ yyjson_val *content = yyjson_obj_get(outer, "content");+ yyjson_val *item0 = content && yyjson_is_arr(content) ? yyjson_arr_get(content, 0) : NULL;+ const char *inner = ha_obj_str(item0, "text");+ yyjson_doc *idoc = inner ? yyjson_read(inner, strlen(inner), 0) : NULL;+ if ((error && yyjson_is_true(error)) || !idoc) {+ if (idoc) {+ yyjson_doc_free(idoc);+ }+ yyjson_doc_free(edoc);+ break;+ }+ yyjson_val *root = yyjson_doc_get_root(idoc);+ yyjson_val *projects = yyjson_obj_get(root, "projects");+ if (!projects || !yyjson_is_arr(projects)) {+ yyjson_doc_free(idoc);+ yyjson_doc_free(edoc);+ break;}- size_t length = strlen(canonical_root);- if (length > best_length) {- best_name = name;- best_length = length;- snprintf(best_root, sizeof(best_root), "%s", canonical_root);++ size_t index;+ size_t maximum;+ yyjson_val *project;+ yyjson_arr_foreach(projects, index, maximum, project) {+ const char *name = ha_obj_str(project, "name");+ const char *project_root = ha_obj_str(project, "root_path");+ char canonical_root[4096];+ if (!name || !name[0] || !project_root || !project_root[0] ||+ !ha_canonical_path(project_root, canonical_root, sizeof(canonical_root)) ||+ !ha_path_contains(canonical_root, canonical_cwd)) {+ continue;+ }+ size_t length = strlen(canonical_root);+ if (length > best_length) {+ char *candidate = strdup(name);+ if (!candidate) {+ continue;+ }+ free(best_name);+ best_name = candidate;+ best_length = length;+ snprintf(best_root, sizeof(best_root), "%s", canonical_root);+ }+ }++ yyjson_val *has_more = yyjson_obj_get(root, "has_more");+ if (!has_more || !yyjson_is_bool(has_more)) {+ yyjson_doc_free(idoc);+ yyjson_doc_free(edoc);+ break;}+ bool more = yyjson_is_true(has_more);+ if (!more) {+ complete = true;+ yyjson_doc_free(idoc);+ yyjson_doc_free(edoc);+ break;+ }+ yyjson_val *next = yyjson_obj_get(root, "next_offset");+ int64_t next_offset = next && yyjson_is_int(next) ? yyjson_get_int(next) : -1;+ yyjson_doc_free(idoc);+ yyjson_doc_free(edoc);+ if (next_offset <= offset) {+ break;+ }+ offset = next_offset;}- char *result = best_name ? strdup(best_name) : NULL;- if (result && root_out && root_out_size > 0U) {++ if (!complete) {+ free(best_name);+ return NULL;+ }+ if (best_name && root_out && root_out_size > 0U) {int written = snprintf(root_out, root_out_size, "%s", best_root);if (written < 0 || (size_t)written >= root_out_size) {- free(result);- result = NULL;+ free(best_name);+ best_name = NULL;}}- yyjson_doc_free(doc);- return result;+ return best_name;}/* Return the nearest indexed graph project for cwd. Probe derived names first@@ -878,6 +971,7 @@ static char *ha_resolve_indexed_project_with_root(cbm_mcp_server_t *srv, const cif (doc && root) {yyjson_mut_doc_set_root(doc, root);yyjson_mut_obj_add_str(doc, root, "project", project);+ yyjson_mut_obj_add_str(doc, root, "format", "json");char *args = yyjson_mut_write(doc, 0, NULL);yyjson_mut_doc_free(doc);if (args) {diff --git a/src/cli/progress_sink.c b/src/cli/progress_sink.cindex 7f1e69425..23868f2b2 100644--- a/src/cli/progress_sink.c+++ b/src/cli/progress_sink.c@@ -31,6 +31,8 @@ static FILE *s_out;static atomic_int s_needs_newline;static int s_gbuf_nodes = NOT_SET;static int s_gbuf_edges = NOT_SET;+static CBMLogLevel s_previous_log_level = CBM_LOG_WARN;+static bool s_raised_log_level;static cbm_mutex_t s_sink_mutex;static atomic_int s_sink_mutex_state = ATOMIC_VAR_INIT(LOCK_UNINITIALIZED);@@ -184,6 +186,13 @@ void cbm_progress_sink_init(FILE *out) {atomic_store(&s_needs_newline, 0);s_gbuf_nodes = NOT_SET;s_gbuf_edges = NOT_SET;+ s_previous_log_level = cbm_log_get_level();+ s_raised_log_level = s_previous_log_level > CBM_LOG_INFO;+ if (s_raised_log_level) {+ /* Progress is an explicit INFO opt-in. The replacement sink below+ * keeps only recognized lifecycle events plus warnings/errors. */+ cbm_log_set_level(CBM_LOG_INFO);+ }cbm_log_set_sink(cbm_progress_sink_fn);cbm_mutex_unlock(&s_sink_mutex);}@@ -197,6 +206,10 @@ void cbm_progress_sink_fini(void) {(void)fflush(s_out);}s_out = NULL;+ if (s_raised_log_level) {+ cbm_log_set_level(s_previous_log_level);+ s_raised_log_level = false;+ }cbm_mutex_unlock(&s_sink_mutex);}@@ -338,6 +351,19 @@ static const event_handler_t handlers[] = {enum { HANDLER_COUNT = sizeof(handlers) / sizeof(handlers[0]) };+/* The progress sink replaces normal logger output. Preserve actionable+ * failures verbatim, but keep routine worker chatter out of the human progress+ * view. Logger callbacks do not include a trailing newline. */+static void passthrough_failure(const char *line) {+ flush_carriage();+ (void)fputs(line, s_out);+ size_t line_len = strlen(line);+ if (line_len == 0 || line[line_len - 1] != '\n') {+ (void)fputc('\n', s_out);+ }+ (void)fflush(s_out);+}+void cbm_progress_sink_fn(const char *line) {progress_sink_mutex_ensure();cbm_mutex_lock(&s_sink_mutex);@@ -345,6 +371,21 @@ void cbm_progress_sink_fn(const char *line) {cbm_mutex_unlock(&s_sink_mutex);return;}+ char level[CBM_SZ_32] = {0};+ if (!extract_kv(line, "level", level, (int)sizeof(level))) {+ cbm_mutex_unlock(&s_sink_mutex);+ return;+ }+ if (strcmp(level, "warn") == 0 || strcmp(level, "error") == 0) {+ passthrough_failure(line);+ cbm_mutex_unlock(&s_sink_mutex);+ return;+ }+ if (strcmp(level, "info") != 0) {+ cbm_mutex_unlock(&s_sink_mutex);+ return;+ }+char msg[CBM_SZ_64] = {0};if (!extract_kv(line, "msg", msg, (int)sizeof(msg))) {cbm_mutex_unlock(&s_sink_mutex);diff --git a/src/cypher/cypher.c b/src/cypher/cypher.cindex 0654cea70..0a0f60c1b 100644--- a/src/cypher/cypher.c+++ b/src/cypher/cypher.c@@ -7,6 +7,7 @@*/#include "cypher/cypher.h"#include "foundation/compat.h"+#include "foundation/constants.h"#include "store/store.h"#include "foundation/platform.h"#include "foundation/limits.h"@@ -2880,6 +2881,9 @@ static void rb_add_row(result_builder_t *rb, const char **values) {static _Thread_local uint64_t g_cypher_deadline_ms = 0; /* absolute; 0 = disarmed */static _Thread_local bool g_cypher_timed_out = false;+/* Sticky for one cbm_cypher_execute call. Unlike row_count, this survives caps+ * that happen before DISTINCT, aggregation, ORDER BY, or the final projection. */+static _Thread_local bool g_cypher_truncated = false;static _Thread_local int64_t g_cypher_deadline_override_ms = -1; /* test hook; <0 = default */static void cypher_deadline_arm(void) {@@ -3494,7 +3498,8 @@ static void rb_apply_order_by(result_builder_t *rb, const cbm_return_clause_t *r}}-static void rb_apply_skip_limit(result_builder_t *rb, int skip_n, int limit) {+static void rb_apply_skip_limit(result_builder_t *rb, int skip_n, int limit,+ bool limit_is_engine_budget) {/* Skip */if (skip_n > 0 && skip_n < rb->row_count) {for (int i = 0; i < skip_n; i++) {@@ -3516,6 +3521,9 @@ static void rb_apply_skip_limit(result_builder_t *rb, int skip_n, int limit) {}/* Limit */if (limit >= 0 && rb->row_count > limit) {+ if (limit_is_engine_budget) {+ g_cypher_truncated = true;+ }for (int i = limit; i < rb->row_count; i++) {for (int c = 0; c < rb->col_count; c++) {safe_str_free(&rb->rows[i][c]);@@ -3759,6 +3767,25 @@ static const char *project_item(binding_t *b, cbm_return_item_t *item, char *funif (is_scalar_value_func(item->func)) {return apply_string_func(item->func, raw, func_buf, buf_sz);}+ /* Direct node/edge fields live in the binding until this row has been+ * copied by rb_add_row. Keep those allocation-backed values intact: the+ * fixed per-column scratch buffer exists only to stabilize computed and+ * JSON-derived rotating-buffer values. Copying every value through it+ * silently clipped long qualified names and paths to 511 bytes before the+ * MCP response budget or prefix directory ever saw them. */+ for (int i = 0; raw && raw[0] && i < b->var_count; i++) {+ const cbm_node_t *node = &b->var_nodes[i];+ if (raw == node->project || raw == node->label || raw == node->name ||+ raw == node->qualified_name || raw == node->file_path || raw == node->properties_json) {+ return raw;+ }+ }+ for (int i = 0; raw && raw[0] && i < b->edge_var_count; i++) {+ const cbm_edge_t *edge = &b->edge_vars[i];+ if (raw == edge->project || raw == edge->type || raw == edge->properties_json) {+ return raw;+ }+ }/* Copy into the caller's per-column buffer. `raw` may point to node_prop's* rotating scratch buffer, which the next column's projection would overwrite* before rb_add_row copies the assembled row — aliasing every such column to@@ -4320,11 +4347,22 @@ static void execute_return_star(cbm_query_t *q, binding_t *bindings, int bind_coconst char *vars[CBM_SZ_32];int vc = collect_pattern_vars(q, vars, CBM_SZ_32);build_star_columns(rb, vars, vc);- for (int bi = 0; bi < bind_count && rb->row_count < max_rows; bi++) {+ int projection_cap = max_rows;+ bool cap_is_engine_budget = true;+ cbm_return_clause_t *ret = q->ret;+ if (ret && ret->limit >= 0 && ret->limit <= max_rows && !ret->distinct &&+ ret->order_key_count == 0 && ret->skip <= 0) {+ projection_cap = ret->limit;+ cap_is_engine_budget = false;+ }+ for (int bi = 0; bi < bind_count && rb->row_count < projection_cap; bi++) {const char *vals[CBM_SZ_128];project_star_row(&bindings[bi], vars, vc, vals);rb_add_row(rb, vals);}+ if (cap_is_engine_budget && bind_count > projection_cap) {+ g_cypher_truncated = true;+ }}/* Format an aggregate value into buf based on function name */@@ -4570,8 +4608,10 @@ static void build_return_columns(result_builder_t *rb, cbm_return_clause_t *ret)static void execute_return_simple(cbm_return_clause_t *ret, binding_t *bindings, int bind_count,int max_rows, result_builder_t *rb) {int proj_cap = max_rows;- if (ret->limit > 0 && !ret->distinct && ret->order_key_count == 0 && ret->skip <= 0) {+ bool cap_is_engine_budget = true;+ if (ret->limit >= 0 && !ret->distinct && ret->order_key_count == 0 && ret->skip <= 0) {proj_cap = ret->limit;+ cap_is_engine_budget = false;}for (int bi = 0; bi < bind_count && rb->row_count < proj_cap; bi++) {const char *vals[CBM_SZ_32];@@ -4582,6 +4622,9 @@ static void execute_return_simple(cbm_return_clause_t *ret, binding_t *bindings,}rb_add_row(rb, vals);}+ if (cap_is_engine_budget && bind_count > proj_cap) {+ g_cypher_truncated = true;+ }}/* Build default 3-column headers (name, qualified_name, label) per variable */@@ -4608,9 +4651,13 @@ static void execute_default_projection(cbm_pattern_t *pat0, binding_t *bindings,int max_rows, result_builder_t *rb) {const char *vars[CYP_MAX_VARS];int vc = 0;- for (int ni = 0; ni < pat0->node_count && vc < CYP_MAX_VARS; ni++) {+ for (int ni = 0; ni < pat0->node_count; ni++) {if (pat0->nodes[ni].variable) {- vars[vc++] = pat0->nodes[ni].variable;+ if (vc < CYP_MAX_VARS) {+ vars[vc++] = pat0->nodes[ni].variable;+ } else {+ g_cypher_truncated = true;+ }}}build_default_columns(rb, vars, vc);@@ -4625,6 +4672,9 @@ static void execute_default_projection(cbm_pattern_t *pat0, binding_t *bindings,}rb_add_row(rb, vals);}+ if (bind_count > max_rows) {+ g_cypher_truncated = true;+ }}/* Worst-case binding_t slot count for a node cross-join: one row per@@ -4917,7 +4967,9 @@ static void execute_return_clause(cbm_query_t *q, cbm_return_clause_t *ret, bindrb_apply_distinct(rb);}rb_apply_order_by(rb, ret);- rb_apply_skip_limit(rb, ret->skip, ret->limit >= 0 ? ret->limit : max_rows);+ bool limit_is_engine_budget = ret->limit < 0;+ rb_apply_skip_limit(rb, ret->skip, limit_is_engine_budget ? max_rows : ret->limit,+ limit_is_engine_budget);}static int execute_single(cbm_store_t *store, cbm_query_t *q, const char *project, int max_rows,@@ -5154,6 +5206,7 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projecmemset(out, 0, sizeof(*out));g_cypher_depth_clamped = 0;g_cypher_trail_truncated = 0;+ g_cypher_truncated = false;cypher_deadline_arm(); /* #601: start the wall-clock budget for this query */if (max_rows <= 0) {max_rows = CYPHER_RESULT_CEILING;@@ -5179,6 +5232,7 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projecif (execute_single(store, q, project, max_rows, &rb) < 0) {rb_free(&rb);cbm_query_free(q);+ out->truncated = g_cypher_truncated;out->error = heap_strdup("query aborted: out of memory or an allocation limit was reached");return CBM_NOT_FOUND;}@@ -5191,6 +5245,7 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projecrb_free(&rb);rb_free(&rb2);cbm_query_free(q);+ out->truncated = g_cypher_truncated;out->error =heap_strdup("query aborted: out of memory or an allocation limit was reached");return CBM_NOT_FOUND;@@ -5214,6 +5269,7 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projecif (g_cypher_timed_out) {rb_free(&rb);cbm_query_free(q);+ out->truncated = g_cypher_truncated;out->error =heap_strdup("query exceeded the execution time limit — narrow the pattern with a WHERE ""filter, use a directed MATCH instead of an unbounded OPTIONAL MATCH, or "@@ -5223,8 +5279,10 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projec/* Check ceiling */if (rb.row_count >= CYPHER_RESULT_CEILING) {+ g_cypher_truncated = true;rb_free(&rb);cbm_query_free(q);+ out->truncated = true;out->error = heap_strdup("result exceeded 100k rows — use narrower filters or add LIMIT");return CBM_NOT_FOUND;}@@ -5233,6 +5291,7 @@ int cbm_cypher_execute(cbm_store_t *store, const char *query, const char *projecout->col_count = rb.col_count;out->rows = rb.rows;out->row_count = rb.row_count;+ out->truncated = g_cypher_truncated || g_cypher_trail_truncated != 0;if (g_cypher_depth_clamped > 0 || g_cypher_trail_truncated) {char wbuf[CBM_SZ_256];if (g_cypher_depth_clamped > 0 && g_cypher_trail_truncated) {diff --git a/src/cypher/cypher.h b/src/cypher/cypher.hindex a1e4462ab..9e66b56ec 100644--- a/src/cypher/cypher.h+++ b/src/cypher/cypher.h@@ -321,6 +321,10 @@ typedef struct {/* rows[row_idx][col_idx] = string value */const char ***rows;int row_count;+ /* True when an internal row/candidate ceiling prevented exhaustive+ * evaluation. A Cypher LIMIT is part of query semantics and does not set+ * this flag by itself. */+ bool truncated;/* Non-NULL when the query was rejected (e.g. result too large) */char *error;/* Non-NULL advisory (caller-visible, not an error): e.g. a variable-diff --git a/src/foundation/log.c b/src/foundation/log.cindex 40c860f50..2179bfdcc 100644--- a/src/foundation/log.c+++ b/src/foundation/log.c@@ -23,7 +23,7 @@* Relaxed ordering is the right level: each is an independent scalar with no* happens-before relationship to publish alongside it, and the log path must* stay cheap enough that nobody is tempted to route around it. */-static _Atomic CBMLogLevel g_log_level = CBM_LOG_INFO;+static _Atomic CBMLogLevel g_log_level = CBM_LOG_WARN;static _Atomic CBMLogFormat g_log_format = CBM_LOG_FORMAT_TEXT;/* Cast, not bare NULL: NULL is ((void*)0) and the implicit void*-to-* function-pointer conversion is not a compile-time constant, whichdiff --git a/src/foundation/log.h b/src/foundation/log.hindex 6150d6ae5..ae85a3bce 100644--- a/src/foundation/log.h+++ b/src/foundation/log.h@@ -44,7 +44,7 @@ typedef enum {* unchanged. Call once at startup before any threads or log lines. */void cbm_log_init_from_env(void);-/* Set minimum log level (default: INFO). */+/* Set minimum log level (default: WARN; INFO is opt-in). */void cbm_log_set_level(CBMLogLevel level);/* Get current log level. */diff --git a/src/main.c b/src/main.cindex 30ba11a5a..ebb3de065 100644--- a/src/main.c+++ b/src/main.c@@ -6,6 +6,7 @@* cli <tool> <json> Run a single tool call and print result* --version Print version and exit* --help Print usage and exit+ * cli --verbose Include informational logs for one-shot commands* --ui=true/false Enable/disable HTTP UI server (persisted)* --port=N Set HTTP UI port (persisted, default 9749)* --tool-profile=analysis|scout Expose a restricted agent tool surface@@ -539,7 +540,11 @@ static bool client_start_parent_watchdog(pid_t initial_ppid) {/* ── CLI mode ───────────────────────────────────────────────────── */-#define CLI_USAGE "Usage: codebase-memory-mcp cli [--progress] [--json] <tool_name> [json_args]\n"+#define CLI_USAGE \+ "Usage: codebase-memory-mcp cli [--progress] [--verbose] [--json] <tool_name> [json_args]\n" \+ " --progress Show lifecycle progress even when stderr is redirected\n" \+ " --verbose Include informational logs (preserves CBM_LOG_LEVEL=debug)\n" \+ " --json Print the raw MCP result envelope\n"/* Extract text content from MCP tool result envelope and print it.* MCP results: {"content":[{"type":"text","text":"..."}],"isError":...}@@ -587,6 +592,24 @@ static bool cli_strip_flag(int *argc, char **argv, const char *flag) {return false;}+/* Outer CLI flags precede the tool name. Keep this distinct from+ * cli_strip_flag(): several MCP tools have their own `verbose` input, so+ * `cli index_status --verbose` must remain a tool argument while+ * `cli --verbose index_status` configures process logging. */+static bool cli_strip_outer_flag(int *argc, char **argv, const char *flag) {+ for (int i = 0; i < *argc && argv[i] && argv[i][0] == '-'; i++) {+ if (strcmp(argv[i], flag) != 0) {+ continue;+ }+ for (int j = i; j < *argc - SKIP_ONE; j++) {+ argv[j] = argv[j + SKIP_ONE];+ }+ (*argc)--;+ return true;+ }+ return false;+}+/* Strip a flag AND its following value from argv, returning the value (a pointer* into the original argv strings, valid for the process lifetime) or NULL if the* flag is absent. */@@ -669,6 +692,10 @@ static char *main_local_cli_daemon_execute(const char *tool_name, const char *arstatic int run_cli(int argc, char **argv, cbm_project_lock_manager_t *project_locks,main_local_maintenance_context_t *maintenance_context) {+ bool verbose_requested = cli_strip_outer_flag(&argc, argv, "--verbose");+ if (verbose_requested && cbm_log_get_level() > CBM_LOG_INFO) {+ cbm_log_set_level(CBM_LOG_INFO);+ }if (argc == 1 && argv && (strcmp(argv[0], "--help") == 0 || strcmp(argv[0], "-h") == 0)) {(void)fputs(CLI_USAGE, stdout);return 0;@@ -898,7 +925,7 @@ static void print_help(void) {printf("codebase-memory-mcp %s\n\n", CBM_VERSION);printf("Usage:\n");printf(" codebase-memory-mcp Run MCP server on stdio\n");- printf(" codebase-memory-mcp cli [--progress] [--json] <tool> [args]\n");+ printf(" codebase-memory-mcp cli [--progress] [--verbose] [--json] <tool> [args]\n");printf(" Run one tool locally, then exit\n");printf(" codebase-memory-mcp install [-y|-n] [--force] [--dry-run] ""[--dir=<path>] [--skip-config]\n");@@ -1610,9 +1637,10 @@ static char *main_local_cli_daemon_execute(const char *tool_name, const char *arreturn NULL;}if (bootstrap.daemon_spawned) {- (void)fprintf(stderr, "hint: this command started a temporary CBM daemon. "- "`codebase-memory-mcp daemon start` keeps one warm and removes this "- "startup cost from every CLI command.\n");+ /* Routine cold-start advice is informational. Default one-shot CLI+ * output stays pipe-clean; `cli --verbose ...` opts into this detail. */+ cbm_log_info("cli.daemon.spawned", "hint",+ "codebase-memory-mcp daemon start keeps one warm");}char session_root[MAIN_PATH_CAP];char allowed_root[MAIN_PATH_CAP];diff --git a/src/mcp/compact_out.c b/src/mcp/compact_out.cindex 2d8bef364..c18c474fc 100644--- a/src/mcp/compact_out.c+++ b/src/mcp/compact_out.c@@ -5,6 +5,7 @@#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <yyjson/yyjson.h>enum { SB_INITIAL_CAP = 1024 };@@ -296,3 +297,646 @@ void cbm_tree_cell_bool(cbm_sb_t *sb, bool v, bool first) {void cbm_tree_row_end(cbm_sb_t *sb) {cbm_sb_append_n(sb, "\n", 1);}++/* ── Response-local prefix directories ─────────────────────────── */++enum {+ TREE_PREFIX_MIN_LEN = 12,+ TREE_PREFIX_MIN_USES = 3,+ TREE_PREFIX_MIN_SAVING = 64,+ TREE_PREFIX_MIN_PERCENT = 15,+ TREE_PREFIX_MAX_REFS = 16,+ TREE_PREFIX_MAX_SEEDS = 1024,+ TREE_PREFIX_MAX_CANDIDATES = 512,+ TREE_PREFIX_MAX_CELLS = 8192,+ TREE_PREFIX_MAX_LEN = 16 * 1024,+};++typedef struct {+ char *text;+ size_t len;+ size_t uses;+ size_t score;+ int id;+ bool active;+} tree_prefix_candidate_t;++static bool tree_column_is_string(const bool *string_cols, int col) {+ return !string_cols || string_cols[col];+}++static bool tree_column_is_prefixable(const bool *string_cols, const bool *prefix_cols, int col) {+ return prefix_cols && prefix_cols[col] && tree_column_is_string(string_cols, col);+}++static void tree_render_table_direct(cbm_sb_t *sb, const char *key, int nrows,+ const char *const *cols, int ncols, const char *const *cells,+ const bool *string_cols) {+ cbm_tree_table_header(sb, key, nrows, cols, ncols);+ for (int row = 0; row < nrows; row++) {+ cbm_tree_row_begin(sb);+ for (int col = 0; col < ncols; col++) {+ const char *value = cells[(size_t)row * (size_t)ncols + (size_t)col];+ if (tree_column_is_string(string_cols, col)) {+ cbm_tree_cell_str(sb, value, col == 0);+ } else {+ if (col > 0) {+ cbm_sb_append_n(sb, " ", 1);+ }+ cbm_sb_append(sb, value ? value : "null");+ }+ }+ cbm_tree_row_end(sb);+ }+}++static int tree_string_ptr_compare(const void *left, const void *right) {+ const char *const *a = (const char *const *)left;+ const char *const *b = (const char *const *)right;+ return strcmp(*a, *b);+}++static int tree_prefix_score_compare(const void *left, const void *right) {+ const tree_prefix_candidate_t *a = (const tree_prefix_candidate_t *)left;+ const tree_prefix_candidate_t *b = (const tree_prefix_candidate_t *)right;+ if (a->score != b->score) {+ return a->score > b->score ? -1 : 1;+ }+ if (a->len != b->len) {+ return a->len > b->len ? -1 : 1;+ }+ return strcmp(a->text, b->text);+}++static bool tree_prefix_candidate_add(tree_prefix_candidate_t *candidates, int *count,+ const char *text, size_t len) {+ if (len < TREE_PREFIX_MIN_LEN || len > TREE_PREFIX_MAX_LEN) {+ return true;+ }+ for (int i = 0; i < *count; i++) {+ if (candidates[i].len == len && memcmp(candidates[i].text, text, len) == 0) {+ return true;+ }+ }+ if (*count >= TREE_PREFIX_MAX_CANDIDATES) {+ return true;+ }+ char *copy = (char *)malloc(len + 1);+ if (!copy) {+ return false;+ }+ memcpy(copy, text, len);+ copy[len] = '\0';+ candidates[*count].text = copy;+ candidates[*count].len = len;+ (*count)++;+ return true;+}++static size_t tree_semantic_prefix_boundary(const char *text, size_t shared) {+ size_t boundary = 0;+ for (size_t i = 0; i < shared; i++) {+ if (text[i] == '/' || text[i] == '\\' || text[i] == '.') {+ boundary = i + 1;+ } else if (text[i] == ':' && i + 1 < shared && text[i + 1] == ':') {+ boundary = i + 2;+ i++;+ }+ }+ return boundary;+}++static bool tree_prefix_matches(const char *value, const tree_prefix_candidate_t *candidate) {+ return value && !needs_quotes(value) && strlen(value) >= candidate->len &&+ memcmp(value, candidate->text, candidate->len) == 0;+}++static int tree_prefix_choice(const char *value, const tree_prefix_candidate_t *candidates,+ int selected_count, bool active_only) {+ int choice = -1;+ size_t longest = 0;+ for (int i = 0; i < selected_count; i++) {+ if ((active_only && !candidates[i].active) || !tree_prefix_matches(value, &candidates[i])) {+ continue;+ }+ if (candidates[i].len > longest) {+ choice = i;+ longest = candidates[i].len;+ }+ }+ return choice;+}++/* Unquoted @N+suffix is reserved for a directory reference whenever a table+ * has a sibling <key>_refs table. Quote matching literals so a decoder can+ * always distinguish data from an encoded reference. */+static bool tree_looks_like_prefix_ref(const char *value) {+ if (!value || value[0] != '@' || !isdigit((unsigned char)value[1])) {+ return false;+ }+ const char *p = value + 2;+ while (isdigit((unsigned char)*p)) {+ p++;+ }+ return *p == '+';+}++static void tree_append_unambiguous_literal(cbm_sb_t *sb, const char *value) {+ if (tree_looks_like_prefix_ref(value)) {+ append_quoted(sb, value);+ } else {+ append_value(sb, value);+ }+}++static void tree_prefix_candidates_free(tree_prefix_candidate_t *candidates, int count) {+ for (int i = 0; i < count; i++) {+ free(candidates[i].text);+ }+}++static void tree_table_rows_impl(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells, const bool *string_cols,+ const bool *prefix_cols) {+ if (!sb || !key || !cols || !cells || nrows < TREE_PREFIX_MIN_USES || ncols < 1 ||+ !prefix_cols || (size_t)nrows > (size_t)-1 / (size_t)ncols) {+ if (sb && key && cols && cells && nrows >= 0 && ncols >= 0) {+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ }+ return;+ }++ size_t cell_count = (size_t)nrows * (size_t)ncols;+ if (cell_count > TREE_PREFIX_MAX_CELLS) {+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }++ const char **seeds = (const char **)malloc(sizeof(*seeds) * TREE_PREFIX_MAX_SEEDS);+ tree_prefix_candidate_t *candidates =+ (tree_prefix_candidate_t *)calloc(TREE_PREFIX_MAX_CANDIDATES, sizeof(*candidates));+ if (!seeds || !candidates) {+ free(seeds);+ free(candidates);+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }++ int seed_count = 0;+ for (size_t i = 0; i < cell_count && seed_count < TREE_PREFIX_MAX_SEEDS; i++) {+ int col = (int)(i % (size_t)ncols);+ if (!tree_column_is_prefixable(string_cols, prefix_cols, col)) {+ continue;+ }+ const char *value = cells[i];+ if (value && strlen(value) >= TREE_PREFIX_MIN_LEN && !needs_quotes(value)) {+ seeds[seed_count++] = value;+ }+ }+ if (seed_count < TREE_PREFIX_MIN_USES) {+ free(seeds);+ free(candidates);+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }+ qsort(seeds, (size_t)seed_count, sizeof(*seeds), tree_string_ptr_compare);++ int candidate_count = 0;+ bool candidate_oom = false;+ for (int i = 1; i < seed_count && !candidate_oom; i++) {+ const char *left = seeds[i - 1];+ const char *right = seeds[i];+ size_t shared = 0;+ while (left[shared] && right[shared] && left[shared] == right[shared] &&+ shared < TREE_PREFIX_MAX_LEN) {+ shared++;+ }+ if (left[shared] == '\0' && right[shared] == '\0') {+ candidate_oom = !tree_prefix_candidate_add(candidates, &candidate_count, left, shared);+ }+ size_t boundary = tree_semantic_prefix_boundary(left, shared);+ if (!candidate_oom && boundary >= TREE_PREFIX_MIN_LEN) {+ candidate_oom =+ !tree_prefix_candidate_add(candidates, &candidate_count, left, boundary);+ }+ }+ free(seeds);+ if (candidate_oom || candidate_count == 0) {+ tree_prefix_candidates_free(candidates, candidate_count);+ free(candidates);+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }++ /* Score candidates independently first. The final byte-for-byte render+ * comparison below accounts for overlap and directory overhead exactly. */+ for (int i = 0; i < candidate_count; i++) {+ for (size_t cell = 0; cell < cell_count; cell++) {+ int col = (int)(cell % (size_t)ncols);+ if (tree_column_is_prefixable(string_cols, prefix_cols, col) &&+ tree_prefix_matches(cells[cell], &candidates[i])) {+ candidates[i].uses++;+ }+ }+ if (candidates[i].uses >= TREE_PREFIX_MIN_USES && candidates[i].len > 5) {+ size_t gross = candidates[i].uses * (candidates[i].len - 5);+ size_t entry_cost = candidates[i].len + 12;+ candidates[i].score = gross > entry_cost ? gross - entry_cost : 0;+ }+ }+ qsort(candidates, (size_t)candidate_count, sizeof(*candidates), tree_prefix_score_compare);++ int selected_count = 0;+ while (selected_count < candidate_count && selected_count < TREE_PREFIX_MAX_REFS &&+ candidates[selected_count].score > 0) {+ selected_count++;+ }+ if (selected_count == 0) {+ tree_prefix_candidates_free(candidates, candidate_count);+ free(candidates);+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }++ int active_count = 0;+ for (int i = 0; i < selected_count; i++) {+ /* Recompute the exclusive longest-prefix assignment without another+ * allocation; shorter overlapping candidates may become unused. */+ size_t exclusive_uses = 0;+ for (size_t cell = 0; cell < cell_count; cell++) {+ int col = (int)(cell % (size_t)ncols);+ if (tree_column_is_prefixable(string_cols, prefix_cols, col) &&+ tree_prefix_choice(cells[cell], candidates, selected_count, false) == i) {+ exclusive_uses++;+ }+ }+ candidates[i].active = exclusive_uses >= TREE_PREFIX_MIN_USES;+ if (candidates[i].active) {+ candidates[i].id = active_count++;+ }+ }+ if (active_count == 0) {+ tree_prefix_candidates_free(candidates, candidate_count);+ free(candidates);+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }++ size_t key_len = strlen(key);+ char *refs_key = (char *)malloc(key_len + sizeof("_refs"));+ char *rule_key = (char *)malloc(key_len + sizeof("_ref_rule"));+ if (!refs_key || !rule_key) {+ free(refs_key);+ free(rule_key);+ tree_prefix_candidates_free(candidates, candidate_count);+ free(candidates);+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ return;+ }+ snprintf(refs_key, key_len + sizeof("_refs"), "%s_refs", key);+ snprintf(rule_key, key_len + sizeof("_ref_rule"), "%s_ref_rule", key);++ cbm_sb_t plain;+ cbm_sb_init(&plain);+ tree_render_table_direct(&plain, key, nrows, cols, ncols, cells, string_cols);+ char *plain_text = cbm_sb_finish(&plain);++ cbm_sb_t compact;+ cbm_sb_init(&compact);+ const char *ref_cols[] = {"id", "prefix"};+ cbm_tree_table_header(&compact, refs_key, active_count, ref_cols, 2);+ for (int i = 0; i < selected_count; i++) {+ if (!candidates[i].active) {+ continue;+ }+ cbm_tree_row_begin(&compact);+ cbm_tree_cell_int(&compact, candidates[i].id, true);+ cbm_sb_append_n(&compact, " ", 1);+ /* Directories are declarations, never recursively expanded refs. Quote+ * a ref-looking prefix anyway so a simple decoder cannot mistake it+ * for another directory entry. */+ tree_append_unambiguous_literal(&compact, candidates[i].text);+ cbm_tree_row_end(&compact);+ }+ cbm_tree_scalar_str(&compact, rule_key, "@N+suffix=prefix+suffix");+ cbm_tree_table_header(&compact, key, nrows, cols, ncols);+ for (int row = 0; row < nrows; row++) {+ cbm_tree_row_begin(&compact);+ for (int col = 0; col < ncols; col++) {+ if (col > 0) {+ cbm_sb_append_n(&compact, " ", 1);+ }+ const char *value = cells[(size_t)row * (size_t)ncols + (size_t)col];+ bool string_cell = tree_column_is_string(string_cols, col);+ int choice = tree_column_is_prefixable(string_cols, prefix_cols, col)+ ? tree_prefix_choice(value, candidates, selected_count, true)+ : -1;+ if (choice >= 0) {+ char ref[24];+ snprintf(ref, sizeof(ref), "@%d+", candidates[choice].id);+ cbm_sb_append(&compact, ref);+ cbm_sb_append(&compact, value + candidates[choice].len);+ } else if (string_cell) {+ tree_append_unambiguous_literal(&compact, value);+ } else {+ cbm_sb_append(&compact, value ? value : "null");+ }+ }+ cbm_tree_row_end(&compact);+ }+ char *compact_text = cbm_sb_finish(&compact);++ bool use_compact = false;+ if (plain_text && compact_text) {+ size_t plain_len = strlen(plain_text);+ size_t compact_len = strlen(compact_text);+ size_t saving = plain_len > compact_len ? plain_len - compact_len : 0;+ use_compact =+ saving >= TREE_PREFIX_MIN_SAVING && saving * 100 >= plain_len * TREE_PREFIX_MIN_PERCENT;+ }+ if (use_compact) {+ cbm_sb_append(sb, compact_text);+ } else if (plain_text) {+ cbm_sb_append(sb, plain_text);+ } else {+ tree_render_table_direct(sb, key, nrows, cols, ncols, cells, string_cols);+ }++ free(plain_text);+ free(compact_text);+ free(refs_key);+ free(rule_key);+ tree_prefix_candidates_free(candidates, candidate_count);+ free(candidates);+}++void cbm_tree_table_rows_typed(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells, const bool *string_cols) {+ tree_table_rows_impl(sb, key, nrows, cols, ncols, cells, string_cols, NULL);+}++void cbm_tree_table_rows(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells) {+ tree_table_rows_impl(sb, key, nrows, cols, ncols, cells, NULL, NULL);+}++void cbm_tree_table_rows_profiled(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells, const bool *string_cols,+ const bool *prefix_cols) {+ tree_table_rows_impl(sb, key, nrows, cols, ncols, cells, string_cols, prefix_cols);+}++/* ── Generic JSON projection ────────────────────────────────────── */++enum { JSON_TREE_MAX_DEPTH = 32 };++static void json_tree_indent(cbm_sb_t *sb, int depth) {+ for (int i = 0; i < depth; i++) {+ cbm_sb_append_n(sb, " ", 2);+ }+}++/* Source and Markdown lose substantial model utility when every newline is+ * 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);+ 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;+ for (;;) {+ const char *newline = strchr(line, '\n');+ const char *end = newline ? newline : line + strlen(line);+ json_tree_indent(sb, depth + 1);+ for (const char *p = line; p < end; p++) {+ unsigned char c = (unsigned char)*p;+ if (c == '\t' || (c >= 0x20 && c != 0x7f && c < 0x80)) {+ cbm_sb_append_n(sb, p, 1);+ } else if (c >= 0x80) {+ size_t sequence = utf8_sequence_length((const unsigned char *)p);+ if (sequence && p + sequence <= end) {+ cbm_sb_append_n(sb, p, sequence);+ p += sequence - 1;+ } else {+ cbm_sb_append_n(sb, "\xEF\xBF\xBD", 3);+ }+ } else {+ char escaped[8];+ snprintf(escaped, sizeof(escaped), "\\u%04x", (unsigned)c);+ cbm_sb_append(sb, escaped);+ }+ }+ cbm_sb_append_n(sb, "\n", 1);+ if (!newline) {+ break;+ }+ line = newline + 1;+ if (*line == '\0') {+ break;+ }+ }+}++static void json_tree_scalar(cbm_sb_t *sb, yyjson_val *value) {+ if (yyjson_is_str(value)) {+ append_value(sb, yyjson_get_str(value));+ } else if (yyjson_is_bool(value)) {+ cbm_sb_append(sb, yyjson_get_bool(value) ? "true" : "false");+ } else if (yyjson_is_null(value)) {+ cbm_sb_append(sb, "null");+ } else if (yyjson_is_num(value)) {+ char *encoded = yyjson_val_write(value, 0, NULL);+ cbm_sb_append(sb, encoded ? encoded : "null");+ free(encoded);+ } else {+ char *encoded = yyjson_val_write(value, 0, NULL);+ append_value(sb, encoded ? encoded : "null");+ free(encoded);+ }+}++static bool json_tree_array_is_object_table(yyjson_val *array, yyjson_val **first_out) {+ if (!array || !first_out) {+ return false;+ }+ size_t count = yyjson_arr_size(array);+ if (count == 0) {+ return false;+ }+ yyjson_val *first = yyjson_arr_get_first(array);+ if (!first || !yyjson_is_obj(first) || yyjson_obj_size(first) == 0) {+ return false;+ }+ size_t expected = yyjson_obj_size(first);+ size_t index;+ size_t maximum;+ yyjson_val *item;+ yyjson_arr_foreach(array, index, maximum, item) {+ if (!yyjson_is_obj(item) || yyjson_obj_size(item) != expected) {+ return false;+ }+ size_t key_index;+ size_t key_maximum;+ 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))) {+ return false;+ }+ }+ }+ *first_out = first;+ return true;+}++static void json_tree_value(cbm_sb_t *sb, const char *key_name, 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) {+ if (!sb || !key_name || !array || !first) {+ return;+ }+ json_tree_indent(sb, depth);+ cbm_sb_append(sb, key_name);+ char count[48];+ snprintf(count, sizeof(count), ": %zu (cols:", yyjson_arr_size(array));+ cbm_sb_append(sb, count);++ size_t key_index;+ size_t key_maximum;+ yyjson_val *column;+ yyjson_val *unused;+ yyjson_obj_foreach(first, key_index, key_maximum, column, unused) {+ cbm_sb_append_n(sb, " ", 1);+ cbm_sb_append(sb, yyjson_get_str(column));+ }+ cbm_sb_append_n(sb, ")\n", 2);++ size_t row_index;+ size_t row_maximum;+ yyjson_val *row;+ yyjson_arr_foreach(array, row_index, row_maximum, row) {+ json_tree_indent(sb, depth + 1);+ bool first_cell = true;+ yyjson_obj_foreach(first, key_index, key_maximum, column, unused) {+ if (!first_cell) {+ cbm_sb_append_n(sb, " ", 1);+ }+ yyjson_val *cell = yyjson_obj_get(row, yyjson_get_str(column));+ json_tree_scalar(sb, cell);+ first_cell = false;+ }+ cbm_sb_append_n(sb, "\n", 1);+ }+}++static void json_tree_array(cbm_sb_t *sb, const char *key_name, 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);+ return;+ }++ json_tree_indent(sb, depth);+ cbm_sb_append(sb, key_name);+ char count[48];+ snprintf(count, sizeof(count), ": %zu\n", yyjson_arr_size(array));+ cbm_sb_append(sb, count);+ size_t index;+ size_t maximum;+ yyjson_val *item;+ yyjson_arr_foreach(array, index, maximum, item) {+ if (yyjson_is_obj(item)) {+ json_tree_indent(sb, depth + 1);+ cbm_sb_append(sb, "-\n");+ size_t field_index;+ size_t field_maximum;+ 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);+ }+ } else if (yyjson_is_arr(item)) {+ json_tree_value(sb, "-", item, depth + 1);+ } else {+ json_tree_indent(sb, depth + 1);+ cbm_sb_append(sb, "- ");+ json_tree_scalar(sb, item);+ cbm_sb_append_n(sb, "\n", 1);+ }+ }+}++static void json_tree_value(cbm_sb_t *sb, const char *key_name, yyjson_val *value, int depth) {+ if (depth >= JSON_TREE_MAX_DEPTH) {+ json_tree_indent(sb, depth);+ cbm_sb_append(sb, key_name);+ cbm_sb_append(sb, ": ");+ char *encoded = yyjson_val_write(value, 0, NULL);+ append_value(sb, encoded ? encoded : "null");+ free(encoded);+ cbm_sb_append_n(sb, "\n", 1);+ return;+ }+ if (yyjson_is_obj(value)) {+ json_tree_indent(sb, depth);+ cbm_sb_append(sb, key_name);+ 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);+ }+ } else if (yyjson_is_arr(value)) {+ json_tree_array(sb, key_name, value, depth);+ } else if (yyjson_is_str(value) &&+ (strchr(yyjson_get_str(value), '\n') || strchr(yyjson_get_str(value), '\r'))) {+ json_tree_indent(sb, depth);+ cbm_sb_append(sb, key_name);+ cbm_sb_append(sb, ": ");+ json_tree_block_string(sb, yyjson_get_str(value), depth);+ } else {+ json_tree_indent(sb, depth);+ cbm_sb_append(sb, key_name);+ cbm_sb_append(sb, ": ");+ json_tree_scalar(sb, value);+ cbm_sb_append_n(sb, "\n", 1);+ }+}++char *cbm_json_to_tree(const char *json) {+ if (!json) {+ return NULL;+ }+ yyjson_doc *document = yyjson_read(json, strlen(json), 0);+ if (!document) {+ return NULL;+ }+ yyjson_val *root = yyjson_doc_get_root(document);+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ if (yyjson_is_obj(root)) {+ size_t index;+ size_t maximum;+ yyjson_val *key;+ yyjson_val *value;+ yyjson_obj_foreach(root, index, maximum, key, value) {+ json_tree_value(&sb, yyjson_get_str(key), value, 0);+ }+ } else if (yyjson_is_arr(root)) {+ json_tree_array(&sb, "items", root, 0);+ } else {+ cbm_sb_append(&sb, "value: ");+ json_tree_scalar(&sb, root);+ cbm_sb_append_n(&sb, "\n", 1);+ }+ yyjson_doc_free(document);+ return cbm_sb_finish(&sb);+}diff --git a/src/mcp/compact_out.h b/src/mcp/compact_out.hindex 7ebb404b1..6706e2086 100644--- a/src/mcp/compact_out.h+++ b/src/mcp/compact_out.h@@ -51,4 +51,27 @@ void cbm_tree_cell_real(cbm_sb_t *sb, double v, bool first);void cbm_tree_cell_bool(cbm_sb_t *sb, bool v, bool first);void cbm_tree_row_end(cbm_sb_t *sb);+/* Emit a flat string table without abbreviating cell values. `cells` is+ * row-major with nrows*ncols entries. */+void cbm_tree_table_rows(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells);++/* Mixed string/literal variant. Literal columns (numbers/booleans) retain+ * their unquoted types. NULL string_cols means every column is a string. */+void cbm_tree_table_rows_typed(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells, const bool *string_cols);++/* Semantic prefix-directory variant. Only columns explicitly marked in+ * prefix_cols may be factored, so labels, diagnostics, and arbitrary query+ * strings are never rewritten. The directory activates only when it saves at+ * least 15% and 64 bytes. */+void cbm_tree_table_rows_profiled(cbm_sb_t *sb, const char *key, int nrows, const char *const *cols,+ int ncols, const char *const *cells, const bool *string_cols,+ const bool *prefix_cols);++/* Convert an arbitrary JSON value to the compact tree representation used by+ * lean MCP responses. Homogeneous object arrays become header-once tables;+ * nested values remain lossless JSON cells. Returns a heap string. */+char *cbm_json_to_tree(const char *json);+#endif /* CBM_MCP_COMPACT_OUT_H */diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 50adb6d4e..43936b0b5 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -41,6 +41,11 @@ enum {MCP_COMPARE_DEFAULT_SCAN_LIMIT = 2000000,MCP_COMPARE_MAX_SCAN_LIMIT = 10000000,MCP_COMPARE_SET_BYTE_BUDGET = 512 * 1024,+ MCP_QUERY_MAX_VISIBLE_ROWS = 99998,+ /* max_output_tokens is model-neutral sizing guidance, not a tokenizer+ * promise. The actual cross-platform contract is this deterministic UTF-8+ * byte ceiling, applied only at whole semantic-unit boundaries. */+ MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE = 4,};#define MCP_MS_TO_US 1000LL#define MCP_S_TO_US 1000000LL@@ -382,117 +387,51 @@ typedef struct {static const tool_def_t TOOLS[] = {{"index_repository", "Index repository",- "Index a repository into the knowledge graph. "- "Special mode 'cross-repo-intelligence': skip extraction, only match Routes/Channels "- "across projects to create CROSS_HTTP_CALLS/CROSS_ASYNC_CALLS/CROSS_CHANNEL edges. "- "Requires target_projects param. Ensure target projects have fresh indexes first. "- "COVERAGE: the response reports files that were NOT fully indexed — 'skipped' (not "- "indexed at all: oversized/read/parse failures) and 'parse_partial' (indexed, but "- "constructs inside the listed line ranges could not be parsed and MAY be missing from "- "the graph). The embedded lists carry counts plus a FEW EXAMPLES only; the complete "- "lists are in the per-run 'logfile' (path in the response) and queryable any time via "- "index_status or structurally via query_graph(graph=\"missed\"). Both signals are "- "best-effort: absence of a flag is NOT a completeness guarantee; prefer grep inside "- "flagged ranges. Separately, 'excluded' + 'not_indexed_files' list what was "- "deliberately NOT indexed (gitignore/.cbmignore/skip-lists) — by design, not failures.",+ "Index a repository. full/moderate add semantic edges; fast omits them; "+ "cross-repo-intelligence links indexed services. Results summarize coverage gaps.","{\"type\":\"object\",\"properties\":{\"repo_path\":{\"type\":\"string\",\"description\":"- "\"Path to the repository\"},"+ "\"Repository path\"},""\"mode\":{\"type\":\"string\",""\"enum\":[\"full\",\"moderate\",\"fast\",\"cross-repo-intelligence\"],"- "\"default\":\"full\",\"description\":\"All modes run type-aware LSP call/usage "- "resolution (per-file + cross-file). full: all files + similarity/semantic edges. "- "moderate: filtered files + similarity/semantic. fast: filtered files, no "- "similarity/semantic. cross-repo-intelligence: match Routes/Channels across projects.\"},"+ "\"default\":\"full\",\"description\":\"full: all files+semantic; moderate: "+ "filtered+semantic; "+ "fast: filtered without semantic; cross-repo-intelligence: link services.\"},""\"target_projects\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"- "\"description\":\"Projects to search for cross-repo links (cross-repo-intelligence mode). "- "Use [\\\"*\\\"] for all indexed projects. Run list_projects to see available projects.\"},"+ "\"description\":\"Cross-repo targets; [\\\"*\\\"] means all.\"},""\"name\":{\"type\":\"string\",\"description\":"- "\"Override the derived project name. Non-ASCII bytes are encoded and unsafe path characters "- "are normalized.\"},"+ "\"Project-name override; Non-ASCII bytes are encoded and unsafe characters normalized.\"},""\"persistence\":{\"type\":\"boolean\",\"default\":false,\"description\":"- "\"Write compressed artifact to .codebase-memory/graph.db.zst for team sharing. "- "Teammates can bootstrap from the artifact instead of full re-indexing.\"}"+ "\"Write .codebase-memory/graph.db.zst.\"}""},\"required\":[\"repo_path\"]}"},{"search_graph", "Search graph",- "Search the code knowledge graph for functions, classes, routes, and variables. Use INSTEAD "- "OF grep/glob when finding code definitions, implementations, or relationships. Three search "- "modes: (1) query='update settings' for BM25 ranked full-text search with camelCase "- "splitting and structural label boosting — recommended for natural-language discovery; "- "(2) name_pattern='.*regex.*' for exact pattern matching; (3) semantic_query=[...] for "- "vector cosine search that bridges vocabulary (finds 'publish' when you search 'send'). "- "The three modes are independent and can be combined in a single call. "- "RESPONSE: prefix-grouped tree rows by default — a shared (qn-prefix, file) group "- "header printed once, then `name label lines in out` per row (full qn = group prefix "- "+ dot + name). in/out = selected degree across CALLS, USAGE, CALL_REFERENCE, "- "INHERITS, and IMPLEMENTS; other edge types are excluded. These are NOT caller/callee "- "counts — use trace_path for callers. Add per-node "- "property columns via "- "fields (e.g. [\"complexity\",\"signature\",\"docstring\"]); format=\"json\" returns "- "the SAME tree model as structured JSON. "- "PAGINATION: results are capped at limit (default 50). The response always includes "- "'total' (full match count before limit) and 'has_more' (true when total > "- "offset+returned). Detect truncation with has_more, then page by re-calling with "- "offset=offset+limit until has_more is false. Narrow first via label/file_pattern/"- "min_degree before paginating large result sets.",+ "Search: BM25 query, regex name/qn, or vector semantic_query. Regex rows keep "+ "qn/file/lines and in/out over CALLS, USAGE, CALL_REFERENCE, INHERITS, IMPLEMENTS. "+ "Defaults: the smaller lossless direct/grouped tree, limit 50, ~3200 tokens (4x byte cap). "+ "Page with offset; detail=ids is qn-only.","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},"- "\"query\":{\"type\":\"string\",\"description\":\"Natural-language or keyword full-text "- "search using BM25 ranking. Tokens are split on whitespace; camelCase identifiers are "- "indexed as individual words (updateCloudClient → update, cloud, client). Results are "- "ranked with structural boosting: Functions/Methods +10, Routes +8, Classes/Interfaces +5. "- "Noise labels (File/Folder/Module/Variable) are filtered out. When provided, name_pattern "- "is ignored.\"},"+ "\"query\":{\"type\":\"string\"},""\"label\":{\"type\":\"string\"},\"name_pattern\":{\"type\":\"string\"},\"qn_pattern\":{""\"type\":\"string\"},\"file_pattern\":{\"type\":\"string\"},""\"relationship\":{\"type\":\"string\"},\"min_degree\":{\"type\":\"integer\"},""\"max_degree\":{\"type\":\"integer\"},\"exclude_entry_points\":{\"type\":\"boolean\"},""\"include_connected\":{\"type\":\"boolean\"},\"semantic_query\":{"- "\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"MUST be an ARRAY of "- "keyword strings (e.g. [\\\"send\\\",\\\"pubsub\\\",\\\"publish\\\"]) — NOT a single string. "- "Each keyword is scored independently via per-keyword min-cosine; results reflect functions "- "that score well on ALL keywords. Requires moderate/full index mode. Results appear in the "- "'semantic_results' field (separate from 'results').\"},\"limit\":{\"type\":"- "\"integer\",\"description\":\"Max results per call. Default 50. Response carries "- "'total' (full match count) and 'has_more' (true if truncated) so callers can "- "detect the limit and paginate.\"},\"offset\":{\"type\":\"integer\",\"default\":0,"- "\"description\":\"Skip the first N matching nodes. Combine with 'limit' to page: "- "increment offset by limit and re-call while has_more is true.\"},"- "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\","- "\"description\":\"Response encoding. tree (default): prefix-grouped text rows. "- "json: the SAME tree model as structured JSON (groups + column-ordered row arrays).\"},"- "\"fields\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":"- "\"Extra per-node property columns, e.g. complexity, cognitive, "- "signature, docstring, return_type, is_test, lines(int). Core row columns "- "(qn/label/file/lines/in/out) are always present — do not request them here. "- "Missing values emit as empty cells.\"},"- "\"detail\":{\"type\":\"string\",\"enum\":[\"ids\",\"default\"],\"default\":\"default\","- "\"description\":\"ids: bare qualified-name enumeration (one column) — cheapest form "- "for wide sweeps where per-row metadata is noise. default: full rows.\"}},"+ "\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"limit\":{\"type\":"+ "\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"+ "\"offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"max_output_tokens\":{\"type\":\"integer\",\"default\":3200,\"minimum\":128,"+ "\"maximum\":1000000},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"]},"+ "\"fields\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},"+ "\"detail\":{\"type\":\"string\",\"enum\":[\"ids\",\"default\"]}},""\"required\":[\"project\"]}"},{"query_graph", "Query graph",- "Execute a Cypher query against the knowledge graph for complex multi-hop patterns, "- "aggregations, and cross-service analysis. The response includes 'total' (returned "- "row count). There is a hard 100k row ceiling — for broad queries add LIMIT in the "- "Cypher itself or use search_graph + offset/limit pagination instead. "- "COMPLEXITY / BOTTLENECKS: every Function and Method node carries queryable complexity "- "properties — cyclomatic (complexity), cognitive, loop_count, loop_depth (max nested-loop "- "depth, a polynomial-degree proxy), plus interprocedural transitive_loop_depth (worst-case "- "nested-loop degree propagated along CALLS edges) and a recursive flag. Additional "- "hot-path signals: linear_scan_in_loop (count of find/contains/indexOf-style scans inside a "- "loop — the hidden O(n^2) that loop_depth misses), alloc_in_loop (allocations/appends inside "- "a loop), recursion_in_loop (a self-call inside a loop), unguarded_recursion (recursion with "- "no conditionally-guarded base case), param_count and max_access_depth (structure smells). "- "Find all hot-path candidates in one query, e.g. MATCH (f:Function) WHERE "- "f.transitive_loop_depth >= 3 OR f.linear_scan_in_loop >= 1 RETURN f.qualified_name, "- "f.transitive_loop_depth, f.linear_scan_in_loop ORDER BY f.transitive_loop_depth DESC. "- "MISSED GRAPH: pass graph=\"missed\" to query the best-effort miss graph instead — the "- "file structure of ONLY the files the indexer could NOT fully index (Project → Folder → "- "File nodes with CONTAINS_FOLDER/CONTAINS_FILE edges; each File carries kind "- "(\"parse_partial\" = indexed but constructs in the flagged line ranges MAY be missing; "- "or a skip phase) and detail (the line ranges / reason)). Example: MATCH (f:File) WHERE "- "f.kind = \\\"parse_partial\\\" RETURN f.file_path, f.detail. Absence from this graph is "- "NOT a completeness guarantee.",+ "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.","{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"Cypher ""query\"},\"project\":{\"type\":\"string\"},""\"graph\":{\"type\":\"string\",\"enum\":[\"code\",\"missed\"],\"default\":\"code\","@@ -500,63 +439,71 @@ static const tool_def_t TOOLS[] = {"missed graph (only files not fully indexed, laid out as their file structure).\"},""\"max_rows\":{\"type\":\"integer\",""\"description\":"- "\"Optional row limit. Default: unlimited up to a 100k row "- "ceiling. No offset support — use search_graph for paginated browsing.\"}},"+ "\"Visible row budget (default 200; max 99998). Zero preserves the legacy maximum "+ "window. This never changes query evaluation.\",\"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.\"},"+ "\"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.\"},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\","+ "\"description\":\"tree may encode repeated prefixes with a local @N+suffix directory; "+ "json keeps direct strings.\"}},""\"required\":[\"query\",\"project\"]}"},{"trace_path", "Trace path",- "Trace paths through the code graph. Modes: calls (callers/callees), data_flow (value "- "propagation with args at each hop), cross_service (through HTTP/async Route nodes). "- "Use INSTEAD OF grep for callers, dependencies, impact analysis, or data flow tracing. "- "RESPONSE: prefix-grouped tree rows — callees/callers grouped under their shared "- "qn-prefix, `name hop` per row (full qn = group prefix + dot + name); exact "- "callees_total/callers_total on every page = ALL nodes reachable within depth (transitive, "- "not just direct; test files excluded unless include_tests). risk/args flags use a flat "- "table. "- "`truncated: true` + `next` = more rows — pass next back as cursor. "- "format=\"json\" returns the SAME tree model as structured JSON.",+ "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.","{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"project\":{""\"type\":\"string\"},\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\","- "\"both\"],\"default\":\"both\"},\"depth\":{\"type\":\"integer\",\"default\":3},"+ "\"both\"],\"default\":\"both\"},\"depth\":{\"type\":\"integer\",\"default\":3,"+ "\"minimum\":1,\"maximum\":15},""\"limit\":{\"type\":\"integer\",\"default\":100,\"minimum\":1,\"maximum\":5000,"- "\"description\":\"Rows per page. callees_total/callers_total always carry the exact full "- "counts; when a page is truncated the response carries next — see cursor.\"},"- "\"cursor\":{\"type\":\"string\",\"description\":\"Resume token from a previous response's "- "'next' field. Pass it back with ALL other arguments identical to get the following page "- "with no duplicates. Cursors outlive nothing: after a reindex you get a stale_cursor error "- "— just re-run the original query.\"},\"mode\":{"+ "\"description\":\"Visible rows per page; a gte relation 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.\"},"+ "\"mode\":{""\"type\":\"string\",\"enum\":[\"calls\",\"data_flow\",\"cross_service\"],\"default\":"- "\"calls\",\"description\":\"calls: follow CALLS edges. data_flow: follow CALLS+DATA_FLOWS "- "with arg expressions. cross_service: follow HTTP_CALLS+ASYNC_CALLS+DATA_FLOWS through "- "Routes, plus CROSS_* cross-repo edges (CROSS_HTTP_CALLS/ASYNC_CALLS/CHANNEL/GRPC_CALLS/"- "GRAPHQL_CALLS/TRPC_CALLS) to hop into other services.\"},\"parameter_name\":{\"type\":"- "\"string\",\"description\":\"For data_flow mode: "- "scope trace to a specific parameter name\"},\"edge_types\":{\"type\":\"array\",\"items\":{"+ "\"calls\",\"description\":\"calls, argument-aware data_flow, or service-boundary 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 risk classification (CRITICAL/HIGH/MEDIUM/LOW) based on hop distance"- "\"},\"include_tests\":{\"type\":\"boolean\",\"default\":false,"- "\"description\":\"Include test files in results. When false (default), test files are "- "filtered out. When true, test nodes are included with a test column/marker.\"},"+ "\"description\":\"Add hop-risk labels.\"},\"include_tests\":{\"type\":\"boolean\","+ "\"default\":false},""\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\","- "\"description\":\"Response encoding. tree (default): prefix-grouped text rows. "- "json: the SAME tree model as structured JSON (groups + column-ordered row arrays).\"},"+ "\"description\":\"tree chooses the smaller complete direct/grouped shape; json preserves "+ "a stable grouped table model.\"},""\"include_evidence\":{\"type\":\"boolean\",\"default\":false,"- "\"description\":\"Add how each hop was resolved: a strategy class (lsp | language_rule | "- "heuristic | unresolved) and the resolver's confidence. Off by default — it adds two "- "columns per row. Use it to judge whether an edge is trustworthy, not to find edges.\"}},"+ "\"description\":\"Add resolver class and confidence.\"}},""\"required\":[\"function_name\",\"project\"]}"},{"get_code_snippet", "Get code snippet",- "Read source code for a function/class/symbol. IMPORTANT: First call search_graph to find the "- "exact qualified_name, then pass it here. This is a read tool, not a search tool. Accepts "- "full qualified_name (exact match) or short function name (returns suggestions if ambiguous). "- "If the response carries a 'coverage_note', the file was only partially indexed — constructs "- "in the noted line ranges may be missing from the graph (best-effort signal); prefer grep "- "there and treat the returned source as ground truth.",+ "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.","{\"type\":\"object\",\"properties\":{\"qualified_name\":{\"type\":\"string\",\"description\":"- "\"Full qualified_name from search_graph, or short function name\"},\"project\":{"+ "\"Qualified name from search_graph, or short name.\"},\"project\":{""\"type\":\"string\"},\"include_neighbors\":{"- "\"type\":\"boolean\",\"default\":false}},\"required\":[\"qualified_name\",\"project\"]}"},+ "\"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.\"},"+ "\"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.\"},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"+ "\"required\":[\"qualified_name\",\"project\"]}"},{"get_file_outline", "Get file outline","Return a compact declaration outline for one exact repository-relative file. Results are "@@ -574,8 +521,12 @@ static const tool_def_t TOOLS[] = {"\"required\":[\"project\",\"file_path\"]}"},{"get_graph_schema", "Get graph schema",- "Get the schema of the knowledge graph (node labels, edge types)",- "{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["+ "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\"},"+ "\"diagnostics\":{\"type\":\"string\",\"enum\":[\"none\",\"full\"],\"default\":\"none\"},"+ "\"limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"+ "\"offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0}},\"required\":[""\"project\"]}"},{"compare_graphs", "Compare graphs",@@ -592,14 +543,9 @@ static const tool_def_t TOOLS[] = {"\"additionalProperties\":false}"},{"get_architecture", "Get architecture",- "Get high-level architecture overview. DEFAULT (no aspects) is a compact summary — "- "overview counts, languages, packages, entry_points; request more via aspects:[...] "- "(structure, dependencies, routes, hotspots, boundaries, layers, clusters, file_tree) or "- "[\"all\"]. 'clusters' runs Leiden community detection over the call/import graph, "- "surfacing the de-facto modules (label, member count, cohesion score, representative "- "top_nodes, binding packages/edge_types) — the real architectural seams, which often cut "- "across the folder layout. Optional path scopes analysis to nodes under that directory "- "prefix (file_path).",+ "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.",/* 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. "@@ -609,134 +555,134 @@ static const tool_def_t TOOLS[] = {"\"entry_points\",\"hotspots\",\"boundaries\",\"layers\",\"file_tree\",\"clusters\",""\"cycles\"]},""\"description\":\"Aspects to include. 'all' = everything; 'overview' = compact summary "- "(all except file_tree); omit = all. 'cycles' is opt-in ONLY (never via all/overview): it "- "scans the whole call graph for circular CALLS dependencies (SCCs of size > 1).\"}},"+ "except file_tree; omit = languages/packages/entry_points. cycles is always opt-in.\"},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},""\"required\":[\"project\"]}"},{"search_code", "Search code",- "Graph-augmented code search. Finds text patterns via grep, then enriches results with "- "the knowledge graph: deduplicates matches into containing functions, ranks by structural "- "importance (definitions first, popular functions next, tests last). "- "Modes: compact (default, signatures only — token efficient), full (source capped at a "- "60-line window around the first match per hit; source_truncated marks the cut — use "- "get_code_snippet for the complete symbol), "- "files (just file paths). Use path_filter regex to scope results. "- "TRUNCATION: enriched results are capped at limit (default 10). Response carries "- "'total_grep_matches' (raw grep hit count) and 'total_results' (deduplicated function "- "count) — compare to limit to detect truncation. There is no offset parameter; to see "- "more, raise limit or narrow the query with file_pattern / path_filter.",+ "Graph-augmented text search. compact (default) returns ranked symbols; full adds bounded "+ "source; files returns paths. Narrow filters or raise limit when has_more.","{\"type\":\"object\",\"properties\":{\"pattern\":{\"type\":\"string\"},\"project\":{\"type\":""\"string\"},\"file_pattern\":{\"type\":\"string\",\"description\":\"Glob for grep ""--include (e.g. *.go)\"},\"path_filter\":{\"type\":\"string\",\"description\":\"Regex ""filter on result file paths (e.g. ^src/ or \\\\.(go|ts)$)\"},\"mode\":{\"type\":\"string\","- "\"enum\":[\"compact\",\"full\",\"files\"],\"default\":\"compact\",\"description\":\"compact: "- "signatures+metadata (default). full: with source. files: just file list.\"},"+ "\"enum\":[\"compact\",\"full\",\"files\"],\"default\":\"compact\",\"description\":\"compact "+ "rows; full bounded source; files paths.\"},""\"context\":{\"type\":\"integer\",\"description\":\"Lines of context around each match ""(like grep -C). Only used in compact mode.\"},""\"regex\":{\"type\":\"boolean\",\"default\":false},\"debug\":{\"type\":\"boolean\",""\"default\":false,\"description\":\"Include scope_ms, scan_ms, and enrich_ms phase timing ""diagnostics.\"},\"limit\":{\"type\":\"integer\","- "\"description\":\"Max enriched results per call. Default 10. Response includes "- "'total_grep_matches' and 'total_results' so callers can detect truncation. No "- "offset parameter — raise limit or narrow with file_pattern / path_filter to see more."- "\",\"default\":10,\"minimum\":1}},\"required\":[\"pattern\",\"project\"]}"},-- {"list_projects", "List projects", "List indexed projects with deterministic pagination",- "{\"type\":\"object\",\"properties\":{\"offset\":{\"type\":\"integer\","- "\"minimum\":0,\"default\":0},"- "\"limit\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100,\"default\":50},"+ "\"default\":10,\"minimum\":1,\"maximum\":500,\"description\":\"Ranked graph rows.\"},"+ "\"raw_limit\":{\"type\":\"integer\",\"default\":5,\"minimum\":0,\"maximum\":100,"+ "\"description\":\"Unclassified grep rows; set 0 to omit.\"},"+ "\"directory_limit\":{\"type\":\"integer\",\"default\":20,\"minimum\":0,"+ "\"maximum\":64,\"description\":\"Directory summary rows; set 0 to omit.\"},"+ "\"match_limit\":{\"type\":\"integer\",\"default\":8,\"minimum\":1,"+ "\"maximum\":500,\"description\":\"Locations per row; exact remainder in matches_omitted.\"},"+ "\"source_max_lines\":{\"type\":\"integer\",\"default\":20,\"minimum\":1,"+ "\"maximum\":200,\"description\":\"Per-result source window in full mode.\"},"+ "\"max_output_tokens\":{\"type\":\"integer\",\"minimum\":128,\"maximum\":1000000,"+ "\"description\":\"Approximate sizing; hard cap 4 UTF-8 bytes/token. Diagnostics yield "+ "before graph rows.\"},"+ "\"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.",+ "{\"type\":\"object\",\"properties\":{"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"},"+ "\"detail\":{\"type\":\"string\",\"enum\":[\"identity\",\"stats\"],"+ "\"default\":\"identity\",\"description\":\"stats adds node/edge/database-size counts.\"},""\"include_details\":{\"type\":\"boolean\",\"default\":false,"- "\"description\":\"Include branch, node/edge counts and database size. Slower.\"},"- "\"metadata_only\":{\"type\":\"boolean\",\"description\":\"Deprecated compatibility "- "alias for include_details=false.\"}}}"},+ "\"description\":\"Alias for detail=stats: include branch, node/edge counts and database "+ "size. Slower.\"},"+ "\"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","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":[""\"project\"]}"},{"index_status", "Index status",- "Get the indexing status of a project: node/edge counts, root path, git context, and the "- "indexing-COVERAGE report — which files the indexer could NOT fully cover (best-effort "- "signal): 'parse_partial' files WERE indexed but contain line ranges tree-sitter could not "- "parse — constructs there MAY be missing from the graph (some are still recovered); "- "'skipped' files were not indexed at all (oversized/read/parse failure). Use this before "- "trusting graph completeness on a file: if a file is listed, ALSO grep it (especially the "- "flagged ranges). IMPORTANT: absence from these lists is NOT a completeness guarantee — the "- "signal only marks what the indexer can detect. For structural queries over the misses use "- "query_graph(graph=\"missed\"). The report also carries 'not_indexed' — files/dirs excluded "- "BY DESIGN (gitignore/.cbmignore/skip-lists): deliberate and deterministic, not failures; "- "change the ignore rules and re-index to include them.",+ "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.","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},""\"verbose\":{\"type\":\"boolean\",\"default\":false,\"description\":\"Include the git ""context block (worktree/shadow path variants). Only needed when debugging where an index "- "lives — omitted by default to keep the status lean.\"}},\"required\":["+ "lives — omitted by default to keep the status lean.\"},"+ "\"diagnostics\":{\"type\":\"string\",\"enum\":[\"none\",\"summary\",\"full\"],"+ "\"default\":\"none\",\"description\":\"Coverage rows: counts only, five samples, or up to "+ "500.\"},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"+ "\"required\":[""\"project\"]}"},{"check_index_coverage", "Check index coverage",- "Check authoritative indexing-coverage metadata for exact repository-relative paths and "- "bounded path scopes. Use this after graph discovery for every cited or operated-on file; "- "use scopes before negative/exhaustive claims because fully skipped files cannot appear in "- "normal graph results. Returns coverage status separately from filesystem metadata freshness, "- "plus structured parse-error ranges and direct-source fallback actions. The signal is "- "best-effort: indexed_no_recorded_gap is not a completeness guarantee. At least one of "- "'paths' or 'scopes' is required; the call is rejected at runtime if both are omitted.",+ "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.","{\"type\":\"object\",\"properties\":{""\"project\":{\"type\":\"string\"},"- "\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"maxItems\":128,"- "\"description\":\"Repository-relative files to check exactly. Required if 'scopes' is "- "omitted.\"},"- "\"scopes\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"maxItems\":32,"- "\"description\":\"Repository-relative path prefixes; use . for the project root. Required "- "if 'paths' is omitted.\"},"- "\"scope_limit\":{\"type\":\"integer\",\"default\":200,\"minimum\":1,\"maximum\":1000},"- "\"scope_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0}},"+ "\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"maxItems\":128},"+ "\"path_limit\":{\"type\":\"integer\",\"default\":20,\"minimum\":1,\"maximum\":128},"+ "\"path_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"scopes\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"maxItems\":32},"+ "\"scope_limit\":{\"type\":\"integer\",\"default\":20,\"minimum\":1,\"maximum\":1000},"+ "\"scope_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"diagnostics\":{\"type\":\"string\",\"enum\":[\"none\",\"full\"],\"default\":\"none\"},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},""\"required\":[\"project\"]""}"},{"detect_changes", "Detect changes",- "Map a git diff to its BLAST RADIUS. Resolves changed files to the symbols they define, then "- "runs ONE multi-source graph traversal to the transitive impact set. RESPONSE: base + "- "merge_base SHA, changed_files list, then impacted = prefix-grouped tree rows (name label "- "hop; "- "full qn = group prefix + dot + name) + an impacted_modules rollup; impacted_total + "- "truncated are exact. Seeds (the changed symbols) are excluded from impacted; a changed file "- "reached from another changed file is not counted as extra impact. format=\"json\" returns "- "the "- "same model as structured JSON.",+ "Map a Git diff to changed files and transitive graph impact. Sections page independently; "+ "totals and continuations stay explicit.","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"scope\":{\"type\":"- "\"string\",\"enum\":[\"files\",\"impact\"],\"description\":\"files: changed files only "- "(no traversal). impact (default): files + the transitive impact set.\"},"+ "\"string\",\"enum\":[\"files\",\"impact\"]},""\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\",\"both\"],\"default\":"- "\"inbound\",\"description\":\"inbound (default) = the blast radius: transitive CALLERS of "- "the "- "changed symbols. outbound = what the changed code depends on. both = union.\"},"- "\"depth\":{\"type\":\"integer\",\"default\":2,\"description\":\"Max traversal hops from the "- "changed symbols.\"},\"limit\":{\"type\":\"integer\",\"default\":200,\"maximum\":5000,"- "\"description\":\"Per-symbol impacted rows shown (nearest hops first). impacted_total is "- "always exact and the impacted_modules rollup always complete regardless.\"},"+ "\"inbound\",\"description\":\"inbound=callers; outbound=dependencies; both=union.\"},"+ "\"depth\":{\"type\":\"integer\",\"default\":2},"+ "\"limit\":{\"type\":\"integer\",\"default\":200,\"maximum\":5000},"+ "\"impact_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"changed_limit\":{\"type\":\"integer\",\"default\":20,\"minimum\":0,\"maximum\":5000},"+ "\"changed_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"module_limit\":{\"type\":\"integer\",\"default\":20,\"minimum\":0,\"maximum\":256},"+ "\"module_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"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.\"},""\"base_branch\":{\"type\":"- "\"string\",\"default\":\"main\"},\"since\":{\"type\":\"string\",\"description\":"- "\"Git ref or tag to compare from (e.g. HEAD~5, v0.5.0). Diffs <ref>...HEAD.\"},"+ "\"string\",\"default\":\"main\"},\"since\":{\"type\":\"string\"},""\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},""\"required\":""[\"project\"]}"},- {"manage_adr", "Manage ADR", "Create or update Architecture Decision Records",+ {"manage_adr", "Manage ADR", "Outline an ADR by default; get reads it; update replaces it","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"mode\":{\"type\":"- "\"string\",\"enum\":[\"get\",\"update\",\"set_sections\",\"sections\"],\"description\":"- "\"update REPLACES the entire ADR document; set_sections rewrites only the named sections "+ "\"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 only lists "- "existing headings\"},\"content\":{\"type\":\"string\",\"description\":\"Complete replacement "+ "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.\","- "\"additionalProperties\":{\"type\":\"string\"}}},\"additionalProperties\":false,"+ "\"additionalProperties\":{\"type\":\"string\"}},"+ "\"section_limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"+ "\"section_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"+ "\"additionalProperties\":false,""\"required\":[\"project\"]}"},- {"ingest_traces", "Ingest traces", "Ingest runtime traces to enhance the knowledge graph",+ {"ingest_traces", "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\":"@@ -1317,33 +1263,19 @@ static const int SUPPORTED_VERSION_COUNT =(int)(sizeof(SUPPORTED_PROTOCOL_VERSIONS) / sizeof(SUPPORTED_PROTOCOL_VERSIONS[0]));static const char MCP_SERVER_INSTRUCTIONS[] =- "Use graph tools first for structural code discovery: search_graph to find symbols, "- "trace_path for callers and callees, get_code_snippet for exact source, query_graph for "- "complex multi-hop patterns, and get_architecture for orientation. Use search_code or "- "filesystem grep for literal or non-code text, or when graph coverage is insufficient. "- "Call list_projects before initial use and index_repository only when a repository is not "- "indexed or to force immediate freshness after a large external update. Once indexed, "- "watched projects auto-refresh in the background; use index_status for project health and "- "check_index_coverage for every cited path and for scopes behind negative or exhaustive "- "claims. Coverage is best-effort, never proof of completeness. Check has_more or nextCursor "- "and paginate when present.";+ "Graph first: search_graph for symbols, trace_path for relationships, get_code_snippet for "+ "source, query_graph for multi-hop, and get_architecture for overview. Use search_code/grep "+ "for literals or coverage gaps. Indexes auto-refresh. Check cited-path coverage; paginate.";static const char MCP_ANALYSIS_SERVER_INSTRUCTIONS[] =- "This is the analysis tool profile; graph and index mutation tools are unavailable. Use "- "list_projects and index_status to select a current graph project, then use search_graph, "- "trace_path, get_code_snippet, query_graph, get_architecture, and search_code for read-only "- "analysis. Call check_index_coverage for every cited path and for scopes behind negative or "- "exhaustive claims; read flagged ranges or skipped files directly. Coverage is best-effort, "- "never proof of completeness. Check has_more or nextCursor and paginate when present. If the "- "project is missing or stale, ask the parent agent to index or refresh it.";+ "analysis tool profile: read-only graph work via search_graph, trace_path, "+ "get_code_snippet, query_graph, get_architecture, or search_code. Use check_index_coverage "+ "for cited paths; paginate.";static const char MCP_SCOUT_SERVER_INSTRUCTIONS[] =- "This is the scout tool profile; only the fast positive-discovery graph tools are available. "- "Use list_projects and index_status to select a current graph project, then use search_graph, "- "trace_path, get_code_snippet, and get_architecture with narrow limits. Call "- "check_index_coverage once for every cited path and read flagged ranges directly. Findings "- "are provisional: do not make absence, exhaustive-impact, or dead-code claims. If the project "- "is missing or stale, ask the parent agent to index or refresh it.";+ "scout tool profile: fast positive discovery via search_graph, trace_path, "+ "get_code_snippet, or get_architecture with narrow limits. Use check_index_coverage for "+ "cited paths. Findings are provisional.";static char *cbm_mcp_initialize_response_for_profile(const char *params_json,cbm_mcp_tool_profile_t profile) {@@ -1622,6 +1554,33 @@ bool cbm_mcp_get_bool_arg(const char *args_json, const char *key) {return result;}+/* Read tools use a compact tree for the model-facing default. Machine callers+ * can request format:"json", which preserves the structuredContent fallback+ * in cbm_mcp_text_result. Keeping this conversion at the final transport edge+ * avoids maintaining a second semantic response model in each handler. */+static bool mcp_wants_json(const char *args_json) {+ char *format = cbm_mcp_get_string_arg(args_json ? args_json : "{}", "format");+ bool wants_json = format && strcmp(format, "json") == 0;+ free(format);+ return wants_json;+}++static char *mcp_result_from_json(const char *args_json, const char *json) {+ if (!json) {+ return cbm_mcp_text_result("out of memory", true);+ }+ if (mcp_wants_json(args_json)) {+ return cbm_mcp_text_result(json, false);+ }+ char *tree = cbm_json_to_tree(json);+ if (!tree) {+ return cbm_mcp_text_result("failed to render compact output", true);+ }+ char *result = cbm_mcp_text_result(tree, false);+ free(tree);+ return result;+}+/* ══════════════════════════════════════════════════════════════════* MCP SERVER* ══════════════════════════════════════════════════════════════════ */@@ -2677,12 +2636,55 @@ static cbm_store_t *resolve_store_fallback_scan(const char *project) {return found;}-/* Open a .db file briefly, collect node/edge counts and root_path,- * then append a JSON entry to arr. */-static void build_project_json_entry(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *dir_path,- const char *name, size_t name_len, int64_t size_bytes,- bool include_details) {- (void)name_len;+typedef struct {+ char *name;+ char *root_path;+ char *db_file;+ char *branch;+ int nodes;+ int edges;+ int64_t size_bytes;+ bool populated;+} mcp_project_record_t;++static void project_record_clear(mcp_project_record_t *record) {+ if (!record) {+ return;+ }+ free(record->name);+ free(record->root_path);+ free(record->db_file);+ free(record->branch);+ memset(record, 0, sizeof(*record));+}++static int project_record_compare(const void *left, const void *right) {+ const mcp_project_record_t *a = left;+ const mcp_project_record_t *b = right;+ int by_name = strcmp(a->name ? a->name : "", b->name ? b->name : "");+ if (by_name != 0) {+ return by_name;+ }+ int by_root = strcmp(a->root_path ? a->root_path : "", b->root_path ? b->root_path : "");+ if (by_root != 0) {+ return by_root;+ }+ return strcmp(a->db_file ? a->db_file : "", b->db_file ? b->db_file : "");+}++typedef enum {+ PROJECT_RECORD_SKIP = 0,+ PROJECT_RECORD_OK = 1,+ PROJECT_RECORD_OOM = -1,+} project_record_status_t;++/* Open a .db file briefly and collect sortable identity only. Counts and Git+ * context are populated after paging so a 50-row response does not repeat+ * heavyweight work for every database in the cache. */+static project_record_status_t read_project_record_identity(const char *dir_path, const char *name,+ int64_t size_bytes,+ mcp_project_record_t *record) {+ memset(record, 0, sizeof(*record));char full_path[CBM_SZ_2K];snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);@@ -2695,104 +2697,133 @@ static void build_project_json_entry(yyjson_mut_doc *doc, yyjson_mut_val *arr, cchar project_name[CBM_SZ_1K];cbm_store_t *pstore = NULL;if (!db_internal_project_name(full_path, project_name, sizeof(project_name), &pstore)) {- return; /* ghost / unreadable — not a resolvable project */+ return PROJECT_RECORD_SKIP; /* ghost / unreadable — not resolvable */}- int nodes = 0;- int edges = 0;- if (include_details) {- nodes = cbm_store_count_nodes(pstore, project_name);- edges = cbm_store_count_edges(pstore, project_name);- }- char root_path_buf[CBM_SZ_1K] = "";+ record->name = heap_strdup(project_name);+ record->db_file = heap_strdup(name);+ record->size_bytes = size_bytes;cbm_project_t proj = {0};if (cbm_store_get_project(pstore, project_name, &proj) == CBM_STORE_OK) {- if (proj.root_path) {- snprintf(root_path_buf, sizeof(root_path_buf), "%s", proj.root_path);- }+ /* root_path is NOT NULL in the store schema, so a missing copy here is+ * allocation failure rather than an empty identity. */+ if (!proj.root_path) {+ cbm_project_free_fields(&proj);+ cbm_store_close(pstore);+ project_record_clear(record);+ return PROJECT_RECORD_OOM;+ }+ /* Store project fields are heap-owned by the caller. Transfer the root+ * identity intact: it is the value used for sorting, output, and branch+ * lookup, so routing it through a fixed buffer would silently change+ * all three for long roots. */+ record->root_path = (char *)proj.root_path;+ proj.root_path = NULL;cbm_project_free_fields(&proj);}cbm_store_close(pstore);+ if (!record->root_path) {+ record->root_path = heap_strdup("");+ }+ if (!record->name || !record->root_path || !record->db_file) {+ project_record_clear(record);+ return PROJECT_RECORD_OOM;+ }+ return PROJECT_RECORD_OK;+}- yyjson_mut_val *p = yyjson_mut_obj(doc);- yyjson_mut_obj_add_strcpy(doc, p, "name", project_name);- yyjson_mut_obj_add_strcpy(doc, p, "root_path", root_path_buf);+static bool populate_project_record(const char *dir_path, bool include_stats,+ mcp_project_record_t *record) {+ if (record->populated) {+ record->populated = true;+ return true;+ }+ if (include_stats) {+ char full_path[CBM_SZ_2K];+ snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, record->db_file);+ cbm_store_t *pstore = cbm_store_open_path_query(full_path);+ if (!pstore) {+ return false;+ }+ record->nodes = cbm_store_count_nodes(pstore, record->name);+ record->edges = cbm_store_count_edges(pstore, record->name);+ cbm_store_close(pstore);+ }/* Listing stays lean: only the branch (the one git fact that* disambiguates same-repo projects). The 12-field git block — mostly* null for non-git roots — cost ~10KB across a full cache and is one* index_status call away for the project you actually care about. */- if (include_details && root_path_buf[0]) {+ if (record->root_path[0]) {cbm_git_context_t gctx = {0};- (void)cbm_git_context_resolve(root_path_buf, &gctx);+ (void)cbm_git_context_resolve(record->root_path, &gctx);if (gctx.is_git && gctx.branch) {- yyjson_mut_obj_add_strcpy(doc, p, "branch", gctx.branch);+ record->branch = heap_strdup(gctx.branch);+ if (!record->branch) {+ cbm_git_context_free(&gctx);+ return false;+ }}cbm_git_context_free(&gctx);}- if (include_details) {- yyjson_mut_obj_add_int(doc, p, "nodes", nodes);- yyjson_mut_obj_add_int(doc, p, "edges", edges);- yyjson_mut_obj_add_int(doc, p, "size_bytes", size_bytes);+ record->populated = true;+ return true;+}++static void add_project_record_json(yyjson_mut_doc *doc, yyjson_mut_val *arr,+ const mcp_project_record_t *record, bool include_stats) {+ yyjson_mut_val *p = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_strcpy(doc, p, "name", record->name);+ yyjson_mut_obj_add_strcpy(doc, p, "root_path", record->root_path);+ if (record->branch) {+ yyjson_mut_obj_add_strcpy(doc, p, "branch", record->branch);+ }+ if (include_stats) {+ yyjson_mut_obj_add_int(doc, p, "nodes", record->nodes);+ yyjson_mut_obj_add_int(doc, p, "edges", record->edges);+ yyjson_mut_obj_add_int(doc, p, "size_bytes", record->size_bytes);}yyjson_mut_arr_add_val(arr, p);}-static int project_db_name_cmp(const void *a, const void *b) {- const char *const *sa = (const char *const *)a;- const char *const *sb = (const char *const *)b;- return strcmp(*sa, *sb);-}/* list_projects: scan cache directory for .db files.* Each project is a single .db file — no central registry needed. */static char *handle_list_projects(cbm_mcp_server_t *srv, const char *args) {(void)srv;- int offset = cbm_mcp_get_int_arg(args, "offset", 0);- int limit = cbm_mcp_get_int_arg(args, "limit", 50);- bool include_details = cbm_mcp_get_bool_arg(args, "include_details");+ bool metadata_only = false;yyjson_doc *args_doc = args ? yyjson_read(args, strlen(args), 0) : NULL;yyjson_val *args_root = args_doc ? yyjson_doc_get_root(args_doc) : NULL;yyjson_val *metadata_value =args_root && yyjson_is_obj(args_root) ? yyjson_obj_get(args_root, "metadata_only") : NULL;- if (metadata_value && yyjson_is_true(metadata_value)) {- include_details = false;- }+ metadata_only = metadata_value && yyjson_is_true(metadata_value);+ char *detail = cbm_mcp_get_string_arg(args, "detail");+ /* `include_details` is the boolean spelling main shipped for the same+ * request; both select the stats projection. */+ bool include_stats = !metadata_only && ((detail && strcmp(detail, "stats") == 0) ||+ cbm_mcp_get_bool_arg(args, "include_details"));+ free(detail);if (args_doc) {yyjson_doc_free(args_doc);}- if (offset < 0) {- offset = 0;- }- if (limit < 1) {- limit = 1;- } else if (limit > 100) {- limit = 100;- }char dir_path[CBM_SZ_1K];cache_dir(dir_path, sizeof(dir_path));cbm_dir_t *d = cbm_opendir(dir_path);- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);- yyjson_mut_val *root = yyjson_mut_obj(doc);- yyjson_mut_doc_set_root(doc, root);- yyjson_mut_val *arr = yyjson_mut_arr(doc);-if (!d) {char msg[CBM_SZ_1K];snprintf(msg, sizeof(msg),"{\"error\":\"cannot read cache directory: %s\",\"hint\":""\"Check directory permissions or run index_repository first.\"}",dir_path);- yyjson_mut_doc_free(doc);return cbm_mcp_text_result(msg, true);}- char **db_names = NULL;- size_t db_count = 0;- size_t db_cap = 0;- bool name_collection_failed = false;+ mcp_project_record_t *records = NULL;+ int record_count = 0;+ int record_cap = 0;+ bool oom = false;cbm_dirent_t *entry;while ((entry = cbm_readdir(d)) != NULL) {const char *name = entry->name;@@ -2800,77 +2831,185 @@ static char *handle_list_projects(cbm_mcp_server_t *srv, const char *args) {if (!is_project_db_file(name, len)) {continue;}- if (db_count == db_cap) {- size_t next_cap = db_cap ? db_cap * 2 : 64;- char **grown = realloc(db_names, next_cap * sizeof(*db_names));+ char full_path[CBM_SZ_2K];+ snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);+ int64_t size_bytes = cbm_file_size(full_path);+ if (size_bytes < 0) {+ continue;+ }+ mcp_project_record_t record = {0};+ project_record_status_t read_status =+ read_project_record_identity(dir_path, name, size_bytes, &record);+ if (read_status == PROJECT_RECORD_OOM) {+ oom = true;+ break;+ }+ if (read_status != PROJECT_RECORD_OK) {+ continue;+ }+ if (record_count == record_cap) {+ int new_cap = record_cap ? record_cap * 2 : 16;+ void *grown = realloc(records, (size_t)new_cap * sizeof(*records));if (!grown) {- name_collection_failed = true;+ project_record_clear(&record);+ oom = true;break;}- db_names = grown;- db_cap = next_cap;- }- db_names[db_count] = heap_strdup(name);- if (!db_names[db_count]) {- name_collection_failed = true;- break;+ records = grown;+ record_cap = new_cap;}- db_count++;+ records[record_count++] = record;}cbm_closedir(d);- if (name_collection_failed) {- for (size_t i = 0; i < db_count; i++) {- free(db_names[i]);+ if (oom) {+ for (int i = 0; i < record_count; i++) {+ project_record_clear(&records[i]);}- free(db_names);- yyjson_mut_doc_free(doc);- return cbm_mcp_text_result(- "{\"error\":\"out of memory while collecting indexed projects\"}", true);+ free(records);+ return cbm_mcp_text_result("out of memory while listing projects", true);}+ qsort(records, (size_t)record_count, sizeof(*records), project_record_compare);- if (db_count > 1) {- qsort(db_names, db_count, sizeof(*db_names), project_db_name_cmp);+ int limit = cbm_mcp_get_int_arg(args, "limit", 50);+ int offset = cbm_mcp_get_int_arg(args, "offset", 0);+ if (limit < 1) {+ limit = 1;+ } else if (limit > 500) {+ limit = 500;}- size_t start = (size_t)offset < db_count ? (size_t)offset : db_count;- size_t end = start + (size_t)limit;- if (end > db_count) {- end = db_count;+ if (offset < 0) {+ offset = 0;}- for (size_t i = start; i < end; i++) {- const char *name = db_names[i];- size_t len = strlen(name);- char full_path[CBM_SZ_2K];- snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);- int64_t size_bytes = cbm_file_size(full_path);- if (size_bytes < 0) {- continue;+ int start = offset < record_count ? offset : record_count;+ int end = start + limit < record_count ? start + limit : record_count;+ if (!metadata_only) {+ for (int i = start; i < end; i++) {+ if (!populate_project_record(dir_path, include_stats, &records[i])) {+ oom = true;+ break;+ }}- build_project_json_entry(doc, arr, dir_path, name, len, size_bytes, include_details);}- for (size_t i = 0; i < db_count; i++) {- free(db_names[i]);+ if (oom) {+ for (int i = 0; i < record_count; i++) {+ project_record_clear(&records[i]);+ }+ free(records);+ return cbm_mcp_text_result("failed to populate project page", true);}- free(db_names);- yyjson_mut_obj_add_val(doc, root, "projects", arr);- yyjson_mut_obj_add_uint(doc, root, "total", db_count);- yyjson_mut_obj_add_int(doc, root, "offset", offset);- yyjson_mut_obj_add_int(doc, root, "limit", limit);- yyjson_mut_obj_add_uint(doc, root, "returned", yyjson_mut_arr_size(arr));- yyjson_mut_obj_add_bool(doc, root, "has_more", end < db_count);+ bool wants_json = mcp_wants_json(args);+ char *payload = NULL;+ if (wants_json) {+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_val *arr = yyjson_mut_arr(doc);+ for (int i = start; i < end; i++) {+ add_project_record_json(doc, arr, &records[i], include_stats);+ }- /* Guide user when no projects are indexed */- if (yyjson_mut_arr_size(arr) == 0) {- yyjson_mut_obj_add_str(doc, root, "hint",- "No projects indexed. Call index_repository(repo_path=...) first.");+ yyjson_mut_obj_add_val(doc, root, "projects", arr);+ yyjson_mut_obj_add_int(doc, root, "total", record_count);+ yyjson_mut_obj_add_int(doc, root, "returned", end - start);+ yyjson_mut_obj_add_bool(doc, root, "has_more", end < record_count);+ if (end < record_count) {+ yyjson_mut_obj_add_int(doc, root, "next_offset", end);+ }+ if (record_count == 0) {+ yyjson_mut_obj_add_str(+ doc, root, "hint",+ "No projects indexed. Call index_repository(repo_path=...) first.");+ }+ payload = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ } else {+ /* Stable union schema: branch is an explicit empty marker instead of+ * changing each object's shape and forcing the generic tree emitter+ * to repeat every key. Values and row order remain direct/copyable. */+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ const char *metadata_cols[] = {"name", "root_path"};+ const char *identity_cols[] = {"name", "root_path", "branch"};+ const char *stats_cols[] = {"name", "root_path", "branch", "nodes", "edges", "size_bytes"};+ const char *const *cols = metadata_only ? metadata_cols+ : include_stats ? stats_cols+ : identity_cols;+ int column_count = metadata_only ? 2 : include_stats ? 6 : 3;+ int page_count = end - start;+ size_t cell_count = (size_t)page_count * (size_t)column_count;+ const char **cells = cell_count > 0 && cell_count <= SIZE_MAX / sizeof(*cells)+ ? malloc(cell_count * sizeof(*cells))+ : NULL;+ char (*numbers)[32] = include_stats && page_count > 0+ ? malloc((size_t)page_count * 3U * sizeof(*numbers))+ : NULL;+ if (cells && (!include_stats || numbers)) {+ for (int row = 0; row < page_count; row++) {+ const mcp_project_record_t *record = &records[start + row];+ size_t base = (size_t)row * (size_t)column_count;+ cells[base] = record->name;+ cells[base + 1U] = record->root_path;+ if (!metadata_only) {+ cells[base + 2U] = record->branch ? record->branch : "";+ }+ if (include_stats) {+ size_t number_base = (size_t)row * 3U;+ snprintf(numbers[number_base], sizeof(numbers[number_base]), "%d",+ record->nodes);+ snprintf(numbers[number_base + 1U], sizeof(numbers[number_base + 1U]), "%d",+ record->edges);+ snprintf(numbers[number_base + 2U], sizeof(numbers[number_base + 2U]), "%lld",+ (long long)record->size_bytes);+ cells[base + 3U] = numbers[number_base];+ cells[base + 4U] = numbers[number_base + 1U];+ cells[base + 5U] = numbers[number_base + 2U];+ }+ }+ const bool string_cols[] = {true, true, true, false, false, false};+ const bool prefix_cols[] = {false, true, false, false, false, false};+ cbm_tree_table_rows_profiled(&sb, "projects", page_count, cols, column_count, cells,+ string_cols, prefix_cols);+ } else {+ cbm_tree_table_header(&sb, "projects", page_count, cols, column_count);+ for (int i = start; i < end; i++) {+ cbm_tree_row_begin(&sb);+ cbm_tree_cell_str(&sb, records[i].name, true);+ cbm_tree_cell_str(&sb, records[i].root_path, false);+ if (!metadata_only) {+ cbm_tree_cell_str(&sb, records[i].branch ? records[i].branch : "", false);+ }+ if (include_stats) {+ cbm_tree_cell_int(&sb, records[i].nodes, false);+ cbm_tree_cell_int(&sb, records[i].edges, false);+ cbm_tree_cell_int(&sb, (long long)records[i].size_bytes, false);+ }+ cbm_tree_row_end(&sb);+ }+ }+ free(numbers);+ free(cells);+ cbm_tree_scalar_int(&sb, "total", record_count);+ cbm_tree_scalar_int(&sb, "returned", end - start);+ cbm_tree_scalar_bool(&sb, "has_more", end < record_count);+ if (end < record_count) {+ cbm_tree_scalar_int(&sb, "next_offset", end);+ }+ if (record_count == 0) {+ cbm_tree_scalar_str(&sb, "hint",+ "No projects indexed. Call index_repository(repo_path=...) first.");+ }+ payload = cbm_sb_finish(&sb);}- char *json = yy_doc_to_str(doc);- yyjson_mut_doc_free(doc);+ for (int i = 0; i < record_count; i++) {+ project_record_clear(&records[i]);+ }+ free(records);- char *result = cbm_mcp_text_result(json, false);- free(json);+ char *result = cbm_mcp_text_result(payload ? payload : "out of memory", payload == NULL);+ free(payload);return result;}@@ -3310,6 +3449,25 @@ static char *handle_compare_graphs(cbm_mcp_server_t *server, const char *args) {static bool sg_field_blocked(const char *f); /* internal-only fields, defined with search_graph */+typedef struct {+ bool node;+ int index;+ int count;+ const char *name;+} mcp_schema_record_t;++static int schema_record_compare(const void *left, const void *right) {+ const mcp_schema_record_t *a = left;+ const mcp_schema_record_t *b = right;+ if (a->node != b->node) {+ return a->node ? -1 : 1;+ }+ if (a->count != b->count) {+ return a->count > b->count ? -1 : 1;+ }+ return strcmp(a->name ? a->name : "", b->name ? b->name : "");+}+static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {char *project = get_project_arg(args);cbm_store_t *store = resolve_store(srv, project);@@ -3321,54 +3479,108 @@ static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {return not_indexed;}+ char *diagnostics = cbm_mcp_get_string_arg(args, "diagnostics");+ bool include_properties = diagnostics && strcmp(diagnostics, "full") == 0;+ free(diagnostics);+cbm_schema_info_t schema = {0};- cbm_store_get_schema(store, project, &schema);+ if (include_properties) {+ cbm_store_get_schema(store, project, &schema);+ } else {+ cbm_store_get_schema_counts(store, project, &schema);+ }++ int limit = cbm_mcp_get_int_arg(args, "limit", 50);+ int offset = cbm_mcp_get_int_arg(args, "offset", 0);+ if (limit < 1) {+ limit = 1;+ } else if (limit > 500) {+ limit = 500;+ }+ if (offset < 0) {+ offset = 0;+ }+ int total = schema.node_label_count + schema.edge_type_count;+ size_t record_capacity = total > 0 ? (size_t)total : 1U;+ mcp_schema_record_t *records = calloc(record_capacity, sizeof(*records));+ if (!records) {+ cbm_store_schema_free(&schema);+ free(project);+ return cbm_mcp_text_result("out of memory while rendering schema", true);+ }+ int record_count = 0;+ for (int i = 0; i < schema.node_label_count; i++) {+ records[record_count++] = (mcp_schema_record_t){true, i, schema.node_labels[i].count,+ schema.node_labels[i].label};+ }+ for (int i = 0; i < schema.edge_type_count; i++) {+ records[record_count++] =+ (mcp_schema_record_t){false, i, schema.edge_types[i].count, schema.edge_types[i].type};+ }+ qsort(records, (size_t)record_count, sizeof(*records), schema_record_compare);+ int start = offset < total ? offset : total;+ int end = start + limit < total ? start + limit : total;yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root);yyjson_mut_val *labels = yyjson_mut_arr(doc);- for (int i = 0; i < schema.node_label_count; i++) {+ for (int page = start; page < end; page++) {+ if (!records[page].node) {+ continue;+ }+ int i = records[page].index;yyjson_mut_val *lbl = yyjson_mut_obj(doc);yyjson_mut_obj_add_str(doc, lbl, "label", schema.node_labels[i].label);yyjson_mut_obj_add_int(doc, lbl, "count", schema.node_labels[i].count);- yyjson_mut_val *props = yyjson_mut_arr(doc);- for (int j = 0; j < schema.node_labels[i].property_count; j++) {- /* Internal similarity intermediates (fp/sp/bt) are blocked from every- * tool response — advertising them here invited agents to request- * fields the server then silently refuses. Filter them from the- * schema so it only describes obtainable properties. */- if (sg_field_blocked(schema.node_labels[i].properties[j])) {- continue;+ if (include_properties) {+ yyjson_mut_val *props = yyjson_mut_arr(doc);+ for (int j = 0; j < schema.node_labels[i].property_count; j++) {+ /* Internal similarity intermediates are never public. */+ if (sg_field_blocked(schema.node_labels[i].properties[j])) {+ continue;+ }+ yyjson_mut_arr_add_str(doc, props, schema.node_labels[i].properties[j]);}- yyjson_mut_arr_add_str(doc, props, schema.node_labels[i].properties[j]);+ yyjson_mut_obj_add_val(doc, lbl, "properties", props);}- yyjson_mut_obj_add_val(doc, lbl, "properties", props);yyjson_mut_arr_add_val(labels, lbl);}yyjson_mut_obj_add_val(doc, root, "node_labels", labels);yyjson_mut_val *types = yyjson_mut_arr(doc);- for (int i = 0; i < schema.edge_type_count; i++) {+ for (int page = start; page < end; page++) {+ if (records[page].node) {+ continue;+ }+ int i = records[page].index;yyjson_mut_val *typ = yyjson_mut_obj(doc);yyjson_mut_obj_add_str(doc, typ, "type", schema.edge_types[i].type);yyjson_mut_obj_add_int(doc, typ, "count", schema.edge_types[i].count);- yyjson_mut_val *eprops = yyjson_mut_arr(doc);- for (int j = 0; j < schema.edge_types[i].property_count; j++) {- yyjson_mut_arr_add_str(doc, eprops, schema.edge_types[i].properties[j]);+ if (include_properties) {+ yyjson_mut_val *eprops = yyjson_mut_arr(doc);+ for (int j = 0; j < schema.edge_types[i].property_count; j++) {+ yyjson_mut_arr_add_str(doc, eprops, schema.edge_types[i].properties[j]);+ }+ yyjson_mut_obj_add_val(doc, typ, "properties", eprops);}- yyjson_mut_obj_add_val(doc, typ, "properties", eprops);yyjson_mut_arr_add_val(types, typ);}yyjson_mut_obj_add_val(doc, root, "edge_types", types);+ yyjson_mut_obj_add_int(doc, root, "total", total);+ yyjson_mut_obj_add_int(doc, root, "returned", end - start);+ yyjson_mut_obj_add_bool(doc, root, "has_more", end < total);+ if (end < total) {+ yyjson_mut_obj_add_int(doc, root, "next_offset", end);+ }/* Check ADR presence */cbm_project_t proj_info = {0};if (cbm_store_get_project(store, project, &proj_info) == 0 && proj_info.root_path) {bool adr_exists = project_has_adr(store, project, proj_info.root_path);yyjson_mut_obj_add_bool(doc, root, "adr_present", adr_exists);- if (!adr_exists) {+ if (!adr_exists && include_properties) {yyjson_mut_obj_add_str(doc, root, "adr_hint","No ADR found. Use manage_adr(mode='update') to persist architectural "@@ -3379,10 +3591,11 @@ static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {char *json = yy_doc_to_str(doc);yyjson_mut_doc_free(doc);+ free(records);cbm_store_schema_free(&schema);free(project);- char *result = cbm_mcp_text_result(json, false);+ char *result = mcp_result_from_json(args, json);free(json);return result;}@@ -3432,31 +3645,32 @@ static yyjson_mut_val *enrich_connected(yyjson_mut_doc *doc, cbm_store_t *store,return conn;}-/* Text-tree variant: the same 1-hop neighbor names ';'-joined into buf (no- * commas/spaces in names, so the cell needs no quoting). Empty when none. */-static void enrich_connected_joined(cbm_store_t *store, int64_t node_id, const char *relationship,- char *buf, size_t bufsz) {- buf[0] = '\0';+/* Text-tree variant: the same 1-hop neighbor names joined without a fixed+ * staging buffer. Identifiers are semantic atoms: emit each in full or omit+ * the entire connected column at the response-budget layer. */+static char *enrich_connected_joined(cbm_store_t *store, int64_t node_id,+ const char *relationship) {const char *et[] = {relationship ? relationship : "CALLS"};- size_t off = 0;+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ bool any = false;const char *dirs[2] = {"inbound", "outbound"};for (int d = 0; d < 2; d++) {cbm_traverse_result_t tr = {0};cbm_store_bfs(store, node_id, dirs[d], et, SKIP_ONE, SKIP_ONE, MCP_DEFAULT_LIMIT, &tr);- for (int j = 0; j < tr.visited_count && off + 2 < bufsz; j++) {+ for (int j = 0; j < tr.visited_count; j++) {if (!tr.visited[j].node.name) {continue;}- int n =- snprintf(buf + off, bufsz - off, "%s%s", off ? ";" : "", tr.visited[j].node.name);- if (n < 0 || (size_t)n >= bufsz - off) {- buf[off] = '\0';- break;+ if (any) {+ cbm_sb_append(&sb, ";");}- off += (size_t)n;+ cbm_sb_append(&sb, tr.visited[j].node.name);+ any = true;}cbm_store_traverse_free(&tr);}+ return cbm_sb_finish(&sb);}/* Build an FTS5 MATCH expression from a free-form query string by splitting@@ -3581,11 +3795,167 @@ static char *bm25_file_pattern_like(const char *file_pattern) {return like;}+typedef struct {+ char *qualified_name;+ char *label;+ char *file_path;+ int start_line;+ int end_line;+ double rank;+} bm25_output_row_t;++static void bm25_output_rows_free(bm25_output_row_t *rows, int count) {+ if (!rows) {+ return;+ }+ for (int i = 0; i < count; i++) {+ free(rows[i].qualified_name);+ free(rows[i].label);+ free(rows[i].file_path);+ }+ free(rows);+}++static void bm25_lines_str(char *out, size_t size, int start, int end) {+ if (start > 0) {+ snprintf(out, size, "%d-%d", start, end > start ? end : start);+ } else {+ out[0] = '\0';+ }+}++static void bm25_emit_metadata_tree(cbm_sb_t *sb, int total, int offset, int returned,+ bool candidate_window_saturated, bool budget_hit,+ bool floor_exceeded, size_t max_output_bytes) {+ bool has_more = total > offset + returned;+ cbm_tree_scalar_int(sb, "total", total);+ cbm_tree_scalar_str(sb, "total_relation", candidate_window_saturated ? "gte" : "eq");+ if (candidate_window_saturated) {+ cbm_tree_scalar_bool(sb, "candidate_window_saturated", true);+ }+ cbm_tree_scalar_str(sb, "search_mode", "bm25");+ cbm_tree_scalar_int(sb, "returned", returned);+ cbm_tree_scalar_bool(sb, "has_more", has_more);+ if (has_more && returned > 0) {+ cbm_tree_scalar_int(sb, "next_offset", offset + returned);+ } else if (has_more) {+ cbm_tree_scalar_bool(sb, "continuation_requires_higher_budget", true);+ }+ bool truncated = has_more || candidate_window_saturated || budget_hit;+ cbm_tree_scalar_bool(sb, "truncated", truncated);+ if (truncated) {+ const char *reason = budget_hit ? "output_budget"+ : has_more ? "page_limit"+ : "candidate_window";+ cbm_tree_scalar_str(sb, "truncation_reason", reason);+ }+ if (budget_hit) {+ cbm_tree_scalar_int(sb, "max_output_bytes", (long long)max_output_bytes);+ }+ if (floor_exceeded) {+ cbm_tree_scalar_bool(sb, "output_budget_floor_exceeded", true);+ cbm_tree_scalar_str(sb, "hint",+ "first identity row exceeds max_output_bytes; raise "+ "max_output_tokens");+ }+}++static void bm25_emit_metadata_json(yyjson_mut_doc *doc, yyjson_mut_val *root, int total,+ int offset, int returned, bool candidate_window_saturated,+ bool budget_hit, bool floor_exceeded, size_t max_output_bytes) {+ bool has_more = total > offset + returned;+ yyjson_mut_obj_add_int(doc, root, "total", total);+ yyjson_mut_obj_add_str(doc, root, "total_relation", candidate_window_saturated ? "gte" : "eq");+ if (candidate_window_saturated) {+ yyjson_mut_obj_add_bool(doc, root, "candidate_window_saturated", true);+ }+ yyjson_mut_obj_add_str(doc, root, "search_mode", "bm25");+ yyjson_mut_obj_add_int(doc, root, "returned", returned);+ yyjson_mut_obj_add_int(doc, root, "count", returned);+ yyjson_mut_obj_add_bool(doc, root, "has_more", has_more);+ if (has_more && returned > 0) {+ yyjson_mut_obj_add_int(doc, root, "next_offset", offset + returned);+ } else if (has_more) {+ yyjson_mut_obj_add_bool(doc, root, "continuation_requires_higher_budget", true);+ }+ bool truncated = has_more || candidate_window_saturated || budget_hit;+ yyjson_mut_obj_add_bool(doc, root, "truncated", truncated);+ if (truncated) {+ const char *reason = budget_hit ? "output_budget"+ : has_more ? "page_limit"+ : "candidate_window";+ yyjson_mut_obj_add_str(doc, root, "truncation_reason", reason);+ }+ if (budget_hit) {+ yyjson_mut_obj_add_uint(doc, root, "max_output_bytes", max_output_bytes);+ }+ if (floor_exceeded) {+ yyjson_mut_obj_add_bool(doc, root, "output_budget_floor_exceeded", true);+ yyjson_mut_obj_add_str(doc, root, "hint",+ "first identity row exceeds max_output_bytes; raise "+ "max_output_tokens");+ }+}++static char *bm25_render(const bm25_output_row_t *rows, int returned, int total, int offset,+ bool candidate_window_saturated, bool tree_format, bool budget_hit,+ bool floor_exceeded, size_t max_output_bytes) {+ if (tree_format) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ static const char *const cols[] = {"qn", "label", "file", "lines", "rank"};+ cbm_tree_table_header(&sb, "results", returned, cols, 5);+ for (int i = 0; i < returned; i++) {+ char lines[CBM_SZ_32];+ bm25_lines_str(lines, sizeof(lines), rows[i].start_line, rows[i].end_line);+ cbm_tree_row_begin(&sb);+ cbm_tree_cell_str(&sb, rows[i].qualified_name, true);+ cbm_tree_cell_str(&sb, rows[i].label, false);+ cbm_tree_cell_str(&sb, rows[i].file_path, false);+ cbm_tree_cell_str(&sb, lines, false);+ cbm_tree_cell_real(&sb, rows[i].rank, false);+ cbm_tree_row_end(&sb);+ }+ bm25_emit_metadata_tree(&sb, total, offset, returned, candidate_window_saturated,+ budget_hit, floor_exceeded, max_output_bytes);+ return cbm_sb_finish(&sb);+ }++ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_val *cols = yyjson_mut_arr(doc);+ static const char *const col_names[] = {"qn", "label", "file", "lines", "rank"};+ for (size_t i = 0; i < sizeof(col_names) / sizeof(col_names[0]); i++) {+ yyjson_mut_arr_add_str(doc, cols, col_names[i]);+ }+ yyjson_mut_obj_add_val(doc, root, "cols", cols);+ yyjson_mut_val *result_rows = yyjson_mut_arr(doc);+ for (int i = 0; i < returned; i++) {+ char lines[CBM_SZ_32];+ bm25_lines_str(lines, sizeof(lines), rows[i].start_line, rows[i].end_line);+ yyjson_mut_val *row = yyjson_mut_arr(doc);+ yyjson_mut_arr_add_strcpy(doc, row, rows[i].qualified_name);+ yyjson_mut_arr_add_strcpy(doc, row, rows[i].label);+ yyjson_mut_arr_add_strcpy(doc, row, rows[i].file_path);+ yyjson_mut_arr_add_strcpy(doc, row, lines);+ yyjson_mut_arr_add_real(doc, row, rows[i].rank);+ yyjson_mut_arr_add_val(result_rows, row);+ }+ yyjson_mut_obj_add_val(doc, root, "rows", result_rows);+ bm25_emit_metadata_json(doc, root, total, offset, returned, candidate_window_saturated,+ budget_hit, floor_exceeded, max_output_bytes);+ char *json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ return json;+}+/* Run the BM25 full-text search path and return the JSON result string.* Returns NULL if FTS5 is unavailable or the query produced no usable tokens,* in which case the caller falls back to the regex-based search path. */static char *bm25_search(cbm_store_t *store, const char *project, const char *query,- const char *file_pattern, int limit, int offset, bool toon) {+ const char *file_pattern, int limit, int offset, bool tree_format,+ size_t max_output_bytes) {sqlite3 *db = cbm_store_get_db(store);if (!db) {return NULL;@@ -3624,7 +3994,7 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu"FROM ("" SELECT rowid, " BM25_WEIGHTS " AS base_rank"" FROM nodes_fts WHERE nodes_fts MATCH ?1"- " ORDER BY base_rank LIMIT ?5"+ " ORDER BY base_rank, rowid LIMIT ?5"") fts ""JOIN nodes n ON n.id = fts.rowid ""WHERE n.project = ?2 "@@ -3693,91 +4063,70 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu}}- if (toon) {- /* TOON: rows are buffered first because the table header carries the- * row count, which sqlite only yields by stepping to completion. */- cbm_sb_t rows;- cbm_sb_init(&rows);- int emitted = 0;- while (sqlite3_step(stmt) == SQLITE_ROW) {- char lines[CBM_SZ_32];- int sl = sqlite3_column_int(stmt, BM25_COL_START);- int el = sqlite3_column_int(stmt, BM25_COL_END);- if (sl > 0) {- snprintf(lines, sizeof(lines), "%d-%d", sl, el > sl ? el : sl);- } else {- lines[0] = '\0';- }- cbm_tree_row_begin(&rows);- cbm_tree_cell_str(&rows, (const char *)sqlite3_column_text(stmt, BM25_COL_QN), true);- cbm_tree_cell_str(&rows, (const char *)sqlite3_column_text(stmt, BM25_COL_LABEL),- false);- cbm_tree_cell_str(&rows, (const char *)sqlite3_column_text(stmt, BM25_COL_FILE), false);- cbm_tree_cell_str(&rows, lines, false);- cbm_tree_cell_real(&rows, sqlite3_column_double(stmt, BM25_COL_RANK), false);- cbm_tree_row_end(&rows);- emitted++;+ /* The top-candidate window is a performance ceiling, not an exact-total+ * boundary. Probe one candidate beyond it so a broad query never presents+ * a window-local count as the complete match count. This is global to the+ * FTS table; saturation is therefore conservatively reported even when+ * later project/path filters might discard the hidden candidates. */+ bool candidate_window_saturated = true;+ {+ const char *probe_sql = "SELECT rowid FROM nodes_fts WHERE nodes_fts MATCH ?1 "+ "ORDER BY bm25(nodes_fts), rowid LIMIT 1 OFFSET ?2";+ sqlite3_stmt *probe = NULL;+ if (sqlite3_prepare_v2(db, probe_sql, BM25_SQL_AUTO_LEN, &probe, NULL) == SQLITE_OK) {+ sqlite3_bind_text(probe, BM25_BIND_QUERY, fts_query, BM25_SQL_AUTO_LEN,+ MCP_SQLITE_TRANSIENT);+ sqlite3_bind_int(probe, BM25_BIND_PROJECT, BM25_INNER_LIMIT);+ int probe_step = sqlite3_step(probe);+ candidate_window_saturated = probe_step != SQLITE_DONE;+ sqlite3_finalize(probe);}- sqlite3_finalize(stmt);- free(file_like);+ }- cbm_sb_t sb;- cbm_sb_init(&sb);- cbm_tree_scalar_int(&sb, "total", total);- cbm_tree_scalar_str(&sb, "search_mode", "bm25");- static const char *const cols[] = {"qn", "label", "file", "lines", "rank"};- cbm_tree_table_header(&sb, "results", emitted, cols, 5);- char *rows_text = cbm_sb_finish(&rows);- cbm_sb_append(&sb, rows_text ? rows_text : "");- free(rows_text);- cbm_tree_scalar_bool(&sb, "has_more", total > offset + emitted);- return cbm_sb_finish(&sb);+ int row_cap = limit > 0 ? limit : BM25_DEFAULT_LIMIT;+ bm25_output_row_t *rows = calloc((size_t)row_cap, sizeof(*rows));+ int row_count = 0;+ while (rows && row_count < row_cap && sqlite3_step(stmt) == SQLITE_ROW) {+ const char *qn = (const char *)sqlite3_column_text(stmt, BM25_COL_QN);+ const char *label = (const char *)sqlite3_column_text(stmt, BM25_COL_LABEL);+ const char *file = (const char *)sqlite3_column_text(stmt, BM25_COL_FILE);+ rows[row_count].qualified_name = heap_strdup(qn ? qn : "");+ rows[row_count].label = heap_strdup(label ? label : "");+ rows[row_count].file_path = heap_strdup(file ? file : "");+ rows[row_count].start_line = sqlite3_column_int(stmt, BM25_COL_START);+ rows[row_count].end_line = sqlite3_column_int(stmt, BM25_COL_END);+ rows[row_count].rank = sqlite3_column_double(stmt, BM25_COL_RANK);+ row_count++;}+ sqlite3_finalize(stmt);+ free(file_like);- /* format:"json" = json-stringified tree: cols + column-ordered row- * arrays (rank order preserved — no grouping on ranked output). */- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);- yyjson_mut_val *root = yyjson_mut_obj(doc);- yyjson_mut_doc_set_root(doc, root);- yyjson_mut_obj_add_int(doc, root, "total", total);- yyjson_mut_obj_add_str(doc, root, "search_mode", "bm25");- yyjson_mut_val *jcols = yyjson_mut_arr(doc);- static const char *const bm25_cols[] = {"qn", "label", "file", "lines", "rank"};- for (size_t ci = 0; ci < sizeof(bm25_cols) / sizeof(bm25_cols[0]); ci++) {- yyjson_mut_arr_add_str(doc, jcols, bm25_cols[ci]);+ if (!rows) {+ return heap_strdup("out of memory");}- yyjson_mut_obj_add_val(doc, root, "cols", jcols);- yyjson_mut_val *rows = yyjson_mut_arr(doc);- int emitted = 0;- while (sqlite3_step(stmt) == SQLITE_ROW) {- char lines[CBM_SZ_32];- int sl = sqlite3_column_int(stmt, BM25_COL_START);- int el = sqlite3_column_int(stmt, BM25_COL_END);- if (sl > 0) {- snprintf(lines, sizeof(lines), "%d-%d", sl, el > sl ? el : sl);- } else {- lines[0] = '\0';+ int returned = row_count;+ bool budget_hit = false;+ char *payload = NULL;+ for (;;) {+ payload = bm25_render(rows, returned, total, offset, candidate_window_saturated,+ tree_format, budget_hit, false, max_output_bytes);+ if (!payload || strlen(payload) <= max_output_bytes || returned == 0) {+ break;}- yyjson_mut_val *row = yyjson_mut_arr(doc);- yyjson_mut_arr_add_strcpy(doc, row, (const char *)sqlite3_column_text(stmt, BM25_COL_QN));- yyjson_mut_arr_add_strcpy(doc, row,- (const char *)sqlite3_column_text(stmt, BM25_COL_LABEL));- yyjson_mut_arr_add_strcpy(doc, row, (const char *)sqlite3_column_text(stmt, BM25_COL_FILE));- yyjson_mut_arr_add_strcpy(doc, row, lines);- yyjson_mut_arr_add_real(doc, row, sqlite3_column_double(stmt, BM25_COL_RANK));- yyjson_mut_arr_add_val(rows, row);- emitted++;+ free(payload);+ payload = NULL;+ budget_hit = true;+ returned--;}- sqlite3_finalize(stmt);- free(file_like);-- yyjson_mut_obj_add_val(doc, root, "rows", rows);- yyjson_mut_obj_add_bool(doc, root, "has_more", total > offset + emitted);- char *json = yy_doc_to_str(doc);- yyjson_mut_doc_free(doc);- return json;+ if (!payload || strlen(payload) > max_output_bytes || (row_count > 0 && returned == 0)) {+ free(payload);+ payload = bm25_render(rows, 0, total, offset, candidate_window_saturated, tree_format, true,+ row_count > 0, max_output_bytes);+ }+ bm25_output_rows_free(rows, row_count);+ return payload;}/* Extract keyword strings from a yyjson array into `keywords`. Returns the@@ -3802,7 +4151,7 @@ static int extract_semantic_keywords(yyjson_val *sq_val, const char **keywords,/* Emit vector-search hits in the json-tree model: "semantic": {cols, rows}* — score order preserved (ranked output is never regrouped). */static void emit_semantic_results(yyjson_mut_doc *doc, yyjson_mut_val *root,- cbm_vector_result_t *vresults, int vcount) {+ const cbm_vector_result_t *vresults, int returned) {yyjson_mut_val *sem = yyjson_mut_obj(doc);yyjson_mut_val *scols = yyjson_mut_arr(doc);static const char *const sem_cols[] = {"qn", "label", "file", "score"};@@ -3811,7 +4160,7 @@ static void emit_semantic_results(yyjson_mut_doc *doc, yyjson_mut_val *root,}yyjson_mut_obj_add_val(doc, sem, "cols", scols);yyjson_mut_val *sem_results = yyjson_mut_arr(doc);- for (int v = 0; v < vcount; v++) {+ for (int v = 0; v < returned; v++) {yyjson_mut_val *vitem = yyjson_mut_arr(doc);yyjson_mut_arr_add_strcpy(doc, vitem, vresults[v].qualified_name);yyjson_mut_arr_add_strcpy(doc, vitem, vresults[v].label);@@ -3865,9 +4214,9 @@ static bool run_semantic_query_core(const char *args, cbm_store_t *store, const}/* ── Tree output for search_graph ───────────────────────────────────- * Default response encoding: grouped tree rows (compact_out.h). The same- * model is available as structured JSON via format:"json"; include_connected- * adds a `connected` column in BOTH encodings. */+ * Default response encoding chooses the smaller complete direct/grouped tree+ * (compact_out.h). format:"json" keeps a stable grouped model;+ * include_connected adds a `connected` column in both encodings. */enum { SG_MAX_EXTRA_FIELDS = 12 };@@ -3956,20 +4305,6 @@ static void sg_toon_property_cell(cbm_sb_t *sb, yyjson_val *v) {}}-/* Append one row's extra-field cells, pulled from the node's properties. */-static void sg_toon_extra_cells(cbm_sb_t *sb, const char *props_json, const char *const *fields,- int nfields) {- yyjson_doc *pd =- (props_json && props_json[0]) ? yyjson_read(props_json, strlen(props_json), 0) : NULL;- yyjson_val *pr = pd ? yyjson_doc_get_root(pd) : NULL;- for (int f = 0; f < nfields; f++) {- yyjson_val *v = (pr && yyjson_is_obj(pr)) ? yyjson_obj_get(pr, fields[f]) : NULL;- sg_toon_property_cell(sb, v);- }- if (pd) {- yyjson_doc_free(pd);- }-}/* "start-end" line range, or empty when the node carries no line info. */static void sg_lines_str(char *out, size_t sz, int start, int end) {@@ -3980,51 +4315,11 @@ static void sg_lines_str(char *out, size_t sz, int start, int end) {}}-/* Emit the regex-path search results as a TOON table. */-static void emit_search_results_toon(cbm_sb_t *sb, const cbm_search_output_t *out, int offset,- const char *const *fields, int nfields, bool detail_ids) {- cbm_tree_scalar_int(sb, "total", out->total);- if (detail_ids) {- /* ids tier: bare qn enumeration — for "list everything matching X"- * sweeps where per-row metadata is noise (LocAgent's fold tier). */- static const char *const id_cols[] = {"qn"};- cbm_tree_table_header(sb, "results", out->count, id_cols, 1);- for (int i = 0; i < out->count; i++) {- cbm_tree_row_begin(sb);- cbm_tree_cell_str(sb, out->results[i].node.qualified_name, true);- cbm_tree_row_end(sb);- }- cbm_tree_scalar_bool(sb, "has_more", out->total > offset + out->count);- return;- }- const char *cols[6 + SG_MAX_EXTRA_FIELDS] = {"qn", "label", "file", "lines", "in", "out"};- int ncols = 6;- for (int f = 0; f < nfields; f++) {- cols[ncols++] = fields[f];- }- cbm_tree_table_header(sb, "results", out->count, cols, ncols);- for (int i = 0; i < out->count; i++) {- const cbm_search_result_t *sr = &out->results[i];- char lines[CBM_SZ_32];- sg_lines_str(lines, sizeof(lines), sr->node.start_line, sr->node.end_line);- cbm_tree_row_begin(sb);- cbm_tree_cell_str(sb, sr->node.qualified_name, true);- cbm_tree_cell_str(sb, sr->node.label, false);- cbm_tree_cell_str(sb, sr->node.file_path, false);- cbm_tree_cell_str(sb, lines, false);- cbm_tree_cell_int(sb, sr->in_degree, false);- cbm_tree_cell_int(sb, sr->out_degree, false);- sg_toon_extra_cells(sb, sr->node.properties_json, fields, nfields);- cbm_tree_row_end(sb);- }- cbm_tree_scalar_bool(sb, "has_more", out->total > offset + out->count);-}-/* ── Tree format (Phase-2 A/B candidate) ────────────────────────────* Prefix-factored, file-grouped output: the shared (qn-prefix, file) pair is* printed ONCE per group, rows beneath carry only the short name + data- * cells. The reconstruction rule (qn = group-prefix + "." + name) is stated- * once in the header so agents can copy exact join keys into follow-up+ * cells. The reconstruction rule accounts for dotless qualified names and is+ * stated once in the header so agents can copy exact join keys into follow-up* calls. Research basis: HDT front-coding (prefix factoring), LocAgent tree* ablation (tree > flat/DOT for LLM comprehension), Lost-in-Distance* (related rows adjacent — grouping by module does exactly that). */@@ -4035,55 +4330,168 @@ static size_t sg_qn_prefix_len(const char *qn) {return last ? (size_t)(last - qn) : 0;}-static int sg_cmp_by_qn(const void *pa, const void *pb) {- const cbm_search_result_t *a = (const cbm_search_result_t *)pa;- const cbm_search_result_t *b = (const cbm_search_result_t *)pb;- const char *qa = a->node.qualified_name ? a->node.qualified_name : "";- const char *qb = b->node.qualified_name ? b->node.qualified_name : "";- return strcmp(qa, qb);+typedef struct {+ int returned;+ int fields_returned;+ int semantic_returned;+ bool connected_returned;+ bool core_hint_returned;+ bool budget_hit;+ bool floor_exceeded;+} sg_render_plan_t;++static bool sg_page_has_more(int total, int offset, int returned) {+ return total > offset + returned;+}++static void sg_emit_paging_tree(cbm_sb_t *sb, int total, int offset, const sg_render_plan_t *plan,+ int requested_fields, bool connected_requested,+ size_t max_output_bytes, bool continuation_supported) {+ bool has_more = continuation_supported && sg_page_has_more(total, offset, plan->returned);+ cbm_tree_scalar_int(sb, "total", total);+ cbm_tree_scalar_int(sb, "returned", plan->returned);+ cbm_tree_scalar_bool(sb, "has_more", has_more);+ if (has_more && plan->returned > 0) {+ cbm_tree_scalar_int(sb, "next_offset", offset + plan->returned);+ } else if (has_more) {+ cbm_tree_scalar_bool(sb, "continuation_requires_higher_budget", true);+ }+ bool truncated = has_more || plan->budget_hit;+ cbm_tree_scalar_bool(sb, "truncated", truncated);+ if (truncated) {+ cbm_tree_scalar_str(sb, "truncation_reason",+ plan->budget_hit ? "output_budget" : "page_limit");+ }+ if (plan->budget_hit) {+ cbm_tree_scalar_int(sb, "max_output_bytes", (long long)max_output_bytes);+ }+ if (requested_fields > plan->fields_returned) {+ cbm_tree_scalar_int(sb, "fields_omitted", requested_fields - plan->fields_returned);+ }+ if (connected_requested && !plan->connected_returned) {+ cbm_tree_scalar_bool(sb, "connected_omitted", true);+ }+ if (plan->floor_exceeded) {+ cbm_tree_scalar_bool(sb, "output_budget_floor_exceeded", true);+ cbm_tree_scalar_str(sb, "hint",+ "first identity row exceeds max_output_bytes; raise "+ "max_output_tokens");+ }+}++static void sg_emit_paging_json(yyjson_mut_doc *doc, yyjson_mut_val *root, int total, int offset,+ const sg_render_plan_t *plan, int requested_fields,+ bool connected_requested, size_t max_output_bytes,+ bool continuation_supported) {+ bool has_more = continuation_supported && sg_page_has_more(total, offset, plan->returned);+ yyjson_mut_obj_add_int(doc, root, "total", total);+ yyjson_mut_obj_add_int(doc, root, "returned", plan->returned);+ yyjson_mut_obj_add_int(doc, root, "count", plan->returned);+ yyjson_mut_obj_add_bool(doc, root, "has_more", has_more);+ if (has_more && plan->returned > 0) {+ yyjson_mut_obj_add_int(doc, root, "next_offset", offset + plan->returned);+ } else if (has_more) {+ yyjson_mut_obj_add_bool(doc, root, "continuation_requires_higher_budget", true);+ }+ bool truncated = has_more || plan->budget_hit;+ yyjson_mut_obj_add_bool(doc, root, "truncated", truncated);+ if (truncated) {+ yyjson_mut_obj_add_str(doc, root, "truncation_reason",+ plan->budget_hit ? "output_budget" : "page_limit");+ }+ if (plan->budget_hit) {+ yyjson_mut_obj_add_uint(doc, root, "max_output_bytes", max_output_bytes);+ }+ if (requested_fields > plan->fields_returned) {+ yyjson_mut_obj_add_int(doc, root, "fields_omitted",+ requested_fields - plan->fields_returned);+ }+ if (connected_requested && !plan->connected_returned) {+ yyjson_mut_obj_add_bool(doc, root, "connected_omitted", true);+ }+ if (plan->floor_exceeded) {+ yyjson_mut_obj_add_bool(doc, root, "output_budget_floor_exceeded", true);+ yyjson_mut_obj_add_str(doc, root, "hint",+ "first identity row exceeds max_output_bytes; raise "+ "max_output_tokens");+ }}-static void emit_search_results_tree(cbm_sb_t *sb, cbm_search_output_t *out, int offset,- const char *const *fields, int nfields, cbm_store_t *store,- const char *relationship, bool include_connected) {- char buf[CBM_SZ_512];- char extra_cols[CBM_SZ_256] = "";+static void emit_search_results_ids_tree(cbm_sb_t *sb, const cbm_search_output_t *out,+ int returned) {+ static const char *const id_cols[] = {"qn"};+ cbm_tree_table_header(sb, "results", returned, id_cols, 1);+ for (int i = 0; i < returned; i++) {+ cbm_tree_row_begin(sb);+ cbm_tree_cell_str(sb, out->results[i].node.qualified_name, true);+ cbm_tree_row_end(sb);+ }+}++static void emit_search_results_ids_json(yyjson_mut_doc *doc, yyjson_mut_val *root,+ const cbm_search_output_t *out, int returned) {+ yyjson_mut_val *cols = yyjson_mut_arr(doc);+ yyjson_mut_arr_add_str(doc, cols, "qn");+ yyjson_mut_obj_add_val(doc, root, "cols", cols);+ yyjson_mut_val *rows = yyjson_mut_arr(doc);+ for (int i = 0; i < returned; i++) {+ yyjson_mut_val *row = yyjson_mut_arr(doc);+ yyjson_mut_arr_add_strcpy(+ doc, row,+ out->results[i].node.qualified_name ? out->results[i].node.qualified_name : "");+ yyjson_mut_arr_add_val(rows, row);+ }+ yyjson_mut_obj_add_val(doc, root, "rows", rows);+}++static void emit_search_results_grouped_tree(cbm_sb_t *sb, const cbm_search_output_t *out,+ const char *const *fields, int nfields,+ cbm_store_t *store, const char *relationship,+ bool include_connected, int returned) {+ cbm_sb_append(sb, "results: ");+ char count_buf[CBM_SZ_32];+ snprintf(count_buf, sizeof(count_buf), "%d", returned);+ cbm_sb_append(sb, count_buf);+ cbm_sb_append(sb, " (rows: name label lines in out");for (int f = 0; f < nfields; f++) {- strncat(extra_cols, " ", sizeof(extra_cols) - strlen(extra_cols) - 1);- strncat(extra_cols, fields[f], sizeof(extra_cols) - strlen(extra_cols) - 1);+ cbm_sb_append(sb, " ");+ cbm_sb_append(sb, fields[f]);}if (include_connected) {- strncat(extra_cols, " connected", sizeof(extra_cols) - strlen(extra_cols) - 1);- }- snprintf(buf, sizeof(buf),- "total: %d\nresults: %d (rows: name label lines in out%s; "- "qn = group prefix + \".\" + name)\n",- out->total, out->count, extra_cols);- cbm_sb_append(sb, buf);- /* Sort by qn so same-prefix rows are adjacent (module clustering). */- if (out->count > 1) {- qsort(out->results, (size_t)out->count, sizeof(cbm_search_result_t), sg_cmp_by_qn);+ cbm_sb_append(sb, " connected");}- char cur_group[CBM_SZ_1K] = "";- for (int i = 0; i < out->count; i++) {+ cbm_sb_append(sb, "; group prefix \"-\" means empty; "+ "qn = prefix empty ? name : prefix + \".\" + name)\n");++ char *previous_prefix = NULL;+ char *previous_file = NULL;+ for (int i = 0; i < returned; i++) {const cbm_search_result_t *sr = &out->results[i];const char *qn = sr->node.qualified_name ? sr->node.qualified_name : "";const char *file = sr->node.file_path ? sr->node.file_path : "";size_t plen = sg_qn_prefix_len(qn);- char group[CBM_SZ_1K];- snprintf(group, sizeof(group), "%.*s (%s)", (int)plen, qn, file);- if (strcmp(group, cur_group) != 0) {- snprintf(cur_group, sizeof(cur_group), "%s", group);- cbm_sb_append(sb, group);- cbm_sb_append(sb, ":\n");+ bool same_group = previous_prefix && strlen(previous_prefix) == plen &&+ memcmp(previous_prefix, qn, plen) == 0 && previous_file &&+ strcmp(previous_file, file) == 0;+ if (!same_group) {+ free(previous_prefix);+ free(previous_file);+ previous_prefix = cbm_strndup(qn, plen);+ previous_file = heap_strdup(file);+ cbm_tree_cell_str(sb, previous_prefix ? previous_prefix : "", true);+ cbm_sb_append(sb, " (");+ cbm_tree_cell_str(sb, previous_file ? previous_file : "", true);+ cbm_sb_append(sb, "):\n");}const char *shortname = plen ? qn + plen + 1 : qn;char lines[CBM_SZ_32];sg_lines_str(lines, sizeof(lines), sr->node.start_line, sr->node.end_line);- char row[CBM_SZ_1K];- snprintf(row, sizeof(row), " %s %s %s %d %d", shortname,- sr->node.label ? sr->node.label : "", lines, sr->in_degree, sr->out_degree);- cbm_sb_append(sb, row);+ cbm_sb_append(sb, " ");+ cbm_tree_cell_str(sb, shortname, true);+ cbm_tree_cell_str(sb, sr->node.label ? sr->node.label : "", false);+ cbm_tree_cell_str(sb, lines, false);+ cbm_tree_cell_int(sb, sr->in_degree, false);+ cbm_tree_cell_int(sb, sr->out_degree, false);/* Extra property columns (fields param). Routed through the shared* cell emitters so values with spaces (signatures, docstrings) are* QUOTED — a raw append would shift every following column. Missing@@ -4103,15 +4511,87 @@ static void emit_search_results_tree(cbm_sb_t *sb, cbm_search_output_t *out, int}}if (include_connected && sr->node.id > 0) {- char joined[CBM_SZ_1K];- enrich_connected_joined(store, sr->node.id, relationship, joined, sizeof(joined));- cbm_tree_cell_str(sb, joined, false); /* empty emits "-" */+ char *joined = enrich_connected_joined(store, sr->node.id, relationship);+ cbm_tree_cell_str(sb, joined ? joined : "", false); /* empty emits "-" */+ free(joined);}cbm_sb_append(sb, "\n");}- snprintf(buf, sizeof(buf), "has_more: %s\n",- out->total > offset + out->count ? "true" : "false");- cbm_sb_append(sb, buf);+ free(previous_prefix);+ free(previous_file);+}++/* The grouped search shape is excellent when rows share a module/file, but its+ * reconstruction rule and group headers are pure overhead for a singleton or+ * a scatter of unrelated rows. The common, no-extra-fields path can be+ * represented as a regular table, so render both byte-for-byte and keep the+ * smaller lossless form. Extra property/connected columns retain the grouped+ * emitter because their cells are dynamically typed. */+static char *render_search_results_flat_tree(const cbm_search_output_t *out, int returned) {+ static const char *const cols[] = {"qn", "label", "file", "lines", "in", "out"};+ static const bool string_cols[] = {true, true, true, true, false, false};+ static const bool prefix_cols[] = {true, false, true, false, false, false};+ enum { COLS = 6, CELL_TEXTS = 3 };+ if (returned == 0) {+ cbm_sb_t empty;+ cbm_sb_init(&empty);+ cbm_tree_table_header(&empty, "results", 0, cols, COLS);+ return cbm_sb_finish(&empty);+ }+ if (returned < 0 || (size_t)returned > (size_t)-1 / (COLS * sizeof(char *)) ||+ (size_t)returned > (size_t)-1 / (CELL_TEXTS * CBM_SZ_32)) {+ return NULL;+ }+ const char **cells = calloc((size_t)returned * COLS, sizeof(*cells));+ char *text = calloc((size_t)returned * CELL_TEXTS, CBM_SZ_32);+ if (!cells || !text) {+ free(cells);+ free(text);+ return NULL;+ }+ for (int i = 0; i < returned; i++) {+ const cbm_search_result_t *sr = &out->results[i];+ char *lines = text + (size_t)(i * CELL_TEXTS) * CBM_SZ_32;+ char *in_degree = lines + CBM_SZ_32;+ char *out_degree = in_degree + CBM_SZ_32;+ sg_lines_str(lines, CBM_SZ_32, sr->node.start_line, sr->node.end_line);+ snprintf(in_degree, CBM_SZ_32, "%d", sr->in_degree);+ snprintf(out_degree, CBM_SZ_32, "%d", sr->out_degree);+ cells[(size_t)i * COLS] = sr->node.qualified_name ? sr->node.qualified_name : "";+ cells[(size_t)i * COLS + 1U] = sr->node.label ? sr->node.label : "";+ cells[(size_t)i * COLS + 2U] = sr->node.file_path ? sr->node.file_path : "";+ cells[(size_t)i * COLS + 3U] = lines;+ cells[(size_t)i * COLS + 4U] = in_degree;+ cells[(size_t)i * COLS + 5U] = out_degree;+ }+ cbm_sb_t flat;+ cbm_sb_init(&flat);+ cbm_tree_table_rows_profiled(&flat, "results", returned, cols, COLS, cells, string_cols,+ prefix_cols);+ char *rendered = cbm_sb_finish(&flat);+ free(cells);+ free(text);+ return rendered;+}++static void emit_search_results_tree(cbm_sb_t *sb, const cbm_search_output_t *out,+ const char *const *fields, int nfields, cbm_store_t *store,+ const char *relationship, bool include_connected,+ int returned) {+ cbm_sb_t grouped;+ cbm_sb_init(&grouped);+ emit_search_results_grouped_tree(&grouped, out, fields, nfields, store, relationship,+ include_connected, returned);+ char *grouped_text = cbm_sb_finish(&grouped);+ char *flat_text =+ nfields == 0 && !include_connected ? render_search_results_flat_tree(out, returned) : NULL;+ if (flat_text && (!grouped_text || strlen(flat_text) < strlen(grouped_text))) {+ cbm_sb_append(sb, flat_text);+ } else if (grouped_text) {+ cbm_sb_append(sb, grouped_text);+ }+ free(flat_text);+ free(grouped_text);}/* json-stringified tree: the SAME grouped model as the text tree, serialized@@ -4119,12 +4599,11 @@ static void emit_search_results_tree(cbm_sb_t *sb, cbm_search_output_t *out, int* (qn_prefix, file) and column-ordered row ARRAYS (never per-row key* envelopes; that legacy shape was 84% key overhead). */static void emit_search_results_tree_json(yyjson_mut_doc *doc, yyjson_mut_val *root,- cbm_search_output_t *out, int offset,- const char *const *fields, int nfields,- cbm_store_t *store, const char *relationship,- bool include_connected) {- yyjson_mut_obj_add_int(doc, root, "total", out->total);- yyjson_mut_obj_add_int(doc, root, "count", out->count);+ const cbm_search_output_t *out, const char *const *fields,+ int nfields, cbm_store_t *store, const char *relationship,+ bool include_connected, int returned) {+ yyjson_mut_obj_add_str(doc, root, "qn_rule",+ "qn = qn_prefix == \"\" ? name : qn_prefix + \".\" + name");yyjson_mut_val *cols = yyjson_mut_arr(doc);static const char *const col_names[] = {"name", "label", "lines", "in", "out"};for (size_t i = 0; i < sizeof(col_names) / sizeof(col_names[0]); i++) {@@ -4137,26 +4616,26 @@ static void emit_search_results_tree_json(yyjson_mut_doc *doc, yyjson_mut_val *ryyjson_mut_arr_add_str(doc, cols, "connected");}yyjson_mut_obj_add_val(doc, root, "cols", cols);- if (out->count > 1) {- qsort(out->results, (size_t)out->count, sizeof(cbm_search_result_t), sg_cmp_by_qn);- }yyjson_mut_val *groups = yyjson_mut_arr(doc);yyjson_mut_val *cur = NULL;yyjson_mut_val *cur_rows = NULL;- char cur_key[CBM_SZ_1K] = "";- for (int i = 0; i < out->count; i++) {+ char *previous_prefix = NULL;+ char *previous_file = NULL;+ for (int i = 0; i < returned; i++) {const cbm_search_result_t *sr = &out->results[i];const char *qn = sr->node.qualified_name ? sr->node.qualified_name : "";const char *file = sr->node.file_path ? sr->node.file_path : "";size_t plen = sg_qn_prefix_len(qn);- char key[CBM_SZ_1K];- snprintf(key, sizeof(key), "%.*s|%s", (int)plen, qn, file);- if (!cur || strcmp(key, cur_key) != 0) {- snprintf(cur_key, sizeof(cur_key), "%s", key);+ bool same_group = previous_prefix && strlen(previous_prefix) == plen &&+ memcmp(previous_prefix, qn, plen) == 0 && previous_file &&+ strcmp(previous_file, file) == 0;+ if (!same_group) {+ free(previous_prefix);+ free(previous_file);+ previous_prefix = cbm_strndup(qn, plen);+ previous_file = heap_strdup(file);cur = yyjson_mut_obj(doc);- char prefix[CBM_SZ_1K];- snprintf(prefix, sizeof(prefix), "%.*s", (int)plen, qn);- yyjson_mut_obj_add_strcpy(doc, cur, "qn_prefix", prefix);+ yyjson_mut_obj_add_strncpy(doc, cur, "qn_prefix", qn, plen);yyjson_mut_obj_add_strcpy(doc, cur, "file", file);cur_rows = yyjson_mut_arr(doc);yyjson_mut_obj_add_val(doc, cur, "rows", cur_rows);@@ -4195,16 +4674,17 @@ static void emit_search_results_tree_json(yyjson_mut_doc *doc, yyjson_mut_val *r}yyjson_mut_arr_add_val(cur_rows, row);}+ free(previous_prefix);+ free(previous_file);yyjson_mut_obj_add_val(doc, root, "groups", groups);- yyjson_mut_obj_add_bool(doc, root, "has_more", out->total > offset + out->count);}/* Emit semantic vector-search results as a TOON table. */static void emit_semantic_results_toon(cbm_sb_t *sb, const cbm_vector_result_t *vresults,- int vcount) {+ int returned) {static const char *const cols[] = {"qn", "label", "file", "score"};- cbm_tree_table_header(sb, "semantic", vcount, cols, 4);- for (int v = 0; v < vcount; v++) {+ cbm_tree_table_header(sb, "semantic", returned, cols, 4);+ for (int v = 0; v < returned; v++) {cbm_tree_row_begin(sb);cbm_tree_cell_str(sb, vresults[v].qualified_name, true);cbm_tree_cell_str(sb, vresults[v].label, false);@@ -4214,6 +4694,99 @@ static void emit_semantic_results_toon(cbm_sb_t *sb, const cbm_vector_result_t *}}+static char *sg_render_payload(bool json_format, const cbm_search_output_t *out, int offset,+ const char *const *fields, int requested_fields, cbm_store_t *store,+ const char *relationship, bool connected_requested, bool detail_ids,+ const cbm_vector_result_t *vresults, int semantic_total,+ bool semantic_only, const char *diagnostic_hint,+ const sg_render_plan_t *plan, size_t max_output_bytes) {+ sg_render_plan_t meta_plan = *plan;+ int page_total = semantic_only ? semantic_total : out->total;+ int page_offset = semantic_only ? 0 : offset;+ if (semantic_only) {+ meta_plan.returned = plan->semantic_returned;+ }++ if (!json_format) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ if (!semantic_only) {+ if (detail_ids) {+ emit_search_results_ids_tree(&sb, out, plan->returned);+ } else {+ emit_search_results_tree(&sb, out, fields, plan->fields_returned, store,+ relationship, plan->connected_returned, plan->returned);+ }+ }+ if (semantic_total > 0 || semantic_only) {+ cbm_tree_scalar_int(&sb, "semantic_total", semantic_total);+ cbm_tree_scalar_int(&sb, "semantic_returned", plan->semantic_returned);+ emit_semantic_results_toon(&sb, vresults, plan->semantic_returned);+ }+ if (plan->core_hint_returned && diagnostic_hint) {+ cbm_tree_scalar_str(&sb, "hint", diagnostic_hint);+ }+ sg_emit_paging_tree(&sb, page_total, page_offset, &meta_plan, requested_fields,+ connected_requested, max_output_bytes, !semantic_only);+ return cbm_sb_finish(&sb);+ }++ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ if (!semantic_only) {+ if (detail_ids) {+ emit_search_results_ids_json(doc, root, out, plan->returned);+ } else {+ emit_search_results_tree_json(doc, root, out, fields, plan->fields_returned, store,+ relationship, plan->connected_returned, plan->returned);+ }+ }+ if (semantic_total > 0 || semantic_only) {+ yyjson_mut_obj_add_int(doc, root, "semantic_total", semantic_total);+ yyjson_mut_obj_add_int(doc, root, "semantic_returned", plan->semantic_returned);+ emit_semantic_results(doc, root, vresults, plan->semantic_returned);+ }+ if (plan->core_hint_returned && diagnostic_hint) {+ yyjson_mut_obj_add_strcpy(doc, root, "hint", diagnostic_hint);+ }+ sg_emit_paging_json(doc, root, page_total, page_offset, &meta_plan, requested_fields,+ connected_requested, max_output_bytes, !semantic_only);+ char *json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ return json;+}++static char *sg_budget_floor(bool json_format, int total, int offset, int semantic_total,+ size_t max_output_bytes, bool semantic_only) {+ sg_render_plan_t floor = {+ .returned = 0,+ .fields_returned = 0,+ .semantic_returned = 0,+ .connected_returned = false,+ .core_hint_returned = false,+ .budget_hit = true,+ .floor_exceeded = true,+ };+ int page_total = total > 0 ? total : semantic_total;+ int page_offset = total > 0 ? offset : 0;+ if (!json_format) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ sg_emit_paging_tree(&sb, page_total, page_offset, &floor, 0, false, max_output_bytes,+ !semantic_only);+ return cbm_sb_finish(&sb);+ }+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ sg_emit_paging_json(doc, root, page_total, page_offset, &floor, 0, false, max_output_bytes,+ !semantic_only);+ char *json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ return json;+}+static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {/* Inner phase split: every tool leaks the same ~4 MB per request, so the* retainer is in what the handlers share -- store resolution or the query@@ -4231,23 +4804,39 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {return not_indexed;}- /* Response encoding: grouped tree rows by default; format:"json" emits- * the SAME tree model as structured JSON (groups + row arrays). */+ /* Response encoding: the default tree chooses direct/grouped by serialized+ * size; format:"json" keeps the stable grouped model. The token argument+ * becomes a deterministic byte ceiling: tokenizers differ, bytes do not. */char *format_arg = cbm_mcp_get_string_arg(args, "format");- bool legacy_json = format_arg && strcmp(format_arg, "json") == 0;+ bool json_format = format_arg && strcmp(format_arg, "json") == 0;free(format_arg);+ int limit = cbm_mcp_get_int_arg(args, "limit", CBM_DEFAULT_SEARCH_LIMIT);+ if (limit < 1) {+ limit = 1;+ } else if (limit > 500) {+ limit = 500;+ }+ int offset = cbm_mcp_get_int_arg(args, "offset", 0);+ if (offset < 0) {+ offset = 0;+ }+ int max_output_tokens = cbm_mcp_get_int_arg(args, "max_output_tokens", 3200);+ if (max_output_tokens < 128) {+ max_output_tokens = 128;+ } else if (max_output_tokens > 1000000) {+ max_output_tokens = 1000000;+ }+ size_t max_output_bytes =+ (size_t)max_output_tokens * (size_t)MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE;/* BM25 path: if `query` is set, run FTS5 full-text search with ranking- * and return early. The regex/vector path below is untouched for all- * other callers. If FTS5 is unavailable or the query is empty after+ * and return early. If FTS5 is unavailable or the query is empty after* tokenization, fall through to the regex path. */char *query = cbm_mcp_get_string_arg(args, "query");if (query && query[0]) {- int q_limit = cbm_mcp_get_int_arg(args, "limit", BM25_DEFAULT_LIMIT);- int q_offset = cbm_mcp_get_int_arg(args, "offset", 0);char *q_file_pattern = cbm_mcp_get_string_arg(args, "file_pattern");- char *bm25_json =- bm25_search(store, project, query, q_file_pattern, q_limit, q_offset, !legacy_json);+ char *bm25_json = bm25_search(store, project, query, q_file_pattern, limit, offset,+ !json_format, max_output_bytes);free(q_file_pattern);if (bm25_json) {free(query);@@ -4266,8 +4855,6 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {char *relationship = cbm_mcp_get_string_arg(args, "relationship");bool exclude_entry_points = cbm_mcp_get_bool_arg(args, "exclude_entry_points");bool include_connected = cbm_mcp_get_bool_arg(args, "include_connected");- int limit = cbm_mcp_get_int_arg(args, "limit", CBM_DEFAULT_SEARCH_LIMIT);- int offset = cbm_mcp_get_int_arg(args, "offset", 0);int min_degree = cbm_mcp_get_int_arg(args, "min_degree", CBM_NOT_FOUND);int max_degree = cbm_mcp_get_int_arg(args, "max_degree", CBM_NOT_FOUND);@@ -4295,112 +4882,14 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {.min_degree = min_degree,.max_degree = max_degree,};- bool has_structural_filters = label || name_pattern || qn_pattern || file_pattern ||- relationship || exclude_entry_points ||- min_degree != CBM_NOT_FOUND || max_degree != CBM_NOT_FOUND;-- if (!legacy_json) {- const char *fields[SG_MAX_EXTRA_FIELDS];- yyjson_doc *fields_owner = NULL;- char *sg_detail = cbm_mcp_get_string_arg(args, "detail");- bool detail_ids = sg_detail && strcmp(sg_detail, "ids") == 0;- free(sg_detail);- bool core_fields_requested = false;- int nfields = sg_parse_fields(args, fields, SG_MAX_EXTRA_FIELDS, &fields_owner,- &core_fields_requested);-- cbm_vector_result_t *vresults = NULL;- int vcount = 0;- bool sq_present = false;- bool sq_type_error =- run_semantic_query_core(args, store, project, limit, &vresults, &vcount, &sq_present);- if (!sq_type_error) {- /* Semantic-only calls get semantic results only: the legacy- * behavior also ran the UNFILTERED regex search and prepended- * up to `limit` unrelated enriched nodes to the response. */- bool semantic_only = sq_present && !has_structural_filters;-- cbm_sb_t sb;- cbm_sb_init(&sb);- cbm_search_output_t tout = {0};- if (!semantic_only) {- cbm_store_search(store, ¶ms, &tout);- /* Grouped tree output is THE default; the flat table remains- * only for detail:"ids" (single column — nothing to group). */- if (detail_ids) {- emit_search_results_toon(&sb, &tout, offset, fields, nfields, detail_ids);- } else {- emit_search_results_tree(&sb, &tout, offset, fields, nfields, store,- relationship, include_connected);- }- if (core_fields_requested) {- cbm_tree_scalar_str(- &sb, "hint",- "some requested fields (file/name/qn/label/lines) are already core "- "row columns and were skipped — `fields` is for extra property "- "columns like complexity, cognitive, signature");- }- if (tout.total == 0) {- if (name_pattern && label) {- cbm_tree_scalar_str(&sb, "hint",- "No results. Try removing the label filter or "- "broadening the name_pattern regex.");- } else if (name_pattern) {- cbm_tree_scalar_str(- &sb, "hint",- "No nodes match this pattern. Check spelling or try a broader regex.");- } else if (label) {- cbm_tree_scalar_str(&sb, "hint",- "No nodes with this label. Available labels: "- "Function, Method, Class, Interface, Route, "- "Variable, Module, Package, File, Folder.");- }- }- }- if (vcount > 0) {- emit_semantic_results_toon(&sb, vresults, vcount);- } else if (semantic_only) {- static const char *const sem_cols[] = {"qn", "label", "file", "score"};- cbm_tree_table_header(&sb, "semantic", 0, sem_cols, 4);- cbm_tree_scalar_str(&sb, "hint",- "No semantic matches. semantic_query needs a moderate/full "- "index; try broader or fewer keywords.");- }- if (vcount > 0) {- cbm_store_free_vector_results(vresults, vcount);- }- if (fields_owner) {- yyjson_doc_free(fields_owner);- }- cbm_store_search_free(&tout);- free(project);- free(label);- free(name_pattern);- free(qn_pattern);- free(file_pattern);- free(relationship);- char *text = cbm_sb_finish(&sb);- char *result = cbm_mcp_text_result(text ? text : "out of memory", text == NULL);- free(text);- return result;- }- /* semantic_query type error: fall through to the shared error text. */- if (fields_owner) {- yyjson_doc_free(fields_owner);- }- free(project);- free(label);- free(name_pattern);- free(qn_pattern);- free(file_pattern);- free(relationship);- return cbm_mcp_text_result(- "semantic_query must be an array of keyword strings, e.g. "- "[\"send\",\"pubsub\",\"publish\"] — not a single string. Split your query "- "into individual keywords; each is scored independently via per-keyword "- "min-cosine.",- true);- }+ const char *fields[SG_MAX_EXTRA_FIELDS];+ yyjson_doc *fields_owner = NULL;+ bool core_fields_requested = false;+ int nfields =+ sg_parse_fields(args, fields, SG_MAX_EXTRA_FIELDS, &fields_owner, &core_fields_requested);+ char *detail_arg = cbm_mcp_get_string_arg(args, "detail");+ bool detail_ids = detail_arg && strcmp(detail_arg, "ids") == 0;+ free(detail_arg);cbm_vector_result_t *vresults = NULL;int vcount = 0;@@ -4408,6 +4897,9 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {bool sq_type_error =run_semantic_query_core(args, store, project, limit, &vresults, &vcount, &sq_present);if (sq_type_error) {+ if (fields_owner) {+ yyjson_doc_free(fields_owner);+ }free(project);free(label);free(name_pattern);@@ -4422,58 +4914,90 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {true);}- bool semantic_only = sq_present && !has_structural_filters;+ /* Semantic-only calls must not prepend an unrelated, unfiltered symbol+ * page. Combined calls retain both independently ranked result sets. */+ bool has_filters = label || name_pattern || qn_pattern || file_pattern || relationship ||+ exclude_entry_points || min_degree != CBM_NOT_FOUND ||+ max_degree != CBM_NOT_FOUND;+ bool semantic_only = sq_present && !has_filters;cbm_search_output_t out = {0};if (!semantic_only) {- cbm_store_search(store, ¶ms, &out);- }-- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);- yyjson_mut_val *root = yyjson_mut_obj(doc);- yyjson_mut_doc_set_root(doc, root);-- /* format:"json" = json-stringified tree: same grouped model as the- * default text output, structured for parsing. include_connected adds a- * nested per-row `connected` array — the legacy per-node-object shape is- * gone. */- {- const char *jfields[SG_MAX_EXTRA_FIELDS];- yyjson_doc *jfields_owner = NULL;- int jnfields = sg_parse_fields(args, jfields, SG_MAX_EXTRA_FIELDS, &jfields_owner, NULL);- emit_search_results_tree_json(doc, root, &out, offset, jfields, jnfields, store,- relationship, include_connected);- if (jfields_owner) {- yyjson_doc_free(jfields_owner);- }+ (void)cbm_store_search(store, ¶ms, &out);}- /* Add diagnostic hint when zero results */- if (out.total == 0) {+ const char *diagnostic_hint = NULL;+ if (semantic_only && vcount == 0) {+ diagnostic_hint = "No semantic matches; use a moderate/full index or broader keywords.";+ } else if (!semantic_only && out.total == 0) {if (name_pattern && label) {- yyjson_mut_obj_add_str(- doc, root, "hint",- "No results. Try removing the label filter or broadening the name_pattern regex.");+ diagnostic_hint = "No results; remove label or broaden name_pattern.";} else if (name_pattern) {- yyjson_mut_obj_add_str(- doc, root, "hint",- "No nodes match this pattern. Check spelling or try a broader regex.");+ diagnostic_hint = "No nodes match; check spelling or broaden the regex.";} else if (label) {- yyjson_mut_obj_add_str(- doc, root, "hint",- "No nodes with this label. Available labels: Function, Method, Class, "- "Interface, Route, Variable, Module, Package, File, Folder.");+ diagnostic_hint = "No nodes have this label; inspect get_graph_schema.";}+ } else if (core_fields_requested) {+ diagnostic_hint = "Core qn/name/label/file/lines fields are already present.";+ }++ int requested_fields = detail_ids ? 0 : nfields;+ sg_render_plan_t plan = {+ .returned = out.count,+ .fields_returned = requested_fields,+ .semantic_returned = vcount,+ .connected_returned = !detail_ids && include_connected,+ .core_hint_returned = diagnostic_hint != NULL,+ .budget_hit = false,+ .floor_exceeded = false,+ };++ char *payload = NULL;+ for (;;) {+ payload =+ sg_render_payload(json_format, &out, offset, fields, requested_fields, store,+ relationship, !detail_ids && include_connected, detail_ids, vresults,+ vcount, semantic_only, diagnostic_hint, &plan, max_output_bytes);+ if (!payload || strlen(payload) <= max_output_bytes) {+ break;+ }+ free(payload);+ payload = NULL;+ plan.budget_hit = true;++ /* Preserve core graph answers in their stable ranked/name order.+ * Diagnostics and opt-in enrichment yield first, then whole lower-+ * ranked rows. No identifier, path, or field value is byte-sliced. */+ if (plan.core_hint_returned) {+ plan.core_hint_returned = false;+ } else if (plan.connected_returned) {+ plan.connected_returned = false;+ } else if (plan.fields_returned > 0) {+ plan.fields_returned--;+ } else if (plan.semantic_returned > 0) {+ plan.semantic_returned--;+ } else if (plan.returned > 0) {+ plan.returned--;+ } else {+ break;+ }+ }++ bool identity_available = out.count > 0 || vcount > 0;+ bool identity_returned = plan.returned > 0 || plan.semantic_returned > 0;+ if (!payload || strlen(payload) > max_output_bytes ||+ (identity_available && plan.budget_hit && !identity_returned)) {+ free(payload);+ payload = sg_budget_floor(json_format, out.total, offset, vcount, max_output_bytes,+ semantic_only);}if (vcount > 0) {- emit_semantic_results(doc, root, vresults, vcount);cbm_store_free_vector_results(vresults, vcount);}-- char *json = yy_doc_to_str(doc);- yyjson_mut_doc_free(doc);+ if (fields_owner) {+ yyjson_doc_free(fields_owner);+ }cbm_store_search_free(&out);-free(project);free(label);free(name_pattern);@@ -4481,16 +5005,261 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {free(file_pattern);free(relationship);- char *result = cbm_mcp_text_result(json, false);- free(json);+ char *result = cbm_mcp_text_result(payload ? payload : "out of memory", payload == NULL);+ free(payload);return result;}+static bool query_graph_semantic_prefix_column(const char *column) {+ if (!column) {+ return false;+ }+ const char *leaf = strrchr(column, '.');+ leaf = leaf ? leaf + 1 : column;+ return strcmp(leaf, "qualified_name") == 0 || strcmp(leaf, "qn") == 0 ||+ strcmp(leaf, "file") == 0 || strcmp(leaf, "file_path") == 0 ||+ strcmp(leaf, "path") == 0 || strcmp(leaf, "root_path") == 0 ||+ strcmp(leaf, "source_file") == 0;+}++static char *query_graph_tree_rows_text(const cbm_cypher_result_t *result, int row_offset,+ int row_count, bool allow_directory) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ bool cell_count_safe = row_count > 0 && result->col_count > 0 &&+ (size_t)row_count <= SIZE_MAX / (size_t)result->col_count;+ size_t cell_count = cell_count_safe ? (size_t)row_count * (size_t)result->col_count : 0;+ cell_count_safe = cell_count_safe && cell_count <= SIZE_MAX / sizeof(const char *);+ const char **cells =+ cell_count_safe ? (const char **)malloc(cell_count * sizeof(*cells)) : NULL;+ if (cells) {+ for (int row = 0; row < row_count; row++) {+ for (int col = 0; col < result->col_count; col++) {+ cells[(size_t)row * (size_t)result->col_count + (size_t)col] =+ result->rows[row_offset + row][col];+ }+ }+ if (allow_directory) {+ bool *prefix_cols = calloc((size_t)result->col_count, sizeof(*prefix_cols));+ if (prefix_cols) {+ for (int col = 0; col < result->col_count; col++) {+ prefix_cols[col] = query_graph_semantic_prefix_column(result->columns[col]);+ }+ cbm_tree_table_rows_profiled(&sb, "rows", row_count,+ (const char *const *)result->columns,+ result->col_count, cells, NULL, prefix_cols);+ free(prefix_cols);+ } else {+ cbm_tree_table_rows(&sb, "rows", row_count, (const char *const *)result->columns,+ result->col_count, cells);+ }+ } else {+ cbm_tree_table_header(&sb, "rows", row_count, (const char *const *)result->columns,+ result->col_count);+ for (int row = 0; row < row_count; row++) {+ cbm_tree_row_begin(&sb);+ for (int col = 0; col < result->col_count; col++) {+ cbm_tree_cell_str(&sb,+ cells[(size_t)row * (size_t)result->col_count + (size_t)col],+ col == 0);+ }+ cbm_tree_row_end(&sb);+ }+ }+ free(cells);+ } else {+ cbm_tree_table_header(&sb, "rows", row_count, (const char *const *)result->columns,+ result->col_count);+ for (int row = 0; row < row_count; row++) {+ cbm_tree_row_begin(&sb);+ for (int col = 0; col < result->col_count; col++) {+ cbm_tree_cell_str(&sb, result->rows[row_offset + row][col], col == 0);+ }+ cbm_tree_row_end(&sb);+ }+ }+ return cbm_sb_finish(&sb);+}++static const char *query_graph_truncation_reason(const cbm_cypher_result_t *result, bool budget_hit,+ bool page_limit_hit) {+ if (budget_hit) {+ return "output_budget";+ }+ if (page_limit_hit) {+ return "page_limit";+ }+ if (result->truncated) {+ return "engine_limit";+ }+ return NULL;+}++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 budget_hit = row_count < visible_count;+ bool materialized_more = row_offset + row_count < result->row_count;+ bool page_limit_hit = !budget_hit && materialized_more;+ bool truncated = budget_hit || materialized_more || result->truncated;++ char *rows_text = query_graph_tree_rows_text(result, row_offset, row_count, allow_directory);+ if (!rows_text) {+ return NULL;+ }+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ cbm_sb_append(&sb, rows_text);+ free(rows_text);+ cbm_tree_scalar_int(&sb, "returned", row_count);+ cbm_tree_scalar_int(&sb, "total", result->row_count);+ cbm_tree_scalar_str(&sb, "total_relation", exact_total ? "eq" : "gte");+ if (row_offset > 0) {+ cbm_tree_scalar_int(&sb, "offset", row_offset);+ }+ cbm_tree_scalar_bool(&sb, "has_more", truncated);+ cbm_tree_scalar_bool(&sb, "truncated", truncated);+ const char *reason = query_graph_truncation_reason(result, budget_hit, page_limit_hit);+ if (reason) {+ cbm_tree_scalar_str(&sb, "truncation_reason", reason);+ }+ if (row_count > 0 && materialized_more) {+ cbm_tree_scalar_int(&sb, "next_offset", row_offset + row_count);+ } else if (budget_hit && row_count == 0) {+ cbm_tree_scalar_str(&sb, "hint",+ "First row exceeds output budget; raise max_output_tokens.");+ }+ if (result->warning) {+ cbm_tree_scalar_str(&sb, "warning", result->warning);+ }+ if (result->row_count == 0 && !result->truncated) {+ cbm_tree_scalar_str(&sb, "hint",+ "Query returned no results. Use get_graph_schema() to see "+ "available labels and edge types.");+ }+ return cbm_sb_finish(&sb);+}++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) {+ 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;+ bool truncated = budget_hit || materialized_more || result->truncated;++ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_val *cols = yyjson_mut_arr(doc);+ for (int i = 0; i < result->col_count; i++) {+ yyjson_mut_arr_add_str(doc, cols, result->columns[i]);+ }+ yyjson_mut_obj_add_val(doc, root, "columns", cols);+ yyjson_mut_val *rows = yyjson_mut_arr(doc);+ for (int row_index = 0; row_index < row_count; row_index++) {+ yyjson_mut_val *row = yyjson_mut_arr(doc);+ for (int col = 0; col < result->col_count; col++) {+ yyjson_mut_arr_add_str(doc, row, result->rows[row_offset + row_index][col]);+ }+ yyjson_mut_arr_add_val(rows, row);+ }+ yyjson_mut_obj_add_val(doc, root, "rows", rows);+ yyjson_mut_obj_add_int(doc, root, "returned", row_count);+ yyjson_mut_obj_add_int(doc, root, "total", result->row_count);+ yyjson_mut_obj_add_str(doc, root, "total_relation", exact_total ? "eq" : "gte");+ if (row_offset > 0) {+ yyjson_mut_obj_add_int(doc, root, "offset", row_offset);+ }+ yyjson_mut_obj_add_bool(doc, root, "has_more", truncated);+ yyjson_mut_obj_add_bool(doc, root, "truncated", truncated);+ const char *reason = query_graph_truncation_reason(result, budget_hit, page_limit_hit);+ if (reason) {+ yyjson_mut_obj_add_str(doc, root, "truncation_reason", reason);+ }+ if (row_count > 0 && materialized_more) {+ 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",+ "First row exceeds output budget; raise max_output_tokens.");+ }+ if (result->warning) {+ yyjson_mut_obj_add_str(doc, root, "warning", result->warning);+ }+ if (result->row_count == 0 && !result->truncated) {+ yyjson_mut_obj_add_str(+ doc, root, "hint",+ "Query returned no results. Use get_graph_schema() to see available labels and "+ "edge types.");+ }+ char *json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ return json;+}++/* A pathological query can make the column expression itself larger than the+ * requested response budget. Do not byte-slice that semantic key. Return a+ * small, explicit recovery envelope and let the caller raise the budget to+ * retrieve the exact columns and first row. */+static char *query_graph_budget_floor_text(const cbm_cypher_result_t *result, int row_offset,+ bool exact_total, bool json_format) {+ if (json_format) {+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_obj_add_val(doc, root, "columns", yyjson_mut_arr(doc));+ yyjson_mut_obj_add_val(doc, root, "rows", yyjson_mut_arr(doc));+ yyjson_mut_obj_add_bool(doc, root, "columns_omitted", true);+ yyjson_mut_obj_add_int(doc, root, "returned", 0);+ yyjson_mut_obj_add_int(doc, root, "total", result->row_count);+ yyjson_mut_obj_add_str(doc, root, "total_relation", exact_total ? "eq" : "gte");+ if (row_offset > 0) {+ yyjson_mut_obj_add_int(doc, root, "offset", row_offset);+ }+ yyjson_mut_obj_add_bool(doc, root, "has_more", true);+ yyjson_mut_obj_add_bool(doc, root, "truncated", true);+ yyjson_mut_obj_add_str(doc, root, "truncation_reason", "output_budget");+ yyjson_mut_obj_add_str(doc, root, "hint",+ "Column metadata or first row exceeds output budget; raise "+ "max_output_tokens.");+ char *json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ return json;+ }++ cbm_sb_t sb;+ cbm_sb_init(&sb);+ cbm_tree_scalar_int(&sb, "rows", 0);+ cbm_tree_scalar_bool(&sb, "columns_omitted", true);+ cbm_tree_scalar_int(&sb, "returned", 0);+ cbm_tree_scalar_int(&sb, "total", result->row_count);+ cbm_tree_scalar_str(&sb, "total_relation", exact_total ? "eq" : "gte");+ if (row_offset > 0) {+ cbm_tree_scalar_int(&sb, "offset", row_offset);+ }+ cbm_tree_scalar_bool(&sb, "has_more", true);+ cbm_tree_scalar_bool(&sb, "truncated", true);+ cbm_tree_scalar_str(&sb, "truncation_reason", "output_budget");+ cbm_tree_scalar_str(&sb, "hint",+ "Column metadata or first row exceeds output budget; raise "+ "max_output_tokens.");+ return cbm_sb_finish(&sb);+}+static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {char *query = cbm_mcp_get_string_arg(args, "query");char *project = get_project_arg(args);cbm_store_t *store = resolve_store(srv, project);- int max_rows = cbm_mcp_get_int_arg(args, "max_rows", 0);+ int visible_limit = cbm_mcp_get_int_arg(args, "max_rows", 200);+ if (visible_limit == 0 || visible_limit > MCP_QUERY_MAX_VISIBLE_ROWS) {+ /* compatibility: max_rows=0 used to mean engine default */+ visible_limit = MCP_QUERY_MAX_VISIBLE_ROWS;+ } else if (visible_limit < 0) {+ visible_limit = 1;+ }+ int row_offset = cbm_mcp_get_int_arg(args, "offset", 0);+ if (row_offset < 0) {+ row_offset = 0;+ }/* graph="missed" (#963): run the SAME cypher against the derived* miss-graph view (shadow project "<project>::missed") instead of the@@ -4531,7 +5300,11 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {}cbm_cypher_result_t result = {0};- int rc = cbm_cypher_execute(store, query, cypher_project, max_rows, &result);+ /* `max_rows` is a presentation budget, never an evaluation budget.+ * Executing at visible_limit+1 corrupts ORDER BY, DISTINCT, aggregation,+ * and SKIP semantics before serialization gets a chance to trim rows.+ * Zero preserves the engine's established 100k safety ceiling. */+ int rc = cbm_cypher_execute(store, query, cypher_project, 0, &result);if (rc < 0) {char *err_msg = result.error ? result.error : "query execution failed";@@ -4548,65 +5321,131 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {bool qg_legacy_json = qg_format && strcmp(qg_format, "json") == 0;free(qg_format);- char *json = NULL;- if (!qg_legacy_json) {- cbm_sb_t sb;- cbm_sb_init(&sb);- cbm_tree_table_header(&sb, "rows", result.row_count, (const char *const *)result.columns,- result.col_count);- for (int r = 0; r < result.row_count; r++) {- cbm_tree_row_begin(&sb);- for (int c = 0; c < result.col_count; c++) {- cbm_tree_cell_str(&sb, result.rows[r][c], c == 0);- }- cbm_tree_row_end(&sb);- }- cbm_tree_scalar_int(&sb, "total", result.row_count);- if (result.warning) {- cbm_tree_scalar_str(&sb, "warning", result.warning);+ int materialized_rows = row_offset < result.row_count ? result.row_count - row_offset : 0;+ int available_rows = materialized_rows < visible_limit ? materialized_rows : visible_limit;+ int max_output_tokens = cbm_mcp_get_int_arg(args, "max_output_tokens", 3200);+ if (max_output_tokens < 128) {+ max_output_tokens = 128;+ } else if (max_output_tokens > 1000000) {+ max_output_tokens = 1000000;+ }+ size_t byte_budget = (size_t)max_output_tokens * (size_t)MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE;+ size_t estimated = 256U;+ for (int c = 0; c < result.col_count; c++) {+ estimated += strlen(result.columns[c]) + 1U;+ }+ int raw_fit_rows = 0;+ for (int r = 0; r < available_rows; r++) {+ size_t row_bytes = 4U;+ for (int c = 0; c < result.col_count; c++) {+ size_t cell_bytes =+ strlen(result.rows[row_offset + r][c] ? result.rows[row_offset + r][c] : "") + 1U;+ row_bytes = row_bytes > SIZE_MAX - cell_bytes ? SIZE_MAX : row_bytes + cell_bytes;}- if (result.row_count == 0) {- cbm_tree_scalar_str(&sb, "hint",- "Query returned no results. Use get_graph_schema() to see "- "available labels and edge types.");+ if (estimated <= byte_budget && row_bytes <= byte_budget - estimated) {+ raw_fit_rows = r + 1;}- json = cbm_sb_finish(&sb);- } else {- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);- yyjson_mut_val *root = yyjson_mut_obj(doc);- yyjson_mut_doc_set_root(doc, root);+ estimated = estimated > SIZE_MAX - row_bytes ? SIZE_MAX : estimated + row_bytes;+ }- /* columns */- yyjson_mut_val *cols = yyjson_mut_arr(doc);- for (int i = 0; i < result.col_count; i++) {- yyjson_mut_arr_add_str(doc, cols, result.columns[i]);- }- yyjson_mut_obj_add_val(doc, root, "columns", cols);+ /* Exact sizing is bounded near the conservative raw estimate. This avoids+ * constructing a 100k-row candidate merely to learn that the default+ * 3,200-token response can hold a few hundred rows. */+ int exact_upper = raw_fit_rows;+ if (exact_upper < available_rows) {+ int headroom = available_rows - exact_upper < 32 ? available_rows - exact_upper : 32;+ exact_upper += headroom;+ }+ bool exact_total = !result.truncated;- /* rows */- yyjson_mut_val *rows = yyjson_mut_arr(doc);- for (int r = 0; r < result.row_count; r++) {- yyjson_mut_val *row = yyjson_mut_arr(doc);- for (int c = 0; c < result.col_count; c++) {- yyjson_mut_arr_add_str(doc, row, result.rows[r][c]);+ int output_rows = 0;+ char *json = NULL;+ if (qg_legacy_json) {+ /* JSON size is monotone in the row prefix, so exact serialized probes+ * safely account for escaping and syntax overhead. */+ int low = 0;+ 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);+ bool fits = candidate && strlen(candidate) <= byte_budget;+ free(candidate);+ if (fits) {+ output_rows = middle;+ low = middle + 1;+ } else {+ high = middle - 1;}- yyjson_mut_arr_add_val(rows, row);}- yyjson_mut_obj_add_val(doc, root, "rows", rows);- yyjson_mut_obj_add_int(doc, root, "total", result.row_count);- if (result.warning) {- yyjson_mut_obj_add_str(doc, root, "warning", result.warning);+ json = query_graph_json_response_text(&result, row_offset, output_rows, available_rows,+ exact_total);+ } 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+ * directory-shaped case once, under a hard construction guard, before+ * 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);+ if (candidate && strlen(candidate) <= byte_budget) {+ output_rows = available_rows;+ json = candidate;+ } else {+ free(candidate);+ }}- if (result.row_count == 0) {- yyjson_mut_obj_add_str(- doc, root, "hint",- "Query returned no results. Use get_graph_schema() to see available labels and "- "edge types.");- }+ if (!json) {+ /* Establish a monotone direct-table baseline first. */+ int low = 0;+ 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);+ bool fits = candidate && strlen(candidate) <= byte_budget;+ free(candidate);+ if (fits) {+ output_rows = middle;+ low = middle + 1;+ } else {+ high = middle - 1;+ }+ }- json = yy_doc_to_str(doc);- yyjson_mut_doc_free(doc);+ /* Directory activation can make N+1 rows smaller than N. For the lean+ * default-sized answer, inspect every bounded candidate in descending+ * order instead of making an invalid binary-search assumption. Skip+ * this expansion for enormous raw payloads; the direct fit remains a+ * truthful, bounded answer and can still be encoded more compactly. */+ int compact_upper = exact_upper;+ size_t expanded_budget = byte_budget <= SIZE_MAX / 4U ? byte_budget * 4U : SIZE_MAX;+ if (available_rows <= 512 && estimated <= expanded_budget) {+ compact_upper = available_rows;+ }+ 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);+ bool fits = candidate && strlen(candidate) <= byte_budget;+ if (fits) {+ output_rows = candidate_rows;+ json = candidate;+ break;+ }+ free(candidate);+ }+ if (!json) {+ json = query_graph_tree_response_text(&result, row_offset, output_rows,+ available_rows, exact_total, true);+ }+ }+ }+ if (json && output_rows == 0 && strlen(json) > byte_budget) {+ free(json);+ json = query_graph_budget_floor_text(&result, row_offset, exact_total, qg_legacy_json);}cbm_cypher_result_free(&result);free(query);@@ -4623,10 +5462,12 @@ static char *handle_query_graph(cbm_mcp_server_t *srv, const char *args) {enum { COVERAGE_FILE_CAP = 500 };static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_store_t *store,- const char *project) {+ const char *project, const char *indexed_at, int sample_limit) {cbm_coverage_row_t *rows = NULL;int count = 0;(void)cbm_store_coverage_get(store, project, &rows, &count);+ cbm_coverage_meta_t meta = {0};+ bool have_meta = cbm_store_coverage_meta_get(store, project, &meta) == CBM_STORE_OK;yyjson_mut_val *pp_files = yyjson_mut_arr(doc);yyjson_mut_val *sk_files = yyjson_mut_arr(doc);@@ -4639,7 +5480,7 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_sfor (int i = 0; i < count; i++) {const char *kind = rows[i].kind ? rows[i].kind : "";if (strcmp(kind, "parse_partial") == 0) {- if (pp_n < COVERAGE_FILE_CAP) {+ if (pp_n < sample_limit) {yyjson_mut_val *fe = yyjson_mut_obj(doc);yyjson_mut_obj_add_strcpy(doc, fe, "path", rows[i].rel_path);yyjson_mut_obj_add_strcpy(doc, fe, "error_ranges",@@ -4648,12 +5489,12 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s}pp_n++;} else if (strcmp(kind, "not_indexed_dir") == 0) {- if (ni_dir_n < COVERAGE_FILE_CAP) {+ if (ni_dir_n < sample_limit) {yyjson_mut_arr_add_strcpy(doc, ni_dirs, rows[i].rel_path);}ni_dir_n++;} else if (strcmp(kind, "not_indexed_file") == 0) {- if (ni_file_n < COVERAGE_FILE_CAP) {+ if (ni_file_n < sample_limit) {yyjson_mut_val *fe = yyjson_mut_obj(doc);yyjson_mut_obj_add_strcpy(doc, fe, "path", rows[i].rel_path);yyjson_mut_obj_add_strcpy(doc, fe, "reason", rows[i].detail ? rows[i].detail : "");@@ -4661,7 +5502,7 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s}ni_file_n++;} else {- if (sk_n < COVERAGE_FILE_CAP) {+ if (sk_n < sample_limit) {yyjson_mut_val *fe = yyjson_mut_obj(doc);yyjson_mut_obj_add_strcpy(doc, fe, "path", rows[i].rel_path);yyjson_mut_obj_add_strcpy(doc, fe, "reason", rows[i].detail ? rows[i].detail : "");@@ -4673,16 +5514,36 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s}cbm_store_free_coverage(rows, count);+ /* Discovery retains a bounded sample of ignored files but records the+ * exact uncapped total atomically beside it. Counts-only status must use+ * that authoritative total: reporting only the stored rows makes a lean+ * response look complete precisely when the discovery cap was hit. */+ bool generation_matches =+ have_meta && indexed_at && meta.generation && strcmp(indexed_at, meta.generation) == 0;+ bool ignored_total_authoritative = generation_matches && meta.ignored_files_total >= ni_file_n;+ int ni_file_total = ni_file_n;+ if (ignored_total_authoritative) {+ ni_file_total = meta.ignored_files_total;+ }+ cbm_store_coverage_meta_clear(&meta);+ int ni_files_shown = ni_file_n < sample_limit ? ni_file_n : sample_limit;+yyjson_mut_val *pp = yyjson_mut_obj(doc);yyjson_mut_obj_add_val(doc, pp, "files", pp_files);yyjson_mut_obj_add_int(doc, pp, "count", pp_n);- yyjson_mut_obj_add_bool(doc, pp, "truncated", pp_n > COVERAGE_FILE_CAP);+ yyjson_mut_obj_add_bool(doc, pp, "truncated", pp_n > sample_limit);+ if (pp_n > sample_limit) {+ yyjson_mut_obj_add_int(doc, pp, "omitted", pp_n - sample_limit);+ }yyjson_mut_obj_add_val(doc, root, "parse_partial", pp);yyjson_mut_val *sk = yyjson_mut_obj(doc);yyjson_mut_obj_add_val(doc, sk, "files", sk_files);yyjson_mut_obj_add_int(doc, sk, "count", sk_n);- yyjson_mut_obj_add_bool(doc, sk, "truncated", sk_n > COVERAGE_FILE_CAP);+ yyjson_mut_obj_add_bool(doc, sk, "truncated", sk_n > sample_limit);+ if (sk_n > sample_limit) {+ yyjson_mut_obj_add_int(doc, sk, "omitted", sk_n - sample_limit);+ }yyjson_mut_obj_add_val(doc, root, "skipped", sk);/* By-design exclusions (#963 "purposely not indexed"): a deliberate,@@ -4693,10 +5554,19 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_syyjson_mut_obj_add_val(doc, ni, "dirs", ni_dirs);yyjson_mut_obj_add_int(doc, ni, "dirs_count", ni_dir_n);yyjson_mut_obj_add_val(doc, ni, "files", ni_files);- yyjson_mut_obj_add_int(doc, ni, "files_count", ni_file_n);+ yyjson_mut_obj_add_int(doc, ni, "files_count", ni_file_total);+ if (!ignored_total_authoritative) {+ yyjson_mut_obj_add_str(doc, ni, "files_count_relation", "gte");+ }yyjson_mut_obj_add_bool(doc, ni, "truncated",- ni_dir_n > COVERAGE_FILE_CAP || ni_file_n > COVERAGE_FILE_CAP);- if (ni_dir_n > 0 || ni_file_n > 0) {+ ni_dir_n > sample_limit || ni_file_total > ni_files_shown);+ if (ni_dir_n > sample_limit) {+ yyjson_mut_obj_add_int(doc, ni, "dirs_omitted", ni_dir_n - sample_limit);+ }+ if (ni_file_total > ni_files_shown) {+ yyjson_mut_obj_add_int(doc, ni, "files_omitted", ni_file_total - ni_files_shown);+ }+ if (sample_limit > 0 && (ni_dir_n > 0 || ni_file_total > 0)) {yyjson_mut_obj_add_str(doc, ni, "note","Purposely not indexed — excluded BY DESIGN via ""gitignore/.cbmignore/skip-lists (see each file's reason). Not an "@@ -4704,7 +5574,7 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s}yyjson_mut_obj_add_val(doc, root, "not_indexed", ni);- if (pp_n > 0 || sk_n > 0) {+ if (sample_limit > 0 && (pp_n > 0 || sk_n > 0)) {yyjson_mut_obj_add_str(doc, root, "coverage_note","Best-effort signal, not a completeness guarantee: parse_partial files WERE indexed, "@@ -4833,9 +5703,9 @@ static const char *coverage_path_freshness(cbm_store_t *store, const char *projereturn matches ? "metadata_match" : "metadata_changed";}-static void coverage_add_ranges(yyjson_mut_doc *doc, yyjson_mut_val *row, const char *detail) {+static bool coverage_add_ranges(yyjson_mut_doc *doc, yyjson_mut_val *row, const char *detail) {if (!detail || !detail[0]) {- return;+ return false;}yyjson_mut_val *ranges = yyjson_mut_arr(doc);const char *p = detail;@@ -4877,22 +5747,34 @@ static void coverage_add_ranges(yyjson_mut_doc *doc, yyjson_mut_val *row, const}if (emitted > 0) {yyjson_mut_obj_add_val(doc, row, "ranges", ranges);+ if (emitted == COVERAGE_RANGE_MAX && *p) {+ yyjson_mut_obj_add_bool(doc, row, "ranges_truncated", true);+ }}+ return emitted > 0;}static void coverage_add_row_json(yyjson_mut_doc *doc, yyjson_mut_val *array,- const cbm_coverage_row_t *row, const char *requested_path) {+ const cbm_coverage_row_t *row, const char *requested_path,+ bool diagnostics_full) {yyjson_mut_val *item = yyjson_mut_obj(doc);yyjson_mut_obj_add_strcpy(doc, item, "path", row->rel_path ? row->rel_path : "");yyjson_mut_obj_add_strcpy(doc, item, "kind", row->kind ? row->kind : "");- yyjson_mut_obj_add_strcpy(doc, item, "detail", row->detail ? row->detail : "");if (requested_path) {yyjson_mut_obj_add_str(doc, item, "match",row->rel_path && strcmp(row->rel_path, requested_path) == 0 ? "exact" : "ancestor");}+ bool ranges_added = false;if (row->kind && strcmp(row->kind, "parse_partial") == 0) {- coverage_add_ranges(doc, item, row->detail);+ ranges_added = coverage_add_ranges(doc, item, row->detail);+ }+ /* A parse_partial detail such as "3-4,9" is byte-for-byte redundant once+ * represented as typed ranges. Preserve raw storage diagnostics on request,+ * and preserve every non-range detail by default because it may explain why+ * a file was skipped or excluded. */+ if (diagnostics_full || !ranges_added) {+ yyjson_mut_obj_add_strcpy(doc, item, "detail", row->detail ? row->detail : "");}yyjson_mut_arr_add_val(array, item);}@@ -4978,6 +5860,19 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *args"paths or scopes is required (arrays; max 128 paths and 32 scopes)", true);}+ int path_limit = cbm_mcp_get_int_arg(args, "path_limit", 20);+ int path_offset = cbm_mcp_get_int_arg(args, "path_offset", 0);+ if (path_limit < 1) {+ path_limit = 1;+ } else if (path_limit > COVERAGE_PATH_MAX) {+ path_limit = COVERAGE_PATH_MAX;+ }+ if (path_offset < 0) {+ path_offset = 0;+ }+ char *diagnostics = cbm_mcp_get_string_arg(args, "diagnostics");+ bool diagnostics_full = diagnostics && strcmp(diagnostics, "full") == 0;+cbm_project_t proj = {0};bool have_project = cbm_store_get_project(store, project, &proj) == CBM_STORE_OK;cbm_coverage_meta_t meta = {0};@@ -5015,11 +5910,15 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argsyyjson_mut_obj_add_val(doc, root, "metadata", meta_obj);yyjson_mut_val *path_results = yyjson_mut_arr(doc);+ int path_returned = 0;size_t idx;size_t max;yyjson_val *value;if (paths) {yyjson_arr_foreach(paths, idx, max, value) {+ if (idx < (size_t)path_offset || idx >= (size_t)path_offset + (size_t)path_limit) {+ continue;+ }yyjson_mut_val *item = yyjson_mut_obj(doc);const char *input = yyjson_is_str(value) ? yyjson_get_str(value) : NULL;yyjson_mut_obj_add_strcpy(doc, item, "requested_path", input ? input : "");@@ -5034,6 +5933,7 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argsyyjson_mut_obj_add_str(doc, item, "recommended_action","use_project_relative_path");yyjson_mut_arr_add_val(path_results, item);+ path_returned++;continue;}yyjson_mut_obj_add_strcpy(doc, item, "path", rel);@@ -5060,16 +5960,24 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argscoverage_recommended_action(status, freshness));yyjson_mut_val *coverage = yyjson_mut_arr(doc);for (int i = 0; i < row_count; i++) {- coverage_add_row_json(doc, coverage, &rows[i], rel);+ coverage_add_row_json(doc, coverage, &rows[i], rel, diagnostics_full);}yyjson_mut_obj_add_val(doc, item, "coverage", coverage);cbm_store_free_coverage(rows, row_count);yyjson_mut_arr_add_val(path_results, item);+ path_returned++;}}yyjson_mut_obj_add_val(doc, root, "paths", path_results);+ yyjson_mut_obj_add_int(doc, root, "path_total", (int64_t)path_count);+ yyjson_mut_obj_add_int(doc, root, "path_returned", path_returned);+ bool path_has_more = (size_t)path_offset + (size_t)path_returned < path_count;+ yyjson_mut_obj_add_bool(doc, root, "path_has_more", path_has_more);+ if (path_has_more) {+ yyjson_mut_obj_add_int(doc, root, "path_next_offset", path_offset + path_returned);+ }- int scope_limit = cbm_mcp_get_int_arg(args, "scope_limit", COVERAGE_SCOPE_DEFAULT_LIMIT);+ int scope_limit = cbm_mcp_get_int_arg(args, "scope_limit", 20);int scope_offset = cbm_mcp_get_int_arg(args, "scope_offset", 0);if (scope_limit < 1) {scope_limit = 1;@@ -5080,6 +5988,8 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argsscope_offset = 0;}yyjson_mut_val *scope_results = yyjson_mut_arr(doc);+ int scope_total = 0;+ int scope_returned = 0;if (scopes) {yyjson_arr_foreach(scopes, idx, max, value) {yyjson_mut_val *item = yyjson_mut_obj(doc);@@ -5105,15 +6015,28 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argsyyjson_mut_obj_add_str(doc, item, "coverage_lookup", "error");}yyjson_mut_obj_add_int(doc, item, "total", row_count);- int start = scope_offset < row_count ? scope_offset : row_count;- int end = start + scope_limit < row_count ? start + scope_limit : row_count;- yyjson_mut_obj_add_bool(doc, item, "has_more", end < row_count);- if (end < row_count) {- yyjson_mut_obj_add_int(doc, item, "next_offset", end);+ int flat_start = scope_total;+ int flat_end = flat_start + row_count;+ int page_start = scope_offset;+ int page_end = scope_offset + scope_limit;+ int start = page_start > flat_start ? page_start - flat_start : 0;+ int end = page_end < flat_end ? page_end - flat_start : row_count;+ if (start < 0) {+ start = 0;+ } else if (start > row_count) {+ start = row_count;}+ if (end < start) {+ end = start;+ } else if (end > row_count) {+ end = row_count;+ }+ int returned = end - start;+ yyjson_mut_obj_add_int(doc, item, "returned", returned);+ yyjson_mut_obj_add_bool(doc, item, "truncated", returned < row_count);yyjson_mut_val *entries = yyjson_mut_arr(doc);for (int i = start; i < end; i++) {- coverage_add_row_json(doc, entries, &rows[i], NULL);+ coverage_add_row_json(doc, entries, &rows[i], NULL, diagnostics_full);}yyjson_mut_obj_add_val(doc, item, "entries", entries);const char *scope_status = !lookup_ok || !generation_matches ? "coverage_unavailable"@@ -5124,9 +6047,18 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argsyyjson_mut_obj_add_str(doc, item, "status", scope_status);cbm_store_free_coverage(rows, row_count);yyjson_mut_arr_add_val(scope_results, item);+ scope_total += row_count;+ scope_returned += returned;}}yyjson_mut_obj_add_val(doc, root, "scopes", scope_results);+ yyjson_mut_obj_add_int(doc, root, "scope_total", scope_total);+ yyjson_mut_obj_add_int(doc, root, "scope_returned", scope_returned);+ yyjson_mut_obj_add_bool(doc, root, "scope_truncated", scope_returned < scope_total);+ yyjson_mut_obj_add_bool(doc, root, "has_more", scope_offset + scope_returned < scope_total);+ if (scope_offset + scope_returned < scope_total) {+ yyjson_mut_obj_add_int(doc, root, "next_offset", scope_offset + scope_returned);+ }yyjson_mut_obj_add_str(doc, root, "caveat","Best-effort signal only. No recorded issue does not prove graph or source completeness; "@@ -5135,6 +6067,7 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argschar *json = yy_doc_to_str(doc);yyjson_mut_doc_free(doc);yyjson_doc_free(adoc);+ free(diagnostics);if (have_meta) {cbm_store_coverage_meta_clear(&meta);}@@ -5144,7 +6077,7 @@ static char *handle_check_index_coverage(cbm_mcp_server_t *srv, const char *argssafe_str_free(&proj.root_path);}free(project);- char *result = cbm_mcp_text_result(json, false);+ char *result = mcp_result_from_json(args, json);free(json);return result;}@@ -5157,6 +6090,14 @@ static char *handle_index_status(cbm_mcp_server_t *srv, const char *args) {* debugging index-location issues — gate it so the common status call* stays lean. */bool verbose = cbm_mcp_get_bool_arg(args, "verbose");+ char *diagnostics = cbm_mcp_get_string_arg(args, "diagnostics");+ int coverage_samples = 0;+ if (diagnostics && strcmp(diagnostics, "summary") == 0) {+ coverage_samples = 5;+ } else if (diagnostics && strcmp(diagnostics, "full") == 0) {+ coverage_samples = COVERAGE_FILE_CAP;+ }+ free(diagnostics);yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root = yyjson_mut_obj(doc);@@ -5170,17 +6111,21 @@ static char *handle_index_status(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_obj_add_int(doc, root, "edges", edges);yyjson_mut_obj_add_str(doc, root, "status", nodes > 0 ? "ready" : "empty");cbm_project_t proj_info = {0};- if (cbm_store_get_project(store, project, &proj_info) == CBM_STORE_OK) {+ bool have_proj_info = cbm_store_get_project(store, project, &proj_info) == CBM_STORE_OK;+ if (have_proj_info) {yyjson_mut_obj_add_strcpy(doc, root, "root_path",proj_info.root_path ? proj_info.root_path : "");+ yyjson_mut_obj_add_strcpy(doc, root, "indexed_at",+ proj_info.indexed_at ? proj_info.indexed_at : "");if (verbose) {add_git_context_json(doc, root, proj_info.root_path);}- safe_str_free(&proj_info.name);- safe_str_free(&proj_info.indexed_at);- safe_str_free(&proj_info.root_path);}- add_coverage_report(doc, root, store, project);+ add_coverage_report(doc, root, store, project, have_proj_info ? proj_info.indexed_at : NULL,+ coverage_samples);+ safe_str_free(&proj_info.name);+ safe_str_free(&proj_info.indexed_at);+ safe_str_free(&proj_info.root_path);if (nodes == 0) {yyjson_mut_obj_add_str(doc, root, "hint",@@ -5194,7 +6139,7 @@ static char *handle_index_status(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_doc_free(doc);free(project);- char *result = cbm_mcp_text_result(json, false);+ char *result = mcp_result_from_json(args, json);free(json);return result;}@@ -5568,19 +6513,19 @@ static void append_cross_repo_summary(yyjson_mut_doc *doc, yyjson_mut_val *root,}}-/* Join a string list into buf with ';' separators (keeps TOON cells- * comma-free so they need no quoting). Truncates silently at sz. */-static void arch_join_list(char *buf, size_t sz, const char **items, int n) {- size_t pos = 0;- buf[0] = '\0';+/* Join a complete string list with ';' separators. The caller owns the result;+ * allocation failure is explicit rather than a partial graph identifier. */+static char *arch_join_list(const char **items, int n) {+ cbm_sb_t joined;+ cbm_sb_init(&joined);for (int i = 0; i < n; i++) {const char *s = items[i] ? items[i] : "";- int w = snprintf(buf + pos, sz - pos, "%s%s", i > 0 ? ";" : "", s);- if (w < 0 || (size_t)w >= sz - pos) {- break;+ if (i > 0) {+ cbm_sb_append(&joined, ";");}- pos += (size_t)w;+ cbm_sb_append(&joined, s);}+ return cbm_sb_finish(&joined);}/* Compute the circular-dependency SCCs (size > 1) of the CALLS graph. Returns@@ -5733,15 +6678,19 @@ static yyjson_mut_val *arch_json_section(yyjson_mut_doc *doc, yyjson_mut_val *roreturn rows;}-/* Fetch the qualified_name for a node id, or a "#<id>" fallback. */-static void arch_node_qn(cbm_store_t *store, int64_t id, char *out, size_t outsz) {+/* Fetch the complete qualified_name for a node id, or a "#<id>" fallback. */+static char *arch_node_qn(cbm_store_t *store, int64_t id) {cbm_node_t n = {0};+ char *out = NULL;if (cbm_store_find_node_by_id(store, id, &n) == CBM_STORE_OK && n.qualified_name) {- snprintf(out, outsz, "%s", n.qualified_name);+ out = heap_strdup(n.qualified_name);} else {- snprintf(out, outsz, "#%lld", (long long)id);+ char fallback[48];+ snprintf(fallback, sizeof(fallback), "#%lld", (long long)id);+ out = heap_strdup(fallback);}free_node_contents(&n);+ return out;}static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {@@ -5846,8 +6795,10 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {int node_count = cbm_store_count_nodes_scoped(store, project, scope_path);int edge_count = cbm_store_count_edges_scoped(store, project, scope_path);- char norm_path[CBM_SZ_512];- bool path_scoped = cbm_store_normalize_arch_path(scope_path, norm_path, sizeof(norm_path));+ size_t norm_path_cap = scope_path ? strlen(scope_path) + 2U : 2U;+ char *norm_path = malloc(norm_path_cap);+ bool path_scoped =+ norm_path && cbm_store_normalize_arch_path(scope_path, norm_path, norm_path_cap);/* Response encoding: tree tables by default; format:"json" emits the* same model as structured JSON ({cols, rows} per section). */@@ -6001,31 +6952,56 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {cbm_tree_table_header(&sb, "clusters", arch.cluster_count, ccols, 7);for (int i = 0; i < arch.cluster_count; i++) {const cbm_cluster_info_t *c = &arch.clusters[i];- char joined[CBM_SZ_1K];cbm_tree_row_begin(&sb);cbm_tree_cell_int(&sb, c->id, true);cbm_tree_cell_str(&sb, c->label, false);cbm_tree_cell_int(&sb, c->members, false);cbm_tree_cell_real(&sb, c->cohesion, false);- arch_join_list(joined, sizeof(joined), c->top_nodes, c->top_node_count);- cbm_tree_cell_str(&sb, joined, false);- arch_join_list(joined, sizeof(joined), c->packages, c->package_count);- cbm_tree_cell_str(&sb, joined, false);- arch_join_list(joined, sizeof(joined), c->edge_types, c->edge_type_count);- cbm_tree_cell_str(&sb, joined, false);+ char *top_nodes = arch_join_list(c->top_nodes, c->top_node_count);+ char *packages = arch_join_list(c->packages, c->package_count);+ char *edge_types = arch_join_list(c->edge_types, c->edge_type_count);+ cbm_tree_cell_str(&sb, top_nodes ? top_nodes : "(out-of-memory)", false);+ cbm_tree_cell_str(&sb, packages ? packages : "(out-of-memory)", false);+ cbm_tree_cell_str(&sb, edge_types ? edge_types : "(out-of-memory)", false);cbm_tree_row_end(&sb);+ free(top_nodes);+ free(packages);+ free(edge_types);}}if (arch.file_tree_count > 0) {static const char *const fcols[] = {"path", "type", "children"};- cbm_tree_table_header(&sb, "file_tree", arch.file_tree_count, fcols, 3);- for (int i = 0; i < arch.file_tree_count; i++) {- cbm_tree_row_begin(&sb);- cbm_tree_cell_str(&sb, arch.file_tree[i].path, true);- cbm_tree_cell_str(&sb, arch.file_tree[i].type, false);- cbm_tree_cell_int(&sb, arch.file_tree[i].children, false);- cbm_tree_row_end(&sb);+ const bool string_cols[] = {true, true, false};+ size_t count = (size_t)arch.file_tree_count;+ const char **cells = count <= SIZE_MAX / (3U * sizeof(*cells))+ ? malloc(count * 3U * sizeof(*cells))+ : NULL;+ char (*child_values)[32] = count <= SIZE_MAX / sizeof(*child_values)+ ? malloc(count * sizeof(*child_values))+ : NULL;+ if (cells && child_values) {+ for (int i = 0; i < arch.file_tree_count; i++) {+ snprintf(child_values[i], sizeof(child_values[i]), "%d",+ arch.file_tree[i].children);+ cells[(size_t)i * 3U] = arch.file_tree[i].path;+ cells[(size_t)i * 3U + 1U] = arch.file_tree[i].type;+ cells[(size_t)i * 3U + 2U] = child_values[i];+ }+ static const bool prefix_cols[] = {true, false, false};+ cbm_tree_table_rows_profiled(&sb, "file_tree", arch.file_tree_count, fcols, 3,+ cells, string_cols, prefix_cols);+ } else {+ cbm_tree_table_header(&sb, "file_tree", arch.file_tree_count, fcols, 3);+ for (int i = 0; i < arch.file_tree_count; i++) {+ cbm_tree_row_begin(&sb);+ cbm_tree_cell_str(&sb, arch.file_tree[i].path, true);+ cbm_tree_cell_str(&sb, arch.file_tree[i].type, false);+ cbm_tree_cell_int(&sb, arch.file_tree[i].children, false);+ cbm_tree_row_end(&sb);+ }}+ free(child_values);+ free(cells);}/* Cross-repo edge summary (mirrors append_cross_repo_summary). */{@@ -6076,20 +7052,29 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {"cycles: %d (rows: size members; circular CALLS dependencies)\n", ncyc);cbm_sb_append(&sb, hdr);for (int c = 0; c < ncyc; c++) {- char row[CBM_SZ_2K];- int off = snprintf(row, sizeof(row), " %d ", sizes[c]);bool clipped = sizes[c] > ARCH_SCC_MEMBERS_SHOWN;int show = clipped ? ARCH_SCC_MEMBERS_SHOWN : sizes[c];- for (int m = 0; m < show && off < (int)sizeof(row) - 2; m++) {- char qn[CBM_SZ_512];- arch_node_qn(store, members[c][m], qn, sizeof(qn));- off += snprintf(row + off, sizeof(row) - off, "%s%s", m ? ";" : "", qn);+ cbm_sb_t member_list;+ cbm_sb_init(&member_list);+ for (int m = 0; m < show; m++) {+ char *qn = arch_node_qn(store, members[c][m]);+ if (m > 0) {+ cbm_sb_append(&member_list, ";");+ }+ cbm_sb_append(&member_list, qn ? qn : "(out-of-memory)");+ free(qn);}- if (clipped && off < (int)sizeof(row) - 8) {- snprintf(row + off, sizeof(row) - off, ";+%d", sizes[c] - show);+ if (clipped) {+ char omitted[48];+ snprintf(omitted, sizeof(omitted), ";+%d", sizes[c] - show);+ cbm_sb_append(&member_list, omitted);}- cbm_sb_append(&sb, row);- cbm_sb_append(&sb, "\n");+ char *member_text = cbm_sb_finish(&member_list);+ cbm_tree_row_begin(&sb);+ cbm_tree_cell_int(&sb, sizes[c], true);+ cbm_tree_cell_str(&sb, member_text ? member_text : "(out-of-memory)", false);+ cbm_tree_row_end(&sb);+ free(member_text);free(members[c]);}free(members);@@ -6104,6 +7089,7 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {}free(project);free(scope_path);+ free(norm_path);char *text = cbm_sb_finish(&sb);char *result = cbm_mcp_text_result(text ? text : "out of memory", text == NULL);free(text);@@ -6337,9 +7323,9 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_val *mem = yyjson_mut_arr(doc);int show = sizes[c] < ARCH_SCC_MEMBERS_SHOWN ? sizes[c] : ARCH_SCC_MEMBERS_SHOWN;for (int m = 0; m < show; m++) {- char qn[CBM_SZ_512];- arch_node_qn(store, members[c][m], qn, sizeof(qn));- yyjson_mut_arr_add_strcpy(doc, mem, qn);+ char *qn = arch_node_qn(store, members[c][m]);+ yyjson_mut_arr_add_strcpy(doc, mem, qn ? qn : "(out-of-memory)");+ free(qn);}yyjson_mut_obj_add_val(doc, o, "members", mem);yyjson_mut_arr_add_val(cyc, o);@@ -6360,6 +7346,7 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {}free(project);free(scope_path);+ free(norm_path);char *result = cbm_mcp_text_result(json, false);free(json);@@ -6436,49 +7423,113 @@ static bool is_test_file(const char *path) {strncmp(path, "__tests__/", SLEN("__tests__/")) == 0;}-/* Convert BFS traversal results into a yyjson_mut array. */-/* Find the CALLS-edge "args" JSON (the serialized arg expressions) on the edge- * that leads to the given hop node, so data_flow mode can surface argument- * expressions (#514). Returns the borrowed substring "[...]" inside the edge's- * properties_json, with its length, or NULL when no args are recorded. */-static const char *bfs_edge_args_for_hop(cbm_traverse_result_t *tr, int64_t hop_node_id,- size_t *out_len) {- for (int e = 0; e < tr->edge_count; e++) {- /* The hop node is the edge endpoint reached from the root side: for an- * outbound trace it is the target, for inbound it is the source. Match- * on either so both directions surface their args. */- if (tr->edges[e].target_id != hop_node_id && tr->edges[e].source_id != hop_node_id) {+/* Filtering belongs before page-window calculation: hidden test rows must not+ * consume the caller's visible limit or become cursor watermarks. Compact the+ * owned traversal array in place while preserving canonical (hop,id) order. */+static void trace_filter_test_rows(cbm_traverse_result_t *tr) {+ int write_index = 0;+ for (int read_index = 0; read_index < tr->visited_count; read_index++) {+ if (is_test_file(tr->visited[read_index].node.file_path)) {+ cbm_node_free_fields(&tr->visited[read_index].node);continue;}- const char *pj = tr->edges[e].properties_json;- if (!pj) {- continue;+ if (write_index != read_index) {+ tr->visited[write_index] = tr->visited[read_index];+ memset(&tr->visited[read_index], 0, sizeof(tr->visited[read_index]));+ }+ write_index++;+ }+ tr->visited_count = write_index;+}++typedef struct {+ const cbm_traverse_result_t *full;+ const cbm_node_t *roots;+ int root_count;+ bool inbound;+} trace_edge_context_t;++static bool trace_root_contains(const trace_edge_context_t *ctx, int64_t node_id) {+ for (int i = 0; ctx && i < ctx->root_count; i++) {+ if (ctx->roots[i].id == node_id) {+ return true;+ }+ }+ return false;+}++static int trace_hop_for_node(const trace_edge_context_t *ctx, int64_t node_id) {+ if (!ctx || !ctx->full) {+ return CBM_NOT_FOUND;+ }+ for (int i = 0; i < ctx->full->visited_count; i++) {+ if (ctx->full->visited[i].node.id == node_id) {+ return ctx->full->visited[i].hop;}- const char *args = strstr(pj, "\"args\"");- if (!args) {+ }+ return CBM_NOT_FOUND;+}++/* Edge collection returns the whole induced subgraph, not a predecessor tree.+ * An arbitrary incident edge can therefore point sideways or away from the+ * root. Select a deterministic edge that can actually precede this shortest-+ * path row: it must have the traversal direction and connect hop h to h-1 (or+ * one of the resolved roots for hop 1). */+static const cbm_edge_info_t *trace_predecessor_edge(const trace_edge_context_t *ctx,+ const cbm_node_hop_t *hop_node) {+ if (!ctx || !ctx->full || !hop_node || hop_node->hop <= 0) {+ return NULL;+ }+ const cbm_edge_info_t *best = NULL;+ int64_t best_predecessor = INT64_MAX;+ for (int e = 0; e < ctx->full->edge_count; e++) {+ const cbm_edge_info_t *edge = &ctx->full->edges[e];+ if ((ctx->inbound && edge->source_id != hop_node->node.id) ||+ (!ctx->inbound && edge->target_id != hop_node->node.id)) {continue;}- const char *open = strchr(args, '[');- if (!open) {+ int64_t predecessor = ctx->inbound ? edge->target_id : edge->source_id;+ bool previous_hop = hop_node->hop == 1+ ? trace_root_contains(ctx, predecessor)+ : trace_hop_for_node(ctx, predecessor) == hop_node->hop - 1;+ if (!previous_hop) {continue;}- int depth = 0;- const char *p = open;- for (; *p; p++) {- if (*p == '[') {- depth++;- } else if (*p == ']') {- depth--;- if (depth == 0) {- p++;- break;- }+ const char *edge_type = edge->type ? edge->type : "";+ const char *best_type = best && best->type ? best->type : "";+ if (!best || predecessor < best_predecessor ||+ (predecessor == best_predecessor && strcmp(edge_type, best_type) < 0)) {+ best = edge;+ best_predecessor = predecessor;+ }+ }+ return best;+}++/* Return the serialized argument-expression array from the selected canonical+ * predecessor edge. The returned slice is borrowed from properties_json. */+static const char *trace_edge_args(const cbm_edge_info_t *edge, size_t *out_len) {+ const char *pj = edge ? edge->properties_json : NULL;+ const char *args = pj ? strstr(pj, "\"args\"") : NULL;+ const char *open = args ? strchr(args, '[') : NULL;+ if (!open) {+ return NULL;+ }+ int depth = 0;+ const char *p = open;+ for (; *p; p++) {+ if (*p == '[') {+ depth++;+ } else if (*p == ']') {+ depth--;+ if (depth == 0) {+ p++;+ break;}}- *out_len = (size_t)(p - open);- return open;}- return NULL;+ *out_len = (size_t)(p - open);+ return open;}/* Classify a resolver strategy into the CLOSED public vocabulary.@@ -6513,36 +7564,24 @@ const char *cbm_mcp_edge_strategy_class(const char *strategy) {return "heuristic";}-/* Find the resolution evidence on the edge that leads to the given hop node —- * the same endpoint-matching rule as bfs_edge_args_for_hop (target for an- * outbound trace, source for inbound, so both directions surface it).- *- * Reads only from tr->edges, and callers pass the PAGINATED view, so evidence- * is emitted for the rows on this page and nothing else.- *- * Returns false when the edge carries no strategy (non-CALLS edges do not). */-static bool bfs_edge_evidence_for_hop(cbm_traverse_result_t *tr, int64_t hop_node_id,- const char **class_out, double *confidence_out) {- for (int e = 0; e < tr->edge_count; e++) {- if (tr->edges[e].target_id != hop_node_id && tr->edges[e].source_id != hop_node_id) {- continue;- }- const char *pj = tr->edges[e].properties_json;- if (!pj) {- continue;- }+/* Read resolution evidence from the already-selected predecessor edge. Returns+ * false when that edge carries no strategy (non-CALLS edges generally do not). */+static bool trace_edge_evidence(const cbm_edge_info_t *edge, const char **class_out,+ double *confidence_out) {+ const char *pj = edge ? edge->properties_json : NULL;+ if (pj) {const char *key = strstr(pj, "\"strategy\"");if (!key) {- continue;+ return false;}const char *open = strchr(key + 10, '"');if (!open) {- continue;+ return false;}open++;const char *close = strchr(open, '"');if (!close || close == open) {- continue;+ return false;}char raw[CBM_SZ_64];size_t len = (size_t)(close - open);@@ -6553,7 +7592,7 @@ static bool bfs_edge_evidence_for_hop(cbm_traverse_result_t *tr, int64_t hop_nodraw[len] = '\0';const char *cls = cbm_mcp_edge_strategy_class(raw);if (!cls) {- continue;+ return false;}*class_out = cls;/* Confidence rides on the same edge; absent is reported as -1 so a@@ -6581,13 +7620,11 @@ static bool bfs_edge_evidence_for_hop(cbm_traverse_result_t *tr, int64_t hop_nod}/* TOON table for one trace direction: callees[N]{qn,hop,...} with optional- * risk / test / evidence / args columns. `name` is omitted (it is the qn's- * last segment); the per-item JSON key envelope was 84% of the legacy- * payload. include_evidence must be forwarded here — flat_trace used to- * drop it (#1542 leftover). */+ * risk / test / args / evidence columns. `name` is omitted (it is the qn's last+ * segment); the per-item JSON key envelope was 84% of the legacy payload. */static void bfs_to_toon_table(cbm_sb_t *sb, const char *key, cbm_traverse_result_t *tr,bool risk_labels, bool include_tests, bool data_flow,- bool include_evidence) {+ bool include_evidence, const trace_edge_context_t *edge_ctx) {int visible = 0;for (int i = 0; i < tr->visited_count; i++) {if (!include_tests && is_test_file(tr->visited[i].node.file_path)) {@@ -6595,7 +7632,6 @@ static void bfs_to_toon_table(cbm_sb_t *sb, const char *key, cbm_traverse_result}visible++;}- /* Max: qn hop risk test strategy confidence args. */const char *cols[7] = {"qn", "hop"};int ncols = 2;if (risk_labels) {@@ -6604,13 +7640,13 @@ static void bfs_to_toon_table(cbm_sb_t *sb, const char *key, cbm_traverse_resultif (include_tests) {cols[ncols++] = "test";}+ if (data_flow) {+ cols[ncols++] = "args";+ }if (include_evidence) {cols[ncols++] = "strategy";cols[ncols++] = "confidence";}- if (data_flow) {- cols[ncols++] = "args";- }cbm_tree_table_header(sb, key, visible, cols, ncols);for (int i = 0; i < tr->visited_count; i++) {const char *fp = tr->visited[i].node.file_path;@@ -6627,35 +7663,35 @@ static void bfs_to_toon_table(cbm_sb_t *sb, const char *key, cbm_traverse_resultif (include_tests) {cbm_tree_cell_bool(sb, test, false);}+ const cbm_edge_info_t *predecessor = (data_flow || include_evidence)+ ? trace_predecessor_edge(edge_ctx, &tr->visited[i])+ : NULL;+ if (data_flow) {+ size_t alen = 0;+ const char *ea = trace_edge_args(predecessor, &alen);+ if (ea && alen > 0) {+ char *args = cbm_strndup(ea, alen);+ cbm_tree_cell_str(sb, args ? args : "", false);+ free(args);+ } else {+ cbm_tree_cell_str(sb, "", false);+ }+ }if (include_evidence) {const char *ev_class = NULL;double ev_conf = -1.0;- if (bfs_edge_evidence_for_hop(tr, tr->visited[i].node.id, &ev_class, &ev_conf)) {- cbm_tree_cell_str(sb, ev_class ? ev_class : "", false);+ if (trace_edge_evidence(predecessor, &ev_class, &ev_conf)) {+ cbm_tree_cell_str(sb, ev_class, false);if (ev_conf >= 0.0) {cbm_tree_cell_real(sb, ev_conf, false);} else {cbm_tree_cell_str(sb, "-", false);}} else {- /* Root hop / non-CALLS: keep column count fixed, same "-"- * placeholders as bfs_to_tree_table. */cbm_tree_cell_str(sb, "-", false);cbm_tree_cell_str(sb, "-", false);}}- if (data_flow) {- size_t alen = 0;- const char *ea = bfs_edge_args_for_hop(tr, tr->visited[i].node.id, &alen);- if (ea && alen > 0 && alen < CBM_SZ_1K) {- char abuf[CBM_SZ_1K];- memcpy(abuf, ea, alen);- abuf[alen] = '\0';- cbm_tree_cell_str(sb, abuf, false);- } else {- cbm_tree_cell_str(sb, "", false);- }- }cbm_tree_row_end(sb);}}@@ -6768,17 +7804,25 @@ static int node_hop_cmp_hop_id(const void *pa, const void *pb) {* more than one graph node — e.g. a real .ts implementation plus an ambient* .d.ts stub, whose inbound CALLS edges are otherwise split across the two* nodes and silently truncated by tracing only one (#546). visited hops are- * deduped by node id; edges are concatenated. Ownership of all heap fields- * transfers into *out, freed by cbm_store_traverse_free. */-static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, int node_count,- const char *direction, const char **edge_types, int edge_type_count,- int depth, int limit, cbm_traverse_result_t *out) {+ * deduped by node id. Edge properties are skipped for lean traces or merged+ * under an explicit edge_limit for data-flow/evidence output. Ownership of all+ * heap fields transfers into *out, freed by cbm_store_traverse_free. */+static int bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, int node_count,+ const char *direction, const char **edge_types, int edge_type_count,+ int depth, int limit, int edge_limit, cbm_traverse_result_t *out) {memset(out, 0, sizeof(*out));int vcap = 0, ecap = 0;for (int k = 0; k < node_count; k++) {cbm_traverse_result_t tr = {0};- cbm_store_bfs(store, nodes[k].id, direction, edge_types, edge_type_count, depth, limit,- &tr);+ int bfs_rc = cbm_store_bfs_with_edge_limit(store, nodes[k].id, direction, edge_types,+ edge_type_count, depth, limit, edge_limit, &tr);+ if (bfs_rc != CBM_STORE_OK) {+ cbm_store_traverse_free(&tr);+ cbm_store_traverse_free(out);+ return bfs_rc;+ }+ out->truncated = out->truncated || tr.truncated;+ out->edges_truncated = out->edges_truncated || tr.edges_truncated;for (int i = 0; i < tr.visited_count; i++) {bool dup = false;for (int j = 0; j < out->visited_count; j++) {@@ -6797,6 +7841,10 @@ static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, intif (dup) {continue;}+ if (out->visited_count >= limit) {+ out->truncated = true;+ continue;+ }if (out->visited_count >= vcap) {vcap = vcap ? vcap * 2 : 8;out->visited = safe_realloc(out->visited, vcap * sizeof(cbm_node_hop_t));@@ -6819,6 +7867,10 @@ static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, intif (edup) {continue;}+ if (edge_limit > 0 && out->edge_count >= edge_limit) {+ out->edges_truncated = true;+ continue;+ }if (out->edge_count >= ecap) {ecap = ecap ? ecap * 2 : 8;out->edges = safe_realloc(out->edges, ecap * sizeof(cbm_edge_info_t));@@ -6834,6 +7886,7 @@ static void bfs_union_same_name(cbm_store_t *store, const cbm_node_t *nodes, intqsort(out->visited, (size_t)out->visited_count, sizeof(cbm_node_hop_t),node_hop_cmp_hop_id);}+ return CBM_STORE_OK;}/* ── Pagination cursors (stateless, exactly-once) ────────────────────@@ -6866,7 +7919,9 @@ typedef struct {/* Hash the params that define the traversal identity. A cursor replayed with* different params must fail loudly, never silently mis-skip. */static uint64_t trace_params_hash(const char *project, const char *func_name, const char *direction,- const char *mode, int depth, bool include_tests, int limit) {+ const char *mode, const char *param_name, int depth,+ bool include_tests, bool risk_labels, bool include_evidence,+ int limit, const char *args) {uint64_t h = 0xcbf29ce484222325ULL;h = cursor_fnv1a64(project ? project : "", h);h = cursor_fnv1a64("|", h);@@ -6875,9 +7930,37 @@ static uint64_t trace_params_hash(const char *project, const char *func_name, coh = cursor_fnv1a64(direction ? direction : "", h);h = cursor_fnv1a64("|", h);h = cursor_fnv1a64(mode ? mode : "", h);+ h = cursor_fnv1a64("|", h);+ h = cursor_fnv1a64(param_name ? param_name : "", h);char nums[64];- snprintf(nums, sizeof(nums), "|%d|%d|%d", depth, include_tests ? 1 : 0, limit);+ /* Output budget changes only how many whole rows fit after the exact+ * watermark; it does not change graph identity. Excluding it lets a caller+ * follow a hard-floor instruction and raise max_output_tokens without+ * invalidating the cursor that reached that page. */+ snprintf(nums, sizeof(nums), "|%d|%d|%d|%d|%d", depth, include_tests ? 1 : 0,+ risk_labels ? 1 : 0, include_evidence ? 1 : 0, limit);h = cursor_fnv1a64(nums, h);++ /* Explicit edge types define the traversed graph. Omitting them from the+ * cursor identity allowed a token minted for CALLS to resume an IMPORTS+ * traversal at an unrelated watermark. Preserve caller order: cursors+ * intentionally require unchanged arguments. */+ yyjson_doc *doc = args ? yyjson_read(args, strlen(args), 0) : NULL;+ yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;+ yyjson_val *types = root && yyjson_is_obj(root) ? yyjson_obj_get(root, "edge_types") : NULL;+ h = cursor_fnv1a64("|edge_types=", h);+ if (types && yyjson_is_arr(types)) {+ size_t index;+ size_t maximum;+ yyjson_val *value;+ yyjson_arr_foreach(types, index, maximum, value) {+ h = cursor_fnv1a64(yyjson_is_str(value) ? yyjson_get_str(value) : "<non-string>", h);+ h = cursor_fnv1a64(";", h);+ }+ }+ if (doc) {+ yyjson_doc_free(doc);+ }return h;}@@ -6894,22 +7977,49 @@ static const char *trace_cursor_decode(const char *token, const char *current_gereturn "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";}const char *p = token + 3;- if (*p != 'o' && *p != 'i') {+ if ((*p != 'o' && *p != 'i') || p[1] != '.') {return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";}out->leg = *p;p += 2; /* leg + '.' */const char *gen_end = strchr(p, '.');- if (!gen_end || (size_t)(gen_end - p) >= sizeof(out->generation)) {+ if (!gen_end || gen_end == p || (size_t)(gen_end - p) >= sizeof(out->generation)) {return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";}memcpy(out->generation, p, (size_t)(gen_end - p));out->generation[gen_end - p] = '\0';- unsigned long long qh = 0;- long long nid = 0;- if (sscanf(gen_end + 1, "%16llx.%d.%lld", &qh, &out->hop, &nid) != 3) {+ const char *hash_start = gen_end + 1;+ const char *hash_end = strchr(hash_start, '.');+ if (!hash_end || hash_end - hash_start != 16) {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ for (const char *digit = hash_start; digit < hash_end; digit++) {+ if (!isxdigit((unsigned char)*digit)) {+ return "invalid_cursor: unrecognized token — re-run the original query without "+ "'cursor'";+ }+ }+ errno = 0;+ char *parsed_end = NULL;+ unsigned long long qh = strtoull(hash_start, &parsed_end, 16);+ if (errno == ERANGE || parsed_end != hash_end) {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ const char *hop_start = hash_end + 1;+ const char *hop_end = strchr(hop_start, '.');+ errno = 0;+ long parsed_hop = hop_end ? strtol(hop_start, &parsed_end, 10) : -1;+ if (!hop_end || hop_end == hop_start || errno == ERANGE || parsed_end != hop_end ||+ parsed_hop < 1 || parsed_hop > INT_MAX) {+ return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";+ }+ const char *node_start = hop_end + 1;+ errno = 0;+ long long nid = strtoll(node_start, &parsed_end, 10);+ if (node_start == parsed_end || errno == ERANGE || *parsed_end != '\0' || nid <= 0) {return "invalid_cursor: unrecognized token — re-run the original query without 'cursor'";}+ out->hop = (int)parsed_hop;out->qhash = qh;out->node_id = nid;if (out->qhash != expected_qhash) {@@ -6923,16 +8033,21 @@ static const char *trace_cursor_decode(const char *token, const char *current_gereturn NULL;}-/* Slice a canonically-ordered traversal at the watermark: index of the first- * row strictly AFTER (hop, id). */-static int trace_watermark_index(const cbm_traverse_result_t *tr, int hop, int64_t node_id) {+/* Validate an exactly-issued watermark and return the first row after it.+ * Treating an arbitrary (hop,id) as an insertion point let syntactically valid+ * but edited cursors skip rows. The watermarked row must still exist in the+ * selected, test-filtered leg for this generation. */+static int trace_watermark_next_index(const cbm_traverse_result_t *tr, int hop, int64_t node_id) {for (int i = 0; i < tr->visited_count; i++) {+ if (tr->visited[i].hop == hop && tr->visited[i].node.id == node_id) {+ return i + SKIP_ONE;+ }if (tr->visited[i].hop > hop ||(tr->visited[i].hop == hop && tr->visited[i].node.id > node_id)) {- return i;+ break;}}- return tr->visited_count;+ return CBM_NOT_FOUND;}/* json-stringified tree for one trace leg: same grouped model as the text@@ -6940,29 +8055,33 @@ static int trace_watermark_index(const cbm_traverse_result_t *tr, int hop, int64* risk/args columns mirror the flags. */static yyjson_mut_val *bfs_to_tree_json(yyjson_mut_doc *doc, cbm_traverse_result_t *tr,bool risk_labels, bool include_tests, bool data_flow,- bool include_evidence) {+ bool include_evidence,+ const trace_edge_context_t *edge_ctx) {yyjson_mut_val *leg = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_str(doc, leg, "qn_rule",+ "qn = qn_prefix == \"\" ? name : qn_prefix + \".\" + name");yyjson_mut_val *cols = yyjson_mut_arr(doc);yyjson_mut_arr_add_str(doc, cols, "name");yyjson_mut_arr_add_str(doc, cols, "hop");if (risk_labels) {yyjson_mut_arr_add_str(doc, cols, "risk");}- /* #1542: include_evidence was implemented on the tree path only, so- * format:"json" silently returned cols ["name","hop"] while the schema and- * --help promised two more. A structured caller — the one most likely to- * ask for json — got no error, just missing fields. */- if (include_evidence) {- yyjson_mut_arr_add_str(doc, cols, "strategy");- yyjson_mut_arr_add_str(doc, cols, "confidence");+ if (include_tests) {+ yyjson_mut_arr_add_str(doc, cols, "test");}if (data_flow) {yyjson_mut_arr_add_str(doc, cols, "args");}+ /* Keep declaration order identical to row emission below. Evidence is at+ * the tail so enabling data_flow cannot put args under a strategy column. */+ if (include_evidence) {+ yyjson_mut_arr_add_str(doc, cols, "strategy");+ yyjson_mut_arr_add_str(doc, cols, "confidence");+ }yyjson_mut_obj_add_val(doc, leg, "cols", cols);yyjson_mut_val *groups = yyjson_mut_arr(doc);yyjson_mut_val *cur_rows = NULL;- char cur_group[CBM_SZ_1K] = "";+ char *cur_group = NULL;bool have_group = false;for (int i = 0; i < tr->visited_count; i++) {if (!include_tests && is_test_file(tr->visited[i].node.file_path)) {@@ -6971,11 +8090,13 @@ static yyjson_mut_val *bfs_to_tree_json(yyjson_mut_doc *doc, cbm_traverse_resultconst char *qn =tr->visited[i].node.qualified_name ? tr->visited[i].node.qualified_name : "";size_t plen = sg_qn_prefix_len(qn);- if (plen >= sizeof(cur_group)) {- plen = 0;- }- if (!have_group || strncmp(cur_group, qn, plen) != 0 || cur_group[plen] != '\0') {- snprintf(cur_group, sizeof(cur_group), "%.*s", (int)plen, qn);+ if (!have_group || strlen(cur_group) != plen || memcmp(cur_group, qn, plen) != 0) {+ char *next_group = cbm_strndup(qn, plen);+ if (!next_group) {+ continue;+ }+ free(cur_group);+ cur_group = next_group;have_group = true;yyjson_mut_val *g = yyjson_mut_obj(doc);yyjson_mut_obj_add_strcpy(doc, g, "qn_prefix", cur_group);@@ -6989,13 +8110,30 @@ static yyjson_mut_val *bfs_to_tree_json(yyjson_mut_doc *doc, cbm_traverse_resultif (risk_labels) {yyjson_mut_arr_add_str(doc, row, cbm_risk_label(cbm_hop_to_risk(tr->visited[i].hop)));}- /* Emit in header order: strategy, confidence, then args. Swapping these- * two blocks mislabeled every include_evidence+data_flow json row- * (#1542 leftover). */+ if (include_tests) {+ yyjson_mut_arr_add_bool(doc, row, is_test_file(tr->visited[i].node.file_path));+ }+ const cbm_edge_info_t *predecessor = (data_flow || include_evidence)+ ? trace_predecessor_edge(edge_ctx, &tr->visited[i])+ : NULL;+ if (data_flow) {+ size_t alen = 0;+ const char *ea = trace_edge_args(predecessor, &alen);+ if (ea && alen > 0) {+ yyjson_mut_val *av = yyjson_mut_rawn(doc, ea, alen);+ if (av) {+ yyjson_mut_arr_add_val(row, av);+ } else {+ yyjson_mut_arr_add_str(doc, row, "");+ }+ } else {+ yyjson_mut_arr_add_str(doc, row, "");+ }+ }if (include_evidence) {const char *ev_class = NULL;double ev_conf = -1.0;- if (bfs_edge_evidence_for_hop(tr, tr->visited[i].node.id, &ev_class, &ev_conf)) {+ if (trace_edge_evidence(predecessor, &ev_class, &ev_conf)) {yyjson_mut_arr_add_strcpy(doc, row, ev_class ? ev_class : "");if (ev_conf >= 0.0) {yyjson_mut_arr_add_real(doc, row, ev_conf);@@ -7011,22 +8149,9 @@ static yyjson_mut_val *bfs_to_tree_json(yyjson_mut_doc *doc, cbm_traverse_resultyyjson_mut_arr_add_null(doc, row);}}- if (data_flow) {- size_t alen = 0;- const char *ea = bfs_edge_args_for_hop(tr, tr->visited[i].node.id, &alen);- if (ea && alen > 0) {- yyjson_mut_val *av = yyjson_mut_rawn(doc, ea, alen);- if (av) {- yyjson_mut_arr_add_val(row, av);- } else {- yyjson_mut_arr_add_str(doc, row, "");- }- } else {- yyjson_mut_arr_add_str(doc, row, "");- }- }yyjson_mut_arr_add_val(cur_rows, row);}+ free(cur_group);yyjson_mut_obj_add_val(doc, leg, "groups", groups);return leg;}@@ -7049,7 +8174,8 @@ static int tree_hop_cmp_qn(const void *pa, const void *pb) {}static void bfs_to_tree_table(cbm_sb_t *sb, const char *key, cbm_traverse_result_t *tr,- bool include_tests, bool include_evidence) {+ bool include_tests, bool include_evidence,+ const trace_edge_context_t *edge_ctx) {int visible = 0;for (int i = 0; i < tr->visited_count; i++) {if (!include_tests && is_test_file(tr->visited[i].node.file_path)) {@@ -7059,54 +8185,134 @@ static void bfs_to_tree_table(cbm_sb_t *sb, const char *key, cbm_traverse_result}char buf[CBM_SZ_256];snprintf(buf, sizeof(buf),- include_evidence- ? "%s: %d (rows: name hop strategy confidence; qn = group prefix + \".\" + "- "name)\n"- : "%s: %d (rows: name hop; qn = group prefix + \".\" + name)\n",- key, visible);+ "%s: %d (rows: name hop%s%s; qn = group prefix empty ? "+ "name : prefix + \".\" + name; \"\" marks empty prefix)\n",+ key, visible, include_tests ? " test" : "",+ include_evidence ? " strategy confidence" : "");cbm_sb_append(sb, buf);- if (tr->visited_count > 1) {- qsort(tr->visited, (size_t)tr->visited_count, sizeof(cbm_node_hop_t), tree_hop_cmp_qn);- }- char cur_group[CBM_SZ_1K] = "";+ cbm_node_hop_t *ordered = visible > 0 ? malloc((size_t)visible * sizeof(*ordered)) : NULL;+ bool ordered_owned = ordered != NULL;+ int ordered_count = 0;for (int i = 0; i < tr->visited_count; i++) {if (!include_tests && is_test_file(tr->visited[i].node.file_path)) {continue;}- const char *qn =- tr->visited[i].node.qualified_name ? tr->visited[i].node.qualified_name : "";- size_t plen = sg_qn_prefix_len(qn);- if (plen >= sizeof(cur_group)) {- plen = 0;+ if (ordered) {+ ordered[ordered_count++] = tr->visited[i];}- if (strncmp(cur_group, qn, plen) != 0 || cur_group[plen] != '\0') {- snprintf(cur_group, sizeof(cur_group), "%.*s", (int)plen, qn);- cbm_sb_append(sb, cur_group);+ }+ if (!ordered && tr->visited_count > 0) {+ /* The caller already applied the test filter; in the allocation+ * failure path retain lossless rows in canonical order. */+ ordered = tr->visited;+ ordered_count = tr->visited_count;+ }+ if (ordered_count > 1) {+ qsort(ordered, (size_t)ordered_count, sizeof(*ordered), tree_hop_cmp_qn);+ }+ char *cur_group = NULL;+ for (int i = 0; i < ordered_count; i++) {+ const char *qn = ordered[i].node.qualified_name ? ordered[i].node.qualified_name : "";+ size_t plen = sg_qn_prefix_len(qn);+ if (!cur_group || strlen(cur_group) != plen || memcmp(cur_group, qn, plen) != 0) {+ char *next_group = cbm_strndup(qn, plen);+ if (!next_group) {+ continue;+ }+ free(cur_group);+ cur_group = next_group;+ cbm_sb_append(sb, cur_group[0] ? cur_group : "\"\"");cbm_sb_append(sb, ":\n");}- char row[CBM_SZ_512];+ cbm_tree_row_begin(sb);+ cbm_tree_cell_str(sb, plen ? qn + plen + 1 : qn, true);+ cbm_tree_cell_int(sb, ordered[i].hop, false);+ if (include_tests) {+ cbm_tree_cell_bool(sb, is_test_file(ordered[i].node.file_path), false);+ }const char *ev_class = NULL;double ev_conf = -1.0;- if (include_evidence &&- bfs_edge_evidence_for_hop(tr, tr->visited[i].node.id, &ev_class, &ev_conf)) {+ const cbm_edge_info_t *predecessor =+ include_evidence ? trace_predecessor_edge(edge_ctx, &ordered[i]) : NULL;+ if (include_evidence && trace_edge_evidence(predecessor, &ev_class, &ev_conf)) {+ cbm_tree_cell_str(sb, ev_class, false);if (ev_conf >= 0.0) {- snprintf(row, sizeof(row), " %s %d %s %.2f\n", plen ? qn + plen + 1 : qn,- tr->visited[i].hop, ev_class, ev_conf);+ cbm_tree_cell_real(sb, ev_conf, false);} else {- snprintf(row, sizeof(row), " %s %d %s -\n", plen ? qn + plen + 1 : qn,- tr->visited[i].hop, ev_class);+ cbm_tree_cell_str(sb, "-", false);}} else if (include_evidence) {/* The root hop has no inbound edge, and non-CALLS edges record no* strategy. Emit placeholders so the column count stays fixed —* a ragged table is worse to parse than an explicit "-". */- snprintf(row, sizeof(row), " %s %d - -\n", plen ? qn + plen + 1 : qn,- tr->visited[i].hop);- } else {- snprintf(row, sizeof(row), " %s %d\n", plen ? qn + plen + 1 : qn, tr->visited[i].hop);+ cbm_tree_cell_str(sb, "-", false);+ cbm_tree_cell_str(sb, "-", false);}- cbm_sb_append(sb, row);+ cbm_tree_row_end(sb);+ }+ free(cur_group);+ if (ordered_owned) {+ free(ordered);+ }+}++/* Grouping removes repeated QN prefixes, but for singleton/scattered legs its+ * rule and group headers cost more than a direct qn column. Both encodings are+ * lossless, so choose the smaller serialized response instead of assuming a+ * directory always wins. */+static void bfs_to_adaptive_tree_table(cbm_sb_t *sb, const char *key, cbm_traverse_result_t *tr,+ bool include_tests, bool include_evidence,+ const trace_edge_context_t *edge_ctx) {+ cbm_sb_t grouped;+ cbm_sb_init(&grouped);+ bfs_to_tree_table(&grouped, key, tr, include_tests, include_evidence, edge_ctx);+ char *grouped_text = cbm_sb_finish(&grouped);++ cbm_sb_t flat;+ cbm_sb_init(&flat);+ bfs_to_toon_table(&flat, key, tr, false, include_tests, false, include_evidence, edge_ctx);+ char *flat_text = cbm_sb_finish(&flat);+ if (flat_text && (!grouped_text || strlen(flat_text) < strlen(grouped_text))) {+ cbm_sb_append(sb, flat_text);+ } else if (grouped_text) {+ cbm_sb_append(sb, grouped_text);+ }+ free(flat_text);+ free(grouped_text);+}++static void trace_emit_omitted_optional_fields_tree(cbm_sb_t *sb, bool risk_labels, bool data_flow,+ bool include_evidence) {+ char names[CBM_SZ_64] = "";+ size_t used = 0;+ if (risk_labels) {+ used += (size_t)snprintf(names + used, sizeof(names) - used, "risk");+ }+ if (data_flow) {+ used += (size_t)snprintf(names + used, sizeof(names) - used, "%sargs", used ? "," : "");+ }+ if (include_evidence) {+ (void)snprintf(names + used, sizeof(names) - used, "%sstrategy,confidence",+ used ? "," : "");+ }+ cbm_tree_scalar_str(sb, "omitted_optional_fields", names);+}++static void trace_emit_omitted_optional_fields_json(yyjson_mut_doc *doc, yyjson_mut_val *root,+ bool risk_labels, bool data_flow,+ bool include_evidence) {+ yyjson_mut_val *names = yyjson_mut_arr(doc);+ if (risk_labels) {+ yyjson_mut_arr_add_str(doc, names, "risk");}+ if (data_flow) {+ yyjson_mut_arr_add_str(doc, names, "args");+ }+ if (include_evidence) {+ yyjson_mut_arr_add_str(doc, names, "strategy");+ yyjson_mut_arr_add_str(doc, names, "confidence");+ }+ yyjson_mut_obj_add_val(doc, root, "omitted_optional_fields", names);}/* Clamp a client-supplied traversal depth to the MCP ceiling (cbm_mcp_max_depth),@@ -7146,6 +8352,14 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {if (trace_limit > MCP_BFS_LIMIT_MAX) {trace_limit = MCP_BFS_LIMIT_MAX;}+ int max_output_tokens = cbm_mcp_get_int_arg(args, "max_output_tokens", 3200);+ if (max_output_tokens < 128) {+ max_output_tokens = 128;+ } else if (max_output_tokens > 1000000) {+ max_output_tokens = 1000000;+ }+ size_t output_budget_bytes =+ (size_t)max_output_tokens * (size_t)MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE;bool risk_labels = cbm_mcp_get_bool_arg(args, "risk_labels");bool include_tests = cbm_mcp_get_bool_arg(args, "include_tests");/* Off by default: two extra columns on every row is exactly the kind of@@ -7209,10 +8423,9 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {true);}if (cursor_arg && cursor_arg[0]) {- uint64_t qh =- trace_params_hash(project, func_name, direction ? direction : "both", mode,- cbm_mcp_get_int_arg(args, "depth", MCP_DEFAULT_DEPTH), include_tests,- cbm_mcp_get_int_arg(args, "limit", MCP_BFS_LIMIT));+ uint64_t qh = trace_params_hash(project, func_name, direction ? direction : "both", mode,+ param_name, depth, include_tests, risk_labels,+ include_evidence, trace_limit, args);const char *cerr = trace_cursor_decode(cursor_arg, generation, qh, &cur);if (cerr) {free(cursor_arg);@@ -7246,6 +8459,18 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {free(param_name);return cbm_mcp_text_result(errbuf, true);}+ if (have_cursor && ((cur.leg == 'o' && strcmp(direction, "inbound") == 0) ||+ (cur.leg == 'i' && strcmp(direction, "outbound") == 0))) {+ free(func_name);+ free(project);+ free(direction);+ free(mode);+ free(param_name);+ return cbm_mcp_text_result(+ "invalid_cursor: cursor leg is incompatible with the requested direction — "+ "re-run the original query without 'cursor'",+ true);+ }/* Find the node by name. If the bare-name lookup misses, fall back to* qualified_name so callers passing a fully-qualified identifier (which@@ -7271,20 +8496,25 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {}if (node_count == 0) {- enum { HINT_BUF_SZ = 512 };- char hint[HINT_BUF_SZ];- snprintf(hint, sizeof(hint),- "{\"error\":\"function not found\",\"function_name\":\"%s\","- "\"hint\":\"Use search_graph(name_pattern=\\\".*%s.*\\\") to find the exact "- "name, then pass it to trace_path.\"}",- func_name, func_name);+ yyjson_mut_doc *error_doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *error_obj = yyjson_mut_obj(error_doc);+ yyjson_mut_doc_set_root(error_doc, error_obj);+ yyjson_mut_obj_add_str(error_doc, error_obj, "error", "function not found");+ yyjson_mut_obj_add_strcpy(error_doc, error_obj, "function_name", func_name);+ yyjson_mut_obj_add_str(error_doc, error_obj, "hint",+ "Use search_graph(name_pattern=...) to find the exact qualified "+ "name, then pass it to trace_path.");+ char *error_json = yy_doc_to_str(error_doc);+ yyjson_mut_doc_free(error_doc);free(func_name);free(project);free(direction);free(mode);free(param_name);cbm_store_free_nodes(nodes, 0);- return cbm_mcp_text_result(hint, true);+ char *result = cbm_mcp_text_result(error_json ? error_json : "function not found", true);+ free(error_json);+ return result;}/* Disambiguate same-named matches: prefer the real definition, and report@@ -7324,6 +8554,8 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {cbm_traverse_result_t tr_in = {0};bool data_flow = mode && strcmp(mode, "data_flow") == 0;+ bool need_edge_data = data_flow || include_evidence;+ int edge_data_limit = need_edge_data ? MCP_BFS_LIMIT_MAX : 0;(void)sel; /* union across all same-name nodes — see bfs_union_same_name (#546) */@@ -7332,13 +8564,34 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {* materializing up to MCP_BFS_LIMIT_MAX rows costs the same traversal —* and gives exact totals plus the rows every later page needs. The page* size (trace_limit) only bounds what THIS response emits. */+ int traversal_rc = CBM_STORE_OK;if (do_outbound) {- bfs_union_same_name(store, nodes, node_count, "outbound", edge_types, edge_type_count,- depth, MCP_BFS_LIMIT_MAX, &tr_out);+ traversal_rc =+ bfs_union_same_name(store, nodes, node_count, "outbound", edge_types, edge_type_count,+ depth, MCP_BFS_LIMIT_MAX, edge_data_limit, &tr_out);}- if (do_inbound) {- bfs_union_same_name(store, nodes, node_count, "inbound", edge_types, edge_type_count, depth,- MCP_BFS_LIMIT_MAX, &tr_in);+ if (traversal_rc == CBM_STORE_OK && do_inbound) {+ traversal_rc =+ bfs_union_same_name(store, nodes, node_count, "inbound", edge_types, edge_type_count,+ depth, MCP_BFS_LIMIT_MAX, edge_data_limit, &tr_in);+ }+ if (traversal_rc != CBM_STORE_OK) {+ cbm_store_traverse_free(&tr_out);+ cbm_store_traverse_free(&tr_in);+ cbm_store_free_nodes(nodes, node_count);+ free(func_name);+ free(project);+ free(direction);+ free(mode);+ free(param_name);+ if (et_doc_keep) {+ yyjson_doc_free(et_doc_keep);+ }+ return cbm_mcp_text_result("trace traversal failed; inspect index_status and retry", true);+ }+ if (!include_tests) {+ trace_filter_test_rows(&tr_out);+ trace_filter_test_rows(&tr_in);}/* Page windows in canonical (hop,id) order. Legs drain in a fixed order@@ -7348,11 +8601,31 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {int out_start = 0;int in_start = 0;if (have_cursor) {+ int watermark_next = CBM_NOT_FOUND;if (cur.leg == 'o') {- out_start = trace_watermark_index(&tr_out, cur.hop, cur.node_id);+ watermark_next = trace_watermark_next_index(&tr_out, cur.hop, cur.node_id);+ out_start = watermark_next;} else {out_start = tr_out.visited_count; /* callees leg already drained */- in_start = trace_watermark_index(&tr_in, cur.hop, cur.node_id);+ watermark_next = trace_watermark_next_index(&tr_in, cur.hop, cur.node_id);+ in_start = watermark_next;+ }+ if (watermark_next == CBM_NOT_FOUND) {+ cbm_store_traverse_free(&tr_out);+ cbm_store_traverse_free(&tr_in);+ cbm_store_free_nodes(nodes, node_count);+ free(func_name);+ free(project);+ free(direction);+ free(mode);+ free(param_name);+ if (et_doc_keep) {+ yyjson_doc_free(et_doc_keep);+ }+ return cbm_mcp_text_result(+ "invalid_cursor: watermark is not present in the selected visible trace leg — "+ "re-run the original query without 'cursor'",+ true);}}int budget = trace_limit;@@ -7371,27 +8644,55 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {in_len = budget;}}+ const int requested_out_len = out_len;+ const int requested_in_len = in_len;+ const int requested_page_rows = requested_out_len + requested_in_len;+ int row_target = requested_page_rows;+ int budget_search_low = 0;+ int budget_search_high = requested_page_rows;+ int budget_search_best = 0;+ bool budget_search_active = false;+ bool output_budget_hit = false;+ bool emit_optional_fields = risk_labels || data_flow || include_evidence;+ bool optional_fields_omitted = false;+ char *json = NULL;++render_trace_output:;+ int rows_left = row_target;+ out_len = requested_out_len < rows_left ? requested_out_len : rows_left;+ rows_left -= out_len;+ in_len = requested_in_len < rows_left ? requested_in_len : rows_left;bool out_more = do_outbound && out_start + out_len < tr_out.visited_count;bool in_more = do_inbound && in_start + in_len < tr_in.visited_count;bool more_rows = out_more || in_more;+ bool engine_saturated = tr_out.truncated || tr_in.truncated;+ bool edge_data_saturated = tr_out.edges_truncated || tr_in.edges_truncated;+ bool trace_truncated =+ more_rows || engine_saturated || edge_data_saturated || output_budget_hit;char next_tok[192] = "";/* Never mint a cursor under a "legacy" generation (no staleness* detection); the truncated flag + raise-limit hint still fire below. */if (more_rows && !gen_legacy) {trace_cursor_t nc = {0};snprintf(nc.generation, sizeof(nc.generation), "%s", generation);- nc.qhash = trace_params_hash(project, func_name, direction, mode, depth, include_tests,- trace_limit);- if (out_more) {- nc.leg = 'o';- nc.hop = tr_out.visited[out_start + out_len - 1].hop;- nc.node_id = tr_out.visited[out_start + out_len - 1].node.id;- } else {+ nc.qhash =+ trace_params_hash(project, func_name, direction, mode, param_name, depth, include_tests,+ risk_labels, include_evidence, trace_limit, args);+ /* The watermark is the last row ACTUALLY emitted, not the leg that+ * happens to have additional rows. At an exact outbound page boundary+ * inbound may be pending with zero emitted rows. */+ if (in_len > 0) {nc.leg = 'i';nc.hop = tr_in.visited[in_start + in_len - 1].hop;nc.node_id = tr_in.visited[in_start + in_len - 1].node.id;+ } else if (out_len > 0) {+ nc.leg = 'o';+ nc.hop = tr_out.visited[out_start + out_len - 1].hop;+ nc.node_id = tr_out.visited[out_start + out_len - 1].node.id;+ }+ if (in_len > 0 || out_len > 0) {+ trace_cursor_encode(&nc, next_tok, sizeof(next_tok));}- trace_cursor_encode(&nc, next_tok, sizeof(next_tok));}/* Window views: visited offset + count; the full edges array stays@@ -7403,6 +8704,10 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {cbm_traverse_result_t view_in = tr_in;view_in.visited = tr_in.visited ? tr_in.visited + in_start : NULL;view_in.visited_count = in_len;+ trace_edge_context_t out_edge_ctx = {+ .full = &tr_out, .roots = nodes, .root_count = node_count, .inbound = false};+ trace_edge_context_t in_edge_ctx = {+ .full = &tr_in, .roots = nodes, .root_count = node_count, .inbound = true};/* Totals must count what the caller can actually enumerate: when* include_tests=false the tables hide test-file rows, so raw@@ -7422,7 +8727,8 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {}}- char *json = NULL;+ free(json);+ json = NULL;if (!trace_legacy_json) {cbm_sb_t sb;cbm_sb_init(&sb);@@ -7433,37 +8739,74 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {}/* Grouped tree is THE default; risk_labels/data_flow keep the flat* table (extra columns) in the same tree syntax. */- bool flat_trace = risk_labels || data_flow;+ bool render_risk = risk_labels && emit_optional_fields;+ bool render_data_flow = data_flow && emit_optional_fields;+ bool render_evidence = include_evidence && emit_optional_fields;+ bool flat_trace = render_risk || render_data_flow;if (do_outbound) {cbm_tree_scalar_int(&sb, "callees_total", out_total);+ cbm_tree_scalar_str(&sb, "callees_total_relation", tr_out.truncated ? "gte" : "eq");if (flat_trace) {- bfs_to_toon_table(&sb, "callees", &view_out, risk_labels, include_tests, data_flow,- include_evidence);+ bfs_to_toon_table(&sb, "callees", &view_out, render_risk, include_tests,+ render_data_flow, render_evidence, &out_edge_ctx);} else {- bfs_to_tree_table(&sb, "callees", &view_out, include_tests, include_evidence);+ bfs_to_adaptive_tree_table(&sb, "callees", &view_out, include_tests,+ render_evidence, &out_edge_ctx);}}if (do_inbound) {cbm_tree_scalar_int(&sb, "callers_total", in_total);+ cbm_tree_scalar_str(&sb, "callers_total_relation", tr_in.truncated ? "gte" : "eq");if (flat_trace) {- bfs_to_toon_table(&sb, "callers", &view_in, risk_labels, include_tests, data_flow,- include_evidence);+ bfs_to_toon_table(&sb, "callers", &view_in, render_risk, include_tests,+ render_data_flow, render_evidence, &in_edge_ctx);} else {- bfs_to_tree_table(&sb, "callers", &view_in, include_tests, include_evidence);+ bfs_to_adaptive_tree_table(&sb, "callers", &view_in, include_tests, render_evidence,+ &in_edge_ctx);}}- if (more_rows) {+ if (trace_truncated) {cbm_tree_scalar_bool(&sb, "truncated", true);+ cbm_tree_scalar_bool(&sb, "has_more", more_rows);+ cbm_tree_scalar_str(+ &sb, "truncation_reason",+ output_budget_hit+ ? "output_budget"+ : (more_rows ? "page_limit"+ : (engine_saturated ? "engine_limit" : "edge_data_limit")));+ if (output_budget_hit) {+ cbm_tree_scalar_int(&sb, "max_output_bytes", (long long)output_budget_bytes);+ }+ if (optional_fields_omitted) {+ cbm_tree_scalar_bool(&sb, "optional_fields_omitted", true);+ trace_emit_omitted_optional_fields_tree(&sb, risk_labels, data_flow,+ include_evidence);+ }+ if (engine_saturated) {+ cbm_tree_scalar_bool(&sb, "engine_saturated", true);+ }+ if (edge_data_saturated) {+ cbm_tree_scalar_bool(&sb, "edge_data_saturated", true);+ }if (next_tok[0]) {cbm_tree_scalar_str(&sb, "next", next_tok);cbm_tree_scalar_str(&sb, "hint","more rows exist — re-call with cursor set to 'next' and ALL ""other arguments identical (no duplicates), or narrow with ""depth/edge_types");- } else {+ } else if (more_rows) {cbm_tree_scalar_str(&sb, "hint","more rows exist — re-call with a higher 'limit' (cursors ""unavailable: index predates generation tracking)");+ } else if (engine_saturated) {+ cbm_tree_scalar_str(+ &sb, "hint",+ "Traversal reached the 5000-node safety ceiling; narrow depth/edge_types "+ "or use query_graph for a differently bounded traversal.");+ } else {+ cbm_tree_scalar_str(&sb, "hint",+ "Optional edge evidence reached its 5000-edge ceiling; narrow "+ "depth/edge_types or disable data_flow/include_evidence.");}}json = cbm_sb_finish(&sb);@@ -7479,27 +8822,164 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {}if (do_outbound) {yyjson_mut_obj_add_int(doc, root, "callees_total", out_total);- yyjson_mut_obj_add_val(doc, root, "callees",- bfs_to_tree_json(doc, &view_out, risk_labels, include_tests,- data_flow, include_evidence));+ yyjson_mut_obj_add_str(doc, root, "callees_total_relation",+ tr_out.truncated ? "gte" : "eq");+ yyjson_mut_obj_add_val(+ doc, root, "callees",+ bfs_to_tree_json(doc, &view_out, risk_labels && emit_optional_fields, include_tests,+ data_flow && emit_optional_fields,+ include_evidence && emit_optional_fields, &out_edge_ctx));+ }+ if (do_inbound) {+ yyjson_mut_obj_add_int(doc, root, "callers_total", in_total);+ yyjson_mut_obj_add_str(doc, root, "callers_total_relation",+ tr_in.truncated ? "gte" : "eq");+ yyjson_mut_obj_add_val(+ doc, root, "callers",+ bfs_to_tree_json(doc, &view_in, risk_labels && emit_optional_fields, include_tests,+ data_flow && emit_optional_fields,+ include_evidence && emit_optional_fields, &in_edge_ctx));+ }+ if (trace_truncated) {+ yyjson_mut_obj_add_bool(doc, root, "truncated", true);+ yyjson_mut_obj_add_bool(doc, root, "has_more", more_rows);+ yyjson_mut_obj_add_str(+ doc, root, "truncation_reason",+ output_budget_hit+ ? "output_budget"+ : (more_rows ? "page_limit"+ : (engine_saturated ? "engine_limit" : "edge_data_limit")));+ if (output_budget_hit) {+ yyjson_mut_obj_add_uint(doc, root, "max_output_bytes", output_budget_bytes);+ }+ if (optional_fields_omitted) {+ yyjson_mut_obj_add_bool(doc, root, "optional_fields_omitted", true);+ trace_emit_omitted_optional_fields_json(doc, root, risk_labels, data_flow,+ include_evidence);+ }+ if (engine_saturated) {+ yyjson_mut_obj_add_bool(doc, root, "engine_saturated", true);+ }+ if (edge_data_saturated) {+ yyjson_mut_obj_add_bool(doc, root, "edge_data_saturated", true);+ }+ if (next_tok[0]) {+ yyjson_mut_obj_add_strcpy(doc, root, "next_cursor", next_tok);+ }+ }+ /* Serialize BEFORE freeing traversal results (yyjson borrows strings) */+ json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ }++ /* Apply the deterministic byte ceiling after serialization. Optional+ * diagnostics yield first; if primary graph rows still do not fit, find+ * the largest whole-row prefix. Cursor watermarks are recomputed on every+ * render, so `next` always follows the last row actually emitted. */+ if (json && strlen(json) > output_budget_bytes) {+ output_budget_hit = true;+ if (emit_optional_fields) {+ emit_optional_fields = false;+ optional_fields_omitted = true;+ goto render_trace_output;+ }+ if (row_target <= 1 || requested_page_rows == 0) {+ free(json);+ bool floor_has_more = requested_page_rows > 0;+ if (!trace_legacy_json) {+ cbm_sb_t floor;+ cbm_sb_init(&floor);+ if (do_outbound) {+ cbm_tree_scalar_int(&floor, "callees_total", out_total);+ cbm_tree_scalar_str(&floor, "callees_total_relation",+ tr_out.truncated ? "gte" : "eq");+ }+ if (do_inbound) {+ cbm_tree_scalar_int(&floor, "callers_total", in_total);+ cbm_tree_scalar_str(&floor, "callers_total_relation",+ tr_in.truncated ? "gte" : "eq");+ }+ cbm_tree_scalar_bool(&floor, "has_more", floor_has_more);+ if (floor_has_more) {+ cbm_tree_scalar_bool(&floor, "continuation_requires_higher_budget", true);+ }+ cbm_tree_scalar_bool(&floor, "truncated", true);+ cbm_tree_scalar_str(&floor, "truncation_reason", "output_budget");+ cbm_tree_scalar_bool(&floor, "output_budget_floor_exceeded", true);+ cbm_tree_scalar_int(&floor, "max_output_bytes", (long long)output_budget_bytes);+ if (optional_fields_omitted) {+ cbm_tree_scalar_bool(&floor, "optional_fields_omitted", true);+ trace_emit_omitted_optional_fields_tree(&floor, risk_labels, data_flow,+ include_evidence);+ }+ cbm_tree_scalar_str(&floor, "hint",+ "raise max_output_tokens; no identifier was sliced");+ json = cbm_sb_finish(&floor);+ } else {+ yyjson_mut_doc *floor_doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *floor = yyjson_mut_obj(floor_doc);+ yyjson_mut_doc_set_root(floor_doc, floor);+ if (do_outbound) {+ yyjson_mut_obj_add_int(floor_doc, floor, "callees_total", out_total);+ yyjson_mut_obj_add_str(floor_doc, floor, "callees_total_relation",+ tr_out.truncated ? "gte" : "eq");+ }+ if (do_inbound) {+ yyjson_mut_obj_add_int(floor_doc, floor, "callers_total", in_total);+ yyjson_mut_obj_add_str(floor_doc, floor, "callers_total_relation",+ tr_in.truncated ? "gte" : "eq");+ }+ yyjson_mut_obj_add_bool(floor_doc, floor, "has_more", floor_has_more);+ if (floor_has_more) {+ yyjson_mut_obj_add_bool(floor_doc, floor, "continuation_requires_higher_budget",+ true);+ }+ yyjson_mut_obj_add_bool(floor_doc, floor, "truncated", true);+ yyjson_mut_obj_add_str(floor_doc, floor, "truncation_reason", "output_budget");+ yyjson_mut_obj_add_bool(floor_doc, floor, "output_budget_floor_exceeded", true);+ yyjson_mut_obj_add_uint(floor_doc, floor, "max_output_bytes", output_budget_bytes);+ if (optional_fields_omitted) {+ yyjson_mut_obj_add_bool(floor_doc, floor, "optional_fields_omitted", true);+ trace_emit_omitted_optional_fields_json(floor_doc, floor, risk_labels,+ data_flow, include_evidence);+ }+ yyjson_mut_obj_add_str(floor_doc, floor, "hint",+ "raise max_output_tokens; no identifier was sliced");+ json = yy_doc_to_str(floor_doc);+ yyjson_mut_doc_free(floor_doc);+ }+ goto trace_output_ready;}- if (do_inbound) {- yyjson_mut_obj_add_int(doc, root, "callers_total", in_total);- yyjson_mut_obj_add_val(doc, root, "callers",- bfs_to_tree_json(doc, &view_in, risk_labels, include_tests,- data_flow, include_evidence));+ if (!budget_search_active) {+ budget_search_active = true;+ budget_search_low = 1;+ budget_search_high = row_target - 1;+ } else {+ budget_search_high = row_target - 1;}- if (more_rows) {- yyjson_mut_obj_add_bool(doc, root, "truncated", true);- if (next_tok[0]) {- yyjson_mut_obj_add_strcpy(doc, root, "next_cursor", next_tok);+ if (budget_search_low > budget_search_high) {+ if (budget_search_best < 1) {+ row_target = 1;+ } else {+ row_target = budget_search_best;}+ budget_search_active = false;+ goto render_trace_output;+ }+ row_target = budget_search_low + (budget_search_high - budget_search_low) / 2;+ goto render_trace_output;+ }+ if (budget_search_active) {+ budget_search_best = row_target;+ budget_search_low = row_target + 1;+ if (budget_search_low <= budget_search_high) {+ row_target = budget_search_low + (budget_search_high - budget_search_low + 1) / 2;+ goto render_trace_output;}- /* Serialize BEFORE freeing traversal results (yyjson borrows strings) */- json = yy_doc_to_str(doc);- yyjson_mut_doc_free(doc);}+trace_output_ready:+/* Now safe to free traversal data */if (do_outbound) {cbm_store_traverse_free(&tr_out);@@ -7543,37 +9023,30 @@ static char *read_file_lines(const char *path, int start, int end) {return NULL;}- size_t cap = CBM_SZ_4K;- char *buf = malloc(cap);- size_t len = 0;- buf[0] = '\0';-- char line[CBM_SZ_2K];- int lineno = 0;- while (fgets(line, sizeof(line), fp)) {- lineno++;- if (lineno < start) {- continue;+ cbm_sb_t selected;+ cbm_sb_init(&selected);+ int lineno = 1;+ int byte;+ while ((byte = fgetc(fp)) != EOF) {+ if (lineno >= start && lineno <= end) {+ char ch = (char)byte;+ cbm_sb_append_n(&selected, &ch, 1U);}- if (lineno > end) {- break;- }- size_t ll = strlen(line);- while (len + ll + SKIP_ONE > cap) {- cap *= PAIR_LEN;- buf = safe_realloc(buf, cap);+ if (byte == '\n') {+ if (lineno >= end) {+ break;+ }+ lineno++;}- memcpy(buf + len, line, ll);- len += ll;- buf[len] = '\0';}(void)fclose(fp);- if (len == 0) {- free(buf);+ char *result = cbm_sb_finish(&selected);+ if (result && result[0] == '\0') {+ free(result);return NULL;}- return buf;+ return result;}/* ── Helper: get project root_path from store ─────────────────── */@@ -9212,13 +10685,44 @@ static bool utf8_is_cont(unsigned char c) {return (c & 0xC0) == 0x80;}+static size_t utf8_sequence_len(const unsigned char *p, const unsigned char *end) {+ size_t remaining = (size_t)(end - p);+ unsigned char c = *p;+ if (c < 0x80) {+ return 1;+ }+ if (c >= 0xC2 && c <= 0xDF && remaining >= 2 && utf8_is_cont(p[1])) {+ return 2;+ }+ if (c == 0xE0 && remaining >= 3 && p[1] >= 0xA0 && p[1] <= 0xBF && utf8_is_cont(p[2])) {+ return 3;+ }+ if (c >= 0xE1 && c <= 0xEC && remaining >= 3 && utf8_is_cont(p[1]) && utf8_is_cont(p[2])) {+ return 3;+ }+ if (c == 0xED && remaining >= 3 && p[1] >= 0x80 && p[1] <= 0x9F && utf8_is_cont(p[2])) {+ return 3;+ }+ if (c >= 0xEE && c <= 0xEF && remaining >= 3 && utf8_is_cont(p[1]) && utf8_is_cont(p[2])) {+ return 3;+ }+ if (c == 0xF0 && remaining >= 4 && p[1] >= 0x90 && p[1] <= 0xBF && utf8_is_cont(p[2]) &&+ utf8_is_cont(p[3])) {+ return 4;+ }+ if (c >= 0xF1 && c <= 0xF3 && remaining >= 4 && utf8_is_cont(p[1]) && utf8_is_cont(p[2]) &&+ utf8_is_cont(p[3])) {+ return 4;+ }+ if (c == 0xF4 && remaining >= 4 && p[1] >= 0x80 && p[1] <= 0x8F && utf8_is_cont(p[2]) &&+ utf8_is_cont(p[3])) {+ return 4;+ }+ return 0;+}+static char *sanitize_utf8_lossy(const char *s) {- enum {- UTF8_REPLACEMENT_LEN = 3,- UTF8_THREE_BYTE_LEN = 3,- UTF8_FOUR_BYTE_LEN = 4,- UTF8_FOURTH_BYTE = 3,- };+ enum { UTF8_REPLACEMENT_LEN = 3 };if (!s) {return NULL;}@@ -9235,32 +10739,7 @@ static char *sanitize_utf8_lossy(const char *s) {const unsigned char *end = p + len;unsigned char *dst = (unsigned char *)out;while (p < end) {- unsigned char c = *p;- size_t n = 0;- if (c < 0x80) {- n = 1;- } else if (c >= 0xC2 && c <= 0xDF && p + 1 < end && utf8_is_cont(p[1])) {- n = 2;- } else if (c == 0xE0 && p + 2 < end && p[1] >= 0xA0 && p[1] <= 0xBF && utf8_is_cont(p[2])) {- n = UTF8_THREE_BYTE_LEN;- } else if (c >= 0xE1 && c <= 0xEC && p + 2 < end && utf8_is_cont(p[1]) &&- utf8_is_cont(p[2])) {- n = UTF8_THREE_BYTE_LEN;- } else if (c == 0xED && p + 2 < end && p[1] >= 0x80 && p[1] <= 0x9F && utf8_is_cont(p[2])) {- n = UTF8_THREE_BYTE_LEN;- } else if (c >= 0xEE && c <= 0xEF && p + 2 < end && utf8_is_cont(p[1]) &&- utf8_is_cont(p[2])) {- n = UTF8_THREE_BYTE_LEN;- } else if (c == 0xF0 && p + UTF8_FOURTH_BYTE < end && p[1] >= 0x90 && p[1] <= 0xBF &&- utf8_is_cont(p[2]) && utf8_is_cont(p[UTF8_FOURTH_BYTE])) {- n = UTF8_FOUR_BYTE_LEN;- } else if (c >= 0xF1 && c <= 0xF3 && p + UTF8_FOURTH_BYTE < end && utf8_is_cont(p[1]) &&- utf8_is_cont(p[2]) && utf8_is_cont(p[UTF8_FOURTH_BYTE])) {- n = UTF8_FOUR_BYTE_LEN;- } else if (c == 0xF4 && p + UTF8_FOURTH_BYTE < end && p[1] >= 0x80 && p[1] <= 0x8F &&- utf8_is_cont(p[2]) && utf8_is_cont(p[UTF8_FOURTH_BYTE])) {- n = UTF8_FOUR_BYTE_LEN;- }+ size_t n = utf8_sequence_len(p, end);if (n > 0) {memcpy(dst, p, n);@@ -9277,6 +10756,26 @@ static char *sanitize_utf8_lossy(const char *s) {return out;}+/* Fixed-width search buffers cannot grow invalid bytes into the three-byte+ * replacement character. Preserve every valid UTF-8 sequence and replace an+ * invalid byte in place with '?', keeping the result valid without losing+ * non-ASCII identifiers, paths, comments, or source text. */+static void sanitize_utf8_inplace(char *s) {+ if (!s) {+ return;+ }+ unsigned char *p = (unsigned char *)s;+ const unsigned char *end = p + strlen(s);+ while (p < end) {+ size_t n = utf8_sequence_len(p, end);+ if (n > 0) {+ p += n;+ } else {+ *p++ = '?';+ }+ }+}+/* Build an enriched snippet response for a resolved node. *//* Add a string array to a JSON object (no-op if count == 0). */static void add_string_array(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key,@@ -9324,25 +10823,209 @@ static void add_snippet_coverage_note(yyjson_mut_doc *doc, yyjson_mut_val *root_cbm_store_free_coverage(rows, count);}+static int snippet_member_cmp(const void *left, const void *right) {+ const cbm_node_t *a = left;+ const cbm_node_t *b = right;+ if (a->start_line != b->start_line) {+ return a->start_line < b->start_line ? -1 : 1;+ }+ if (a->end_line != b->end_line) {+ return a->end_line < b->end_line ? -1 : 1;+ }+ int qn_cmp = strcmp(a->qualified_name ? a->qualified_name : "",+ b->qualified_name ? b->qualified_name : "");+ if (qn_cmp != 0) {+ return qn_cmp;+ }+ return a->id < b->id ? -1 : a->id > b->id ? 1 : 0;+}++static void snippet_obj_set_int(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key,+ int value) {+ (void)yyjson_mut_obj_remove_key(obj, key);+ yyjson_mut_obj_add_int(doc, obj, key, value);+}++static void snippet_obj_set_bool(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key,+ bool value) {+ (void)yyjson_mut_obj_remove_key(obj, key);+ yyjson_mut_obj_add_bool(doc, obj, key, value);+}++static char *snippet_render_payload(yyjson_mut_doc *doc, const char *args) {+ char *json = yy_doc_to_str(doc);+ if (!json || mcp_wants_json(args)) {+ return json;+ }+ char *tree = cbm_json_to_tree(json);+ free(json);+ return tree;+}++static int snippet_source_line_count(const char *source) {+ if (!source || !source[0]) {+ return 0;+ }+ int lines = 1;+ for (const char *p = source; *p; p++) {+ if (*p == '\n' && p[1] != '\0') {+ lines++;+ }+ }+ return lines;+}++/* Copy at most `line_limit` complete physical lines. A single over-budget+ * line therefore yields no source instead of a corrupt byte prefix. */+static char *snippet_source_line_prefix(const char *source, int line_limit) {+ if (!source || line_limit <= 0) {+ return NULL;+ }+ const char *end = source;+ int lines = 0;+ while (*end && lines < line_limit) {+ const char *newline = strchr(end, '\n');+ if (!newline) {+ end += strlen(end);+ break;+ }+ end = newline + 1;+ lines++;+ }+ size_t len = (size_t)(end - source);+ char *copy = malloc(len + 1U);+ if (!copy) {+ return NULL;+ }+ memcpy(copy, source, len);+ copy[len] = '\0';+ return copy;+}++static void snippet_set_source_prefix(yyjson_mut_doc *doc, yyjson_mut_val *root,+ const char *whole_source, int line_count, int start,+ int original_end) {+ (void)yyjson_mut_obj_remove_key(root, "source");+ (void)yyjson_mut_obj_remove_key(root, "source_omitted");+ (void)yyjson_mut_obj_remove_key(root, "next_start_line");+ (void)yyjson_mut_obj_remove_key(root, "continuation_requires_higher_budget");+ (void)yyjson_mut_obj_remove_key(root, "continuation");+ if (line_count > 0) {+ char *prefix = snippet_source_line_prefix(whole_source, line_count);+ if (prefix) {+ yyjson_mut_obj_add_strcpy(doc, root, "source", prefix);+ free(prefix);+ } else {+ yyjson_mut_obj_add_bool(doc, root, "source_omitted", true);+ line_count = 0;+ }+ } else {+ yyjson_mut_obj_add_bool(doc, root, "source_omitted", true);+ }+ int returned_end = line_count > 0 ? start + line_count - 1 : start;+ snippet_obj_set_int(doc, root, "end_line", returned_end);+ snippet_obj_set_bool(doc, root, "source_truncated", true);+ snippet_obj_set_bool(doc, root, "source_clipped", true);+ (void)yyjson_mut_obj_remove_key(root, "truncation_reason");+ yyjson_mut_obj_add_str(doc, root, "truncation_reason", "output_budget");+ if (line_count > 0) {+ yyjson_mut_obj_add_int(doc, root, "next_start_line", returned_end + 1);+ } else {+ yyjson_mut_obj_add_bool(doc, root, "continuation_requires_higher_budget", true);+ yyjson_mut_obj_add_str(+ doc, root, "continuation",+ "raise max_output_tokens; no complete source line fits the current budget");+ }+ snippet_obj_set_int(doc, root, "original_end_line", original_end);+ snippet_obj_set_int(doc, root, "source_lines_returned", line_count);+}++static char *snippet_budget_floor(bool json_format, int max_output_tokens) {+ if (!json_format) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ cbm_tree_scalar_str(&sb, "source_mode", "omitted");+ cbm_tree_scalar_bool(&sb, "truncated", true);+ cbm_tree_scalar_str(&sb, "truncation_reason", "output_budget");+ cbm_tree_scalar_int(&sb, "max_output_tokens", max_output_tokens);+ cbm_tree_scalar_bool(&sb, "continuation_requires_higher_budget", true);+ cbm_tree_scalar_str(&sb, "continuation",+ "raise max_output_tokens; no partial line or identifier was emitted");+ return cbm_sb_finish(&sb);+ }+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_obj_add_str(doc, root, "source_mode", "omitted");+ yyjson_mut_obj_add_bool(doc, root, "truncated", true);+ yyjson_mut_obj_add_str(doc, root, "truncation_reason", "output_budget");+ yyjson_mut_obj_add_int(doc, root, "max_output_tokens", max_output_tokens);+ yyjson_mut_obj_add_bool(doc, root, "continuation_requires_higher_budget", true);+ yyjson_mut_obj_add_str(doc, root, "continuation",+ "raise max_output_tokens; no partial line or identifier was emitted");+ char *json = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ return json;+}+static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,const char *match_method, bool include_neighbors,- cbm_node_t *alternatives, int alt_count) {+ cbm_node_t *alternatives, int alt_count, const char *args) {char *root_path = get_project_root(srv, node->project);- int start = node->start_line > 0 ? node->start_line : SKIP_ONE;- int end = node->end_line > start ? node->end_line : start + SNIPPET_DEFAULT_LINES;+ int original_start = node->start_line > 0 ? node->start_line : SKIP_ONE;+ /* A one-line symbol legitimately has end == start. Treat only missing or+ * inverted end metadata as unknown; expanding a valid one-line node by 50+ * lines both wastes output and lies about the continuation range. */+ int original_end =+ node->end_line >= original_start ? node->end_line : original_start + SNIPPET_DEFAULT_LINES;+ char *source_mode = cbm_mcp_get_string_arg(args, "source_mode");+ bool explicit_full = source_mode && strcmp(source_mode, "full") == 0;+ bool explicit_outline = source_mode && strcmp(source_mode, "outline") == 0;+ bool container =+ node->label && (strcmp(node->label, "File") == 0 || strcmp(node->label, "Module") == 0 ||+ strcmp(node->label, "Class") == 0 || strcmp(node->label, "Interface") == 0);+ bool outline =+ explicit_outline || (!explicit_full && container && original_end - original_start >= 200);+ free(source_mode);++ int start = outline ? original_start : cbm_mcp_get_int_arg(args, "start_line", original_start);+ if (start < original_start || start > original_end) {+ start = original_start;+ }+ int end = original_end;+ int max_lines = cbm_mcp_get_int_arg(args, "max_lines", 0);+ int max_output_tokens =+ cbm_mcp_get_int_arg(args, "max_output_tokens", explicit_full ? 0 : 2500);+ if (max_output_tokens < 0) {+ max_output_tokens = 0;+ } else if (max_output_tokens > 0 && max_output_tokens < 128) {+ max_output_tokens = 128;+ } else if (max_output_tokens > 1000000) {+ max_output_tokens = 1000000;+ }+ if (max_lines > MCP_SNIPPET_MAX_LINES) {+ max_lines = MCP_SNIPPET_MAX_LINES;+ }+ if (!outline && max_lines > 0 && start + max_lines - 1 < end) {+ end = start + max_lines - 1;+ }/* Context-bomb guard: a structural node (Module/File) spans its whole file,* so an unclipped read returned the ENTIRE source — a field-eval agent that* fell back to a Module snippet pulled 400KB in one call. Cap the line span* (far above any real function) and flag it; the exact range is still in* start_line/end_line for a targeted re-read. */bool snippet_clipped = false;- if (end - start + 1 > MCP_SNIPPET_MAX_LINES) {+ if (!outline && end - start + 1 > MCP_SNIPPET_MAX_LINES) {end = start + MCP_SNIPPET_MAX_LINES - 1;snippet_clipped = true;}+ if (!outline && end < original_end) {+ snippet_clipped = true;+ }char *abs_path = NULL;- char *source = resolve_snippet_source(root_path, node->file_path, start, end, &abs_path);+ char *source =+ outline ? NULL : resolve_snippet_source(root_path, node->file_path, start, end, &abs_path);yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root_obj = yyjson_mut_obj(doc);@@ -9363,11 +11046,79 @@ static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,yyjson_mut_obj_add_int(doc, root_obj, "start_line", start);yyjson_mut_obj_add_int(doc, root_obj, "end_line", end);if (snippet_clipped) {- yyjson_mut_obj_add_bool(doc, root_obj, "source_clipped", true);- yyjson_mut_obj_add_int(doc, root_obj, "clipped_at_lines", MCP_SNIPPET_MAX_LINES);- }-- if (source) {+ yyjson_mut_obj_add_bool(doc, root_obj, "source_truncated", true);+ yyjson_mut_obj_add_bool(doc, root_obj, "source_clipped", true); /* compatibility */+ yyjson_mut_obj_add_int(doc, root_obj, "next_start_line", end + 1);+ yyjson_mut_obj_add_int(doc, root_obj, "original_end_line", original_end);+ }++ yyjson_mut_val *outline_members = NULL;+ int outline_member_offset = 0;+ int outline_members_total = 0;+ int outline_members_returned = 0;+ if (outline) {+ cbm_node_t *members = NULL;+ int member_count = 0;+ (void)cbm_store_find_nodes_by_file(srv->store, node->project, node->file_path, &members,+ &member_count);+ if (member_count > 1) {+ qsort(members, (size_t)member_count, sizeof(*members), snippet_member_cmp);+ }+ int member_limit = cbm_mcp_get_int_arg(args, "member_limit", 50);+ int member_offset = cbm_mcp_get_int_arg(args, "member_offset", 0);+ if (member_limit < 1) {+ member_limit = 1;+ } else if (member_limit > 500) {+ member_limit = 500;+ }+ if (member_offset < 0) {+ member_offset = 0;+ }+ int eligible = 0;+ for (int i = 0; i < member_count; i++) {+ if (members[i].id != node->id && members[i].start_line >= original_start &&+ members[i].end_line <= original_end) {+ eligible++;+ }+ }+ yyjson_mut_val *member_rows = yyjson_mut_arr(doc);+ int seen = 0;+ int emitted = 0;+ for (int i = 0; i < member_count && emitted < member_limit; i++) {+ if (members[i].id == node->id || members[i].start_line < original_start ||+ members[i].end_line > original_end) {+ continue;+ }+ if (seen++ < member_offset) {+ continue;+ }+ yyjson_mut_val *member = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_strcpy(doc, member, "qualified_name",+ members[i].qualified_name ? members[i].qualified_name : "");+ yyjson_mut_obj_add_strcpy(doc, member, "label",+ members[i].label ? members[i].label : "");+ yyjson_mut_obj_add_int(doc, member, "start_line", members[i].start_line);+ yyjson_mut_obj_add_int(doc, member, "end_line", members[i].end_line);+ yyjson_mut_arr_add_val(member_rows, member);+ emitted++;+ }+ yyjson_mut_obj_add_str(doc, root_obj, "source_mode", "outline");+ yyjson_mut_obj_add_val(doc, root_obj, "members", member_rows);+ yyjson_mut_obj_add_int(doc, root_obj, "members_total", eligible);+ yyjson_mut_obj_add_int(doc, root_obj, "members_returned", emitted);+ yyjson_mut_obj_add_bool(doc, root_obj, "members_has_more",+ member_offset + emitted < eligible);+ if (member_offset + emitted < eligible) {+ yyjson_mut_obj_add_int(doc, root_obj, "next_member_offset", member_offset + emitted);+ }+ yyjson_mut_obj_add_bool(doc, root_obj, "full_source_available", true);+ outline_members = member_rows;+ outline_member_offset = member_offset;+ outline_members_total = eligible;+ outline_members_returned = emitted;+ cbm_store_free_nodes(members, member_count);+ } else if (source) {+ yyjson_mut_obj_add_str(doc, root_obj, "source_mode", "full");char *safe_source = sanitize_utf8_lossy(source);if (safe_source) {yyjson_mut_obj_add_strcpy(doc, root_obj, "source", safe_source);@@ -9376,6 +11127,7 @@ static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,yyjson_mut_obj_add_str(doc, root_obj, "source", "(source not available)");}} else {+ yyjson_mut_obj_add_str(doc, root_obj, "source_mode", "full");yyjson_mut_obj_add_str(doc, root_obj, "source", "(source not available)");}@@ -9426,7 +11178,82 @@ static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,yyjson_mut_obj_add_val(doc, root_obj, "alternatives", arr);}- char *json = yy_doc_to_str(doc);+ bool bounded_default = max_output_tokens > 0;+ size_t snippet_byte_budget =+ bounded_default ? (size_t)max_output_tokens * (size_t)MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE+ : (size_t)-1;+ bool json_format = mcp_wants_json(args);+ char *payload = snippet_render_payload(doc, args);++ /* An outline is already the quality-preserving alternative to dumping a+ * large container. If its member page is still too large, page whole+ * member rows before considering the minimal floor; retain symbol identity+ * and an exact continuation offset throughout. */+ if (bounded_default && payload && strlen(payload) > snippet_byte_budget && outline &&+ outline_members) {+ (void)yyjson_mut_obj_remove_key(root_obj, "truncation_reason");+ yyjson_mut_obj_add_str(doc, root_obj, "truncation_reason", "output_budget");+ while (strlen(payload) > snippet_byte_budget && outline_members_returned > 0) {+ free(payload);+ outline_members_returned--;+ yyjson_mut_arr_remove(outline_members, (size_t)outline_members_returned);+ snippet_obj_set_int(doc, root_obj, "members_returned", outline_members_returned);+ snippet_obj_set_bool(doc, root_obj, "members_has_more",+ outline_member_offset + outline_members_returned <+ outline_members_total);+ (void)yyjson_mut_obj_remove_key(root_obj, "next_member_offset");+ if (outline_member_offset + outline_members_returned < outline_members_total) {+ yyjson_mut_obj_add_int(doc, root_obj, "next_member_offset",+ outline_member_offset + outline_members_returned);+ }+ payload = snippet_render_payload(doc, args);+ if (!payload) {+ break;+ }+ }+ }++ if (bounded_default && payload && strlen(payload) > snippet_byte_budget && !outline && source) {+ char *safe_whole_source = sanitize_utf8_lossy(source);+ int available_lines = snippet_source_line_count(safe_whole_source);+ int low = 0;+ int high = available_lines;+ int best_lines = -1;+ char *best_payload = NULL;+ while (low <= high) {+ int middle = low + (high - low) / 2;+ snippet_set_source_prefix(doc, root_obj, safe_whole_source, middle, start,+ original_end);+ char *candidate = snippet_render_payload(doc, args);+ if (candidate && strlen(candidate) <= snippet_byte_budget) {+ free(best_payload);+ best_payload = candidate;+ best_lines = middle;+ low = middle + 1;+ } else {+ free(candidate);+ high = middle - 1;+ }+ }+ free(payload);+ if (best_payload) {+ snippet_set_source_prefix(doc, root_obj, safe_whole_source, best_lines, start,+ original_end);+ payload = best_payload;+ } else {+ snippet_set_source_prefix(doc, root_obj, safe_whole_source, 0, start, original_end);+ payload = snippet_render_payload(doc, args);+ }+ free(safe_whole_source);+ }++ /* Large outlines/neighbor/alternative metadata still obey the default+ * ceiling. Do not slice identifiers: if the metadata floor itself cannot+ * fit, return a small continuation record. */+ if (bounded_default && (!payload || strlen(payload) > snippet_byte_budget)) {+ free(payload);+ payload = snippet_budget_floor(json_format, max_output_tokens);+ }yyjson_mut_doc_free(doc);yyjson_doc_free(props_doc); /* safe if NULL */for (int i = 0; i < nb_caller_count; i++) {@@ -9441,8 +11268,8 @@ static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,free(abs_path);free(source);- char *result = cbm_mcp_text_result(json, false);- free(json);+ char *result = cbm_mcp_text_result(payload ? payload : "out of memory", payload == NULL);+ free(payload);return result;}@@ -9704,7 +11531,7 @@ static char *handle_get_code_snippet(cbm_mcp_server_t *srv, const char *args) {cbm_node_t node = {0};int rc = cbm_store_find_node_by_qn(store, effective_project, qn, &node);if (rc == CBM_STORE_OK) {- char *result = build_snippet_response(srv, &node, NULL, include_neighbors, NULL, 0);+ char *result = build_snippet_response(srv, &node, NULL, include_neighbors, NULL, 0, args);free_node_contents(&node);free(qn);free(project);@@ -9720,7 +11547,8 @@ static char *handle_get_code_snippet(cbm_mcp_server_t *srv, const char *args) {if (suffix_count == SKIP_ONE) {copy_node(&suffix_nodes[0], &node);cbm_store_free_nodes(suffix_nodes, suffix_count);- char *result = build_snippet_response(srv, &node, "suffix", include_neighbors, NULL, 0);+ char *result =+ build_snippet_response(srv, &node, "suffix", include_neighbors, NULL, 0, args);free_node_contents(&node);free(qn);free(project);@@ -9737,7 +11565,8 @@ static char *handle_get_code_snippet(cbm_mcp_server_t *srv, const char *args) {if (!snip_ambiguous) {copy_node(&suffix_nodes[ssel], &node);cbm_store_free_nodes(suffix_nodes, suffix_count);- char *result = build_snippet_response(srv, &node, "suffix", include_neighbors, NULL, 0);+ char *result =+ build_snippet_response(srv, &node, "suffix", include_neighbors, NULL, 0, args);free_node_contents(&node);free(qn);free(project);@@ -9765,25 +11594,27 @@ static char *handle_get_code_snippet(cbm_mcp_server_t *srv, const char *args) {/* Intermediate grep match */typedef struct {- char file[CBM_SZ_512];+ char *file;int line;char content[CBM_SZ_1K];+ bool content_truncated;} grep_match_t;/* Deduped result: one per containing graph node */typedef struct {int64_t node_id; /* 0 = raw match (no containing node) */char node_name[CBM_SZ_256];- char qualified_name[CBM_SZ_512];+ char *qualified_name;char label[CBM_SZ_64];- char file[CBM_SZ_512];+ char *file;int start_line;int end_line;int in_degree;int out_degree;int score;- int match_lines[CBM_SZ_64];+ int *match_lines;int match_count;+ int match_capacity;} search_result_t;typedef struct {@@ -9794,6 +11625,46 @@ typedef struct {bool include_phase_timings;} search_metrics_t;+typedef struct {+ char *name;+ int count;+} search_dir_count_t;++static bool set_search_result_identity(search_result_t *result, const cbm_node_t *node);+static bool append_search_match_line(search_result_t *result, int line);++static void free_grep_matches(grep_match_t *matches, int count) {+ if (!matches) {+ return;+ }+ for (int i = 0; i < count; i++) {+ free(matches[i].file);+ }+ free(matches);+}++static void free_search_results(search_result_t *results, int count) {+ if (!results) {+ return;+ }+ for (int i = 0; i < count; i++) {+ free(results[i].qualified_name);+ free(results[i].file);+ free(results[i].match_lines);+ }+ free(results);+}++static void free_search_dirs(search_dir_count_t *directories, int count) {+ if (!directories) {+ return;+ }+ for (int i = 0; i < count; i++) {+ free(directories[i].name);+ }+ free(directories);+}+/* Score a result for ranking: project source first, vendored last, tests lowest */enum { SCORE_FUNC = 10, SCORE_ROUTE = 15, SCORE_VENDORED = -50, SCORE_TEST = -5 };enum { MAX_LINE_SPAN = 999999 };@@ -9969,7 +11840,12 @@ void cbm_search_code_build_grep_cmd(char *cmd, size_t cmd_sz, bool use_regex, bostatic yyjson_mut_val *build_dedup_files_array(yyjson_mut_doc *doc, search_result_t *sr,int output_count, grep_match_t *raw, int raw_count) {yyjson_mut_val *files_arr = yyjson_mut_arr(doc);- char *seen_files[CBM_SZ_512];+ size_t seen_capacity = (size_t)output_count + (size_t)raw_count;+ const char **seen_files = seen_capacity > 0 ? calloc(seen_capacity, sizeof(*seen_files)) : NULL;+ if (!files_arr || (seen_capacity > 0 && !seen_files)) {+ free(seen_files);+ return NULL;+ }int seen_count = 0;for (int fi = 0; fi < output_count; fi++) {bool dup = false;@@ -9979,12 +11855,12 @@ static yyjson_mut_val *build_dedup_files_array(yyjson_mut_doc *doc, search_resulbreak;}}- if (!dup && seen_count < CBM_SZ_512) {+ if (!dup) {seen_files[seen_count++] = sr[fi].file;yyjson_mut_arr_add_str(doc, files_arr, sr[fi].file);}}- for (int fi = 0; fi < raw_count && seen_count < CBM_SZ_512; fi++) {+ for (int fi = 0; fi < raw_count; fi++) {bool dup = false;for (int j = 0; j < seen_count; j++) {if (strcmp(seen_files[j], raw[fi].file) == 0) {@@ -9997,24 +11873,37 @@ static yyjson_mut_val *build_dedup_files_array(yyjson_mut_doc *doc, search_resulyyjson_mut_arr_add_str(doc, files_arr, raw[fi].file);}}+ free(seen_files);return files_arr;}/* Attach source or context lines to a search result JSON item. */static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, search_result_t *r,- int mode, int context_lines, const char *root_path) {+ int mode, int context_lines, int source_max_lines,+ const char *root_path) {enum { MODE_FULL = 1 };if (r->start_line <= 0 || r->end_line <= 0) {return;}- char abs_path[CBM_SZ_1K];- snprintf(abs_path, sizeof(abs_path), "%s/%s", root_path, r->file);+ size_t root_length = strlen(root_path);+ size_t file_length = strlen(r->file);+ if (root_length > SIZE_MAX - file_length - 2U) {+ return;+ }+ char *abs_path = malloc(root_length + file_length + 2U);+ if (!abs_path) {+ return;+ }+ memcpy(abs_path, root_path, root_length);+ abs_path[root_length] = '/';+ memcpy(abs_path + root_length + 1U, r->file, file_length + 1U);/* Containment: a search result whose indexed path resolves outside the* project root (a `..` segment, or a symlink/junction that discovery* followed) must not be read back into the response. Same guard the* snippet path already uses. */if (!cbm_path_within_root(root_path, abs_path)) {+ free(abs_path);return;}@@ -10023,15 +11912,20 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear* whole-symbol dumps ran to 5.7KB × N hits (142KB responses). The* complete symbol stays one get_code_snippet call away;* source_start/source_truncated make the cut explicit. */- enum { SC_FULL_MAX_LINES = 60, SC_FULL_LEAD = 5 };+ enum { SC_FULL_LEAD = 5 };+ if (source_max_lines <= 0) {+ yyjson_mut_obj_add_bool(doc, item, "source_omitted", true);+ free(abs_path);+ return;+ }int s = r->start_line;int e = r->end_line;bool truncated = false;- if (e - s + 1 > SC_FULL_MAX_LINES) {+ if (e - s + 1 > source_max_lines) {if (r->match_count > 0 && r->match_lines[0] - SC_FULL_LEAD > s) {s = r->match_lines[0] - SC_FULL_LEAD;}- e = s + SC_FULL_MAX_LINES - 1;+ e = s + source_max_lines - 1;if (e > r->end_line) {e = r->end_line;}@@ -10039,11 +11933,8 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear}char *source = read_file_lines(abs_path, s, e);if (source) {- char *safe_source = sanitize_utf8_lossy(source);- if (safe_source) {- yyjson_mut_obj_add_strcpy(doc, item, "source", safe_source);- free(safe_source);- }+ sanitize_utf8_inplace(source);+ yyjson_mut_obj_add_strcpy(doc, item, "source", source);free(source);if (truncated) {yyjson_mut_obj_add_int(doc, item, "source_start", s);@@ -10058,66 +11949,92 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear}char *ctx = read_file_lines(abs_path, ctx_start, ctx_end);if (ctx) {- char *safe_context = sanitize_utf8_lossy(ctx);- if (safe_context) {- yyjson_mut_obj_add_strcpy(doc, item, "context", safe_context);- free(safe_context);- }+ sanitize_utf8_inplace(ctx);+ yyjson_mut_obj_add_strcpy(doc, item, "context", ctx);yyjson_mut_obj_add_int(doc, item, "context_start", ctx_start);free(ctx);}}+ free(abs_path);}-/* Build directory distribution object from search results (top-level dir → count). */-/* Aggregate hits by top-level directory. Shared by the JSON object and the- * TOON table emission. Returns the number of distinct directories. */-static int aggregate_search_dirs(search_result_t *sr, int sr_count, char dir_names[][CBM_SZ_128],- int *dir_counts, int max_dirs) {+/* Aggregate hits by top-level directory. Directory keys are allocation-backed:+ * truncating them used to merge distinct directories that shared their first+ * 127 bytes, making the diagnostic count look exact when it was not. */+static bool aggregate_search_dirs(search_result_t *sr, int sr_count,+ search_dir_count_t **directories_out, int *count_out) {+ *directories_out = NULL;+ *count_out = 0;+ if (sr_count <= 0) {+ return true;+ }+ search_dir_count_t *directories = calloc((size_t)sr_count, sizeof(*directories));+ if (!directories) {+ return false;+ }int dir_n = 0;for (int di = 0; di < sr_count; di++) {- char top[CBM_SZ_128] = "";- const char *slash = strchr(sr[di].file, '/');- if (slash) {- size_t dlen = (size_t)(slash - sr[di].file + SKIP_ONE);- if (dlen >= sizeof(top)) {- dlen = sizeof(top) - SKIP_ONE;- }- memcpy(top, sr[di].file, dlen);- top[dlen] = '\0';- } else {- snprintf(top, sizeof(top), "%s", sr[di].file);- }+ const char *file = sr[di].file ? sr[di].file : "";+ const char *slash = strchr(file, '/');+ size_t directory_length = slash ? (size_t)(slash - file + SKIP_ONE) : strlen(file);int found = CBM_NOT_FOUND;for (int d = 0; d < dir_n; d++) {- if (strcmp(dir_names[d], top) == 0) {+ if (strlen(directories[d].name) == directory_length &&+ memcmp(directories[d].name, file, directory_length) == 0) {found = d;break;}}if (found >= 0) {- dir_counts[found]++;- } else if (dir_n < max_dirs) {- snprintf(dir_names[dir_n], CBM_SZ_128, "%s", top);- dir_counts[dir_n] = SKIP_ONE;+ directories[found].count++;+ } else {+ directories[dir_n].name = cbm_strndup(file, directory_length);+ if (!directories[dir_n].name) {+ free_search_dirs(directories, dir_n);+ return false;+ }+ directories[dir_n].count = SKIP_ONE;dir_n++;}}- return dir_n;+ *directories_out = directories;+ *count_out = dir_n;+ return true;+}++static int count_truncated_raw_content(const grep_match_t *raw, int raw_count) {+ int count = 0;+ for (int i = 0; i < raw_count; i++) {+ if (raw[i].content_truncated) {+ count++;+ }+ }+ return count;}-static yyjson_mut_val *build_dir_distribution(yyjson_mut_doc *doc, search_result_t *sr,- int sr_count) {- yyjson_mut_val *dirs = yyjson_mut_obj(doc);- char dir_names[CBM_SZ_64][CBM_SZ_128];- int dir_counts[CBM_SZ_64];- int dir_n = aggregate_search_dirs(sr, sr_count, dir_names, dir_counts, CBM_SZ_64);- for (int d = 0; d < dir_n; d++) {- yyjson_mut_val *key = yyjson_mut_strcpy(doc, dir_names[d]);- yyjson_mut_val *val = yyjson_mut_int(doc, dir_counts[d]);- yyjson_mut_obj_add(dirs, key, val);+static int search_match_lines_shown(const search_result_t *result, int match_limit) {+ return result->match_count < match_limit ? result->match_count : match_limit;+}++static char *search_match_lines_text(const search_result_t *result, int match_limit) {+ int shown = search_match_lines_shown(result, match_limit);+ size_t capacity = (size_t)shown * 16U + 1U;+ char *text = malloc(capacity);+ if (!text) {+ return NULL;+ }+ size_t used = 0;+ text[0] = '\0';+ for (int i = 0; i < shown; i++) {+ int written = snprintf(text + used, capacity - used, "%s%d", i > 0 ? ";" : "",+ result->match_lines[i]);+ if (written < 0 || (size_t)written >= capacity - used) {+ free(text);+ return NULL;+ }+ used += (size_t)written;}- return dirs;+ return text;}/* TOON emission for compact-mode search results: one row per hit@@ -10125,77 +12042,164 @@ static yyjson_mut_val *build_dir_distribution(yyjson_mut_doc *doc, search_result* qn's last segment), a raw[] table for uncorrelated matches, a dirs[]* 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 gm_count, int limit,- bool warn_literal_pipe, const search_metrics_t *metrics) {- enum { MAX_RAW = 20, SEARCH_SLOW_MS = 5000 };+ int raw_count, int gm_count, int output_count,+ int raw_output, int directory_output, 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);- int output_count = sr_count < limit ? sr_count : limit;- static const char *const cols[] = {"qn", "label", "file", "lines", "matches", "in", "out"};- cbm_tree_table_header(&sb, "results", output_count, cols, 7);+ static const char *const cols[] = {"qn", "label", "file", "lines",+ "matches", "matches_omitted", "in", "out"};+ typedef struct {+ char lines[CBM_SZ_32];+ char *matches;+ char matches_omitted[CBM_SZ_32];+ char inbound[CBM_SZ_32];+ char outbound[CBM_SZ_32];+ } search_tree_row_t;+ search_tree_row_t *rendered =+ output_count > 0 ? calloc((size_t)output_count, sizeof(*rendered)) : NULL;+ const char **cells =+ output_count > 0 ? calloc((size_t)output_count * 8U, sizeof(*cells)) : NULL;+ if (output_count > 0 && (!rendered || !cells)) {+ free(cells);+ free(rendered);+ cbm_sb_free(&sb);+ return NULL;+ }for (int ri = 0; ri < output_count; ri++) {search_result_t *r = &sr[ri];- char lines[CBM_SZ_32];if (r->start_line > 0) {- snprintf(lines, sizeof(lines), "%d-%d", r->start_line,+ snprintf(rendered[ri].lines, sizeof(rendered[ri].lines), "%d-%d", r->start_line,r->end_line > r->start_line ? r->end_line : r->start_line);- } else {- lines[0] = '\0';- }- /* match line numbers ';'-joined (no comma → no cell quoting) */- char matches[CBM_SZ_256];- size_t mpos = 0;- matches[0] = '\0';- for (int j = 0; j < r->match_count && mpos + 12 < sizeof(matches); j++) {- int n = snprintf(matches + mpos, sizeof(matches) - mpos, "%s%d", j > 0 ? ";" : "",- r->match_lines[j]);- if (n < 0) {- break;+ }+ rendered[ri].matches = search_match_lines_text(r, match_limit);+ if (!rendered[ri].matches) {+ for (int j = 0; j < ri; j++) {+ free(rendered[j].matches);}- mpos += (size_t)n;+ free(cells);+ free(rendered);+ cbm_sb_free(&sb);+ return NULL;}- cbm_tree_row_begin(&sb);- cbm_tree_cell_str(&sb, r->qualified_name, true);- cbm_tree_cell_str(&sb, r->label, false);- cbm_tree_cell_str(&sb, r->file, false);- cbm_tree_cell_str(&sb, lines, false);- cbm_tree_cell_str(&sb, matches, false);- cbm_tree_cell_int(&sb, r->in_degree, false);- cbm_tree_cell_int(&sb, r->out_degree, false);- cbm_tree_row_end(&sb);+ snprintf(rendered[ri].matches_omitted, sizeof(rendered[ri].matches_omitted), "%d",+ r->match_count - search_match_lines_shown(r, match_limit));+ snprintf(rendered[ri].inbound, sizeof(rendered[ri].inbound), "%d", r->in_degree);+ snprintf(rendered[ri].outbound, sizeof(rendered[ri].outbound), "%d", r->out_degree);+ size_t base = (size_t)ri * 8U;+ cells[base] = r->qualified_name;+ cells[base + 1] = r->label;+ cells[base + 2] = r->file;+ cells[base + 3] = rendered[ri].lines;+ cells[base + 4] = rendered[ri].matches;+ cells[base + 5] = rendered[ri].matches_omitted;+ cells[base + 6] = rendered[ri].inbound;+ cells[base + 7] = rendered[ri].outbound;+ }+ if (output_count > 0 && rendered && cells) {+ static const bool string_cols[] = {true, true, true, true, true, false, false, false};+ static const bool prefix_cols[] = {true, false, true, false, false, false, false, false};+ cbm_tree_table_rows_profiled(&sb, "results", output_count, cols, 8, cells, string_cols,+ prefix_cols);+ } else {+ cbm_tree_table_header(&sb, "results", 0, cols, 8);+ }+ for (int ri = 0; ri < output_count; ri++) {+ free(rendered[ri].matches);}+ free(cells);+ free(rendered);- int raw_output = raw_count < MAX_RAW ? raw_count : MAX_RAW;if (raw_output > 0) {static const char *const rcols[] = {"file", "line", "content"};- cbm_tree_table_header(&sb, "raw", raw_output, rcols, 3);+ const char **raw_cells = calloc((size_t)raw_output * 3U, sizeof(*raw_cells));+ char (*line_text)[CBM_SZ_32] = calloc((size_t)raw_output, sizeof(*line_text));+ if (!raw_cells || !line_text) {+ free(line_text);+ free(raw_cells);+ cbm_sb_free(&sb);+ return NULL;+ }for (int ri = 0; ri < raw_output; ri++) {- cbm_tree_row_begin(&sb);- cbm_tree_cell_str(&sb, raw[ri].file, true);- cbm_tree_cell_int(&sb, raw[ri].line, false);- cbm_tree_cell_str(&sb, raw[ri].content, false);- cbm_tree_row_end(&sb);+ snprintf(line_text[ri], sizeof(line_text[ri]), "%d", raw[ri].line);+ raw_cells[(size_t)ri * 3U] = raw[ri].file;+ raw_cells[(size_t)ri * 3U + 1U] = line_text[ri];+ raw_cells[(size_t)ri * 3U + 2U] = raw[ri].content;}+ static const bool raw_string_cols[] = {true, false, true};+ static const bool raw_prefix_cols[] = {true, false, false};+ cbm_tree_table_rows_profiled(&sb, "raw", raw_output, rcols, 3, raw_cells, raw_string_cols,+ raw_prefix_cols);+ free(line_text);+ free(raw_cells);}- char dir_names[CBM_SZ_64][CBM_SZ_128];- int dir_counts[CBM_SZ_64];- int dir_n = aggregate_search_dirs(sr, sr_count, dir_names, dir_counts, CBM_SZ_64);- if (dir_n > 0) {+ search_dir_count_t *directories = NULL;+ int dir_n = 0;+ if (!aggregate_search_dirs(sr, sr_count, &directories, &dir_n)) {+ cbm_sb_free(&sb);+ return NULL;+ }+ if (directory_output > dir_n) {+ directory_output = dir_n;+ }+ if (directory_output > 0) {static const char *const dcols[] = {"dir", "hits"};- cbm_tree_table_header(&sb, "dirs", dir_n, dcols, 2);- for (int d = 0; d < dir_n; d++) {- cbm_tree_row_begin(&sb);- cbm_tree_cell_str(&sb, dir_names[d], true);- cbm_tree_cell_int(&sb, dir_counts[d], false);- cbm_tree_row_end(&sb);+ const char **dir_cells = calloc((size_t)directory_output * 2U, sizeof(*dir_cells));+ char (*count_text)[CBM_SZ_32] = calloc((size_t)directory_output, sizeof(*count_text));+ if (!dir_cells || !count_text) {+ free(count_text);+ free(dir_cells);+ free_search_dirs(directories, dir_n);+ cbm_sb_free(&sb);+ return NULL;+ }+ for (int d = 0; d < directory_output; d++) {+ snprintf(count_text[d], sizeof(count_text[d]), "%d", directories[d].count);+ dir_cells[(size_t)d * 2U] = directories[d].name;+ dir_cells[(size_t)d * 2U + 1U] = count_text[d];}+ static const bool dir_string_cols[] = {true, false};+ static const bool dir_prefix_cols[] = {true, false};+ cbm_tree_table_rows_profiled(&sb, "directories", directory_output, dcols, 2, dir_cells,+ dir_string_cols, dir_prefix_cols);+ free(count_text);+ free(dir_cells);}+ free_search_dirs(directories, dir_n);cbm_tree_scalar_int(&sb, "total_grep_matches", gm_count);cbm_tree_scalar_int(&sb, "total_results", sr_count);cbm_tree_scalar_int(&sb, "raw_match_count", raw_count);+ cbm_tree_scalar_str(&sb, "total_relation", scan_saturated ? "gte" : "eq");+ cbm_tree_scalar_int(&sb, "results_returned", output_count);+ bool has_more = output_count < sr_count;+ cbm_tree_scalar_bool(&sb, "has_more", has_more);+ cbm_tree_scalar_int(&sb, "raw_returned", raw_output);+ cbm_tree_scalar_bool(&sb, "raw_has_more", raw_output < raw_count);+ int truncated_raw_content = count_truncated_raw_content(raw, raw_count);+ if (truncated_raw_content > 0) {+ cbm_tree_scalar_int(&sb, "raw_content_truncated", truncated_raw_content);+ }+ cbm_tree_scalar_int(&sb, "directories_total", dir_n);+ cbm_tree_scalar_int(&sb, "directories_returned", directory_output);+ cbm_tree_scalar_bool(&sb, "directories_has_more", directory_output < dir_n);+ if (scan_saturated) {+ cbm_tree_scalar_bool(&sb, "scan_saturated", true);+ }+ cbm_tree_scalar_bool(&sb, "truncated",+ has_more || raw_output < raw_count || directory_output < dir_n ||+ scan_saturated || budget_hit);+ if (budget_hit) {+ cbm_tree_scalar_str(&sb, "truncation_reason", "output_budget");+ }+ if (source_lines_returned >= 0) {+ cbm_tree_scalar_int(&sb, "source_max_lines_returned", source_lines_returned);+ }if (metrics->include_phase_timings) {cbm_tree_scalar_int(&sb, "scope_ms", (long long)metrics->scope_ms);cbm_tree_scalar_int(&sb, "scan_ms", (long long)metrics->scan_ms);@@ -10218,28 +12222,32 @@ 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 gm_count, int limit, int mode,- int context_lines, const char *root_path,- bool warn_literal_pipe, const search_metrics_t *metrics) {+ int raw_count, int gm_count, int output_count, int raw_output,+ int directory_output, 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);yyjson_mut_val *root_obj = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root_obj);- int output_count = sr_count < limit ? sr_count : limit;-if (mode == MODE_FILES) {- yyjson_mut_obj_add_val(doc, root_obj, "files",- build_dedup_files_array(doc, sr, output_count, raw, raw_count));+ yyjson_mut_val *files = build_dedup_files_array(doc, sr, output_count, raw, raw_output);+ if (!files) {+ yyjson_mut_doc_free(doc);+ return NULL;+ }+ yyjson_mut_obj_add_val(doc, root_obj, "files", files);} else {/* json-stringified tree: cols + column-ordered row arrays. FULL mode* appends a per-row object cell with the (guarded, windowed) source;* context requests append the corresponding context object. */bool attach_context = context_lines > 0 && mode != MODE_FULL;yyjson_mut_val *jcols = yyjson_mut_arr(doc);- static const char *const sc_cols[] = {"qn", "label", "file", "lines",- "matches", "in", "out"};+ static const char *const sc_cols[] = {"qn", "label", "file", "lines",+ "matches", "matches_omitted", "in", "out"};for (size_t ci = 0; ci < sizeof(sc_cols) / sizeof(sc_cols[0]); ci++) {yyjson_mut_arr_add_str(doc, jcols, sc_cols[ci]);}@@ -10264,22 +12272,23 @@ static char *assemble_search_output(search_result_t *sr, int sr_count, grep_matcyyjson_mut_arr_add_strcpy(doc, row, r->file);yyjson_mut_arr_add_strcpy(doc, row, lines);yyjson_mut_val *ml = yyjson_mut_arr(doc);- for (int j = 0; j < r->match_count; j++) {+ int matches_shown = search_match_lines_shown(r, match_limit);+ for (int j = 0; j < matches_shown; j++) {yyjson_mut_arr_add_int(doc, ml, r->match_lines[j]);}yyjson_mut_arr_add_val(row, ml);+ yyjson_mut_arr_add_int(doc, row, r->match_count - matches_shown);yyjson_mut_arr_add_int(doc, row, r->in_degree);yyjson_mut_arr_add_int(doc, row, r->out_degree);if (mode == MODE_FULL || attach_context) {yyjson_mut_val *src = yyjson_mut_obj(doc);- attach_result_source(doc, src, r, mode, context_lines, root_path);+ attach_result_source(doc, src, r, mode, context_lines, source_max_lines, root_path);yyjson_mut_arr_add_val(row, src);}yyjson_mut_arr_add_val(results_arr, row);}yyjson_mut_obj_add_val(doc, root_obj, "rows", results_arr);- enum { MAX_RAW = 20 };yyjson_mut_val *raw_obj = yyjson_mut_obj(doc);yyjson_mut_val *rcols = yyjson_mut_arr(doc);yyjson_mut_arr_add_str(doc, rcols, "file");@@ -10287,7 +12296,6 @@ static char *assemble_search_output(search_result_t *sr, int sr_count, grep_matcyyjson_mut_arr_add_str(doc, rcols, "content");yyjson_mut_obj_add_val(doc, raw_obj, "cols", rcols);yyjson_mut_val *raw_arr = yyjson_mut_arr(doc);- int raw_output = raw_count < MAX_RAW ? raw_count : MAX_RAW;for (int ri = 0; ri < raw_output; ri++) {yyjson_mut_val *row = yyjson_mut_arr(doc);yyjson_mut_arr_add_str(doc, row, raw[ri].file);@@ -10299,12 +12307,53 @@ static char *assemble_search_output(search_result_t *sr, int sr_count, grep_matcyyjson_mut_obj_add_val(doc, root_obj, "raw_matches", raw_obj);}- yyjson_mut_obj_add_val(doc, root_obj, "directories", build_dir_distribution(doc, sr, sr_count));+ search_dir_count_t *directories = NULL;+ int dir_total = 0;+ if (!aggregate_search_dirs(sr, sr_count, &directories, &dir_total)) {+ yyjson_mut_doc_free(doc);+ return NULL;+ }+ if (directory_output > dir_total) {+ directory_output = dir_total;+ }+ yyjson_mut_val *directory_object = yyjson_mut_obj(doc);+ for (int d = 0; d < directory_output; d++) {+ yyjson_mut_val *key = yyjson_mut_strcpy(doc, directories[d].name);+ yyjson_mut_val *value = yyjson_mut_int(doc, directories[d].count);+ yyjson_mut_obj_add(directory_object, key, value);+ }+ yyjson_mut_obj_add_val(doc, root_obj, "directories", directory_object);+ free_search_dirs(directories, dir_total);/* Summary stats */yyjson_mut_obj_add_int(doc, root_obj, "total_grep_matches", gm_count);yyjson_mut_obj_add_int(doc, root_obj, "total_results", sr_count);yyjson_mut_obj_add_int(doc, root_obj, "raw_match_count", raw_count);+ yyjson_mut_obj_add_str(doc, root_obj, "total_relation", scan_saturated ? "gte" : "eq");+ yyjson_mut_obj_add_int(doc, root_obj, "results_returned", output_count);+ bool has_more = output_count < sr_count;+ yyjson_mut_obj_add_bool(doc, root_obj, "has_more", has_more);+ yyjson_mut_obj_add_int(doc, root_obj, "raw_returned", raw_output);+ yyjson_mut_obj_add_bool(doc, root_obj, "raw_has_more", raw_output < raw_count);+ int truncated_raw_content = count_truncated_raw_content(raw, raw_count);+ if (truncated_raw_content > 0) {+ yyjson_mut_obj_add_int(doc, root_obj, "raw_content_truncated", truncated_raw_content);+ }+ yyjson_mut_obj_add_int(doc, root_obj, "directories_total", dir_total);+ yyjson_mut_obj_add_int(doc, root_obj, "directories_returned", directory_output);+ yyjson_mut_obj_add_bool(doc, root_obj, "directories_has_more", directory_output < dir_total);+ if (scan_saturated) {+ yyjson_mut_obj_add_bool(doc, root_obj, "scan_saturated", true);+ }+ yyjson_mut_obj_add_bool(doc, root_obj, "truncated",+ has_more || raw_output < raw_count || directory_output < dir_total ||+ scan_saturated || budget_hit);+ if (budget_hit) {+ yyjson_mut_obj_add_str(doc, root_obj, "truncation_reason", "output_budget");+ }+ if (mode == MODE_FULL) {+ yyjson_mut_obj_add_int(doc, root_obj, "source_max_lines_returned", source_max_lines);+ }if (metrics->include_phase_timings) {yyjson_mut_obj_add_uint(doc, root_obj, "scope_ms", metrics->scope_ms);yyjson_mut_obj_add_uint(doc, root_obj, "scan_ms", metrics->scan_ms);@@ -10336,23 +12385,129 @@ static char *assemble_search_output(search_result_t *sr, int sr_count, grep_matcsnprintf(ems, sizeof(ems), "%d", (int)metrics->elapsed_ms);cbm_log_warn("search.slow", "elapsed_ms", ems); /* visibility in logs */}- if (yyjson_mut_arr_size(warnings) > 0) {- yyjson_mut_obj_add_val(doc, root_obj, "warnings", warnings);+ if (yyjson_mut_arr_size(warnings) > 0) {+ yyjson_mut_obj_add_val(doc, root_obj, "warnings", warnings);+ }++ char *json = yy_doc_to_str(doc);+ if (json) {+ sanitize_utf8_inplace(json);+ }+ yyjson_mut_doc_free(doc);++ return json;+}++/* Render the same search response model in either direct JSON or the lean tree+ * form. Compact search has a purpose-built table renderer so repeated paths+ * and qualified-name prefixes can use the response-local directory. Full and+ * files mode first build the canonical JSON model, then project it to tree. */+static char *render_search_payload(search_result_t *sr, int sr_count, grep_match_t *raw,+ int raw_count, int gm_count, int output_count, int raw_output,+ int directory_output, 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, gm_count, output_count, raw_output, directory_output,+ match_limit, scan_saturated, warn_literal_pipe, metrics, budget_hit, -1);+ }++ char *json = assemble_search_output(sr, sr_count, raw, raw_count, gm_count, output_count,+ raw_output, directory_output, match_limit, mode,+ context_lines, source_max_lines, root_path, scan_saturated,+ warn_literal_pipe, metrics, budget_hit);+ if (!json || json_format) {+ return json;+ }+ char *tree = cbm_json_to_tree(json);+ free(json);+ return tree;+}++#ifdef CBM_ENABLE_TEST_SEAMS+char *cbm_mcp_render_search_rows_for_testing(const char *const *qualified_names,+ const char *const *file_paths, int row_count,+ bool json_format) {+ if (!qualified_names || !file_paths || row_count < 0) {+ return NULL;+ }+ search_result_t *results = row_count > 0 ? calloc((size_t)row_count, sizeof(*results)) : NULL;+ if (row_count > 0 && !results) {+ return NULL;+ }+ int initialized = 0;+ for (int i = 0; i < row_count; i++) {+ cbm_node_t node = {.id = i + SKIP_ONE,+ .label = "Function",+ .name = "synthetic",+ .qualified_name = qualified_names[i],+ .file_path = file_paths[i],+ .start_line = SKIP_ONE,+ .end_line = SKIP_ONE};+ if (!set_search_result_identity(&results[i], &node)) {+ free_search_results(results, initialized);+ return NULL;+ }+ if (!append_search_match_line(&results[i], SKIP_ONE)) {+ free_search_results(results, initialized + 1);+ return NULL;+ }+ initialized++;+ }+ static const search_metrics_t zero_metrics = {0};+ char *payload = render_search_payload(results, row_count, NULL, 0, row_count, row_count, 0,+ row_count, row_count > 0 ? 1 : 0, 0, 0, 0, "", false,+ false, &zero_metrics, false, json_format);+ free_search_results(results, initialized);+ return payload;+}+#endif++/* A pathological single qualified name, path, or source line can be larger+ * than the caller's entire budget. Never byte-slice it: return a small,+ * truthful floor that tells the caller how to request the omitted rows. */+static char *search_budget_floor(int sr_count, int raw_count, int gm_count, bool scan_saturated,+ bool json_format, int max_output_tokens) {+ if (!json_format) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ static const char *const cols[] = {"qn", "label", "file", "lines",+ "matches", "matches_omitted", "in", "out"};+ cbm_tree_table_header(&sb, "results", 0, cols, 8);+ cbm_tree_scalar_int(&sb, "total_grep_matches", gm_count);+ cbm_tree_scalar_int(&sb, "total_results", sr_count);+ cbm_tree_scalar_int(&sb, "raw_match_count", raw_count);+ cbm_tree_scalar_str(&sb, "total_relation", scan_saturated ? "gte" : "eq");+ cbm_tree_scalar_int(&sb, "results_returned", 0);+ cbm_tree_scalar_bool(&sb, "has_more", sr_count > 0);+ cbm_tree_scalar_bool(&sb, "truncated", true);+ cbm_tree_scalar_str(&sb, "truncation_reason", "output_budget");+ cbm_tree_scalar_int(&sb, "max_output_tokens", max_output_tokens);+ cbm_tree_scalar_str(&sb, "continuation",+ "raise max_output_tokens; no partial row was emitted");+ return cbm_sb_finish(&sb);}+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_obj_add_int(doc, root, "total_grep_matches", gm_count);+ yyjson_mut_obj_add_int(doc, root, "total_results", sr_count);+ yyjson_mut_obj_add_int(doc, root, "raw_match_count", raw_count);+ yyjson_mut_obj_add_str(doc, root, "total_relation", scan_saturated ? "gte" : "eq");+ yyjson_mut_obj_add_int(doc, root, "results_returned", 0);+ yyjson_mut_obj_add_bool(doc, root, "has_more", sr_count > 0);+ yyjson_mut_obj_add_bool(doc, root, "truncated", true);+ yyjson_mut_obj_add_str(doc, root, "truncation_reason", "output_budget");+ yyjson_mut_obj_add_int(doc, root, "max_output_tokens", max_output_tokens);+ yyjson_mut_obj_add_str(doc, root, "continuation",+ "raise max_output_tokens; no partial row was emitted");char *json = yy_doc_to_str(doc);- if (json) {- char *safe_json = sanitize_utf8_lossy(json);- if (safe_json) {- free(json);- json = safe_json;- }- }yyjson_mut_doc_free(doc);-- char *result = cbm_mcp_text_result(json, false);- free(json);- return result;+ return json;}/* Read grep output from fp, parse file:line:content format, apply path filter,@@ -10369,16 +12524,45 @@ static const char *strip_root_prefix(const char *path, const char *root, size_treturn p;}+static int grep_match_cmp(const void *left, const void *right) {+ const grep_match_t *a = left;+ const grep_match_t *b = right;+ int file_order = strcmp(a->file, b->file);+ if (file_order != 0) {+ return file_order;+ }+ return (a->line > b->line) - (a->line < b->line);+}+static grep_match_t *collect_grep_matches(FILE *fp, const char *root_path, size_t root_len,bool has_path_filter, cbm_regex_t *path_regex,- int grep_limit, int *out_count) {+ int grep_limit, int *out_count, bool *out_saturated,+ bool *out_oom) {int gm_cap = CBM_SZ_64;int gm_count = 0;- grep_match_t *gm = malloc(gm_cap * sizeof(grep_match_t));- char line[CBM_SZ_2K];+ grep_match_t *gm = calloc((size_t)gm_cap, sizeof(*gm));+ char *line = NULL;+ size_t line_capacity = 0;- while (fgets(line, sizeof(line), fp) && gm_count < grep_limit) {- size_t len = strlen(line);+ if (out_saturated) {+ *out_saturated = false;+ }+ if (out_oom) {+ *out_oom = gm == NULL;+ }+ if (!gm) {+ *out_count = 0;+ return NULL;+ }+ for (;;) {+ ssize_t line_length = cbm_getline(&line, &line_capacity, fp);+ if (line_length < 0) {+ if (!feof(fp) && out_oom) {+ *out_oom = true;+ }+ break;+ }+ size_t len = (size_t)line_length;while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {line[--len] = '\0';}@@ -10414,16 +12598,53 @@ static grep_match_t *collect_grep_matches(FILE *fp, const char *root_path, size_continue;}- safe_grow(gm, gm_count, gm_cap, PAIR_LEN);- snprintf(gm[gm_count].file, sizeof(gm[0].file), "%s", file);+ if (gm_count >= grep_limit) {+ if (out_saturated) {+ *out_saturated = true;+ }+ break;+ }++ if (gm_count >= gm_cap) {+ int next_capacity = gm_cap * PAIR_LEN;+ grep_match_t *grown = realloc(gm, (size_t)next_capacity * sizeof(*gm));+ if (!grown) {+ if (out_oom) {+ *out_oom = true;+ }+ break;+ }+ memset(grown + gm_cap, 0, (size_t)(next_capacity - gm_cap) * sizeof(*grown));+ gm = grown;+ gm_cap = next_capacity;+ }+ gm[gm_count].file = heap_strdup(file);+ if (!gm[gm_count].file) {+ if (out_oom) {+ *out_oom = true;+ }+ break;+ }gm[gm_count].line = (int)strtol(sep1 + SKIP_ONE, NULL, CBM_DECIMAL_BASE);- char *safe_content = sanitize_utf8_lossy(sep2 + SKIP_ONE);- snprintf(gm[gm_count].content, sizeof(gm[0].content), "%s",- safe_content ? safe_content : sep2 + SKIP_ONE);- free(safe_content);+ const char *content = sep2 + SKIP_ONE;+ size_t content_length = strlen(content);+ gm[gm_count].content_truncated = content_length >= sizeof(gm[gm_count].content);+ size_t content_copy = content_length;+ if (content_copy >= sizeof(gm[gm_count].content)) {+ content_copy = sizeof(gm[gm_count].content) - SKIP_ONE;+ }+ memcpy(gm[gm_count].content, content, content_copy);+ gm[gm_count].content[content_copy] = '\0';+ sanitize_utf8_inplace(gm[gm_count].content);gm_count++;}+ free(line);+ if (out_oom && *out_oom) {+ free_grep_matches(gm, gm_count);+ *out_count = 0;+ return NULL;+ }*out_count = gm_count;return gm;}@@ -10444,52 +12665,97 @@ static int find_tightest_node(cbm_node_t *nodes, int count, int line) {return best;}+static bool set_search_result_identity(search_result_t *result, const cbm_node_t *node) {+ result->qualified_name = heap_strdup(node->qualified_name ? node->qualified_name : "");+ result->file = heap_strdup(node->file_path ? node->file_path : "");+ if (!result->qualified_name || !result->file) {+ free(result->qualified_name);+ free(result->file);+ result->qualified_name = NULL;+ result->file = NULL;+ return false;+ }+ result->node_id = node->id;+ snprintf(result->node_name, sizeof(result->node_name), "%s", node->name ? node->name : "");+ snprintf(result->label, sizeof(result->label), "%s", node->label ? node->label : "");+ result->start_line = node->start_line;+ result->end_line = node->end_line;+ return true;+}++static bool append_search_match_line(search_result_t *result, int line) {+ if (result->match_count >= result->match_capacity) {+ int next_capacity = result->match_capacity > 0 ? result->match_capacity * PAIR_LEN : 8;+ if (next_capacity < result->match_capacity ||+ (size_t)next_capacity > SIZE_MAX / sizeof(*result->match_lines)) {+ return false;+ }+ int *grown = realloc(result->match_lines, (size_t)next_capacity * sizeof(*grown));+ if (!grown) {+ return false;+ }+ result->match_lines = grown;+ result->match_capacity = next_capacity;+ }+ result->match_lines[result->match_count++] = line;+ return true;+}+/* Add a grep hit to the search result set (merge into existing or create new). */-static void add_to_search_results(search_result_t **sr, int *sr_count, int *sr_cap, cbm_node_t *n,+static bool add_to_search_results(search_result_t **sr, int *sr_count, int *sr_cap, cbm_node_t *n,int line) {for (int j = 0; j < *sr_count; j++) {if ((*sr)[j].node_id == n->id) {- if ((*sr)[j].match_count < CBM_SZ_64) {- (*sr)[j].match_lines[(*sr)[j].match_count++] = line;- }- return;+ return append_search_match_line(&(*sr)[j], line);}}if (*sr_count >= *sr_cap) {- *sr_cap *= PAIR_LEN;- *sr = safe_realloc(*sr, *sr_cap * sizeof(search_result_t));- memset(&(*sr)[*sr_count], 0, (*sr_cap - *sr_count) * sizeof(search_result_t));+ int next_capacity = *sr_cap * PAIR_LEN;+ search_result_t *grown = realloc(*sr, (size_t)next_capacity * sizeof(**sr));+ if (!grown) {+ return false;+ }+ memset(grown + *sr_cap, 0, (size_t)(next_capacity - *sr_cap) * sizeof(*grown));+ *sr = grown;+ *sr_cap = next_capacity;}search_result_t *r = &(*sr)[*sr_count];- r->node_id = n->id;- snprintf(r->node_name, sizeof(r->node_name), "%s", n->name ? n->name : "");- snprintf(r->qualified_name, sizeof(r->qualified_name), "%s",- n->qualified_name ? n->qualified_name : "");- snprintf(r->label, sizeof(r->label), "%s", n->label ? n->label : "");- snprintf(r->file, sizeof(r->file), "%s", n->file_path ? n->file_path : "");- r->start_line = n->start_line;- r->end_line = n->end_line;- r->match_lines[0] = line;- r->match_count = SKIP_ONE;+ if (!set_search_result_identity(r, n)) {+ return false;+ }+ if (!append_search_match_line(r, line)) {+ free(r->qualified_name);+ free(r->file);+ r->qualified_name = NULL;+ r->file = NULL;+ return false;+ }(*sr_count)++;+ return true;}/* Match a single grep hit to the tightest containing node, then add to sr or raw. */-static void classify_grep_hit(grep_match_t *hit, cbm_node_t *file_nodes, int file_node_count,+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_count, int *raw_cap) {int best = find_tightest_node(file_nodes, file_node_count, hit->line);if (best >= 0) {- add_to_search_results(sr, sr_count, sr_cap, &file_nodes[best], hit->line);+ return add_to_search_results(sr, sr_count, sr_cap, &file_nodes[best], hit->line);} else {if (*raw_count >= *raw_cap) {- *raw_cap = (*raw_cap == 0) ? CBM_SZ_32 : *raw_cap * PAIR_LEN;- *raw = safe_realloc(*raw, *raw_cap * sizeof(grep_match_t));- }- if (*raw) {- (*raw)[(*raw_count)++] = *hit;+ int next_capacity = (*raw_cap == 0) ? CBM_SZ_32 : *raw_cap * PAIR_LEN;+ grep_match_t *grown = realloc(*raw, (size_t)next_capacity * sizeof(**raw));+ if (!grown) {+ return false;+ }+ *raw = grown;+ *raw_cap = next_capacity;}+ (*raw)[*raw_count] = *hit;+ hit->file = NULL;+ (*raw_count)++;}+ return true;}/* Free a file_nodes array returned from cbm_store_find_nodes_by_file. */@@ -10506,10 +12772,12 @@ static void free_file_nodes(cbm_node_t *nodes, int count) {}/* Classify all grep matches file-by-file into search results and raw hits. */-static void classify_all_grep_hits(grep_match_t *gm, int gm_count, cbm_store_t *store,+static bool classify_all_grep_hits(grep_match_t *gm, int gm_count, cbm_store_t *store,const char *project, search_result_t **sr, int *sr_count,int *sr_cap, grep_match_t **raw, int *raw_count, int *raw_cap) {- qsort(gm, gm_count, sizeof(grep_match_t), (int (*)(const void *, const void *))strcmp);+ if (gm_count > SKIP_ONE) {+ qsort(gm, (size_t)gm_count, sizeof(*gm), grep_match_cmp);+ }int i = 0;while (i < gm_count) {const char *cur_file = gm[i].file;@@ -10523,11 +12791,15 @@ static void classify_all_grep_hits(grep_match_t *gm, int gm_count, cbm_store_t *cbm_store_find_nodes_by_file(store, project, cur_file, &file_nodes, &file_node_count);}for (int mi = file_start; mi < i; mi++) {- classify_grep_hit(&gm[mi], file_nodes, file_node_count, sr, sr_count, sr_cap, raw,- raw_count, raw_cap);+ if (!classify_grep_hit(&gm[mi], file_nodes, file_node_count, sr, sr_count, sr_cap, raw,+ raw_count, raw_cap)) {+ free_file_nodes(file_nodes, file_node_count);+ return false;+ }}free_file_nodes(file_nodes, file_node_count);}+ return true;}/* Write indexed file list for scoped grep. Returns true if scoped.@@ -10554,13 +12826,19 @@ static bool write_scoped_filelist(cbm_mcp_server_t *srv, const char *project, cochar **indexed_files = NULL;int indexed_count = 0;int list_rc = cbm_store_list_files(pre_store, project, &indexed_files, &indexed_count);- if (list_rc != CBM_STORE_OK || indexed_count == 0) {+ if (list_rc != CBM_STORE_OK) {for (int fi = 0; fi < indexed_count; fi++) {free(indexed_files[fi]);}free(indexed_files);return false;}+ if (indexed_count == 0) {+ /* cbm_store_list_files owns an allocation even for an empty successful+ * result; no element loop below can release that outer array. */+ free(indexed_files);+ return false;+ }bool ok = false;int written = 0;if (fl) {@@ -10923,6 +13201,47 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {int mode = parse_search_mode(mode_str);free(mode_str);+ if (limit < 1) {+ limit = 1;+ } else if (limit > 500) {+ limit = 500;+ }+ int raw_limit = cbm_mcp_get_int_arg(args, "raw_limit", 5);+ if (raw_limit < 0) {+ raw_limit = 0;+ } else if (raw_limit > 100) {+ raw_limit = 100;+ }+ int directory_limit = cbm_mcp_get_int_arg(args, "directory_limit", 20);+ if (directory_limit < 0) {+ directory_limit = 0;+ } else if (directory_limit > 64) {+ directory_limit = 64;+ }+ int match_limit = cbm_mcp_get_int_arg(args, "match_limit", 8);+ if (match_limit < 1) {+ match_limit = 1;+ } else if (match_limit > 500) {+ match_limit = 500;+ }+ int source_max_lines = cbm_mcp_get_int_arg(args, "source_max_lines", 20);+ if (source_max_lines < 1) {+ source_max_lines = 1;+ } else if (source_max_lines > 200) {+ source_max_lines = 200;+ }+ /* Full source is an explicit detail request and gets a larger default;+ * compact/files stay lean. Every mode still has an exact serialized-byte+ * ceiling, and callers can raise it deliberately. */+ int max_output_tokens =+ cbm_mcp_get_int_arg(args, "max_output_tokens", mode == 1 ? 12000 : 3200);+ if (max_output_tokens < 128) {+ max_output_tokens = 128;+ } else if (max_output_tokens > 1000000) {+ max_output_tokens = 1000000;+ }+ size_t byte_budget = (size_t)max_output_tokens * (size_t)MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE;+cbm_regex_t path_regex;bool has_path_filter = compile_path_filter(path_filter, &path_regex);free(path_filter);@@ -11088,6 +13407,8 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {/* Collect grep matches into array */int gm_count = 0;+ bool scan_saturated = false;+ bool grep_oom = false;grep_match_t *gm = NULL;uint64_t scan_t0 = metrics.include_phase_timings ? cbm_now_ms() : 0;if (scoped && scoped_written == 0 && !scan_cancellation_latched && !scan_deadline_latched) {@@ -11095,7 +13416,8 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {* Skip the grep subprocess: xargs on an empty filelist is* platform-dependent (GNU execs grep once with no operands, BSD* skips), and the post-grep filter would drop every hit anyway. */- gm = malloc(sizeof(grep_match_t)); /* empty set; freed below */+ gm = calloc(1U, sizeof(*gm)); /* empty set; freed below */+ grep_oom = gm == NULL;search_scratch_close(&scratch);} else {char cmd[CBM_SZ_4K];@@ -11150,7 +13472,7 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {"search failed: contained output could not be read");}gm = collect_grep_matches(fp, root_path, strlen(root_path), has_path_filter, &path_regex,- grep_limit, &gm_count);+ grep_limit, &gm_count, &scan_saturated, &grep_oom);(void)fclose(fp);(void)cbm_unlink(output_path);/* Both scratch files and the private directory go here — unlike the old@@ -11161,6 +13483,18 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {metrics.scan_ms = cbm_now_ms() - scan_t0;}+ if (grep_oom) {+ free_grep_matches(gm, gm_count);+ free(root_path);+ free(pattern);+ free(project);+ free(file_pattern);+ if (has_path_filter) {+ cbm_regfree(&path_regex);+ }+ return cbm_mcp_text_result("out of memory", true);+ }+/* ── Phase 2+3: Block expansion + graph ranking ──────────── *//* Sort grep matches by file for contiguous processing.* Then: one SQL query per unique file for nodes, one batch query for all degrees. */@@ -11170,23 +13504,49 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {int sr_cap = CBM_SZ_32;int sr_count = 0;- search_result_t *sr = calloc(sr_cap, sizeof(search_result_t));+ search_result_t *sr = calloc((size_t)sr_cap, sizeof(*sr));int raw_cap = CBM_SZ_32;int raw_count = 0;- grep_match_t *raw = malloc(raw_cap * sizeof(grep_match_t));-- /* Sort matches by file path for contiguous per-file processing */- qsort(gm, gm_count, sizeof(grep_match_t), (int (*)(const void *, const void *))strcmp);-- classify_all_grep_hits(gm, gm_count, store, project, &sr, &sr_count, &sr_cap, &raw, &raw_count,- &raw_cap);+ grep_match_t *raw = calloc((size_t)raw_cap, sizeof(*raw));++ if (!sr || !raw ||+ !classify_all_grep_hits(gm, gm_count, store, project, &sr, &sr_count, &sr_cap, &raw,+ &raw_count, &raw_cap)) {+ free_grep_matches(gm, gm_count);+ free_search_results(sr, sr_count);+ free_grep_matches(raw, raw_count);+ free(root_path);+ free(pattern);+ free(project);+ free(file_pattern);+ if (has_path_filter) {+ cbm_regfree(&path_regex);+ }+ return cbm_mcp_text_result("out of memory", true);+ }/* Phase 3: batch degree query — ONE query for all results instead of 2×N */if (store && sr_count > 0) {int64_t *ids = malloc(sr_count * sizeof(int64_t));int *in_degs = malloc(sr_count * sizeof(int));int *out_degs = malloc(sr_count * sizeof(int));+ if (!ids || !in_degs || !out_degs) {+ free(ids);+ free(in_degs);+ free(out_degs);+ free_grep_matches(gm, gm_count);+ free_search_results(sr, sr_count);+ free_grep_matches(raw, raw_count);+ free(root_path);+ free(pattern);+ free(project);+ free(file_pattern);+ if (has_path_filter) {+ cbm_regfree(&path_regex);+ }+ return cbm_mcp_text_result("out of memory", true);+ }for (int j = 0; j < sr_count; j++) {ids[j] = sr[j].node_id;}@@ -11216,27 +13576,132 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {/* ── Phase 4: Context assembly (extracted helper) ─────────── */- /* compact mode (default) emits tree tables; format:"json" emits the- * same model as structured JSON ({cols, rows}; full adds a per-row- * source cell; files is a plain list). */+ /* Compact mode defaults to the lean tree. format:"json" preserves the+ * released machine shape ({cols, rows}; full adds a per-row source cell;+ * files is a plain list). */char *sc_format = cbm_mcp_get_string_arg(args, "format");bool sc_legacy_json = sc_format && strcmp(sc_format, "json") == 0;free(sc_format);- char *result = NULL;- if (mode == 0 && !sc_legacy_json) {- char *toon_text = assemble_search_output_toon(sr, sr_count, raw, raw_count, gm_count, limit,- pat_has_pipe && !use_regex, &metrics);- result = cbm_mcp_text_result(toon_text ? toon_text : "out of memory", toon_text == NULL);- free(toon_text);- } else {- result =- assemble_search_output(sr, sr_count, raw, raw_count, gm_count, limit, mode,- context_lines, root_path, pat_has_pipe && !use_regex, &metrics);+ int output_count = sr_count < limit ? sr_count : limit;+ int raw_output = raw_count < raw_limit ? raw_count : raw_limit;+ search_dir_count_t *directories = NULL;+ int dir_total = 0;+ if (!aggregate_search_dirs(sr, sr_count, &directories, &dir_total)) {+ free_grep_matches(gm, gm_count);+ free_search_results(sr, sr_count);+ free_grep_matches(raw, raw_count);+ free(root_path);+ free(pattern);+ free(project);+ free(file_pattern);+ if (has_path_filter) {+ cbm_regfree(&path_regex);+ }+ return cbm_mcp_text_result("out of memory", true);+ }+ free_search_dirs(directories, dir_total);+ int directory_output = dir_total < directory_limit ? dir_total : directory_limit;+ bool warn_literal_pipe = pat_has_pipe && !use_regex;+ char *payload = render_search_payload(+ sr, sr_count, raw, raw_count, gm_count, output_count, raw_output, directory_output,+ match_limit, mode, context_lines, source_max_lines, root_path, scan_saturated,+ warn_literal_pipe, &metrics, false, sc_legacy_json);++ if (payload && strlen(payload) > byte_budget) {+ free(payload);+ payload = render_search_payload(sr, sr_count, raw, raw_count, gm_count, output_count,+ raw_output, directory_output, match_limit, mode,+ context_lines, source_max_lines, root_path, scan_saturated,+ warn_literal_pipe, &metrics, true, sc_legacy_json);+ }++ /* Preserve ranked graph answers. Unclassified raw grep rows and directory+ * diagnostics yield first, at whole-row boundaries. */+ while (payload && strlen(payload) > byte_budget && raw_output > 0) {+ raw_output--;+ free(payload);+ payload = render_search_payload(sr, sr_count, raw, raw_count, gm_count, output_count,+ raw_output, directory_output, match_limit, mode,+ context_lines, source_max_lines, root_path, scan_saturated,+ warn_literal_pipe, &metrics, true, sc_legacy_json);+ }+ while (payload && strlen(payload) > byte_budget && directory_output > 0) {+ directory_output--;+ free(payload);+ payload = render_search_payload(sr, sr_count, raw, raw_count, gm_count, output_count,+ raw_output, directory_output, match_limit, mode,+ context_lines, source_max_lines, root_path, scan_saturated,+ warn_literal_pipe, &metrics, true, sc_legacy_json);+ }++ /* Full source is the next detail tier. Find the largest whole-line window+ * that fits while retaining every ranked result identity. */+ if (payload && strlen(payload) > byte_budget && mode == 1 && source_max_lines > 0) {+ int low = 0;+ int high = source_max_lines - 1;+ int best_lines = -1;+ char *best_payload = NULL;+ while (low <= high) {+ int middle = low + (high - low) / 2;+ char *candidate = render_search_payload(+ sr, sr_count, raw, raw_count, gm_count, output_count, raw_output, directory_output,+ match_limit, mode, context_lines, middle, root_path, scan_saturated,+ warn_literal_pipe, &metrics, true, sc_legacy_json);+ if (candidate && strlen(candidate) <= byte_budget) {+ free(best_payload);+ best_payload = candidate;+ best_lines = middle;+ low = middle + 1;+ } else {+ free(candidate);+ high = middle - 1;+ }+ }+ free(payload);+ if (best_payload) {+ payload = best_payload;+ source_max_lines = best_lines;+ } else {+ source_max_lines = 0;+ payload = render_search_payload(+ sr, sr_count, raw, raw_count, gm_count, output_count, raw_output, directory_output,+ match_limit, mode, context_lines, source_max_lines, root_path, scan_saturated,+ warn_literal_pipe, &metrics, true, sc_legacy_json);+ }+ }++ /* If identities themselves exceed the ceiling, find the largest fitting+ * row prefix. Check every smaller prefix in descending order: response-local+ * prefix factoring can activate at a threshold, so encoded size is not+ * guaranteed to be monotonic in the row count. */+ if (payload && strlen(payload) > byte_budget && output_count > 0) {+ char *best_payload = NULL;+ for (int candidate_rows = output_count - 1; candidate_rows >= 0; candidate_rows--) {+ char *candidate = render_search_payload(+ sr, sr_count, raw, raw_count, gm_count, candidate_rows, raw_output,+ directory_output, match_limit, mode, context_lines, source_max_lines, root_path,+ scan_saturated, warn_literal_pipe, &metrics, true, sc_legacy_json);+ if (candidate && strlen(candidate) <= byte_budget) {+ best_payload = candidate;+ break;+ }+ free(candidate);+ }+ free(payload);+ payload = best_payload;+ }++ if (!payload || strlen(payload) > byte_budget) {+ free(payload);+ payload = search_budget_floor(sr_count, raw_count, gm_count, scan_saturated, sc_legacy_json,+ max_output_tokens);}- free(gm);- free(sr);- free(raw);+ char *result = cbm_mcp_text_result(payload ? payload : "out of memory", payload == NULL);+ free(payload);+ free_grep_matches(gm, gm_count);+ free_search_results(sr, sr_count);+ free_grep_matches(raw, raw_count);free(root_path);free(pattern);free(project);@@ -11570,23 +14035,17 @@ static void detect_collect_seeds(cbm_store_t *store, const char *project, const* ("src/mcp/mcp.c" -> "src/mcp"), a quotient of the blast radius coarse enough* to fit yet specific enough to localize (one segment collapses a whole tree* to "src"). Falls back to one segment, then the whole path. */-static void detect_module_of(const char *file, char *out, size_t outsz) {+static char *detect_module_of(const char *file) {if (!file || !file[0]) {- snprintf(out, outsz, "(root)");- return;+ return heap_strdup("(root)");}const char *s1 = strchr(file, '/');if (!s1) {- snprintf(out, outsz, "%s", file);- return;+ return heap_strdup(file);}const char *s2 = strchr(s1 + 1, '/');size_t len = s2 ? (size_t)(s2 - file) : strlen(file);- if (len >= outsz) {- len = outsz - 1;- }- memcpy(out, file, len);- out[len] = '\0';+ return cbm_strndup(file, len);}/* Aggregate the impact set into the 2-segment module rollup. Fills up to@@ -11595,80 +14054,140 @@ static void detect_module_of(const char *file, char *out, size_t outsz) {* tree and json emitters so both encodings carry the same model. */enum { DETECT_MODCAP = 256 };-static int detect_module_rollup(const cbm_traverse_result_t *impact, char mods[][CBM_SZ_128],- int *mcnt, int *overflow) {+typedef struct {+ char *name;+ int count;+} detect_module_row_t;++static int detect_module_rollup(const cbm_traverse_result_t *impact, detect_module_row_t *modules,+ int *overflow) {int nmods = 0;*overflow = 0;for (int i = 0; i < impact->visited_count; i++) {- char m[CBM_SZ_128];- detect_module_of(impact->visited[i].node.file_path, m, sizeof(m));+ char *module = detect_module_of(impact->visited[i].node.file_path);+ if (!module) {+ (*overflow)++;+ continue;+ }int j = 0;for (; j < nmods; j++) {- if (strcmp(mods[j], m) == 0) {- mcnt[j]++;+ if (strcmp(modules[j].name, module) == 0) {+ modules[j].count++;break;}}if (j == nmods) {if (nmods < DETECT_MODCAP) {- snprintf(mods[nmods], CBM_SZ_128, "%s", m);- mcnt[nmods] = 1;+ modules[nmods].name = module;+ modules[nmods].count = 1;nmods++;+ module = NULL;} else {(*overflow)++;}}+ free(module);}return nmods;}-/* Emit the impacted set as a grouped tree leg: rows grouped under their shared- * (qn-prefix, file), `name label hop` per row. At most `limit` rows are listed- * (the visited array is hop-ordered, so the closest — highest-signal — impact- * shows first); impacted_total always carries the exact full count, and- * `impacted_shown < impacted_total` is the honest truncation signal. The- * module rollup (emitted by the caller) stays complete regardless. */-static void detect_emit_impacted_tree(cbm_sb_t *sb, cbm_traverse_result_t *tr, int limit) {+static void detect_module_rollup_free(detect_module_row_t *modules, int count) {+ for (int i = 0; i < count; i++) {+ free(modules[i].name);+ }+ free(modules);+}++/* Emit one losslessly pageable window of the impacted set. The visited array+ * is hop-ordered, so page zero preserves the closest, highest-signal rows.+ * Engine saturation is reported as a lower-bound total, never as an exact+ * count. */+static void detect_emit_impacted_tree(cbm_sb_t *sb, const cbm_traverse_result_t *tr, int start,+ int count, bool engine_saturated) {cbm_tree_scalar_int(sb, "impacted_total", tr->visited_count);- int shown = tr->visited_count < limit ? tr->visited_count : limit;+ cbm_tree_scalar_str(sb, "impacted_total_relation", engine_saturated ? "gte" : "eq");+ int shown = count;/* qn order for stable grouping, but keep hop-closeness: sort by (hop) is* lost under qn sort, so group AFTER selecting the nearest `shown` rows —* the visited array is already (hop,id)-ordered from the BFS. */- char hdr[CBM_SZ_128];- snprintf(hdr, sizeof(hdr),- "impacted_shown: %d\nimpacted: %d (rows: name label hop; qn = group prefix + \".\" "- "+ name; nearest hops first)\n",- shown, shown);- cbm_sb_append(sb, hdr);- if (shown > 1) {- qsort(tr->visited, (size_t)shown, sizeof(cbm_node_hop_t), tree_hop_cmp_qn);- }- char cur_group[CBM_SZ_1K] = "";- for (int i = 0; i < shown; i++) {- const char *qn =- tr->visited[i].node.qualified_name ? tr->visited[i].node.qualified_name : "";- const char *file = tr->visited[i].node.file_path ? tr->visited[i].node.file_path : "";- size_t plen = sg_qn_prefix_len(qn);- char group[CBM_SZ_1K];- snprintf(group, sizeof(group), "%.*s (%s)", (int)plen, qn, file);- if (strcmp(group, cur_group) != 0) {- snprintf(cur_group, sizeof(cur_group), "%s", group);- cbm_sb_append(sb, group);- cbm_sb_append(sb, ":\n");+ cbm_tree_scalar_int(sb, "impacted_shown", shown);+ cbm_node_hop_t *selected = NULL;+ const cbm_node_hop_t *rows = tr->visited;+ if (shown > 0) {+ selected = malloc((size_t)shown * sizeof(*selected));+ if (selected) {+ memcpy(selected, tr->visited + start, (size_t)shown * sizeof(*selected));+ rows = selected;+ } else {+ rows = tr->visited + start;+ }+ }+ if (shown > 1 && selected) {+ qsort(selected, (size_t)shown, sizeof(*selected), tree_hop_cmp_qn);+ }+ static const char *const columns[] = {"qn", "label", "file", "hop"};+ const char **cells = shown > 0 ? calloc((size_t)shown * 4U, sizeof(*cells)) : NULL;+ char (*hop_text)[32] = shown > 0 ? calloc((size_t)shown, sizeof(*hop_text)) : NULL;+ if (shown == 0 || (cells && hop_text)) {+ for (int i = 0; i < shown; i++) {+ size_t base = (size_t)i * 4U;+ cells[base] = rows[i].node.qualified_name ? rows[i].node.qualified_name : "";+ cells[base + 1U] = rows[i].node.label ? rows[i].node.label : "";+ cells[base + 2U] = rows[i].node.file_path ? rows[i].node.file_path : "";+ snprintf(hop_text[i], sizeof(hop_text[i]), "%d", rows[i].hop);+ cells[base + 3U] = hop_text[i];+ }+ static const bool string_cols[] = {true, true, true, false};+ static const bool prefix_cols[] = {true, false, true, false};+ cbm_tree_table_rows_profiled(sb, "impacted", shown, columns, 4, cells, string_cols,+ prefix_cols);+ } else {+ cbm_tree_table_header(sb, "impacted", 0, columns, 4);+ cbm_tree_scalar_str(sb, "impacted_render_error", "out_of_memory");+ }+ free(hop_text);+ free(cells);+ free(selected);+ bool has_more = start + shown < tr->visited_count;+ cbm_tree_scalar_bool(sb, "impacted_has_more", has_more);+ if (has_more && shown > 0) {+ cbm_tree_scalar_int(sb, "impacted_next_offset", start + shown);+ } else if (has_more) {+ cbm_tree_scalar_bool(sb, "impacted_continuation_requires_higher_budget", true);+ }+}++/* Portable, allocation-backed line reader. Git permits paths longer than the+ * former 1 KiB stack buffer on supported platforms; splitting one path into+ * several fake files would corrupt both traversal seeds and output. */+static char *detect_read_line(FILE *stream, bool *oom) {+ cbm_sb_t line;+ cbm_sb_init(&line);+ bool saw_byte = false;+ for (;;) {+ int ch = fgetc(stream);+ if (ch == EOF) {+ break;+ }+ saw_byte = true;+ char byte = (char)ch;+ cbm_sb_append_n(&line, &byte, 1);+ if (line.oom || ch == '\n') {+ break;+ }+ }+ if (line.oom) {+ if (oom) {+ *oom = true;}- char row[CBM_SZ_512];- snprintf(row, sizeof(row), " %s %s %d\n", plen ? qn + plen + 1 : qn,- tr->visited[i].node.label ? tr->visited[i].node.label : "", tr->visited[i].hop);- cbm_sb_append(sb, row);+ cbm_sb_free(&line);+ return NULL;}- if (shown < tr->visited_count) {- char more[CBM_SZ_256];- snprintf(more, sizeof(more),- "impacted_omitted: %d (see impacted_modules for the full rollup; raise 'limit' "- "or lower 'depth' to see specifics)\n",- tr->visited_count - shown);- cbm_sb_append(sb, more);+ if (!saw_byte) {+ cbm_sb_free(&line);+ return NULL;}+ return cbm_sb_finish(&line);}static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {@@ -11823,8 +14342,9 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {bool legacy_json = fmt && strcmp(fmt, "json") == 0;free(fmt);- /* Per-symbol impacted-row display cap (the module rollup stays complete).- * impacted_total always reports the true count, so this never hides scale. */+ /* 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. */int imp_limit = cbm_mcp_get_int_arg(args, "limit", MCP_DEFAULT_IMPACT_LIMIT);if (imp_limit < 1) {imp_limit = 1;@@ -11832,6 +14352,36 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {if (imp_limit > MCP_BFS_LIMIT_MAX) {imp_limit = MCP_BFS_LIMIT_MAX;}+ int impact_offset = cbm_mcp_get_int_arg(args, "impact_offset", 0);+ if (impact_offset < 0) {+ impact_offset = 0;+ }+ int changed_limit = cbm_mcp_get_int_arg(args, "changed_limit", 20);+ int changed_offset = cbm_mcp_get_int_arg(args, "changed_offset", 0);+ if (changed_limit < 0) {+ changed_limit = 0;+ } else if (changed_limit > MCP_BFS_LIMIT_MAX) {+ changed_limit = MCP_BFS_LIMIT_MAX;+ }+ if (changed_offset < 0) {+ changed_offset = 0;+ }+ int module_limit = cbm_mcp_get_int_arg(args, "module_limit", 20);+ int module_offset = cbm_mcp_get_int_arg(args, "module_offset", 0);+ if (module_limit < 0) {+ module_limit = 0;+ } else if (module_limit > DETECT_MODCAP) {+ module_limit = DETECT_MODCAP;+ }+ if (module_offset < 0) {+ module_offset = 0;+ }+ int max_output_tokens = cbm_mcp_get_int_arg(args, "max_output_tokens", 3200);+ if (max_output_tokens < 128) {+ max_output_tokens = 128;+ } else if (max_output_tokens > 1000000) {+ max_output_tokens = 1000000;+ }/* Collect changed file paths into a C array (drives seeds, the rollup, and* both output encodings). */@@ -11912,13 +14462,18 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {}}- char line[CBM_SZ_1K];- while (fgets(line, sizeof(line), fp)) {+ bool changed_line_oom = false;+ for (;;) {+ char *line = detect_read_line(fp, &changed_line_oom);+ if (!line) {+ break;+ }size_t len = strlen(line);while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {line[--len] = '\0';}if (len == 0) {+ free(line);continue;}/* Strip the `git status --porcelain` 2-char code + space; for a rename@@ -11934,6 +14489,7 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {}}if (path_line[0] == '\0') {+ free(line);continue;}/* Dedup: the three git sources are sorted+unioned on POSIX but not on@@ -11946,6 +14502,7 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {}}if (dup) {+ free(line);continue;}if (file_count >= file_cap) {@@ -11957,9 +14514,24 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {detect_collect_seeds(store, project, path_line, hunks, hunk_count, &seeds, &seed_count,&seed_cap);}+ free(line);}(void)fclose(fp);(void)cbm_unlink(output_path);+ if (changed_line_oom) {+ for (int i = 0; i < file_count; i++) {+ free(files[i]);+ }+ free(files);+ free(seeds);+ free(hunks);+ free(direction);+ free(root_path);+ free(project);+ free(base_branch);+ free(scope);+ return cbm_mcp_text_result("out of memory while reading changed paths", true);+ }int git_status = git_result.exit_code;/* merge-base SHA: the exact commit the diff is measured against, so the@@ -12023,8 +14595,42 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {}bool is_error = (git_status != 0 && file_count == 0);+ int changed_start = changed_offset < file_count ? changed_offset : file_count;+ int changed_returned = file_count - changed_start;+ if (changed_returned > changed_limit) {+ changed_returned = changed_limit;+ }++ detect_module_row_t *modules = NULL;+ int nmods = 0;+ int module_overflow = 0;+ if (want_symbols && impact.visited_count > 0) {+ modules = calloc(DETECT_MODCAP, sizeof(*modules));+ if (modules) {+ nmods = detect_module_rollup(&impact, modules, &module_overflow);+ }+ }+ /* Overflow is represented as one explicit aggregate row. This is the exact+ * 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);+ int module_start = module_offset < module_total ? module_offset : module_total;+ int module_returned = module_total - module_start;+ if (module_returned > module_limit) {+ module_returned = module_limit;+ }+ int imp_start = impact_offset < impact.visited_count ? impact_offset : impact.visited_count;+ int imp_returned = impact.visited_count - imp_start;+ if (imp_returned > imp_limit) {+ imp_returned = imp_limit;+ }+ size_t output_budget_bytes =+ (size_t)max_output_tokens * (size_t)MCP_OUTPUT_BYTES_PER_TOKEN_ESTIMATE;+ bool output_budget_hit = false;+ bool output_budget_floor_exceeded = false;char *out_str = NULL;+render_detect_output:if (!legacy_json) {cbm_sb_t sb;cbm_sb_init(&sb);@@ -12033,6 +14639,13 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {cbm_tree_scalar_str(&sb, "merge_base", merge_base);}cbm_tree_scalar_str(&sb, "direction", direction);+ if (output_budget_hit) {+ cbm_tree_scalar_str(&sb, "truncation_reason", "output_budget");+ cbm_tree_scalar_int(&sb, "max_output_bytes", (long long)output_budget_bytes);+ }+ if (output_budget_floor_exceeded) {+ cbm_tree_scalar_bool(&sb, "output_budget_floor_exceeded", true);+ }if (is_error) {char hint_buf[CBM_SZ_256];snprintf(hint_buf, sizeof(hint_buf),@@ -12040,40 +14653,70 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {base_branch);cbm_tree_scalar_str(&sb, "hint", hint_buf);}- /* changed files (the git result) */+ /* Changed files are independently pageable: traversal still used every+ * 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);+ } else if (changed_has_more) {+ cbm_tree_scalar_bool(&sb,+ changed_limit == 0 ? "changed_continuation_requires_positive_limit"+ : "changed_continuation_requires_higher_budget",+ true);+ }char cf[CBM_SZ_64];- snprintf(cf, sizeof(cf), "changed_files: %d\n", file_count);+ snprintf(cf, sizeof(cf), "changed_files: %d\n", changed_returned);cbm_sb_append(&sb, cf);- for (int i = 0; i < file_count; i++) {+ for (int i = changed_start; i < changed_start + changed_returned; i++) {cbm_sb_append(&sb, " ");cbm_sb_append(&sb, files[i]);cbm_sb_append(&sb, "\n");}cbm_tree_scalar_int(&sb, "seed_symbols", seed_count);if (want_symbols) {- detect_emit_impacted_tree(&sb, &impact, imp_limit);- /* module rollup: a quotient view of the blast radius */- if (impact.visited_count > 0) {- cbm_sb_append(&sb, "impacted_modules: (rows: module count)\n");- char (*mods)[CBM_SZ_128] = malloc(DETECT_MODCAP * CBM_SZ_128);- int *mcnt = malloc(DETECT_MODCAP * sizeof(int));- if (mods && mcnt) {- int overflow = 0;- int nmods = detect_module_rollup(&impact, mods, mcnt, &overflow);- for (int j = 0; j < nmods; j++) {- char mrow[CBM_SZ_256];- snprintf(mrow, sizeof(mrow), " %s %d\n", mods[j], mcnt[j]);- cbm_sb_append(&sb, mrow);- }- if (overflow > 0) {- char orow[CBM_SZ_128];- snprintf(orow, sizeof(orow), " (other) %d\n", overflow);- cbm_sb_append(&sb, orow);- }+ detect_emit_impacted_tree(&sb, &impact, imp_start, imp_returned, truncated);+ /* 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_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);+ } else if (module_has_more) {+ cbm_tree_scalar_bool(&sb,+ module_limit == 0+ ? "module_continuation_requires_positive_limit"+ : "module_continuation_requires_higher_budget",+ true);+ }+ static const char *const columns[] = {"module", "count"};+ const char **cells =+ module_returned > 0 ? calloc((size_t)module_returned * 2U, sizeof(*cells)) : NULL;+ char (*count_text)[32] =+ module_returned > 0 ? calloc((size_t)module_returned, sizeof(*count_text)) : NULL;+ if (module_returned == 0 || (cells && count_text)) {+ for (int row = 0; row < module_returned; row++) {+ int j = module_start + row;+ cells[(size_t)row * 2U] = j < nmods ? modules[j].name : "(other)";+ snprintf(count_text[row], sizeof(count_text[row]), "%d",+ j < nmods ? modules[j].count : module_overflow);+ cells[(size_t)row * 2U + 1U] = count_text[row];}- free(mods);- free(mcnt);+ static const bool string_cols[] = {true, false};+ static const bool prefix_cols[] = {true, false};+ cbm_tree_table_rows_profiled(&sb, "impacted_modules", module_returned, columns, 2,+ cells, string_cols, prefix_cols);+ } else {+ cbm_tree_table_header(&sb, "impacted_modules", 0, columns, 2);+ cbm_tree_scalar_str(&sb, "module_render_error", "out_of_memory");}+ free(count_text);+ free(cells);if (truncated) {cbm_tree_scalar_bool(&sb, "truncated", true);cbm_tree_scalar_str(&sb, "hint",@@ -12092,17 +14735,38 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_obj_add_strcpy(doc, root_obj, "merge_base", merge_base);}yyjson_mut_obj_add_strcpy(doc, root_obj, "direction", direction);+ if (output_budget_hit) {+ yyjson_mut_obj_add_str(doc, root_obj, "truncation_reason", "output_budget");+ yyjson_mut_obj_add_uint(doc, root_obj, "max_output_bytes", output_budget_bytes);+ }+ if (output_budget_floor_exceeded) {+ yyjson_mut_obj_add_bool(doc, root_obj, "output_budget_floor_exceeded", 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);+ } else if (changed_has_more) {+ yyjson_mut_obj_add_bool(doc, root_obj,+ changed_limit == 0+ ? "changed_continuation_requires_positive_limit"+ : "changed_continuation_requires_higher_budget",+ true);+ }yyjson_mut_val *cf = yyjson_mut_arr(doc);- for (int i = 0; i < file_count; i++) {+ for (int i = changed_start; i < changed_start + changed_returned; i++) {yyjson_mut_arr_add_strcpy(doc, cf, files[i]);}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);- int imp_shown = impact.visited_count < imp_limit ? impact.visited_count : imp_limit;- yyjson_mut_obj_add_int(doc, root_obj, "impacted_shown", imp_shown);+ yyjson_mut_obj_add_str(doc, root_obj, "impacted_total_relation", truncated ? "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 = 0; i < imp_shown; i++) {+ for (int i = imp_start; i < imp_start + imp_returned; i++) {yyjson_mut_val *o = yyjson_mut_obj(doc);yyjson_mut_obj_add_strcpy(doc, o, "qn",@@ -12116,30 +14780,45 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_arr_add_val(imp, o);}yyjson_mut_obj_add_val(doc, root_obj, "impacted", imp);- /* Model parity with the tree encoding: the complete module rollup. */- if (impact.visited_count > 0) {- char (*mods)[CBM_SZ_128] = malloc(DETECT_MODCAP * CBM_SZ_128);- int *mcnt = malloc(DETECT_MODCAP * sizeof(int));- if (mods && mcnt) {- int overflow = 0;- int nmods = detect_module_rollup(&impact, mods, mcnt, &overflow);- yyjson_mut_val *rollup = yyjson_mut_arr(doc);- for (int j = 0; j < nmods; j++) {- yyjson_mut_val *o = yyjson_mut_obj(doc);- yyjson_mut_obj_add_strcpy(doc, o, "module", mods[j]);- yyjson_mut_obj_add_int(doc, o, "count", mcnt[j]);- yyjson_mut_arr_add_val(rollup, o);- }- if (overflow > 0) {- yyjson_mut_val *o = yyjson_mut_obj(doc);- yyjson_mut_obj_add_strcpy(doc, o, "module", "(other)");- yyjson_mut_obj_add_int(doc, o, "count", overflow);- yyjson_mut_arr_add_val(rollup, o);+ 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);+ } else if (impacted_has_more) {+ yyjson_mut_obj_add_bool(doc, root_obj, "impacted_continuation_requires_higher_budget",+ true);+ }+ /* Model parity with the tree encoding: complete totals, paged rows. */+ 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");+ 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",+ module_start + module_returned);+ } else if (module_has_more) {+ yyjson_mut_obj_add_bool(doc, root_obj,+ module_limit == 0+ ? "module_continuation_requires_positive_limit"+ : "module_continuation_requires_higher_budget",+ true);+ }+ yyjson_mut_val *rollup = yyjson_mut_arr(doc);+ for (int j = module_start; j < module_start + module_returned; j++) {+ yyjson_mut_val *o = yyjson_mut_obj(doc);+ if (j < nmods) {+ yyjson_mut_obj_add_strcpy(doc, o, "module", modules[j].name);+ yyjson_mut_obj_add_int(doc, o, "count", modules[j].count);+ } else {+ yyjson_mut_obj_add_str(doc, o, "module", "(other)");+ yyjson_mut_obj_add_int(doc, o, "count", module_overflow);}- yyjson_mut_obj_add_val(doc, root_obj, "impacted_modules", rollup);+ yyjson_mut_arr_add_val(rollup, o);}- free(mods);- free(mcnt);+ yyjson_mut_obj_add_val(doc, root_obj, "impacted_modules", rollup);}yyjson_mut_obj_add_bool(doc, root_obj, "truncated", truncated);if (is_error) {@@ -12153,7 +14832,61 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_doc_free(doc);}+ /* Exact serialized-size check with semantic reductions only. Low-value+ * rollups and file names yield as whole sections before graph rows. The+ * continuations above remain valid even when a requested page is omitted+ * by this soft budget. */+ if (out_str && strlen(out_str) > output_budget_bytes) {+ output_budget_hit = true;+ if (module_returned > 0) {+ module_returned = 0;+ } else if (changed_returned > 0) {+ changed_returned = 0;+ } else if (imp_returned > 0) {+ /* Prefix-directory activation can make N compact rows smaller+ * than N-1 direct rows. Probe every smaller whole-row prefix so+ * the response retains the largest page that actually fits. */+ imp_returned--;+ } else if (!output_budget_floor_exceeded) {+ output_budget_floor_exceeded = true;+ } else {+ free(out_str);+ out_str = NULL;+ if (!legacy_json) {+ cbm_sb_t floor;+ cbm_sb_init(&floor);+ cbm_tree_scalar_str(&floor, "truncation_reason", "output_budget");+ cbm_tree_scalar_bool(&floor, "output_budget_floor_exceeded", 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 "+ "max_output_tokens (no path or identifier was sliced)");+ out_str = cbm_sb_finish(&floor);+ } else {+ yyjson_mut_doc *floor_doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *floor = yyjson_mut_obj(floor_doc);+ yyjson_mut_doc_set_root(floor_doc, floor);+ yyjson_mut_obj_add_str(floor_doc, floor, "truncation_reason", "output_budget");+ yyjson_mut_obj_add_bool(floor_doc, floor, "output_budget_floor_exceeded", true);+ yyjson_mut_obj_add_uint(floor_doc, floor, "max_output_bytes", output_budget_bytes);+ yyjson_mut_obj_add_str(+ floor_doc, floor, "hint",+ "mandatory detect_changes metadata exceeds the budget; raise "+ "max_output_tokens (no path or identifier was sliced)");+ out_str = yy_doc_to_str(floor_doc);+ yyjson_mut_doc_free(floor_doc);+ }+ goto detect_output_done;+ }+ free(out_str);+ out_str = NULL;+ goto render_detect_output;+ }++detect_output_done:+cbm_store_traverse_free(&impact);+ detect_module_rollup_free(modules, nmods);for (int i = 0; i < file_count; i++) {free(files[i]);}@@ -12204,6 +14937,117 @@ static void adr_list_sections_from_content(yyjson_mut_doc *doc, yyjson_mut_val *yyjson_mut_obj_add_val(doc, root_obj, "sections", sections);}+static int adr_line_count(const char *content) {+ if (!content || !content[0]) {+ return 0;+ }+ int lines = 1;+ for (const char *p = content; *p; p++) {+ if (*p == '\n' && p[1]) {+ lines++;+ }+ }+ return lines;+}++typedef struct {+ const char *text;+ size_t text_len;+ int level;+ int start_line;+ int end_line;+} adr_heading_row_t;++static int adr_collect_headings(const char *content, adr_heading_row_t **out_rows,+ int *out_total_lines) {+ *out_rows = NULL;+ *out_total_lines = adr_line_count(content);+ if (!content || !content[0]) {+ return 0;+ }+ int capacity = 16;+ int count = 0;+ adr_heading_row_t *rows = malloc((size_t)capacity * sizeof(*rows));+ if (!rows) {+ return 0;+ }+ const char *p = content;+ int line = 1;+ while (*p) {+ const char *eol = strchr(p, '\n');+ const char *line_end = eol ? eol : p + strlen(p);+ const char *trimmed_end = line_end;+ if (trimmed_end > p && trimmed_end[-1] == '\r') {+ trimmed_end--;+ }+ int level = 0;+ while (p + level < trimmed_end && p[level] == '#') {+ level++;+ }+ if (level > 0 && level <= 6 && p + level < trimmed_end && p[level] == ' ') {+ if (count == capacity) {+ capacity *= 2;+ rows = safe_realloc(rows, (size_t)capacity * sizeof(*rows));+ }+ if (count > 0) {+ rows[count - 1].end_line = line - 1;+ }+ rows[count++] = (adr_heading_row_t){.text = p,+ .text_len = (size_t)(trimmed_end - p),+ .level = level,+ .start_line = line,+ .end_line = *out_total_lines};+ }+ if (!eol) {+ break;+ }+ p = eol + 1;+ line++;+ }+ *out_rows = rows;+ return count;+}++static void adr_add_outline(yyjson_mut_doc *doc, yyjson_mut_val *root_obj, const char *content,+ int offset, int limit) {+ int total_lines = 0;+ adr_heading_row_t *rows = NULL;+ int total = adr_collect_headings(content, &rows, &total_lines);+ if (offset < 0) {+ offset = 0;+ }+ if (offset > total) {+ offset = total;+ }+ int returned = total - offset;+ if (returned > limit) {+ returned = limit;+ }+ yyjson_mut_obj_add_str(doc, root_obj, "mode", "outline");+ yyjson_mut_val *headings = yyjson_mut_arr(doc);+ for (int i = 0; i < returned; i++) {+ const adr_heading_row_t *row = &rows[offset + i];+ yyjson_mut_val *item = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_int(doc, item, "index", offset + i);+ yyjson_mut_obj_add_strncpy(doc, item, "heading", row->text, row->text_len);+ yyjson_mut_obj_add_int(doc, item, "level", row->level);+ yyjson_mut_obj_add_int(doc, item, "start_line", row->start_line);+ yyjson_mut_obj_add_int(doc, item, "end_line", row->end_line);+ yyjson_mut_arr_add_val(headings, item);+ }+ yyjson_mut_obj_add_val(doc, root_obj, "headings", headings);+ yyjson_mut_obj_add_int(doc, root_obj, "total_lines", total_lines);+ yyjson_mut_obj_add_int(doc, root_obj, "sections_total", total);+ yyjson_mut_obj_add_int(doc, root_obj, "sections_returned", returned);+ bool has_more = offset + returned < total;+ yyjson_mut_obj_add_bool(doc, root_obj, "sections_has_more", has_more);+ if (has_more) {+ yyjson_mut_obj_add_int(doc, root_obj, "next_section_offset", offset + returned);+ }+ yyjson_mut_obj_add_bool(doc, root_obj, "full_content_available", content != NULL);+ free(rows);+}+/* Read the legacy file-based ADR (<root>/.codebase-memory/adr.md), used by* older versions. Returns a heap buffer (caller frees) or NULL if missing/* empty. Kept only to migrate old ADRs into the store (#256). */@@ -12392,7 +15236,23 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {char *content = cbm_mcp_get_string_arg(args, "content");if (!mode_str) {- mode_str = heap_strdup("get");+ mode_str = heap_strdup("outline");+ }++ bool valid_mode = strcmp(mode_str, "outline") == 0 || strcmp(mode_str, "get") == 0 ||+ strcmp(mode_str, "sections") == 0 || strcmp(mode_str, "update") == 0 ||+ strcmp(mode_str, "set_sections") == 0 || strcmp(mode_str, "store") == 0;+ if (!valid_mode) {+ free(project);+ free(mode_str);+ free(content);+ return cbm_mcp_text_result(+ "invalid mode: use outline, get, sections, set_sections, or update", true);+ }+ if ((strcmp(mode_str, "update") == 0 || strcmp(mode_str, "store") == 0) && !content) {+ free(project);+ free(mode_str);+ return cbm_mcp_text_result("content is required for update", true);}/* `sections` used to be advertised as an input argument, but it was never@@ -12633,9 +15493,20 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {}} else if (strcmp(mode_str, "sections") == 0) {adr_list_sections_from_content(doc, root_obj, adr_content);+ } else if (strcmp(mode_str, "outline") == 0) {+ int section_limit = cbm_mcp_get_int_arg(args, "section_limit", 50);+ int section_offset = cbm_mcp_get_int_arg(args, "section_offset", 0);+ if (section_limit < 1) {+ section_limit = 1;+ } else if (section_limit > 500) {+ section_limit = 500;+ }+ adr_add_outline(doc, root_obj, adr_content, section_offset, section_limit);} else { /* get */if (adr_content) {yyjson_mut_obj_add_strcpy(doc, root_obj, "content", adr_content);+ yyjson_mut_obj_add_int(doc, root_obj, "total_lines", adr_line_count(adr_content));+ yyjson_mut_obj_add_bool(doc, root_obj, "content_complete", true);} else {yyjson_mut_obj_add_str(doc, root_obj, "content", "");yyjson_mut_obj_add_str(doc, root_obj, "status", "no_adr");@@ -12645,6 +15516,7 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {char *json = yy_doc_to_str(doc);yyjson_mut_doc_free(doc);+ bool legacy_json_result = write_request || strcmp(mode_str, "sections") == 0;if (have_adr) {cbm_store_adr_free(&adr);}@@ -12661,7 +15533,8 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {free(mode_str);free(content);- char *result = cbm_mcp_text_result(json, is_error);+ char *result =+ legacy_json_result ? cbm_mcp_text_result(json, is_error) : mcp_result_from_json(args, json);free(json);return result;}diff --git a/src/mcp/mcp_internal.h b/src/mcp/mcp_internal.hindex 673fd0c5d..a9e67d832 100644--- a/src/mcp/mcp_internal.h+++ b/src/mcp/mcp_internal.h@@ -75,5 +75,13 @@ bool cbm_search_code_windows_path_matches_prefilter(const char *path, const charvoid cbm_search_code_build_grep_cmd(char *cmd, size_t cmd_sz, bool use_regex, bool scoped,const char *file_pattern, const char *tmpfile,const char *filelist, const char *root_path);+#ifdef CBM_ENABLE_TEST_SEAMS+/* Filesystem PATH_MAX prevents a portable end-to-end fixture for multi-KiB+ * stored paths. This seam drives the normal search result ownership,+ * directory aggregation, and renderer pipeline with synthetic identities. */+char *cbm_mcp_render_search_rows_for_testing(const char *const *qualified_names,+ const char *const *file_paths, int row_count,+ bool json_format);+#endif#endifdiff --git a/src/store/store.c b/src/store/store.cindex 03e42b0ed..7e3663c8d 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -8,6 +8,7 @@// for ISO timestamp+#include <limits.h>#include <stdint.h>#include "foundation/constants.h"#include "foundation/hash_table.h"@@ -5393,10 +5394,14 @@ void cbm_store_search_free(cbm_search_output_t *out) {static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_hop_t *visited,int visited_count, const char *types_clause, const char **edge_types,- int edge_type_count, cbm_edge_info_t **out_edges,- int *out_edge_count) {+ int edge_type_count, int max_edges, cbm_edge_info_t **out_edges,+ int *out_edge_count, bool *out_truncated) {*out_edges = NULL;*out_edge_count = 0;+ *out_truncated = false;+ if (max_edges == 0) {+ return CBM_STORE_OK;+ }/* Visited-ID set via a per-connection TEMP table. The previous approach* interpolated the ids into a fixed 4KB SQL string: past ~1000 visited@@ -5408,22 +5413,37 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho"CREATE TEMP TABLE IF NOT EXISTS bfs_ids (id INTEGER PRIMARY KEY);""DELETE FROM bfs_ids;",NULL, NULL, NULL) != SQLITE_OK) {- return CBM_STORE_OK; /* best-effort: nodes without edges beat an error */+ store_set_error_sqlite(s, "bfs edge ids");+ return CBM_STORE_ERR;}sqlite3_stmt *ins = NULL;if (sqlite3_prepare_v2(s->db, "INSERT OR IGNORE INTO bfs_ids(id) VALUES (?1)", CBM_NOT_FOUND,&ins, NULL) != SQLITE_OK) {- return CBM_STORE_OK;+ store_set_error_sqlite(s, "bfs edge ids prepare");+ return CBM_STORE_ERR;}sqlite3_bind_int64(ins, SKIP_ONE, start_id);- (void)sqlite3_step(ins);+ if (sqlite3_step(ins) != SQLITE_DONE) {+ store_set_error_sqlite(s, "bfs edge root id");+ sqlite3_finalize(ins);+ return CBM_STORE_ERR;+ }for (int i = 0; i < visited_count; i++) {sqlite3_reset(ins);sqlite3_bind_int64(ins, SKIP_ONE, visited[i].node.id);- (void)sqlite3_step(ins);+ if (sqlite3_step(ins) != SQLITE_DONE) {+ store_set_error_sqlite(s, "bfs edge visited id");+ sqlite3_finalize(ins);+ return CBM_STORE_ERR;+ }}sqlite3_finalize(ins);+ char limit_clause[ST_BUF_64] = "";+ if (max_edges > 0) {+ snprintf(limit_clause, sizeof(limit_clause), " LIMIT %d",+ max_edges < INT_MAX ? max_edges + SKIP_ONE : max_edges);+ }char edge_sql[ST_SQL_BUF];snprintf(edge_sql, sizeof(edge_sql),"SELECT n1.name, n2.name, e.type, e.source_id, e.target_id, e.properties "@@ -5432,15 +5452,15 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho"JOIN nodes n2 ON n2.id = e.target_id ""WHERE e.source_id IN (SELECT id FROM bfs_ids) ""AND e.target_id IN (SELECT id FROM bfs_ids) "- "AND e.type IN (%s)",- types_clause);+ "AND e.type IN (%s) "+ "ORDER BY e.source_id, e.target_id, e.type%s",+ types_clause, limit_clause);sqlite3_stmt *estmt = NULL;int rc = sqlite3_prepare_v2(s->db, edge_sql, CBM_NOT_FOUND, &estmt, NULL);if (rc != SQLITE_OK) {- *out_edges = NULL;- *out_edge_count = 0;- return CBM_STORE_OK;+ store_set_error_sqlite(s, "bfs edges prepare");+ return CBM_STORE_ERR;}if (edge_type_count > 0) {@@ -5479,6 +5499,15 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho}sqlite3_finalize(estmt);+ if (max_edges > 0 && en > max_edges) {+ en = max_edges;+ safe_str_free(&edges[en].from_name);+ safe_str_free(&edges[en].to_name);+ safe_str_free(&edges[en].type);+ safe_str_free(&edges[en].properties_json);+ *out_truncated = true;+ }+*out_edges = edges;*out_edge_count = en;return CBM_STORE_OK;@@ -5533,8 +5562,11 @@ static int bfs_cte_row_limit_for_depth(int max_results, int max_depth) {static int store_bfs(cbm_store_t *s, int64_t start_id, const char *direction,const char **edge_types, int edge_type_count, int max_depth, int max_results,- bool trail, cbm_traverse_result_t *out) {+ bool trail, int max_edges, cbm_traverse_result_t *out) {memset(out, 0, sizeof(*out));+ if (max_results < 0) {+ max_results = 0;+ }cbm_node_t root = {0};int rc = cbm_store_find_node_by_id(s, start_id, &root);@@ -5611,7 +5643,9 @@ static int store_bfs(cbm_store_t *s, int64_t start_id, const char *direction,"GROUP BY n.id ""ORDER BY hop, n.id ""LIMIT %d;",- (long long)start_id, next_id, join_cond, types_clause, max_depth, max_results);+ /* One extra row makes max_results saturation observable. */+ (long long)start_id, next_id, join_cond, types_clause, max_depth,+ max_results < INT_MAX ? max_results + SKIP_ONE : max_results);}sqlite3_stmt *stmt = NULL;@@ -5664,14 +5698,26 @@ static int store_bfs(cbm_store_t *s, int64_t start_id, const char *direction,snprintf(limit_buf, sizeof(limit_buf), "%d", cte_row_limit);cbm_log_warn("cypher.trail_truncated", "cte_rows", limit_buf, "result", "partial");}+ if (!trail && n > max_results) {+ /* The extra probe row fired: drop it and report the ceiling honestly. */+ n = max_results;+ cbm_node_free_fields(&visited[n].node);+ out->truncated = true;+ }out->visited = visited;out->visited_count = n;- /* Collect edges between visited nodes (including root) */- if (n > 0) {- bfs_collect_edges(s, start_id, out->visited, n, types_clause, edge_types, edge_type_count,- &out->edges, &out->edge_count);+ /* Edge properties are a secondary, potentially dense all-pairs lookup.+ * Lean callers pass max_edges=0 and avoid it entirely; diagnostics callers+ * pass an explicit ceiling and receive an honest saturation bit. */+ if (n > 0 && max_edges != 0) {+ rc = bfs_collect_edges(s, start_id, out->visited, n, types_clause, edge_types,+ edge_type_count, max_edges, &out->edges, &out->edge_count,+ &out->edges_truncated);+ if (rc != CBM_STORE_OK) {+ return rc;+ }} else {out->edges = NULL;out->edge_count = 0;@@ -5683,14 +5729,23 @@ static int store_bfs(cbm_store_t *s, int64_t start_id, const char *direction,int cbm_store_bfs(cbm_store_t *s, int64_t start_id, const char *direction, const char **edge_types,int edge_type_count, int max_depth, int max_results, cbm_traverse_result_t *out) {return store_bfs(s, start_id, direction, edge_types, edge_type_count, max_depth, max_results,- false, out);+ false, -1, out);}int cbm_store_bfs_trail(cbm_store_t *s, int64_t start_id, const char *direction,const char **edge_types, int edge_type_count, int max_depth,int max_results, cbm_traverse_result_t *out) {return store_bfs(s, start_id, direction, edge_types, edge_type_count, max_depth, max_results,- true, out);+ true, -1, out);+}++int cbm_store_bfs_with_edge_limit(cbm_store_t *s, int64_t start_id, const char *direction,+ const char **edge_types, int edge_type_count, int max_depth,+ int max_results, int max_edges, cbm_traverse_result_t *out) {+ /* Bounded edge-data variant for lean callers: node traversal is the plain+ * shortest-path BFS; max_edges=0 skips the all-pairs edge lookup entirely. */+ return store_bfs(s, start_id, direction, edge_types, edge_type_count, max_depth, max_results,+ false, max_edges, out);}/* Multi-source BFS: one recursive CTE anchored on ALL seeds (via a tempdiff --git a/src/store/store.h b/src/store/store.hindex 165356c31..dc1c2afce 100644--- a/src/store/store.h+++ b/src/store/store.h@@ -238,8 +238,10 @@ typedef struct {int visited_count;cbm_edge_info_t *edges;int edge_count;- /* True when trail expansion hit its recursive-row safety budget. */+ /* True when trail expansion hit its recursive-row safety budget (or, for+ * the plain BFS, the max_results ceiling); counts are lower bounds. */bool truncated;+ bool edges_truncated; /* optional edge-data ceiling reached; node counts stay exact */} cbm_traverse_result_t;/* ── Schema introspection ───────────────────────────────────────── */@@ -710,6 +712,13 @@ int cbm_store_bfs(cbm_store_t *s, int64_t start_id, const char *direction, constint cbm_store_bfs_trail(cbm_store_t *s, int64_t start_id, const char *direction,const char **edge_types, int edge_type_count, int max_depth,int max_results, cbm_traverse_result_t *out);+/* BFS with an explicit edge-data budget. max_edges=0 skips the secondary+ * all-pairs edge lookup; max_edges>0 collects at most that many edges and+ * raises out->edges_truncated on saturation. Node traversal is unchanged.+ * This is intended for lean callers that need nodes but not edge properties. */+int cbm_store_bfs_with_edge_limit(cbm_store_t *s, int64_t start_id, const char *direction,+ const char **edge_types, int edge_type_count, int max_depth,+ int max_results, int max_edges, cbm_traverse_result_t *out);/* Multi-source BFS from ALL seed ids at once (one CTE, temp-table anchored).* Seeds are EXCLUDED from the result (impact semantics); MIN(hop) across thediff --git a/src/ui/http_server.c b/src/ui/http_server.cindex b806b10c6..f47ac59be 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -1775,7 +1775,8 @@ static bool rpc_is_allowed_for_ui(const char *body, size_t body_len) {const char *name_text = yyjson_is_str(name) ? yyjson_get_str(name) : NULL;bool allowed =method_text && strcmp(method_text, "tools/call") == 0 && name_text &&- (strcmp(name_text, "list_projects") == 0 || strcmp(name_text, "get_code_snippet") == 0);+ (strcmp(name_text, "list_projects") == 0 || strcmp(name_text, "get_graph_schema") == 0 ||+ strcmp(name_text, "get_code_snippet") == 0);yyjson_doc_free(document);return allowed;}diff --git a/tests/scale_contract.sh b/tests/scale_contract.shindex 5798f91d5..e1458d49d 100644--- a/tests/scale_contract.sh+++ b/tests/scale_contract.sh@@ -45,11 +45,10 @@ project_name() { printf '%s' "$1" | sed 's#^/##; s#[^A-Za-z0-9._-]#-#g'; }# Run query_graph and print the first integer in the JSON response (or -1).query_count() {local proj="$1" cypher="$2" resp- resp="$("$BIN" cli query_graph "{\"project\":\"$proj\",\"query\":\"$cypher\"}" 2>/dev/null)"- printf '%s' "$resp" | "$PY" -c 'import sys,re-s=sys.stdin.read()-m=re.findall(r"-?\d+", s)-print(m[0] if m else -1)' 2>/dev/null || echo -1+ resp="$("$BIN" cli query_graph "{\"project\":\"$proj\",\"query\":\"$cypher\",\"format\":\"json\"}" 2>/dev/null)"+ printf '%s' "$resp" | "$PY" -c 'import json,sys+d=json.load(sys.stdin); rows=d.get("rows", [])+print(rows[0][0] if rows and rows[0] else -1)' 2>/dev/null || echo -1}assert_lang() {diff --git a/tests/test_cli.c b/tests/test_cli.cindex d3f804313..8d691f128 100644--- a/tests/test_cli.c+++ b/tests/test_cli.c@@ -21,6 +21,7 @@#include <daemon/runtime.h>#include <daemon/version_cohort.h>#include <foundation/constants.h>+#include <foundation/log.h>#include <foundation/platform.h>#include <mcp/mcp.h>#include <pipeline/pipeline.h>@@ -103,6 +104,53 @@ TEST(cli_progress_sink_accepts_worker_json_logs) {PASS();}+TEST(cli_progress_sink_enables_lifecycle_info_then_restores_quiet_default) {+ FILE *out = tmpfile();+ ASSERT_NOT_NULL(out);+ cbm_log_set_level(CBM_LOG_WARN);++ cbm_progress_sink_init(out);+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);+ cbm_log_info("pipeline.discover", "files", "3");+ cbm_progress_sink_fini();+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);++ ASSERT_EQ(fseek(out, 0, SEEK_SET), 0);+ char rendered[256] = {0};+ size_t rendered_size = fread(rendered, 1, sizeof(rendered) - 1, out);+ (void)fclose(out);+ ASSERT_TRUE(rendered_size > 0);+ ASSERT_NOT_NULL(strstr(rendered, "Discovering files (3 found)"));+ PASS();+}++TEST(cli_progress_sink_suppresses_noise_and_preserves_failures) {+ FILE *out = tmpfile();+ ASSERT_NOT_NULL(out);++ cbm_progress_sink_init(out);+ cbm_progress_sink_fn("level=info msg=parallel.extract.progress done=1 total=2");+ cbm_progress_sink_fn("level=debug msg=worker.detail value=drop-debug");+ cbm_progress_sink_fn(+ "{\"level\":\"info\",\"event\":\"worker.detail\",\"value\":\"drop-info\"}");+ cbm_progress_sink_fn("level=warn msg=worker.warning detail=keep-text");+ cbm_progress_sink_fn(+ "{\"level\":\"error\",\"event\":\"worker.failure\",\"detail\":\"keep-json\"}");+ cbm_progress_sink_fini();++ ASSERT_EQ(fseek(out, 0, SEEK_SET), 0);+ char rendered[1024] = {0};+ size_t rendered_size = fread(rendered, 1, sizeof(rendered) - 1, out);+ (void)fclose(out);++ ASSERT_TRUE(rendered_size > 0);+ ASSERT_STR_EQ(rendered,+ "\r Extracting: 1/2 files (50%)\n"+ "level=warn msg=worker.warning detail=keep-text\n"+ "{\"level\":\"error\",\"event\":\"worker.failure\",\"detail\":\"keep-json\"}\n");+ PASS();+}+enum { CLI_PROGRESS_RACE_THREADS = 4, CLI_PROGRESS_RACE_ROUNDS = 32 };typedef struct {@@ -8810,6 +8858,57 @@ TEST(cli_hook_session_resolves_custom_named_index_by_root_path) {PASS();}+TEST(cli_hook_session_exhausts_project_registry_pages) {+ enum { DECOY_DATABASES = 500 };+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-hook-project-pages-XXXXXX");+ if (!cbm_mkdtemp(tmpdir))+ FAIL("cbm_mkdtemp failed");+ char cache[512];+ char decoy_root[512];+ char target_root[512];+ char decoy_db[640];+ char target_db[640];+ snprintf(cache, sizeof(cache), "%s/cache", tmpdir);+ snprintf(decoy_root, sizeof(decoy_root), "%s/decoy", tmpdir);+ snprintf(target_root, sizeof(target_root), "%s/target", tmpdir);+ snprintf(decoy_db, sizeof(decoy_db), "%s/decoy-000.db", cache);+ snprintf(target_db, sizeof(target_db), "%s/target.db", cache);+ test_mkdirp(cache);+ test_mkdirp(decoy_root);+ test_mkdirp(target_root);++ cbm_store_t *store = cbm_store_open_path(decoy_db);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, "aaa-decoy", decoy_root), CBM_STORE_OK);+ cbm_store_close(store);+ for (int i = 1; i < DECOY_DATABASES; i++) {+ char copy[640];+ snprintf(copy, sizeof(copy), "%s/decoy-%03d.db", cache, i);+ ASSERT_EQ(cbm_copy_file(decoy_db, copy), 0);+ }++ store = cbm_store_open_path(target_db);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, "zzz-custom-project", target_root), CBM_STORE_OK);+ cbm_store_close(store);++ char *saved_cache = save_test_env("CBM_CACHE_DIR");+ cbm_setenv("CBM_CACHE_DIR", cache, 1);+ char input[1024];+ snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}",+ target_root);+ char *output = cbm_hook_augment_lifecycle_json(input);+ bool matched = output && strstr(output, "zzz-custom-project") && strstr(output, "is indexed");++ free(output);+ restore_test_env("CBM_CACHE_DIR", saved_cache);+ test_rmdir_r(tmpdir);+ if (!matched)+ FAIL("SessionStart must exhaust list_projects pages before resolving root_path");+ PASS();+}+TEST(cli_hook_session_sanitizes_untrusted_project_metadata) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-hook-untrusted-project-XXXXXX");@@ -10398,6 +10497,55 @@ TEST(cli_hook_augment_bash_pattern_extractor) {PASS();}+TEST(cli_hook_augment_coverage_requests_machine_json) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-hook-coverage-json-XXXXXX");+ if (!cbm_mkdtemp(tmpdir))+ FAIL("cbm_mkdtemp failed");+ char repo[512];+ char source[640];+ char db_path[640];+ snprintf(repo, sizeof(repo), "%s/repo", tmpdir);+ snprintf(source, sizeof(source), "%s/src/partial.c", repo);+ snprintf(db_path, sizeof(db_path), "%s/hook.db", tmpdir);+ test_mkdirp(repo);+ char source_dir[640];+ snprintf(source_dir, sizeof(source_dir), "%s/src", repo);+ test_mkdirp(source_dir);+ write_test_file(source, "int partial(void) { return 1; }\n");++ cbm_store_t *store = cbm_store_open_path(db_path);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, "repo", repo), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_upsert_file_hash(store, "repo", "src/partial.c", "fixture", 1, 32),+ CBM_STORE_OK);+ const cbm_coverage_row_t row = {+ .rel_path = "src/partial.c", .kind = "parse_partial", .detail = "12-14"};+ ASSERT_EQ(cbm_store_coverage_replace(store, "repo", &row, 1), CBM_STORE_OK);+ cbm_store_close(store);++ char *saved_cache = save_test_env("CBM_CACHE_DIR");+ cbm_setenv("CBM_CACHE_DIR", tmpdir, 1);+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_mcp_server_set_project(srv, "repo");++ char input[2048];+ snprintf(input, sizeof(input),+ "{\"hook_event_name\":\"PostToolUse\",\"tool_name\":\"Read\","+ "\"tool_input\":{\"file_path\":\"%s\"},\"cwd\":\"%s\"}",+ source, repo);+ char *output = cbm_hook_augment_process(srv, input);+ bool matched = output && strstr(output, "PARTIALLY indexed") && strstr(output, "12-14");++ free(output);+ cbm_mcp_server_free(srv);+ restore_test_env("CBM_CACHE_DIR", saved_cache);+ test_rmdir_r(tmpdir);+ if (!matched)+ FAIL("Post-read hook must parse check_index_coverage's explicit JSON response");+ PASS();+}TEST(cli_hook_augment_lifecycle_output_contract) {static const struct {@@ -14018,6 +14166,8 @@ SUITE(cli) {RUN_TEST(cli_raw_mcp_result_preserves_tool_error_status);RUN_TEST(cli_maintenance_cancellation_forces_failure_status);RUN_TEST(cli_progress_sink_accepts_worker_json_logs);+ RUN_TEST(cli_progress_sink_enables_lifecycle_info_then_restores_quiet_default);+ RUN_TEST(cli_progress_sink_suppresses_noise_and_preserves_failures);RUN_TEST(cli_progress_sink_serializes_concurrent_callbacks);RUN_TEST(cli_sha256_file_matches_known_vector);RUN_TEST(cli_checksum_manifest_requires_exact_filename_and_accepts_star);@@ -14243,6 +14393,7 @@ SUITE(cli) {RUN_TEST(cli_augment_installs_session_context_and_subagent);RUN_TEST(cli_augment_session_uses_workspace_roots);RUN_TEST(cli_hook_session_resolves_custom_named_index_by_root_path);+ RUN_TEST(cli_hook_session_exhausts_project_registry_pages);RUN_TEST(cli_hook_session_sanitizes_untrusted_project_metadata);RUN_TEST(cli_hook_ownership_requires_exact_command_identity);RUN_TEST(cli_gemini_hook_upgrade_migrates_released_exact_commands);@@ -14274,6 +14425,7 @@ SUITE(cli) {RUN_TEST(cli_hook_augment_context_tracks_search_json_shape);RUN_TEST(cli_hook_augment_bash_pretooluse_reaches_augmenter);RUN_TEST(cli_hook_augment_bash_pattern_extractor);+ RUN_TEST(cli_hook_augment_coverage_requests_machine_json);RUN_TEST(cli_hook_augment_lifecycle_output_contract);RUN_TEST(cli_hook_augment_subagent_tier_router_contract);RUN_TEST(cli_hook_augment_subagent_no_project_guidance_is_read_only);diff --git a/tests/test_cypher.c b/tests/test_cypher.cindex bf4770c02..899dd0fc3 100644--- a/tests/test_cypher.c+++ b/tests/test_cypher.c@@ -810,6 +810,9 @@ TEST(cypher_exec_optional_saturated_does_not_fabricate_no_match) {/* The discriminator: C has 5 callees, so claiming it has none is a* fabrication. Pre-fix this is exactly what the saturated path emitted. */ASSERT_FALSE(saw_c);+ /* Late filtering leaves fewer than max_rows output rows, but the earlier+ * relationship materialization still saturated its candidate budget. */+ ASSERT_TRUE(r.truncated);cbm_cypher_result_free(&r);cbm_store_close(s);@@ -1274,6 +1277,9 @@ TEST(cypher_exec_varlength_path_semantics_issue797) {ASSERT_EQ(r4.row_count, 0);ASSERT_NOT_NULL(r4.warning);ASSERT_NOT_NULL(strstr(r4.warning, "clamped"));+ /* The warning reports the policy clamp, but this shallow fixture has no+ * candidate beyond the ceiling, so evaluation was still exhaustive. */+ ASSERT_FALSE(r4.truncated);cbm_cypher_result_free(&r4);cbm_store_close(s);@@ -1783,6 +1789,7 @@ TEST(cypher_exec_variable_length) {ASSERT_EQ(rc, 0);/* Should find: ValidateOrder (1 hop), SubmitOrder (2 hops), LogError (1 hop) */ASSERT_GTE(r.row_count, 3);+ ASSERT_FALSE(r.truncated);cbm_cypher_result_free(&r);cbm_store_close(s);@@ -1866,6 +1873,7 @@ TEST(cypher_exec_var_length_explicit_bound_capped) {ASSERT_TRUE(saw_n10); /* within the ceiling — proves the traversal really ran */ASSERT_FALSE(saw_n11); /* clamped away */ASSERT_FALSE(saw_n12);+ ASSERT_TRUE(r.truncated);cbm_cypher_result_free(&r);cbm_store_close(s);@@ -2786,6 +2794,7 @@ TEST(cypher_apply_limit) {int rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN f.name LIMIT 5", "lim", 0, &r);ASSERT_EQ(rc, 0);ASSERT_EQ(r.row_count, 5);+ ASSERT_FALSE(r.truncated);cbm_cypher_result_free(&r);/* No LIMIT, max_rows=10 → capped at 10 */@@ -2793,6 +2802,7 @@ TEST(cypher_apply_limit) {rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN f.name", "lim", 10, &r);ASSERT_EQ(rc, 0);ASSERT_EQ(r.row_count, 10);+ ASSERT_TRUE(r.truncated);cbm_cypher_result_free(&r);/* LIMIT above max_rows → explicit limit wins */@@ -2800,12 +2810,142 @@ TEST(cypher_apply_limit) {rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN f.name LIMIT 30", "lim", 10, &r);ASSERT_EQ(rc, 0);ASSERT_EQ(r.row_count, 30);+ ASSERT_FALSE(r.truncated);cbm_cypher_result_free(&r);cbm_store_close(s);PASS();}+/* max_rows is an engine output budget, not Cypher query semantics. Callers+ * need to distinguish a complete short result from one cut off by that budget.+ * An explicit LIMIT remains complete because it is part of the query itself. */+TEST(cypher_result_reports_max_rows_saturation) {+ cbm_store_t *s = cbm_store_open_memory();+ cbm_store_upsert_project(s, "sat", "/tmp/sat");++ for (int i = 0; i < 7; i++) {+ char name[32];+ char qn[64];+ snprintf(name, sizeof(name), "func%d", i);+ snprintf(qn, sizeof(qn), "sat.func%d", i);+ cbm_node_t n = {.project = "sat",+ .label = "Function",+ .name = name,+ .qualified_name = qn,+ .file_path = "test.c"};+ cbm_store_upsert_node(s, &n);+ }++ cbm_cypher_result_t r = {0};+ int rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN f.name", "sat", 3, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 3);+ ASSERT_TRUE(r.truncated);+ cbm_cypher_result_free(&r);++ memset(&r, 0, sizeof(r));+ rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN f.name", "sat", 10, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 7);+ ASSERT_FALSE(r.truncated);+ cbm_cypher_result_free(&r);++ memset(&r, 0, sizeof(r));+ rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN f.name LIMIT 3", "sat", 10, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 3);+ ASSERT_FALSE(r.truncated);+ cbm_cypher_result_free(&r);++ /* RETURN * historically keeps max_rows as its output cap even when a+ * larger Cypher LIMIT is present; preserve that behavior and report it. */+ memset(&r, 0, sizeof(r));+ rc = cbm_cypher_execute(s, "MATCH (f:Function) RETURN * LIMIT 5", "sat", 3, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 3);+ ASSERT_TRUE(r.truncated);+ cbm_cypher_result_free(&r);++ cbm_store_close(s);+ PASS();+}++/* An unlabeled scan has a max_rows*10 candidate budget. Aggregation can hide+ * that loss behind one output row, so row_count alone cannot report it. */+TEST(cypher_result_reports_scan_saturation_before_aggregation) {+ cbm_store_t *s = cbm_store_open_memory();+ cbm_store_upsert_project(s, "scan_sat", "/tmp/scan_sat");++ for (int i = 0; i < 11; i++) {+ char name[32];+ char qn[64];+ snprintf(name, sizeof(name), "node%d", i);+ snprintf(qn, sizeof(qn), "scan_sat.node%d", i);+ cbm_node_t n = {+ .project = "scan_sat", .label = "Function", .name = name, .qualified_name = qn};+ cbm_store_upsert_node(s, &n);+ }++ cbm_cypher_result_t r = {0};+ int rc = cbm_cypher_execute(s, "MATCH (n) RETURN count(*) AS n", "scan_sat", 1, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 1);+ ASSERT_STR_EQ(r.rows[0][0], "10");+ ASSERT_TRUE(r.truncated);+ cbm_cypher_result_free(&r);++ memset(&r, 0, sizeof(r));+ rc = cbm_cypher_execute(s, "MATCH (n) RETURN count(*) AS n", "scan_sat", 2, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 1);+ ASSERT_STR_EQ(r.rows[0][0], "11");+ ASSERT_FALSE(r.truncated);+ cbm_cypher_result_free(&r);++ cbm_store_close(s);+ PASS();+}++/* Variable-length traversal historically materializes at most 100 visited+ * nodes. Probe one extra candidate so an exact 100 is distinguishable from a+ * graph with additional reachable nodes, while preserving the 100-row output. */+TEST(cypher_result_reports_variable_length_candidate_saturation) {+ cbm_store_t *s = cbm_store_open_memory();+ cbm_store_upsert_project(s, "bfs_sat", "/tmp/bfs_sat");++ cbm_node_t root = {.project = "bfs_sat",+ .label = "Function",+ .name = "root",+ .qualified_name = "bfs_sat.root"};+ int64_t root_id = cbm_store_upsert_node(s, &root);+ for (int i = 0; i < 101; i++) {+ char name[32];+ char qn[64];+ snprintf(name, sizeof(name), "target%03d", i);+ snprintf(qn, sizeof(qn), "bfs_sat.target%03d", i);+ cbm_node_t target = {+ .project = "bfs_sat", .label = "Var", .name = name, .qualified_name = qn};+ int64_t target_id = cbm_store_upsert_node(s, &target);+ cbm_edge_t edge = {+ .project = "bfs_sat", .source_id = root_id, .target_id = target_id, .type = "CALLS"};+ cbm_store_insert_edge(s, &edge);+ }++ cbm_cypher_result_t r = {0};+ int rc = cbm_cypher_execute(s,+ "MATCH (a:Function {name: \"root\"})-[:CALLS*1..2]->(b:Var) "+ "RETURN b.name",+ "bfs_sat", 1000, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 100);+ ASSERT_TRUE(r.truncated);++ cbm_cypher_result_free(&r);+ cbm_store_close(s);+ PASS();+}+/* ══════════════════════════════════════════════════════════════════* PHASE 1: SIMPLE OPERATORS* ══════════════════════════════════════════════════════════════════ */@@ -4360,6 +4500,9 @@ SUITE(cypher) {RUN_TEST(cypher_edge_filter_regex);RUN_TEST(cypher_edge_builtin_type_filter);RUN_TEST(cypher_apply_limit);+ RUN_TEST(cypher_result_reports_max_rows_saturation);+ RUN_TEST(cypher_result_reports_scan_saturation_before_aggregation);+ RUN_TEST(cypher_result_reports_variable_length_candidate_saturation);/* Phase 1: Simple operators */RUN_TEST(cypher_lex_neq_operators);RUN_TEST(cypher_lex_ends_keyword);diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.cindex 43bf5eb78..991506a74 100644--- a/tests/test_daemon_runtime.c+++ b/tests/test_daemon_runtime.c@@ -2079,6 +2079,8 @@ TEST(daemon_runtime_activation_ack_snapshots_then_interrupts_all_clients) {bool second_interrupted = false;bool exited = false;atomic_store_explicit(&runtime_activation_shutdown_log_seen, false, memory_order_release);+ CBMLogLevel previous_log_level = cbm_log_get_level();+ cbm_log_set_level(CBM_LOG_INFO);cbm_log_set_sink(runtime_test_activation_shutdown_sink);if (started) {@@ -2095,6 +2097,7 @@ TEST(daemon_runtime_activation_ack_snapshots_then_interrupts_all_clients) {second_interrupted = !cbm_daemon_runtime_client_heartbeat(second, RUNTIME_TEST_TIMEOUT_MS);}cbm_log_set_sink(NULL);+ cbm_log_set_level(previous_log_level);if (first) {(void)cbm_daemon_runtime_client_close(first, RUNTIME_TEST_TIMEOUT_MS);first = NULL;diff --git a/tests/test_httpd.c b/tests/test_httpd.cindex 3ac680197..8cc0c1772 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -1172,19 +1172,26 @@ TEST(ui_server_mutations_require_json_content_type) {TEST(ui_server_rpc_allows_only_ui_read_tools) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);- const char *body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","- "\"params\":{\"name\":\"list_projects\",\"arguments\":{}}}";char req[1024];- snprintf(req, sizeof(req),- "POST /rpc HTTP/1.1\r\n"- "Content-Type: application/json\r\n"- "Content-Length: %d\r\n\r\n%s",- (int)strlen(body), body);char resp[8192];- int n = th_http(cbm_http_server_port(ts.srv), req, resp, sizeof(resp));- ASSERT_GT(n, 0);- ASSERT_EQ(th_status(resp), 200);- ASSERT_NOT_NULL(strstr(resp, "\"jsonrpc\""));+ int n = 0;+ static const char *allowed_tools[] = {"list_projects", "get_graph_schema", "get_code_snippet"};+ for (size_t i = 0; i < sizeof(allowed_tools) / sizeof(allowed_tools[0]); i++) {+ char body[512];+ snprintf(body, sizeof(body),+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"%s\",\"arguments\":{}}}",+ allowed_tools[i]);+ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\n"+ "Content-Type: application/json\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ strlen(body), body);+ n = th_http(cbm_http_server_port(ts.srv), req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"jsonrpc\""));+ }static const char *blocked_tools[] = {"delete_project", "manage_adr", "ingest_traces","index_repository"};diff --git a/tests/test_incremental.c b/tests/test_incremental.cindex 7ae91f971..c94afedda 100644--- a/tests/test_incremental.c+++ b/tests/test_incremental.c@@ -1568,26 +1568,29 @@ TEST(tool_qg_two_hop) {TEST(tool_qg_max_rows) {double ms;- /* Query without max_rows — gets many results */+ /* Query without max_rows — its explicit Cypher LIMIT is the visible cap. */char *r1 = call_tool_timed("query_graph", &ms,"{\"project\":\"%s\",""\"query\":\"MATCH (n:Function) RETURN n.name LIMIT 100\"}",g_project);TOOL_OK(r1, ms);- int total_unlimited = count_in_response(r1, "total");+ int returned_unlimited = count_in_response(r1, "returned");free(r1);- /* Same query without LIMIT but with max_rows=3 — must cap results */+ /* max_rows caps presentation, not evaluation: returned is bounded while+ * total remains the exact full materialized count. */char *r2 = call_tool_timed("query_graph", &ms,"{\"project\":\"%s\",""\"query\":\"MATCH (n:Function) RETURN n.name\",""\"max_rows\":3}",g_project);TOOL_OK(r2, ms);+ int returned_limited = count_in_response(r2, "returned");int total_limited = count_in_response(r2, "total");- ASSERT_LTE(total_limited, 3);- /* Without max_rows should have more than with */- ASSERT_GT(total_unlimited, total_limited);+ ASSERT_EQ(returned_limited, 3);+ ASSERT_GT(total_limited, returned_limited);+ ASSERT_GT(returned_unlimited, returned_limited);+ ASSERT_NOT_NULL(strstr(r2, "page_limit"));free(r2);PASS();}@@ -2262,8 +2265,11 @@ TEST(tool_qg_max_rows_1) {"\"max_rows\":1}",g_project);TOOL_OK(r, ms);+ int returned = count_in_response(r, "returned");int total = count_in_response(r, "total");- ASSERT_EQ(total, 1);+ ASSERT_EQ(returned, 1);+ ASSERT_GT(total, returned);+ ASSERT_NOT_NULL(strstr(r, "page_limit"));free(r);PASS();}diff --git a/tests/test_index_resilience.c b/tests/test_index_resilience.cindex 14909a4e4..20799dd67 100644--- a/tests/test_index_resilience.c+++ b/tests/test_index_resilience.c@@ -392,7 +392,7 @@ TEST(index_parse_partial_reported) {ASSERT_TRUE(marked);char qargs[900];- snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\"}", lp.project);+ snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\",\"diagnostics\":\"full\"}", lp.project);char *qresp = cbm_mcp_handle_tool(lp.srv, "index_status", qargs);ASSERT_NOT_NULL(qresp);ASSERT_NOT_NULL(strstr(qresp, "split.c"));@@ -516,7 +516,7 @@ TEST(index_parse_partial_clears_on_fix) {/* Flagged after the first (full) index. */char qargs[900];- snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\"}", lp.project);+ snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\",\"diagnostics\":\"full\"}", lp.project);char *cov1 = cbm_mcp_handle_tool(lp.srv, "index_status", qargs);ASSERT_NOT_NULL(cov1);ASSERT_NOT_NULL(strstr(cov1, "flaky.c"));@@ -635,7 +635,7 @@ TEST(index_not_indexed_by_design_reported) {/* index_status carries the persisted by-design section. */char qargs[900];- snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\"}", lp.project);+ snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\",\"diagnostics\":\"full\"}", lp.project);char *sresp = cbm_mcp_handle_tool(lp.srv, "index_status", qargs);ASSERT_NOT_NULL(sresp);ASSERT_NOT_NULL(strstr(sresp, "not_indexed"));@@ -663,6 +663,7 @@ TEST(index_not_indexed_by_design_reported) {char *resp2 = cbm_mcp_handle_tool(lp.srv, "index_repository", iargs);ASSERT_NOT_NULL(resp2);free(resp2);+ snprintf(qargs, sizeof(qargs), "{\"project\":\"%s\",\"diagnostics\":\"full\"}", lp.project);char *sresp2 = cbm_mcp_handle_tool(lp.srv, "index_status", qargs);ASSERT_NOT_NULL(sresp2);ASSERT_NOT_NULL(strstr(sresp2, "secret.py"));diff --git a/tests/test_log.c b/tests/test_log.cindex 562768567..3dcfd35d4 100644--- a/tests/test_log.c+++ b/tests/test_log.c@@ -55,15 +55,29 @@ static const char *capture_end(void) {}TEST(log_level_default) {- /* Default level should be INFO */+ /* Routine informational output is opt-in; libraries start quiet. */+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);+ PASS();+}++TEST(log_level_env_keeps_info_and_debug_opt_in) {+ cbm_setenv("CBM_LOG_LEVEL", "info", 1);+ cbm_log_init_from_env();ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);++ cbm_setenv("CBM_LOG_LEVEL", "debug", 1);+ cbm_log_init_from_env();+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_DEBUG);++ cbm_unsetenv("CBM_LOG_LEVEL");+ cbm_log_set_level(CBM_LOG_WARN);PASS();}TEST(log_level_set) {cbm_log_set_level(CBM_LOG_WARN);ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);- cbm_log_set_level(CBM_LOG_INFO); /* restore */+ cbm_log_set_level(CBM_LOG_WARN); /* restore */PASS();}@@ -72,7 +86,7 @@ TEST(log_info_output) {capture_start();cbm_log_info("test.msg", "key1", "val1", "key2", "val2");const char *output = capture_end();- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "level=info"));ASSERT(cbm_str_contains_raw(output, "msg=test.msg"));@@ -86,7 +100,7 @@ TEST(log_filtered_by_level) {capture_start();cbm_log_info("should.not.appear");const char *output = capture_end();- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);/* Should be empty — info is below warn threshold */ASSERT_EQ(strlen(output), 0);@@ -98,7 +112,7 @@ TEST(log_error_output) {capture_start();cbm_log_error("critical.fail", "err", "OOM");const char *output = capture_end();- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "level=error"));ASSERT(cbm_str_contains_raw(output, "msg=critical.fail"));@@ -111,7 +125,7 @@ TEST(log_int_helper) {capture_start();cbm_log_int(CBM_LOG_INFO, "pass.timing", "elapsed_ms", 42);const char *output = capture_end();- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "elapsed_ms=42"));PASS();@@ -124,7 +138,7 @@ TEST(log_json_output) {cbm_log_info("test.msg", "key1", "val1", "key2", "line\nbreak");const char *output = capture_end();cbm_log_set_format(CBM_LOG_FORMAT_TEXT);- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "\"level\":\"info\""));ASSERT(cbm_str_contains_raw(output, "\"event\":\"test.msg\""));@@ -139,7 +153,7 @@ TEST(log_text_sanitizes_control_chars) {capture_start();cbm_log_info("test\nmsg", "key", "line\r\nbreak\tvalue");const char *output = capture_end();- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "msg=test_msg"));ASSERT(cbm_str_contains_raw(output, "key=line__break_value"));@@ -157,7 +171,7 @@ TEST(log_sink_tee_keeps_stderr) {cbm_log_info("tee.msg", "key", "val");const char *output = capture_end();cbm_log_set_sink(NULL);- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "msg=tee.msg"));ASSERT(cbm_str_contains_raw(sink_buf, "msg=tee.msg"));@@ -171,7 +185,7 @@ TEST(log_operational_helpers) {cbm_log_mcp_request("tools/call", "search_graph", false, 1250);cbm_log_http_request("graph_ui", "GET", "/api/layout", 200, 7, 0, 42);const char *output = capture_end();- cbm_log_set_level(CBM_LOG_INFO);+ cbm_log_set_level(CBM_LOG_WARN);ASSERT(cbm_str_contains_raw(output, "msg=mcp.request"));ASSERT(cbm_str_contains_raw(output, "protocol=jsonrpc"));@@ -235,7 +249,7 @@ TEST(log_level_from_env_textual) {ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);cbm_unsetenv("CBM_LOG_LEVEL");- cbm_log_set_level(CBM_LOG_INFO); /* restore */+ cbm_log_set_level(CBM_LOG_WARN); /* restore */PASS();}@@ -260,7 +274,7 @@ TEST(log_level_from_env_numeric) {ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);cbm_unsetenv("CBM_LOG_LEVEL");- cbm_log_set_level(CBM_LOG_INFO); /* restore */+ cbm_log_set_level(CBM_LOG_WARN); /* restore */PASS();}@@ -279,12 +293,13 @@ TEST(log_level_from_env_invalid_ignored) {cbm_log_init_from_env();ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);- cbm_log_set_level(CBM_LOG_INFO); /* restore */+ cbm_log_set_level(CBM_LOG_WARN); /* restore */PASS();}SUITE(log) {RUN_TEST(log_level_default);+ RUN_TEST(log_level_env_keeps_info_and_debug_opt_in);RUN_TEST(log_level_set);RUN_TEST(log_info_output);RUN_TEST(log_filtered_by_level);diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex dc7716b14..7d5d3d593 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -681,6 +681,282 @@ TEST(tree_cell_sanitizes_control_and_invalid_utf8) {PASS();}+TEST(json_to_tree_uses_header_once_rows_without_losing_metadata) {+ const char *json =+ "{\"projects\":[{\"name\":\"alpha\",\"nodes\":10},{\"name\":\"beta\",\"nodes\":20}],"+ "\"total\":2,\"has_more\":false,\"nested\":{\"warning\":\"keep me\"}}";+ char *tree = cbm_json_to_tree(json);+ ASSERT_NOT_NULL(tree);+ ASSERT_STR_EQ(tree, "projects: 2 (cols: name nodes)\n"+ " alpha 10\n"+ " beta 20\n"+ "total: 2\n"+ "has_more: false\n"+ "nested:\n"+ " warning: \"keep me\"\n");+ free(tree);+ PASS();+}++TEST(json_to_tree_keeps_multiline_source_readable) {+ const char *json = "{\"source\":\"int main(void) {\\n\\treturn 0;\\n}\","+ "\"content\":\"# Decision\\n\\nKeep graph answers compact.\\n\"}";+ char *tree = cbm_json_to_tree(json);+ ASSERT_NOT_NULL(tree);+ ASSERT_STR_EQ(tree, "source: |-\n"+ " int main(void) {\n"+ " \treturn 0;\n"+ " }\n"+ "content: |\n"+ " # Decision\n"+ " \n"+ " Keep graph answers compact.\n");+ ASSERT_NULL(strstr(tree, "\\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. */+static bool profiled_single_column_round_trips(const char *output, const char *key,+ const char *const *expected, int expected_count) {+ char refs_header[128];+ char rows_header[128];+ snprintf(refs_header, sizeof(refs_header), "%s_refs:", key);+ snprintf(rows_header, sizeof(rows_header), "\n%s:", key);+ const char *refs = strstr(output, refs_header);+ const char *rows = refs ? strstr(refs, rows_header) : NULL;+ if (!refs || !rows) {+ return false;+ }+ const char *line = strchr(refs, '\n');+ if (!line) {+ return false;+ }+ line++;+ char *prefixes[16] = {0};+ while (line < rows && line[0] == ' ' && line[1] == ' ') {+ char *end = NULL;+ long id = strtol(line + 2, &end, 10);+ if (id < 0 || id >= 16 || !end || *end != ' ') {+ goto fail;+ }+ const char *prefix = end + 1;+ const char *newline = strchr(prefix, '\n');+ if (!newline || newline > rows) {+ goto fail;+ }+ prefixes[id] = cbm_strndup(prefix, (size_t)(newline - prefix));+ if (!prefixes[id]) {+ goto fail;+ }+ line = newline + 1;+ }+ line = strchr(rows + 1, '\n');+ if (!line) {+ goto fail;+ }+ line++;+ for (int row = 0; row < expected_count; row++) {+ if (line[0] != ' ' || line[1] != ' ') {+ goto fail;+ }+ const char *value = line + 2;+ const char *newline = strchr(value, '\n');+ if (!newline) {+ goto fail;+ }+ char *decoded = NULL;+ if (value[0] == '@' && isdigit((unsigned char)value[1])) {+ char *ref_end = NULL;+ long id = strtol(value + 1, &ref_end, 10);+ if (id < 0 || id >= 16 || !ref_end || *ref_end != '+' || !prefixes[id]) {+ goto fail;+ }+ size_t prefix_len = strlen(prefixes[id]);+ size_t suffix_len = (size_t)(newline - (ref_end + 1));+ decoded = malloc(prefix_len + suffix_len + 1U);+ if (!decoded) {+ goto fail;+ }+ memcpy(decoded, prefixes[id], prefix_len);+ memcpy(decoded + prefix_len, ref_end + 1, suffix_len);+ decoded[prefix_len + suffix_len] = '\0';+ } else {+ decoded = cbm_strndup(value, (size_t)(newline - value));+ }+ bool equal = decoded && strcmp(decoded, expected[row]) == 0;+ free(decoded);+ if (!equal) {+ goto fail;+ }+ line = newline + 1;+ }+ for (int i = 0; i < 16; i++) {+ free(prefixes[i]);+ }+ return true;++fail:+ for (int i = 0; i < 16; i++) {+ free(prefixes[i]);+ }+ return false;+}++TEST(tree_table_uses_prefix_dictionary_only_when_it_materially_wins) {+ enum { ROWS = 20, COLS = 3 };+ const char *cols[COLS] = {"qn", "file", "literal"};+ const char *cells[ROWS * COLS];+ char qns[ROWS][128];+ char literals[ROWS][64];+ for (int i = 0; i < ROWS; i++) {+ snprintf(qns[i], sizeof(qns[i]), "cbm-lean-output.tests.test_c_lsp.function_%02d", i);+ snprintf(literals[i], sizeof(literals[i]), "@0+literal_%02d", i);+ cells[i * COLS] = qns[i];+ cells[i * COLS + 1] = "tests/test_c_lsp.c";+ cells[i * COLS + 2] = literals[i];+ }+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ const bool prefix_cols[COLS] = {true, true, false};+ cbm_tree_table_rows_profiled(&sb, "rows", ROWS, cols, COLS, cells, NULL, prefix_cols);+ char *out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NOT_NULL(strstr(out, "rows_refs:"));+ ASSERT_NOT_NULL(strstr(out, "rows_ref_rule: @N+suffix=prefix+suffix"));+ ASSERT_NOT_NULL(strstr(out, "cbm-lean-output.tests.test_c_lsp."));+ ASSERT_NOT_NULL(strstr(out, "@0+function_00"));+ ASSERT_NOT_NULL(strstr(out, "tests/test_c_lsp.c"));+ ASSERT_NOT_NULL(strstr(out, "@1+")); /* exact repeated value: empty suffix */+ ASSERT_NOT_NULL(strstr(out, "\"@0+literal_00\"")); /* data, not a ref */+ ASSERT_LT((int)strlen(out), 1200);+ size_t compact_len = strlen(out);+ free(out);++ cbm_sb_init(&sb);+ cbm_tree_table_rows_typed(&sb, "rows", ROWS, cols, COLS, cells, NULL);+ char *direct = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(direct);+ ASSERT_TRUE(compact_len + 64U <= strlen(direct));+ ASSERT_TRUE(compact_len * 100U <= strlen(direct) * 85U);+ free(direct);++ const char *typed_cols[COLS] = {"path", "type", "children"};+ const bool string_cols[COLS] = {true, true, false};+ const bool typed_prefix_cols[COLS] = {true, false, false};+ const char *typed_cells[ROWS * COLS];+ char paths[ROWS][128];+ char children[ROWS][8];+ for (int i = 0; i < ROWS; i++) {+ snprintf(paths[i], sizeof(paths[i]), "services/orders/internal/handlers/file_%02d.go", i);+ snprintf(children[i], sizeof(children[i]), "%d", i + 1);+ typed_cells[i * COLS] = paths[i];+ typed_cells[i * COLS + 1] = "file";+ typed_cells[i * COLS + 2] = children[i];+ }+ cbm_sb_init(&sb);+ cbm_tree_table_rows_profiled(&sb, "file_tree", ROWS, typed_cols, COLS, typed_cells, string_cols,+ typed_prefix_cols);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NOT_NULL(strstr(out, "file_tree_refs:"));+ ASSERT_NOT_NULL(strstr(out, "services/orders/internal/handlers/"));+ ASSERT_NOT_NULL(strstr(out, "@0+file_00.go file 1"));+ ASSERT_NULL(strstr(out, "file \"1\""));+ free(out);++ const char *small_cols[] = {"qn", "file"};+ const char *small_cells[] = {"alpha.long.qualified.Name", "src/a.c", "beta.long.qualified.Name",+ "src/b.c"};+ cbm_sb_init(&sb);+ cbm_tree_table_rows(&sb, "rows", 2, small_cols, 2, small_cells);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NULL(strstr(out, "rows_refs:"));+ ASSERT_NOT_NULL(strstr(out, "alpha.long.qualified.Name src/a.c"));+ free(out);++ /* Arbitrary string columns stay literal unless the caller explicitly marks+ * them as semantic paths/QNs. */+ cbm_sb_init(&sb);+ cbm_tree_table_rows(&sb, "rows", ROWS, cols, COLS, cells);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NULL(strstr(out, "rows_refs:"));+ ASSERT_NOT_NULL(strstr(out, "cbm-lean-output.tests.test_c_lsp.function_00"));+ free(out);++ /* Decode every emitted reference across Unix, Windows, C++ and UTF-8+ * semantic boundaries, including an exact repeat with an empty suffix. */+ enum { ROUNDTRIP_ROWS = 36 };+ char roundtrip_values[ROUNDTRIP_ROWS][128];+ const char *roundtrip_cells[ROUNDTRIP_ROWS];+ for (int i = 0; i < ROUNDTRIP_ROWS; i++) {+ if (i < 8) {+ snprintf(roundtrip_values[i], sizeof(roundtrip_values[i]),+ "services/orders/internal/handlers/file_%02d.go", i);+ } else if (i < 16) {+ snprintf(roundtrip_values[i], sizeof(roundtrip_values[i]),+ "acme::orders::handlers::function_%02d", i);+ } else if (i < 24) {+ snprintf(roundtrip_values[i], sizeof(roundtrip_values[i]),+ "C:\\workspace\\orders\\handlers\\file_%02d.cpp", i);+ } else if (i < 32) {+ snprintf(roundtrip_values[i], sizeof(roundtrip_values[i]),+ "paket.über.modul.handler_%02d", i);+ } else {+ snprintf(roundtrip_values[i], sizeof(roundtrip_values[i]),+ "services/orders/shared/exact/value.go");+ }+ roundtrip_cells[i] = roundtrip_values[i];+ }+ const char *roundtrip_cols[] = {"path"};+ const bool roundtrip_string_cols[] = {true};+ const bool roundtrip_prefix_cols[] = {true};+ cbm_sb_init(&sb);+ cbm_tree_table_rows_profiled(&sb, "roundtrip", ROUNDTRIP_ROWS, roundtrip_cols, 1,+ roundtrip_cells, roundtrip_string_cols, roundtrip_prefix_cols);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NOT_NULL(strstr(out, "roundtrip_refs:"));+ ASSERT_TRUE(+ profiled_single_column_round_trips(out, "roundtrip", roundtrip_cells, ROUNDTRIP_ROWS));+ free(out);++ /* A declaration that itself resembles a ref is quoted and remains a+ * literal: directory expansion applies only to the sibling data table. */+ char refish_values[ROWS][96];+ const char *refish_cells[ROWS];+ for (int i = 0; i < ROWS; i++) {+ snprintf(refish_values[i], sizeof(refish_values[i]), "@0+namespace.component.member_%02d",+ i);+ refish_cells[i] = refish_values[i];+ }+ cbm_sb_init(&sb);+ cbm_tree_table_rows_profiled(&sb, "refish", ROWS, roundtrip_cols, 1, refish_cells,+ roundtrip_string_cols, roundtrip_prefix_cols);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NOT_NULL(strstr(out, "\"@0+namespace.component.\""));+ ASSERT_NOT_NULL(strstr(out, " @0+member_00\n"));+ free(out);++ for (int i = 0; i < ROWS; i++) {+ snprintf(refish_values[i], sizeof(refish_values[i]), "123456789012.member_%02d", i);+ }+ cbm_sb_init(&sb);+ cbm_tree_table_rows_profiled(&sb, "numeric_prefix", ROWS, roundtrip_cols, 1, refish_cells,+ roundtrip_string_cols, roundtrip_prefix_cols);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_NOT_NULL(strstr(out, "\"123456789012.\""));+ ASSERT_NOT_NULL(strstr(out, " @0+member_00\n"));+ free(out);+ PASS();+}+/* ══════════════════════════════════════════════════════════════════* JSON-RPC PARSING* ══════════════════════════════════════════════════════════════════ */@@ -918,13 +1194,48 @@ TEST(mcp_tools_list_latest_metadata) {* relationships used for call/reference/type centrality, not every edge* family (for example DEFINES or CONTAINS_FILE). Keep the public contract* aligned with the store query. */- ASSERT_NOT_NULL(strstr(json, "in/out = selected degree across CALLS, USAGE, CALL_REFERENCE, "- "INHERITS, and IMPLEMENTS"));+ ASSERT_NOT_NULL(strstr(json, "Regex rows keep qn/file/lines and in/out over CALLS"));+ ASSERT_NOT_NULL(strstr(json, "USAGE"));+ ASSERT_NOT_NULL(strstr(json, "CALL_REFERENCE"));+ ASSERT_NOT_NULL(strstr(json, "INHERITS"));+ ASSERT_NOT_NULL(strstr(json, "IMPLEMENTS"));ASSERT_NULL(strstr(json, "TOTAL degree across ALL edge types"));free(json);PASS();}+TEST(mcp_metadata_byte_budget) {+ /* Tool metadata is paid on discovery before any graph answer is returned.+ * Byte ceilings are deterministic across tokenizers and force deliberate+ * review when a schema or new tool grows the model-visible baseline. */+ char *init = cbm_mcp_initialize_response(NULL);+ ASSERT_NOT_NULL(init);+ ASSERT_LT((int)strlen(init), 512);+ free(init);++ char *json = cbm_mcp_tools_list();+ ASSERT_NOT_NULL(json);+ ASSERT_LT((int)strlen(json), 16 * 1024);++ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *tools = yyjson_obj_get(yyjson_doc_get_root(doc), "tools");+ ASSERT_NOT_NULL(tools);+ ASSERT_EQ((int)yyjson_arr_size(tools), cbm_mcp_tool_count());+ size_t idx;+ size_t max;+ yyjson_val *tool;+ yyjson_arr_foreach(tools, idx, max, tool) {+ char *serialized = yyjson_val_write(tool, 0, NULL);+ ASSERT_NOT_NULL(serialized);+ ASSERT_LT((int)strlen(serialized), 3200);+ free(serialized);+ }+ yyjson_doc_free(doc);+ free(json);+ PASS();+}+TEST(mcp_tools_have_behavior_annotations) {struct {const char *name;@@ -2028,6 +2339,112 @@ TEST(tool_search_graph_semantic_only_skips_structural_results_issue1295) {PASS();}+/* A singleton dotless QN is smaller as a direct row than as a one-entry group.+ * The adaptive tree must preserve it byte-for-byte without paying a grouping+ * rule; structured JSON retains its stable grouped machine shape. */+TEST(tool_search_graph_grouped_dotless_qn_round_trips) {+ 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 = "search-dotless-qn";+ const char *qualified_name = "__route__ANY__/api/adr";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/search-dotless-qn"), CBM_STORE_OK);+ cbm_node_t route = {.project = project,+ .label = "Route",+ .name = "dotless_route",+ .qualified_name = qualified_name,+ .file_path = "src/routes.c",+ .start_line = 7,+ .end_line = 7};+ ASSERT_GT(cbm_store_upsert_node(store, &route), 0);++ const char *tree_args =+ "{\"project\":\"search-dotless-qn\",\"name_pattern\":\"dotless_route\"}";+ char *response = cbm_mcp_handle_tool(srv, "search_graph", tree_args);+ char *tree = extract_text_content(response);+ ASSERT_NOT_NULL(tree);+ ASSERT_NULL(strstr(tree, "group prefix"));+ ASSERT_NOT_NULL(strstr(tree, "(cols: qn label file lines in out)"));+ ASSERT_NOT_NULL(strstr(tree, "__route__ANY__/api/adr Route src/routes.c 7-7"));+ ASSERT_NULL(strstr(tree, ".__route__ANY__/api/adr"));+ free(tree);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "search_graph",+ "{\"project\":\"search-dotless-qn\",\"name_pattern\":\"dotless_route\","+ "\"format\":\"json\"}");+ char *json = extract_text_content(response);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "qn_rule")),+ "qn = qn_prefix == \"\" ? name : qn_prefix + \".\" + name");+ yyjson_val *groups = yyjson_obj_get(root, "groups");+ ASSERT_NOT_NULL(groups);+ ASSERT_EQ(yyjson_arr_size(groups), 1);+ yyjson_val *group = yyjson_arr_get_first(groups);+ const char *prefix = yyjson_get_str(yyjson_obj_get(group, "qn_prefix"));+ ASSERT_NOT_NULL(prefix);+ ASSERT_STR_EQ(prefix, "");+ yyjson_val *rows = yyjson_obj_get(group, "rows");+ ASSERT_NOT_NULL(rows);+ ASSERT_EQ(yyjson_arr_size(rows), 1);+ const char *name = yyjson_get_str(yyjson_arr_get(yyjson_arr_get_first(rows), 0));+ ASSERT_NOT_NULL(name);+ char reconstructed[128];+ if (prefix[0]) {+ snprintf(reconstructed, sizeof(reconstructed), "%s.%s", prefix, name);+ } else {+ snprintf(reconstructed, sizeof(reconstructed), "%s", name);+ }+ ASSERT_STR_EQ(reconstructed, qualified_name);++ yyjson_doc_free(doc);+ free(json);+ free(response);+ cbm_mcp_server_free(srv);+ PASS();+}++static yyjson_val *trace_grouped_row_named(yyjson_val *leg, const char *name,+ const char **prefix_out) {+ if (prefix_out) {+ *prefix_out = NULL;+ }+ yyjson_val *groups = leg ? yyjson_obj_get(leg, "groups") : NULL;+ if (!groups || !yyjson_is_arr(groups)) {+ return NULL;+ }+ size_t group_index;+ size_t group_max;+ yyjson_val *group;+ yyjson_arr_foreach(groups, group_index, group_max, group) {+ yyjson_val *rows = yyjson_obj_get(group, "rows");+ if (!rows || !yyjson_is_arr(rows)) {+ continue;+ }+ size_t row_index;+ size_t row_max;+ yyjson_val *row;+ yyjson_arr_foreach(rows, row_index, row_max, row) {+ yyjson_val *row_name = yyjson_is_arr(row) ? yyjson_arr_get(row, 0) : NULL;+ if (!row_name || !yyjson_is_str(row_name) ||+ strcmp(yyjson_get_str(row_name), name) != 0) {+ continue;+ }+ if (prefix_out) {+ *prefix_out = yyjson_get_str(yyjson_obj_get(group, "qn_prefix"));+ }+ return row;+ }+ }+ return NULL;+}+/* callers_total/callees_total must count what the caller can enumerate: with* include_tests=false (default) test-file rows are hidden from the table, so* the totals must apply the same filter — a raw visited_count overstated the@@ -2182,6 +2599,12 @@ TEST(tool_get_architecture_cycles_detects_scc) {cbm_store_upsert_project(st, proj, "/tmp/cyc");const char *names[5] = {"A", "B", "C", "D", "E"};+ enum { LONG_CYCLE_QN_BYTES = 2500 };+ char *long_cycle_qn = malloc(LONG_CYCLE_QN_BYTES + 16U);+ ASSERT_NOT_NULL(long_cycle_qn);+ memcpy(long_cycle_qn, "cycproj.m.", 10U);+ memset(long_cycle_qn + 10U, 'x', LONG_CYCLE_QN_BYTES);+ memcpy(long_cycle_qn + 10U + LONG_CYCLE_QN_BYTES, ".A", 3U);int64_t id[5];for (int i = 0; i < 5; i++) {char qn[32];@@ -2189,7 +2612,7 @@ TEST(tool_get_architecture_cycles_detects_scc) {cbm_node_t n = {.project = proj,.label = "Function",.name = names[i],- .qualified_name = qn,+ .qualified_name = i == 0 ? long_cycle_qn : qn,.file_path = "m.c",.start_line = i + 1,.end_line = i + 2};@@ -2216,13 +2639,39 @@ TEST(tool_get_architecture_cycles_detects_scc) {char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);ASSERT_NOT_NULL(strstr(inner, "cycles: 1")); /* exactly one SCC of size>1 */- ASSERT_NOT_NULL(strstr(inner, "cycproj.m.A"));+ ASSERT_NOT_NULL(strstr(inner, long_cycle_qn));ASSERT_NOT_NULL(strstr(inner, "cycproj.m.B"));ASSERT_NOT_NULL(strstr(inner, "cycproj.m.C"));ASSERT_NULL(strstr(inner, "cycproj.m.D")); /* acyclic node not in any cycle */free(inner);free(resp);+ resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":711,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"get_architecture\",\"arguments\":{\"project\":\"cycproj\","+ "\"aspects\":[\"cycles\"],\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ yyjson_doc *cycle_doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(cycle_doc);+ yyjson_val *cycles = yyjson_obj_get(yyjson_doc_get_root(cycle_doc), "cycles");+ yyjson_val *cycle = yyjson_arr_get_first(cycles);+ yyjson_val *members = cycle ? yyjson_obj_get(cycle, "members") : NULL;+ bool found_long_qn = false;+ size_t member_index, member_max;+ yyjson_val *member;+ yyjson_arr_foreach(members, member_index, member_max, member) {+ const char *value = yyjson_get_str(member);+ if (value && strcmp(value, long_cycle_qn) == 0) {+ found_long_qn = true;+ }+ }+ ASSERT_TRUE(found_long_qn);+ yyjson_doc_free(cycle_doc);+ free(inner);+ free(resp);+/* default call (no aspects) must NOT run the scan. */resp = cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":72,\"method\":\"tools/call\",\"params\":{"@@ -2234,6 +2683,7 @@ TEST(tool_get_architecture_cycles_detects_scc) {free(inner);free(resp);cbm_mcp_server_free(srv);+ free(long_cycle_qn);PASS();}@@ -2283,10 +2733,43 @@ TEST(tool_get_code_snippet_clips_whole_file_node) {ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "source_mode: outline"));+ /* Container defaults carry the member outline, never raw whole-file source. */+ ASSERT_TRUE(strlen(inner) < 4000);+ ASSERT_NOT_NULL(strstr(inner, "end_line: 2000"));+ ASSERT_NULL(strstr(inner, "source_truncated"));+ ASSERT_NULL(strstr(inner, "next_start_line"));+ ASSERT_NULL(strstr(inner, "line_0000"));+ ASSERT_NULL(strstr(inner, "line_1999"));+ free(inner);+ free(resp);++ /* Explicit full is the compatibility/detail opt-in: without an explicit+ * token or line budget it reaches the established 500-line safety ceiling,+ * rather than inheriting auto mode's lean 2.5k-token estimate. */+ resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":72,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"get_code_snippet\",\"arguments\":{\"project\":\"test-project\","+ "\"qualified_name\":\"test-project.big\",\"source_mode\":\"full\","+ "\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "line_0499"));+ ASSERT_NULL(strstr(inner, "line_0500"));+ ASSERT_NOT_NULL(strstr(inner, "\"next_start_line\":501"));+ free(inner);+ free(resp);++ resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":71,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"get_code_snippet\",\"arguments\":{\"project\":\"test-project\","+ "\"qualified_name\":\"test-project.big\",\"source_mode\":\"full\","+ "\"max_output_tokens\":10000,\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);ASSERT_NOT_NULL(strstr(inner, "\"source_clipped\":true"));- /* The whole 2000-line file (~100KB) must NOT be in the response. */- ASSERT_TRUE(strlen(inner) < 60000);- /* The last line must be absent (clipped), the first present. */ASSERT_NOT_NULL(strstr(inner, "line_0000"));ASSERT_NULL(strstr(inner, "line_1999"));free(inner);@@ -2296,6 +2779,171 @@ TEST(tool_get_code_snippet_clips_whole_file_node) {PASS();}+TEST(tool_get_code_snippet_omits_over_budget_whole_line) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_snipwide_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char src_path[512];+ snprintf(src_path, sizeof(src_path), "%s/wide.c", tmp);+ FILE *fp = fopen(src_path, "wb");+ ASSERT_NOT_NULL(fp);+ fputs("void wide(void) { /* TOKEN_NEEDLE ", fp);+ for (int i = 0; i < 40000; i++) {+ fputc('x', fp);+ }+ fputs(" */ }\n", fp);+ fclose(fp);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "snippet-wide";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "wide",+ .qualified_name = "snippet-wide.wide",+ .file_path = "wide.c",+ .start_line = 1,+ .end_line = 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);++ char *response = cbm_mcp_handle_tool(+ srv, "get_code_snippet",+ "{\"project\":\"snippet-wide\",\"qualified_name\":\"snippet-wide.wide\","+ "\"format\":\"json\"}");+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_TRUE(strlen(inner) <= 2500U * 4U);+ ASSERT_NOT_NULL(strstr(inner, "\"source_omitted\":true"));+ ASSERT_NOT_NULL(strstr(inner, "\"truncation_reason\":\"output_budget\""));+ ASSERT_NOT_NULL(strstr(inner, "\"qualified_name\":\"snippet-wide.wide\""));+ ASSERT_NOT_NULL(strstr(inner, "wide.c"));+ ASSERT_NOT_NULL(strstr(inner, "\"start_line\":1"));+ ASSERT_NOT_NULL(strstr(inner, "\"end_line\":1"));+ ASSERT_NOT_NULL(strstr(inner, "\"original_end_line\":1"));+ ASSERT_NOT_NULL(strstr(inner, "\"source_lines_returned\":0"));+ ASSERT_NOT_NULL(strstr(inner, "\"continuation_requires_higher_budget\":true"));+ ASSERT_NOT_NULL(strstr(inner, "raise max_output_tokens"));+ ASSERT_NULL(strstr(inner, "next_start_line"));+ ASSERT_NULL(strstr(inner, "cursor"));+ ASSERT_NULL(strstr(inner, "TOKEN_NEEDLE"));+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(+ srv, "get_code_snippet",+ "{\"project\":\"snippet-wide\",\"qualified_name\":\"snippet-wide.wide\"}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "source_omitted: true"));+ ASSERT_NOT_NULL(strstr(inner, "qualified_name: snippet-wide.wide"));+ ASSERT_NOT_NULL(strstr(inner, "wide.c"));+ ASSERT_NOT_NULL(strstr(inner, "start_line: 1"));+ ASSERT_NOT_NULL(strstr(inner, "end_line: 1"));+ ASSERT_NOT_NULL(strstr(inner, "original_end_line: 1"));+ ASSERT_NOT_NULL(strstr(inner, "source_lines_returned: 0"));+ ASSERT_NOT_NULL(strstr(inner, "continuation_requires_higher_budget: true"));+ ASSERT_NOT_NULL(strstr(inner, "raise max_output_tokens"));+ ASSERT_NULL(strstr(inner, "next_start_line"));+ ASSERT_NULL(strstr(inner, "cursor"));+ ASSERT_NULL(strstr(inner, "TOKEN_NEEDLE"));+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(+ srv, "get_code_snippet",+ "{\"project\":\"snippet-wide\",\"qualified_name\":\"snippet-wide.wide\","+ "\"max_output_tokens\":20000,\"format\":\"json\"}");+ 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);+ const char *full_source = yyjson_get_str(yyjson_obj_get(root, "source"));+ ASSERT_NOT_NULL(full_source);+ ASSERT_EQ(strlen(full_source),+ strlen("void wide(void) { /* TOKEN_NEEDLE ") + 40000U + strlen(" */ }\n"));+ ASSERT_NOT_NULL(strstr(full_source, "TOKEN_NEEDLE"));+ ASSERT_STR_EQ(full_source + strlen(full_source) - strlen(" */ }\n"), " */ }\n");+ ASSERT_NULL(yyjson_obj_get(root, "source_omitted"));+ ASSERT_NULL(yyjson_obj_get(root, "continuation_requires_higher_budget"));+ yyjson_doc_free(doc);++ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cbm_unlink(src_path);+ cbm_rmdir(tmp);+ PASS();+}++TEST(tool_get_code_snippet_pages_outline_rows_to_exact_budget) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_snipoutline_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char src_path[512];+ snprintf(src_path, sizeof(src_path), "%s/module.py", tmp);+ FILE *fp = fopen(src_path, "wb");+ ASSERT_NOT_NULL(fp);+ for (int i = 0; i < 400; i++) {+ fprintf(fp, "# line %d\n", i + 1);+ }+ fclose(fp);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "snippet-outline";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);+ cbm_node_t module = {.project = project,+ .label = "Module",+ .name = "module",+ .qualified_name = "snippet-outline.very.long.package.module",+ .file_path = "module.py",+ .start_line = 1,+ .end_line = 400};+ ASSERT_GT(cbm_store_upsert_node(store, &module), 0);+ for (int i = 0; i < 80; i++) {+ char name[64];+ char qn[512];+ snprintf(name, sizeof(name), "member_%02d", i);+ snprintf(qn, sizeof(qn),+ "snippet-outline.very.long.package.module.subsystem.component.member_%02d", i);+ cbm_node_t member = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = qn,+ .file_path = "module.py",+ .start_line = i * 4 + 2,+ .end_line = i * 4 + 4};+ ASSERT_GT(cbm_store_upsert_node(store, &member), 0);+ }++ char *response =+ cbm_mcp_handle_tool(srv, "get_code_snippet",+ "{\"project\":\"snippet-outline\","+ "\"qualified_name\":\"snippet-outline.very.long.package.module\","+ "\"max_output_tokens\":128,\"format\":\"json\"}");+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_TRUE(strlen(inner) <= 128U * 4U);+ ASSERT_NOT_NULL(strstr(inner, "snippet-outline.very.long.package.module"));+ ASSERT_NOT_NULL(strstr(inner, "\"source_mode\":\"outline\""));+ ASSERT_NOT_NULL(strstr(inner, "\"members_has_more\":true"));+ ASSERT_NOT_NULL(strstr(inner, "\"next_member_offset\":"));+ ASSERT_NOT_NULL(strstr(inner, "\"truncation_reason\":\"output_budget\""));++ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cbm_unlink(src_path);+ cbm_rmdir(tmp);+ PASS();+}+/* EVERY tool, not just the one that was reported.** The duplication was invisible per-tool: each result looked reasonable on its@@ -2408,7 +3056,7 @@ TEST(tool_search_graph_includes_node_properties) {char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);ASSERT_NOT_NULL(strstr(inner, "results:")); /* TOON table header */- ASSERT_NOT_NULL(strstr(inner, "(rows: name label lines in out;"));+ ASSERT_NOT_NULL(strstr(inner, "(cols: qn label file lines in out)"));ASSERT_NOT_NULL(strstr(inner, "HandleRequest"));ASSERT_NULL(strstr(inner, "func HandleRequest")); /* signature not spilled */ASSERT_NULL(strstr(inner, "is_exported"));@@ -2476,25 +3124,106 @@ TEST(tool_search_graph_includes_node_properties) {PASS();}-TEST(tool_output_byte_budgets) {- /* GUARD: absolute byte ceilings on default tool outputs. Re-bloat (e.g.- * a property blob sneaking back into row emission — the fp field alone- * is ~450B/hit) blows these ceilings immediately. The numbers are- * generous vs the measured compact outputs (search hit rows ≈ 90B) but- * far below the legacy verbose sizes (≈1.5KB/hit). */+TEST(tool_index_status_keeps_authoritative_ignored_total_when_rows_are_sampled) {char tmp[256];cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);- /* search_graph: 1-hit search must stay under 600B. */- char *resp = cbm_mcp_server_handle(- srv, "{\"jsonrpc\":\"2.0\",\"id\":46,\"method\":\"tools/call\","- "\"params\":{\"name\":\"search_graph\","- "\"arguments\":{\"project\":\"test-project\",\"label\":\"Function\","- "\"name_pattern\":\"HandleRequest\",\"limit\":5}}}");- ASSERT_NOT_NULL(resp);- char *inner = extract_text_content(resp);- ASSERT_NOT_NULL(inner);+ cbm_coverage_row_t row = {+ .rel_path = "generated/ignored-0000.js", .kind = "not_indexed_file", .detail = "gitignore"};+ cbm_project_t project = {0};+ ASSERT_EQ(cbm_store_get_project(store, "test-project", &project), CBM_STORE_OK);+ ASSERT_NOT_NULL(project.indexed_at);+ cbm_coverage_meta_t meta = {.generation = project.indexed_at,+ .index_mode = "fast",+ .recorded_at = "2026-08-12T00:00:00Z",+ .recording_status = "truncated",+ .ignored_files_stored = 1,+ .ignored_files_total = 2500,+ .coverage_version = 1,+ .hash_records_complete = true};+ ASSERT_EQ(cbm_store_coverage_replace_ex(store, "test-project", &row, 1, &meta), CBM_STORE_OK);++ char *response = cbm_mcp_handle_tool(srv, "index_status",+ "{\"project\":\"test-project\",\"format\":\"json\"}");+ 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 *not_indexed = yyjson_obj_get(yyjson_doc_get_root(doc), "not_indexed");+ ASSERT_NOT_NULL(not_indexed);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(not_indexed, "files_count")), 2500);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(not_indexed, "files_omitted")), 2500);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(not_indexed, "truncated")));+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(not_indexed, "files")), 0);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(+ srv, "index_status",+ "{\"project\":\"test-project\",\"diagnostics\":\"full\",\"format\":\"json\"}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ not_indexed = yyjson_obj_get(yyjson_doc_get_root(doc), "not_indexed");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(not_indexed, "files_count")), 2500);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(not_indexed, "files_omitted")), 2499);+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(not_indexed, "files")), 1);+ ASSERT_NOT_NULL(strstr(inner, "generated/ignored-0000.js"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ /* A total from another index generation is diagnostic history, not the+ * exact count for the current graph. Keep the recorded row count and mark+ * its relation unknown instead of presenting stale metadata as truth. */+ meta.generation = "stale-generation";+ meta.ignored_files_total = 4000;+ ASSERT_EQ(cbm_store_coverage_replace_ex(store, "test-project", &row, 1, &meta), CBM_STORE_OK);+ response = cbm_mcp_handle_tool(srv, "index_status",+ "{\"project\":\"test-project\",\"format\":\"json\"}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ not_indexed = yyjson_obj_get(yyjson_doc_get_root(doc), "not_indexed");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(not_indexed, "files_count")), 1);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(not_indexed, "files_count_relation")), "gte");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(not_indexed, "files_omitted")), 1);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ cbm_project_free_fields(&project);++ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+}++TEST(tool_output_byte_budgets) {+ /* GUARD: absolute byte ceilings on default tool outputs. Re-bloat (e.g.+ * a property blob sneaking back into row emission — the fp field alone+ * is ~450B/hit) blows these ceilings immediately. The numbers are+ * generous vs the measured compact outputs (search hit rows ≈ 90B) but+ * far below the legacy verbose sizes (≈1.5KB/hit). */+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);++ /* search_graph: 1-hit search must stay under 600B. */+ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":46,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_graph\","+ "\"arguments\":{\"project\":\"test-project\",\"label\":\"Function\","+ "\"name_pattern\":\"HandleRequest\",\"limit\":5}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);ASSERT_NOT_NULL(strstr(inner, "HandleRequest")); /* non-vacuous: hit present */ASSERT_LT((int)strlen(inner), 600);free(inner);@@ -2590,11 +3319,18 @@ TEST(tool_lean_defaults_schema_and_status) {n.end_line = 2;n.properties_json = "{\"fp\":\"x\",\"sp\":\"y\",\"bt\":\"z\",\"complexity\":3}";ASSERT_GT(cbm_store_upsert_node(st, &n), 0);+ ASSERT_EQ(cbm_store_upsert_file_hash(st, "test-project", "src/lean-default-partial.c",+ "fixture", 1, 1),+ CBM_STORE_OK);+ cbm_coverage_row_t coverage = {+ .rel_path = "src/lean-default-partial.c", .kind = "parse_partial", .detail = "7-9"};+ ASSERT_EQ(cbm_store_coverage_replace(st, "test-project", &coverage, 1), CBM_STORE_OK);char *resp =cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":48,\"method\":\"tools/call\",""\"params\":{\"name\":\"get_graph_schema\","- "\"arguments\":{\"project\":\"test-project\"}}}");+ "\"arguments\":{\"project\":\"test-project\","+ "\"diagnostics\":\"full\",\"format\":\"json\"}}}");ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);@@ -2609,20 +3345,41 @@ TEST(tool_lean_defaults_schema_and_status) {/* index_status: no git block by default... */resp = cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":49,\"method\":\"tools/call\",""\"params\":{\"name\":\"index_status\","- "\"arguments\":{\"project\":\"test-project\"}}}");+ "\"arguments\":{\"project\":\"test-project\","+ "\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"status\":"));+ ASSERT_NOT_NULL(strstr(inner, "\"indexed_at\":"));+ ASSERT_NULL(strstr(inner, "\"git\":"));+ ASSERT_NOT_NULL(strstr(inner, "\"parse_partial\":"));+ ASSERT_NOT_NULL(strstr(inner, "\"count\":1"));+ ASSERT_NOT_NULL(strstr(inner, "\"truncated\":true"));+ ASSERT_NULL(strstr(inner, "src/lean-default-partial.c"));+ free(inner);+ free(resp);++ /* Coverage identities are diagnostic detail: full restores the exact+ * persisted path without changing the counts-only default. */+ resp = cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":501,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\","+ "\"diagnostics\":\"full\",\"format\":\"json\"}}}");ASSERT_NOT_NULL(resp);inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "\"status\""));- ASSERT_NULL(strstr(inner, "\"git\""));+ ASSERT_NOT_NULL(strstr(inner, "src/lean-default-partial.c"));+ ASSERT_NOT_NULL(strstr(inner, "\"count\":1"));free(inner);free(resp);/* ...and present with verbose:true. */- resp = cbm_mcp_server_handle(srv,- "{\"jsonrpc\":\"2.0\",\"id\":50,\"method\":\"tools/call\","- "\"params\":{\"name\":\"index_status\","- "\"arguments\":{\"project\":\"test-project\",\"verbose\":true}}}");+ resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":50,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\",\"verbose\":true,"+ "\"format\":\"json\"}}}");ASSERT_NOT_NULL(resp);inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);@@ -2727,7 +3484,7 @@ TEST(tool_output_regression_gate) {6000, "node_labels"},{"{\"jsonrpc\":\"2.0\",\"id\":72,\"method\":\"tools/call\",\"params\":{""\"name\":\"index_status\",\"arguments\":{\"project\":\"test-project\"}}}",- 7000, "\"status\""},+ 2500, "status:"},{"{\"jsonrpc\":\"2.0\",\"id\":73,\"method\":\"tools/call\",\"params\":{""\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"test-project\",""\"function_name\":\"HandleRequest\",\"direction\":\"both\"}}}",@@ -2803,6 +3560,235 @@ TEST(tool_search_graph_query_honors_file_pattern_issue552) {PASS();}+TEST(tool_search_graph_bm25_reports_candidate_saturation) {+ 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 = "bm25-saturation";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/bm25-saturation"), CBM_STORE_OK);++ for (int i = 0; i < 2001; i++) {+ char qn[64];+ snprintf(qn, sizeof(qn), "bm25-saturation.fn_%04d", i);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "saturationneedle",+ .qualified_name = qn,+ .file_path = "many.c",+ .start_line = i + 1,+ .end_line = i + 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);+ }+ ASSERT_EQ(cbm_store_exec(store, "INSERT INTO nodes_fts(nodes_fts) VALUES('delete-all');"),+ CBM_STORE_OK);+ ASSERT_EQ(cbm_store_exec(store, "INSERT INTO nodes_fts(rowid, name, qualified_name, label, "+ "file_path) SELECT id, cbm_camel_split(name), qualified_name, "+ "label, file_path FROM nodes;"),+ CBM_STORE_OK);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":553,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_graph\",\"arguments\":{"+ "\"project\":\"bm25-saturation\",\"query\":\"saturationneedle\","+ "\"limit\":10,\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"total\":2000"));+ ASSERT_NOT_NULL(strstr(inner, "\"total_relation\":\"gte\""));+ ASSERT_NOT_NULL(strstr(inner, "\"candidate_window_saturated\":true"));+ ASSERT_NOT_NULL(strstr(inner, "\"truncated\":true"));+ free(inner);+ free(resp);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_search_graph_budget_preserves_long_values_and_continuation) {+ 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 = "search-byte-budget";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/search-byte-budget"), CBM_STORE_OK);++ enum { PREFIX_LEN = 3900, PATH_LEN = 3900, DOC_LEN = 5000 };+ char *prefix = malloc(PREFIX_LEN + 1U);+ char *path_a = malloc(PATH_LEN + 1U);+ char *path_b = malloc(PATH_LEN + 1U);+ char *doc_value = malloc(DOC_LEN + 1U);+ char *qn_a = malloc(PREFIX_LEN + sizeof(".a_budget"));+ char *qn_b = malloc(PREFIX_LEN + sizeof(".b_budget"));+ char *properties = malloc(DOC_LEN + sizeof("{\"doc\":\"\"}"));+ ASSERT_NOT_NULL(prefix);+ ASSERT_NOT_NULL(path_a);+ ASSERT_NOT_NULL(path_b);+ ASSERT_NOT_NULL(doc_value);+ ASSERT_NOT_NULL(qn_a);+ ASSERT_NOT_NULL(qn_b);+ ASSERT_NOT_NULL(properties);+ memset(prefix, 'q', PREFIX_LEN);+ prefix[PREFIX_LEN] = '\0';+ memset(path_a, 'a', PATH_LEN);+ memset(path_b, 'b', PATH_LEN);+ path_a[PATH_LEN] = '\0';+ path_b[PATH_LEN] = '\0';+ memset(doc_value, 'v', DOC_LEN);+ doc_value[DOC_LEN] = '\0';+ snprintf(qn_a, PREFIX_LEN + sizeof(".a_budget"), "%s.a_budget", prefix);+ snprintf(qn_b, PREFIX_LEN + sizeof(".b_budget"), "%s.b_budget", prefix);+ snprintf(properties, DOC_LEN + sizeof("{\"doc\":\"\"}"), "{\"doc\":\"%s\"}", doc_value);++ cbm_node_t first = {.project = project,+ .label = "Function",+ .name = "a_budget",+ .qualified_name = qn_a,+ .file_path = path_a,+ .start_line = 1,+ .end_line = 2,+ .properties_json = properties};+ cbm_node_t second = {.project = project,+ .label = "Function",+ .name = "b_budget",+ .qualified_name = qn_b,+ .file_path = path_b,+ .start_line = 3,+ .end_line = 4,+ .properties_json = properties};+ ASSERT_GT(cbm_store_upsert_node(store, &first), 0);+ ASSERT_GT(cbm_store_upsert_node(store, &second), 0);+ ASSERT_EQ(cbm_store_exec(store, "INSERT INTO nodes_fts(nodes_fts) VALUES('delete-all');"),+ CBM_STORE_OK);+ ASSERT_EQ(cbm_store_exec(store, "INSERT INTO nodes_fts(rowid, name, qualified_name, label, "+ "file_path) SELECT id, cbm_camel_split(name), qualified_name, "+ "label, file_path FROM nodes;"),+ CBM_STORE_OK);++ /* Roomy tree and JSON carry the complete multi-KiB qn prefix, path, and+ * requested property value. Grouping is a directory-like representation,+ * never character truncation. */+ const char *roomy_args = "{\"project\":\"search-byte-budget\",\"name_pattern\":\"._budget\","+ "\"fields\":[\"doc\"],\"limit\":2,\"max_output_tokens\":100000}";+ char *response = cbm_mcp_handle_tool(srv, "search_graph", roomy_args);+ char *tree = extract_text_content(response);+ ASSERT_NOT_NULL(tree);+ ASSERT_NOT_NULL(strstr(tree, prefix));+ ASSERT_NOT_NULL(strstr(tree, path_a));+ ASSERT_NOT_NULL(strstr(tree, path_b));+ ASSERT_NOT_NULL(strstr(tree, doc_value));+ ASSERT_NOT_NULL(strstr(tree, "a_budget"));+ ASSERT_NOT_NULL(strstr(tree, "b_budget"));+ free(response);++ const char *roomy_json_args =+ "{\"project\":\"search-byte-budget\",\"name_pattern\":\"._budget\","+ "\"fields\":[\"doc\"],\"limit\":2,\"max_output_tokens\":100000,"+ "\"format\":\"json\"}";+ response = cbm_mcp_handle_tool(srv, "search_graph", roomy_json_args);+ char *json = extract_text_content(response);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ yyjson_val *groups = yyjson_obj_get(root, "groups");+ ASSERT_EQ(yyjson_arr_size(groups), 2);+ for (int i = 0; i < 2; i++) {+ yyjson_val *group = yyjson_arr_get(groups, (size_t)i);+ yyjson_val *rows = yyjson_obj_get(group, "rows");+ yyjson_val *row = yyjson_arr_get(rows, 0);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(group, "qn_prefix")), prefix);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(group, "file")), i == 0 ? path_a : path_b);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(row, 0)), i == 0 ? "a_budget" : "b_budget");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(row, 5)), doc_value);+ }+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "returned")), 2);+ yyjson_doc_free(doc);++ /* Default budget drops the optional 5 KiB field, then the lower-ranked+ * complete row. The continuation returns that full row without overlap. */+ const char *page_args = "{\"project\":\"search-byte-budget\",\"name_pattern\":\"._budget\","+ "\"fields\":[\"doc\"],\"limit\":2}";+ char *page_response = cbm_mcp_handle_tool(srv, "search_graph", page_args);+ char *page = extract_text_content(page_response);+ ASSERT_NOT_NULL(page);+ ASSERT_TRUE(strlen(page) <= 12800U);+ ASSERT_NOT_NULL(strstr(page, prefix));+ ASSERT_NOT_NULL(strstr(page, path_a));+ ASSERT_NOT_NULL(strstr(page, "a_budget"));+ ASSERT_NULL(strstr(page, path_b));+ ASSERT_NULL(strstr(page, doc_value));+ ASSERT_NOT_NULL(strstr(page, "returned: 1"));+ ASSERT_NOT_NULL(strstr(page, "next_offset: 1"));+ ASSERT_NOT_NULL(strstr(page, "fields_omitted: 1"));+ ASSERT_NOT_NULL(strstr(page, "truncation_reason: output_budget"));++ const char *next_args = "{\"project\":\"search-byte-budget\",\"name_pattern\":\"._budget\","+ "\"limit\":2,\"offset\":1}";+ char *next_response = cbm_mcp_handle_tool(srv, "search_graph", next_args);+ char *next = extract_text_content(next_response);+ ASSERT_NOT_NULL(next);+ ASSERT_NOT_NULL(strstr(next, prefix));+ ASSERT_NOT_NULL(strstr(next, path_b));+ ASSERT_NOT_NULL(strstr(next, "b_budget"));+ ASSERT_NULL(strstr(next, path_a));+ ASSERT_NOT_NULL(strstr(next, "returned: 1"));+ ASSERT_NOT_NULL(strstr(next, "has_more: false"));++ /* If mandatory identity cannot fit, both encodings return bounded,+ * machine-readable floor metadata and no partial identifier fragment. */+ const char *formats[] = {"tree", "json"};+ for (int i = 0; i < 2; i++) {+ char args[256];+ snprintf(args, sizeof(args),+ "{\"project\":\"search-byte-budget\",\"name_pattern\":\"a_budget\","+ "\"max_output_tokens\":128,\"format\":\"%s\"}",+ formats[i]);+ char *floor_response = cbm_mcp_handle_tool(srv, "search_graph", args);+ char *floor = extract_text_content(floor_response);+ ASSERT_NOT_NULL(floor);+ ASSERT_TRUE(strlen(floor) <= 512U);+ ASSERT_NOT_NULL(strstr(floor, "output_budget_floor_exceeded"));+ ASSERT_NOT_NULL(strstr(floor, "continuation_requires_higher_budget"));+ ASSERT_NULL(strstr(floor, "next_offset"));+ ASSERT_NULL(strstr(floor, prefix));+ ASSERT_NULL(strstr(floor, path_a));+ free(floor);+ free(floor_response);+ }++ char *bm25_floor_response =+ cbm_mcp_handle_tool(srv, "search_graph",+ "{\"project\":\"search-byte-budget\",\"query\":\"budget\","+ "\"max_output_tokens\":128,\"format\":\"json\"}");+ char *bm25_floor = extract_text_content(bm25_floor_response);+ ASSERT_NOT_NULL(bm25_floor);+ ASSERT_NOT_NULL(strstr(bm25_floor, "continuation_requires_higher_budget"));+ ASSERT_NULL(strstr(bm25_floor, "next_offset"));+ ASSERT_NULL(strstr(bm25_floor, prefix));+ free(bm25_floor);+ free(bm25_floor_response);++ free(next);+ free(next_response);+ free(page);+ free(page_response);+ free(json);+ free(response);+ free(tree);+ free(prefix);+ free(path_a);+ free(path_b);+ free(doc_value);+ free(qn_a);+ free(qn_b);+ free(properties);+ cbm_mcp_server_free(srv);+ PASS();+}+/* Resource discovery methods this server doesn't populate must return EMPTY* lists, not -32601 Method-not-found: clients like Cline probe them on connect* and surface the errors as a failed connection (#958). */@@ -2847,6 +3833,561 @@ TEST(tool_query_graph_basic) {PASS();}+TEST(tool_query_graph_default_budget_is_truthful_and_expandable) {+ 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-budget";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/query-budget"), CBM_STORE_OK);+ for (int i = 0; i < 202; i++) {+ char name[32];+ char qualified_name[64];+ snprintf(name, sizeof(name), "row_%03d", i);+ snprintf(qualified_name, sizeof(qualified_name), "query-budget.rows.%s", name);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = qualified_name,+ .file_path = "rows.c",+ .start_line = i + 1,+ .end_line = i + 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);+ }++ char *response = cbm_mcp_handle_tool(+ srv, "query_graph",+ "{\"project\":\"query-budget\",\"query\":\"MATCH (n) RETURN n.name ORDER BY n.name\","+ "\"format\":\"json\",\"max_output_tokens\":20000}");+ ASSERT_NOT_NULL(response);+ 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 *rows = yyjson_obj_get(root, "rows");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "returned")), 200);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "total")), 202);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "total_relation")), "eq");+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "truncation_reason")), "page_limit");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "next_offset")), 200);+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "rows")), 200);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ /* Response paging keeps the same evaluated result set and row order. */+ response = cbm_mcp_handle_tool(+ srv, "query_graph",+ "{\"project\":\"query-budget\",\"query\":\"MATCH (n) RETURN n.name ORDER BY n.name\","+ "\"format\":\"json\",\"offset\":200,\"max_output_tokens\":20000}");+ ASSERT_NOT_NULL(response);+ 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")), 2);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "offset")), 200);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));+ rows = yyjson_obj_get(root, "rows");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_arr_get_first(rows), 0)), "row_200");+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(+ srv, "query_graph",+ "{\"project\":\"query-budget\",\"query\":\"MATCH (n) RETURN n.name ORDER BY n.name\","+ "\"format\":\"json\",\"max_rows\":250,\"max_output_tokens\":20000}");+ ASSERT_NOT_NULL(response);+ 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")), 202);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "total")), 202);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "total_relation")), "eq");+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ /* Legacy max_rows=0 remains the spelling for the maximum visible window. */+ response = cbm_mcp_handle_tool(+ srv, "query_graph",+ "{\"project\":\"query-budget\",\"query\":\"MATCH (n) RETURN n.name ORDER BY n.name\","+ "\"format\":\"json\",\"max_rows\":0,\"max_output_tokens\":20000}");+ ASSERT_NOT_NULL(response);+ 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")), 202);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ /* The display limit must not become a pre-aggregation/pre-SKIP execution+ * cap. Both answers need all 202 bindings even though max_rows defaults to+ * 200. This is RED if handle_query_graph executes with limit+1. */+ response = cbm_mcp_handle_tool(+ srv, "query_graph",+ "{\"project\":\"query-budget\",\"query\":\"MATCH (n) RETURN count(*) AS n\","+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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);+ rows = yyjson_obj_get(root, "rows");+ ASSERT_EQ(yyjson_arr_size(rows), 1);+ yyjson_val *first = yyjson_arr_get_first(rows);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(first, 0)), "202");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "total_relation")), "eq");+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(srv, "query_graph",+ "{\"project\":\"query-budget\","+ "\"query\":\"MATCH (n) RETURN n.name ORDER BY n.name SKIP 200\","+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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")), 2);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "total")), 2);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "total_relation")), "eq");+ yyjson_doc_free(doc);+ free(inner);+ free(response);+ 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);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ const char *project = "query-wide-row";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/query-wide-row"), CBM_STORE_OK);++ char large[5001];+ for (int i = 0; i < 5000; i++) {+ large[i] = i % 2 == 0 ? '\\' : '"';+ }+ large[5000] = '\0';+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = large,+ .qualified_name = "query-wide-row.wide",+ .file_path = "wide.c"};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);++ const char *formats[] = {"tree", "json"};+ for (int i = 0; i < 2; i++) {+ char args[384];+ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"query\":\"MATCH (n) RETURN n.name\","+ "\"format\":\"%s\",\"max_output_tokens\":128}",+ project, formats[i]);+ char *response = cbm_mcp_handle_tool(srv, "query_graph", args);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_LTE((int)strlen(inner), 512);+ if (strcmp(formats[i], "json") == 0) {+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *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_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "truncation_reason")),+ "output_budget");+ yyjson_doc_free(doc);+ } else {+ ASSERT_NOT_NULL(strstr(inner, "returned: 0"));+ ASSERT_NOT_NULL(strstr(inner, "truncation_reason: output_budget"));+ }+ free(inner);+ free(response);+ }++ /* Query expressions are response metadata too. A pathological alias must+ * not bypass the budget when zero rows fit, and must never be byte-sliced+ * into a false column name. */+ char alias[5001];+ memset(alias, 'a', sizeof(alias) - 1);+ alias[sizeof(alias) - 1] = '\0';+ char wide_query_args[5500];+ snprintf(wide_query_args, sizeof(wide_query_args),+ "{\"project\":\"%s\",\"query\":\"MATCH (n) RETURN n.name AS %s\","+ "\"format\":\"json\",\"max_output_tokens\":128}",+ project, alias);+ char *response = cbm_mcp_handle_tool(srv, "query_graph", wide_query_args);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_LTE((int)strlen(inner), 512);+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "columns_omitted")));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "returned")), 0);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "truncation_reason")), "output_budget");+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_query_graph_prefix_directory_is_lossless_and_json_stays_direct) {+ 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 = "prefix-directory";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/prefix-directory"), CBM_STORE_OK);+ for (int i = 0; i < 24; i++) {+ char name[32];+ char qualified_name[128];+ snprintf(name, sizeof(name), "function_%03d", i);+ snprintf(qualified_name, sizeof(qualified_name), "prefix-directory.src.deep.module.%s",+ name);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = qualified_name,+ .file_path = "src/deep/module/shared_file.c",+ .start_line = i + 1,+ .end_line = i + 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 n.qualified_name";+ char args[512];+ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"query\":\"%s\",\"max_output_tokens\":20000}", project, query);+ char *response = cbm_mcp_handle_tool(srv, "query_graph", args);+ ASSERT_NOT_NULL(response);+ ASSERT_NULL(strstr(response, "structuredContent"));+ char *tree = extract_text_content(response);+ ASSERT_NOT_NULL(tree);+ ASSERT_NOT_NULL(strstr(tree, "rows_refs:"));+ ASSERT_NOT_NULL(strstr(tree, "rows_ref_rule: @N+suffix=prefix+suffix"));+ ASSERT_NOT_NULL(strstr(tree, "prefix-directory.src.deep.module."));+ ASSERT_NOT_NULL(strstr(tree, "src/deep/module/shared_file.c"));+ ASSERT_NOT_NULL(strstr(tree, "returned: 24"));+ ASSERT_NOT_NULL(strstr(tree, "total_relation: eq"));++ /* Decode one representative reference from the wire text. Its prefix plus+ * suffix must reproduce the direct qualified name byte-for-byte. */+ const char *suffix = strstr(tree, "+function_000");+ ASSERT_NOT_NULL(suffix);+ const char *token = suffix;+ while (token > tree && token[-1] != ' ' && token[-1] != '\n') {+ token--;+ }+ ASSERT_EQ(*token, '@');+ char *id_end = NULL;+ long ref_id = strtol(token + 1, &id_end, 10);+ ASSERT_NOT_NULL(id_end);+ ASSERT_EQ(*id_end, '+');+ char map_needle[32];+ snprintf(map_needle, sizeof(map_needle), "\n %ld ", ref_id);+ const char *map = strstr(tree, map_needle);+ ASSERT_NOT_NULL(map);+ const char *prefix = map + strlen(map_needle);+ const char *prefix_end = strchr(prefix, '\n');+ ASSERT_NOT_NULL(prefix_end);+ size_t prefix_len = (size_t)(prefix_end - prefix);+ size_t suffix_len = strcspn(id_end + 1, " \n");+ char reconstructed[160];+ ASSERT_TRUE(prefix_len + suffix_len < sizeof(reconstructed));+ memcpy(reconstructed, prefix, prefix_len);+ memcpy(reconstructed + prefix_len, id_end + 1, suffix_len);+ reconstructed[prefix_len + suffix_len] = '\0';+ ASSERT_STR_EQ(reconstructed, "prefix-directory.src.deep.module.function_000");+ free(tree);+ free(response);++ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"query\":\"%s\",\"format\":\"json\","+ "\"max_output_tokens\":20000}",+ project, query);+ response = cbm_mcp_handle_tool(srv, "query_graph", args);+ ASSERT_NOT_NULL(response);+ tree = extract_text_content(response);+ ASSERT_NOT_NULL(tree);+ ASSERT_NULL(strstr(tree, "rows_refs"));+ yyjson_doc *doc = yyjson_read(tree, strlen(tree), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *rows = yyjson_obj_get(yyjson_doc_get_root(doc), "rows");+ ASSERT_EQ(yyjson_arr_size(rows), 24);+ yyjson_val *first = yyjson_arr_get_first(rows);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(first, 0)), reconstructed);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(first, 1)), "src/deep/module/shared_file.c");+ yyjson_doc_free(doc);+ free(tree);+ free(response);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_query_graph_prefix_directory_recovers_rows_beyond_raw_estimate) {+ 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 = "prefix-large-shared-root";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/prefix-large-shared-root"),+ CBM_STORE_OK);++ enum { PREFIX_CAP = 4096, NODE_COUNT = 200 };+ char *prefix = malloc(PREFIX_CAP);+ ASSERT_NOT_NULL(prefix);+ size_t prefix_len = 0;+ while (prefix_len + sizeof("verylongsegment.") < 3000U) {+ memcpy(prefix + prefix_len, "verylongsegment.", sizeof("verylongsegment.") - 1U);+ prefix_len += sizeof("verylongsegment.") - 1U;+ }+ prefix[prefix_len] = '\0';+ for (int i = 0; i < NODE_COUNT; i++) {+ char name[32];+ snprintf(name, sizeof(name), "function_%03d", i);+ size_t qn_cap = prefix_len + strlen(name) + 1U;+ char *qualified_name = malloc(qn_cap);+ ASSERT_NOT_NULL(qualified_name);+ snprintf(qualified_name, qn_cap, "%s%s", prefix, name);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = qualified_name,+ .file_path = "src/shared.c",+ .start_line = i + 1,+ .end_line = i + 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);+ free(qualified_name);+ }++ char *response =+ cbm_mcp_handle_tool(srv, "query_graph",+ "{\"project\":\"prefix-large-shared-root\","+ "\"query\":\"MATCH (n:Function) RETURN n.qualified_name AS qn ORDER BY "+ "n.qualified_name\"}");+ char *tree = extract_text_content(response);+ ASSERT_NOT_NULL(tree);+ ASSERT_LTE(strlen(tree), 3200U * 4U);+ ASSERT_NOT_NULL(strstr(tree, "rows_refs:"));+ ASSERT_NOT_NULL(strstr(tree, prefix));+ ASSERT_NOT_NULL(strstr(tree, "returned: 200"));+ ASSERT_NOT_NULL(strstr(tree, "+function_199"));++ free(tree);+ free(response);+ free(prefix);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_list_projects_tree_uses_one_stable_header_and_keeps_json_direct) {+ char cache[256];+ snprintf(cache, sizeof(cache), "%s/cbm-list-lean-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(cache));+ const char *saved_cache = getenv("CBM_CACHE_DIR");+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;+ cbm_setenv("CBM_CACHE_DIR", cache, 1);++ enum { PROJECTS = 12 };+ for (int i = 0; i < PROJECTS; i++) {+ char project[32];+ char db_path[512];+ char root_path[512];+ snprintf(project, sizeof(project), "lean-project-%02d", i);+ snprintf(db_path, sizeof(db_path), "%s/%s.db", cache, project);+ snprintf(root_path, sizeof(root_path),+ "/workspaces/organization/shared/services/lean-project-%02d", i);+ cbm_store_t *store = cbm_store_open_path(db_path);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, project, root_path), CBM_STORE_OK);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "entry",+ .qualified_name = "shared.module.entry",+ .file_path = "src/main.c",+ .start_line = 1,+ .end_line = 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);+ cbm_store_close(store);+ }++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ char *identity_response = cbm_mcp_handle_tool(srv, "list_projects", "{\"limit\":50}");+ char *identity = extract_text_content(identity_response);+ char *tree_response =+ cbm_mcp_handle_tool(srv, "list_projects", "{\"limit\":50,\"detail\":\"stats\"}");+ char *tree = extract_text_content(tree_response);+ char *json_response = cbm_mcp_handle_tool(+ srv, "list_projects", "{\"limit\":50,\"format\":\"json\",\"detail\":\"stats\"}");+ char *json = extract_text_content(json_response);+ char *page_response = cbm_mcp_handle_tool(srv, "list_projects", "{\"limit\":5}");+ char *page = extract_text_content(page_response);++ bool tree_shape =+ tree && strstr(tree, "projects_refs:") &&+ strstr(tree, "projects: 12 (cols: name root_path branch nodes edges size_bytes)") &&+ strstr(tree, "lean-project-00") && strstr(tree, "lean-project-11") &&+ strstr(tree, "total: 12") && strstr(tree, "returned: 12") &&+ strstr(tree, "has_more: false") && !strstr(tree, "\"name\":");+ bool identity_lean = identity && strstr(identity, "projects_refs:") &&+ strstr(identity, "projects: 12 (cols: name root_path branch)") &&+ !strstr(identity, "size_bytes") && !strstr(identity, " nodes edges");+ bool tree_is_leaner = tree && json && strlen(tree) < strlen(json);+ bool tree_not_duplicated = tree_response && !strstr(tree_response, "structuredContent");+ bool page_truthful = page && strstr(page, "projects: 5") && strstr(page, "returned: 5") &&+ strstr(page, "has_more: true") && strstr(page, "next_offset: 5");+ bool json_direct = false;+ bool json_structured = json_response && strstr(json_response, "structuredContent");+ yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;+ if (doc) {+ yyjson_val *projects = yyjson_obj_get(yyjson_doc_get_root(doc), "projects");+ yyjson_val *first = projects ? yyjson_arr_get_first(projects) : NULL;+ json_direct = projects && yyjson_arr_size(projects) == PROJECTS && first &&+ yyjson_obj_get(first, "name") && yyjson_obj_get(first, "root_path") &&+ yyjson_obj_get(first, "nodes") && yyjson_obj_get(first, "edges") &&+ yyjson_obj_get(first, "size_bytes") && !strstr(json, "rows_refs");+ yyjson_doc_free(doc);+ }++ free(identity);+ free(identity_response);+ free(tree);+ free(tree_response);+ free(json);+ free(json_response);+ free(page);+ free(page_response);+ cbm_mcp_server_free(srv);+ restore_cache_dir(saved_cache_copy);+ free(saved_cache_copy);+ for (int i = 0; i < PROJECTS; i++) {+ char project[32];+ snprintf(project, sizeof(project), "lean-project-%02d", i);+ cleanup_project_db(cache, project);+ }+ cbm_rmdir(cache);++ ASSERT_TRUE(tree_shape);+ ASSERT_TRUE(identity_lean);+ ASSERT_TRUE(tree_is_leaner);+ ASSERT_TRUE(tree_not_duplicated);+ ASSERT_TRUE(page_truthful);+ ASSERT_TRUE(json_direct);+ ASSERT_TRUE(json_structured);+ PASS();+}++/* The stored project root is dynamic identity, not a display-sized field.+ * Keep a syntactically valid segmented path beyond 1 KiB intact in both wire+ * encodings; the default detail also routes that same value through branch+ * discovery before emission. */+TEST(tool_list_projects_preserves_root_beyond_one_kib) {+ char cache[256];+ snprintf(cache, sizeof(cache), "%s/cbm-list-long-root-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(cache));+ const char *saved_cache = getenv("CBM_CACHE_DIR");+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;+ cbm_setenv("CBM_CACHE_DIR", cache, 1);++ enum { ROOT_CAP = 1536 };+ char *long_root = malloc(ROOT_CAP);+ ASSERT_NOT_NULL(long_root);+ size_t root_len = 0;+ const char root_start[] = "/tmp";+ const char segment[] = "/segment";+ const char tail[] = "/lossless-tail";+ memcpy(long_root, root_start, sizeof(root_start) - 1U);+ root_len = sizeof(root_start) - 1U;+ while (root_len + sizeof(segment) - 1U + sizeof(tail) < ROOT_CAP) {+ memcpy(long_root + root_len, segment, sizeof(segment) - 1U);+ root_len += sizeof(segment) - 1U;+ }+ memcpy(long_root + root_len, tail, sizeof(tail));+ root_len += sizeof(tail) - 1U;+ ASSERT_TRUE(root_len > 1024U);++ const char *project = "long-root-project";+ const char *db_file = "long-root-record";+ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/%s.db", cache, db_file);+ cbm_store_t *store = cbm_store_open_path(db_path);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, project, long_root), CBM_STORE_OK);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "entry",+ .qualified_name = "long.root.entry",+ .file_path = "src/main.c",+ .start_line = 1,+ .end_line = 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);+ cbm_store_close(store);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ char *tree_response = cbm_mcp_handle_tool(srv, "list_projects", "{\"limit\":50}");+ char *tree = extract_text_content(tree_response);+ ASSERT_NOT_NULL(tree);+ const char *tree_root = strstr(tree, long_root);+ ASSERT_NOT_NULL(tree_root);+ ASSERT_EQ(tree_root[root_len], ' ');+ ASSERT_NOT_NULL(strstr(tree_root, "/lossless-tail"));++ char *json_response =+ cbm_mcp_handle_tool(srv, "list_projects", "{\"limit\":50,\"format\":\"json\"}");+ char *json = extract_text_content(json_response);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *projects = yyjson_obj_get(yyjson_doc_get_root(doc), "projects");+ ASSERT_NOT_NULL(projects);+ ASSERT_EQ(yyjson_arr_size(projects), 1);+ yyjson_val *listed = yyjson_arr_get_first(projects);+ const char *listed_root = yyjson_get_str(yyjson_obj_get(listed, "root_path"));+ ASSERT_NOT_NULL(listed_root);+ ASSERT_EQ(strlen(listed_root), root_len);+ ASSERT_STR_EQ(listed_root, long_root);++ yyjson_doc_free(doc);+ free(json);+ free(json_response);+ free(tree);+ free(tree_response);+ cbm_mcp_server_free(srv);+ restore_cache_dir(saved_cache_copy);+ free(saved_cache_copy);+ cleanup_project_db(cache, db_file);+ cbm_rmdir(cache);+ free(long_root);+ PASS();+}+TEST(tool_index_status_no_project) {cbm_mcp_server_t *srv = setup_mcp_with_data();@@ -2892,8 +4433,9 @@ TEST(tool_check_index_coverage_finds_path_beyond_status_cap) {}ASSERT_EQ(cbm_store_coverage_replace(st, project, rows, ROW_COUNT), CBM_STORE_OK);- char *status =- cbm_mcp_handle_tool(srv, "index_status", "{\"project\":\"coverage-cap-regression\"}");+ char *status = cbm_mcp_handle_tool(+ srv, "index_status",+ "{\"project\":\"coverage-cap-regression\",\"diagnostics\":\"full\",\"format\":\"json\"}");ASSERT_NOT_NULL(status);char *status_inner = extract_text_content(status);ASSERT_NOT_NULL(status_inner);@@ -2904,13 +4446,16 @@ TEST(tool_check_index_coverage_finds_path_beyond_status_cap) {char *coverage = cbm_mcp_handle_tool(srv, "check_index_coverage",- "{\"project\":\"coverage-cap-regression\",\"paths\":[\"src/partial-0501.c\"]}");+ "{\"project\":\"coverage-cap-regression\",\"paths\":[\"src/partial-0501.c\"],"+ "\"format\":\"json\"}");ASSERT_NOT_NULL(coverage);char *coverage_inner = extract_text_content(coverage);ASSERT_NOT_NULL(coverage_inner);ASSERT_NOT_NULL(strstr(coverage_inner, "src/partial-0501.c"));ASSERT_NOT_NULL(strstr(coverage_inner, "\"status\":\"partial\""));- ASSERT_NOT_NULL(strstr(coverage_inner, "777-790"));+ ASSERT_NOT_NULL(strstr(coverage_inner, "\"start\":777"));+ ASSERT_NOT_NULL(strstr(coverage_inner, "\"end\":790"));+ ASSERT_NULL(strstr(coverage_inner, "\"detail\":\"777-790\""));free(coverage_inner);free(coverage);@@ -2920,6 +4465,91 @@ TEST(tool_check_index_coverage_finds_path_beyond_status_cap) {PASS();}+TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics) {+ 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 = "coverage-path-page";+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/coverage-path-page"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);+ cbm_coverage_row_t row = {+ .rel_path = "path-00.c", .kind = "parse_partial", .detail = "11-19,27"};+ ASSERT_EQ(cbm_store_upsert_file_hash(store, project, "path-00.c", "fixture", 1, 1),+ CBM_STORE_OK);+ ASSERT_EQ(cbm_store_coverage_replace(store, project, &row, 1), CBM_STORE_OK);+ cbm_coverage_row_t *stored_rows = NULL;+ int stored_count = 0;+ ASSERT_EQ(cbm_store_coverage_get_path(store, project, "path-00.c", &stored_rows, &stored_count),+ CBM_STORE_OK);+ ASSERT_EQ(stored_count, 1);+ cbm_store_free_coverage(stored_rows, stored_count);++ char args[4096];+ size_t used =+ (size_t)snprintf(args, sizeof(args), "{\"project\":\"coverage-path-page\",\"paths\":[");+ for (int i = 0; i < 25; i++) {+ used += (size_t)snprintf(args + used, sizeof(args) - used, "%s\"path-%02d.c\"",+ i ? "," : "", i);+ }+ (void)snprintf(args + used, sizeof(args) - used, "],\"format\":\"json\"}");++ char *response = cbm_mcp_handle_tool(srv, "check_index_coverage", args);+ ASSERT_NOT_NULL(response);+ 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);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_total")), 25);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_returned")), 20);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "path_has_more")));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_next_offset")), 20);+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "paths")), 20);+ ASSERT_NOT_NULL(strstr(inner, "\"start\":11"));+ ASSERT_NULL(strstr(inner, "\"detail\":\"11-19,27\""));+ ASSERT_NULL(strstr(inner, "path-20.c"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ used = (size_t)snprintf(args, sizeof(args), "{\"project\":\"coverage-path-page\",\"paths\":[");+ for (int i = 0; i < 25; i++) {+ used += (size_t)snprintf(args + used, sizeof(args) - used, "%s\"path-%02d.c\"",+ i ? "," : "", i);+ }+ (void)snprintf(args + used, sizeof(args) - used,+ "],\"path_offset\":20,\"diagnostics\":\"full\",\"format\":\"json\"}");+ response = cbm_mcp_handle_tool(srv, "check_index_coverage", args);+ ASSERT_NOT_NULL(response);+ 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, "path_returned")), 5);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "path_has_more")));+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "paths")), 5);+ ASSERT_NOT_NULL(strstr(inner, "path-20.c"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ char *full =+ cbm_mcp_handle_tool(srv, "check_index_coverage",+ "{\"project\":\"coverage-path-page\",\"paths\":[\"path-00.c\"],"+ "\"diagnostics\":\"full\",\"format\":\"json\"}");+ ASSERT_NOT_NULL(full);+ char *full_inner = extract_text_content(full);+ ASSERT_NOT_NULL(full_inner);+ ASSERT_NOT_NULL(strstr(full_inner, "\"detail\":\"11-19,27\""));+ free(full_inner);+ free(full);++ cbm_mcp_server_free(srv);+ PASS();+}+TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges) {char tmp[256];cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));@@ -2940,7 +4570,7 @@ TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges) {cbm_mcp_handle_tool(srv, "check_index_coverage","{\"project\":\"test-project\",""\"paths\":[\"main.go\",\"generated/pkg/a.c\",\"../escape.c\"],"- "\"scopes\":[\".\"]}");+ "\"scopes\":[\".\"],\"format\":\"json\"}");ASSERT_NOT_NULL(coverage);char *inner = extract_text_content(coverage);ASSERT_NOT_NULL(inner);@@ -2970,7 +4600,8 @@ TEST(tool_check_index_coverage_preserves_multiple_scope_labels) {char *coverage = cbm_mcp_handle_tool(srv, "check_index_coverage","{\"project\":\"test-project\","- "\"scopes\":[\"alpha/one\",\"bravo/two\",\"charl/tri\"]}");+ "\"scopes\":[\"alpha/one\",\"bravo/two\",\"charl/tri\"],"+ "\"format\":\"json\"}");ASSERT_NOT_NULL(coverage);char *inner = extract_text_content(coverage);ASSERT_NOT_NULL(inner);@@ -3084,7 +4715,8 @@ TEST(tool_check_index_coverage_rejects_stale_generation) {ASSERT_EQ(write_coverage_meta(store, "stale-generation", "complete"), CBM_STORE_OK);char *response = cbm_mcp_handle_tool(srv, "check_index_coverage",- "{\"project\":\"test-project\",\"paths\":[\"main.go\"]}");+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],"+ "\"format\":\"json\"}");ASSERT_NOT_NULL(response);char *inner = extract_text_content(response);ASSERT_NOT_NULL(inner);@@ -3113,7 +4745,8 @@ TEST(tool_check_index_coverage_requires_source_when_file_metadata_changed) {CBM_STORE_OK);char *response = cbm_mcp_handle_tool(srv, "check_index_coverage",- "{\"project\":\"test-project\",\"paths\":[\"main.go\"]}");+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],"+ "\"format\":\"json\"}");ASSERT_NOT_NULL(response);char *inner = extract_text_content(response);ASSERT_NOT_NULL(inner);@@ -3144,7 +4777,8 @@ TEST(tool_check_index_coverage_surfaces_lookup_errors) {char *response = cbm_mcp_handle_tool(srv, "check_index_coverage",- "{\"project\":\"test-project\",\"paths\":[\"main.go\"],\"scopes\":[\".\"]}");+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],\"scopes\":[\".\"],"+ "\"format\":\"json\"}");ASSERT_NOT_NULL(response);char *inner = extract_text_content(response);ASSERT_NOT_NULL(inner);@@ -3167,10 +4801,11 @@ TEST(tool_index_status_includes_git_metadata) {cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));ASSERT_NOT_NULL(srv);- char *resp = cbm_mcp_server_handle(- srv, "{\"jsonrpc\":\"2.0\",\"id\":16,\"method\":\"tools/call\","- "\"params\":{\"name\":\"index_status\","- "\"arguments\":{\"project\":\"test-project\",\"verbose\":true}}}");+ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":16,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\",\"verbose\":true,"+ "\"format\":\"json\"}}}");ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);@@ -3379,8 +5014,8 @@ TEST(tool_trace_union_records_min_hop_across_seeds) {char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);/* tgt is one hop from seed B — the union must record hop 1, not seed A's 2. */- ASSERT_NOT_NULL(strstr(inner, " tgt 1"));- ASSERT_NULL(strstr(inner, " tgt 2"));+ ASSERT_NOT_NULL(strstr(inner, "dualproj.c.tgt 1"));+ ASSERT_NULL(strstr(inner, "dualproj.c.tgt 2"));free(inner);free(resp);cbm_mcp_server_free(srv);@@ -3471,7 +5106,7 @@ TEST(tool_trace_pagination_exactly_once) {/* Exactly-once: every callee appears on exactly ONE page. */for (int i = 0; i < CALLEES; i++) {char qn[48];- snprintf(qn, sizeof(qn), " c%02d 1\n", i);+ snprintf(qn, sizeof(qn), "pageproj.m.c%02d 1\n", i);int seen = 0;for (int p = 0; p < 3; p++) {if (strstr(pages[p], qn)) {@@ -3506,22 +5141,688 @@ TEST(tool_trace_pagination_exactly_once) {ASSERT_NOT_NULL(strstr(inner, "cursor_params_mismatch"));free(inner);- /* Stale: an index run (upsert_project bumps the generation) invalidates- * outstanding cursors with a loud, actionable error. */- cbm_store_upsert_project(st, proj, "/tmp/page");- snprintf(req2, sizeof(req2),- "{\"jsonrpc\":\"2.0\",\"id\":82,\"method\":\"tools/call\",\"params\":{"- "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","- "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"- "\"cursor\":\"%s\"}}}",- tok1);- resp = cbm_mcp_server_handle(srv, req2);- ASSERT_NOT_NULL(resp);- inner = extract_text_content(resp);- free(resp);+ /* Corrupt/trailing cursor bytes are rejected exactly, never accepted by a+ * permissive numeric parse that resumes from an attacker-chosen suffix. */+ snprintf(req2, sizeof(req2),+ "{\"jsonrpc\":\"2.0\",\"id\":83,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"+ "\"cursor\":\"%sjunk\"}}}",+ tok1);+ resp = cbm_mcp_server_handle(srv, req2);+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "invalid_cursor"));+ free(inner);++ /* The leg is part of the continuation state, not a caller-editable hint.+ * Flipping an outbound token to inbound must fail for an outbound query. */+ char tampered[192];+ snprintf(tampered, sizeof(tampered), "%s", tok1);+ ASSERT_EQ(tampered[3], 'o');+ tampered[3] = 'i';+ snprintf(req2, sizeof(req2),+ "{\"jsonrpc\":\"2.0\",\"id\":84,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"+ "\"cursor\":\"%s\"}}}",+ tampered);+ resp = cbm_mcp_server_handle(srv, req2);+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "invalid_cursor"));+ free(inner);++ /* A validly encoded watermark must be one the server actually emitted in+ * the selected visible leg; a changed node id cannot act as an arbitrary+ * insertion point. */+ const char *node_sep = strrchr(tok1, '.');+ ASSERT_NOT_NULL(node_sep);+ size_t prefix_len = (size_t)(node_sep - tok1) + 1U;+ snprintf(tampered, sizeof(tampered), "%.*s9223372036854775807", (int)prefix_len, tok1);+ snprintf(req2, sizeof(req2),+ "{\"jsonrpc\":\"2.0\",\"id\":85,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"+ "\"cursor\":\"%s\"}}}",+ tampered);+ resp = cbm_mcp_server_handle(srv, req2);+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "invalid_cursor"));+ free(inner);++ /* Stale: an index run (upsert_project bumps the generation) invalidates+ * outstanding cursors with a loud, actionable error. */+ cbm_store_upsert_project(st, proj, "/tmp/page");+ snprintf(req2, sizeof(req2),+ "{\"jsonrpc\":\"2.0\",\"id\":82,\"method\":\"tools/call\",\"params\":{"+ "\"name\":\"trace_call_path\",\"arguments\":{\"project\":\"pageproj\","+ "\"function_name\":\"hub\",\"direction\":\"outbound\",\"limit\":5,"+ "\"cursor\":\"%s\"}}}",+ tok1);+ resp = cbm_mcp_server_handle(srv, req2);+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ free(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "stale_cursor"));+ free(inner);++ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_trace_paging_filters_before_window_and_hashes_effective_args) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "trace-visible-page";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-visible-page"), CBM_STORE_OK);++ cbm_node_t hub = {.project = project,+ .label = "Function",+ .name = "hub",+ .qualified_name = "trace-visible-page.hub",+ .file_path = "src/hub.c",+ .start_line = 1,+ .end_line = 3};+ cbm_node_t hidden = {.project = project,+ .label = "Function",+ .name = "hidden_test",+ .qualified_name = "trace-visible-page.hidden_test",+ .file_path = "tests/hidden_test.c",+ .start_line = 1,+ .end_line = 3};+ cbm_node_t callee = {.project = project,+ .label = "Function",+ .name = "visible_callee",+ .qualified_name = "trace-visible-page.visible_callee",+ .file_path = "src/callee.c",+ .start_line = 1,+ .end_line = 3};+ cbm_node_t caller = {.project = project,+ .label = "Function",+ .name = "visible_caller",+ .qualified_name = "trace-visible-page.visible_caller",+ .file_path = "src/caller.c",+ .start_line = 1,+ .end_line = 3};+ int64_t hub_id = cbm_store_upsert_node(store, &hub);+ int64_t hidden_id = cbm_store_upsert_node(store, &hidden); /* lower id: would consume page */+ int64_t callee_id = cbm_store_upsert_node(store, &callee);+ int64_t caller_id = cbm_store_upsert_node(store, &caller);+ ASSERT_GT(hub_id, 0);+ ASSERT_GT(hidden_id, 0);+ ASSERT_GT(callee_id, 0);+ ASSERT_GT(caller_id, 0);+ cbm_edge_t edges[] = {+ {.project = project, .source_id = hub_id, .target_id = hidden_id, .type = "CALLS"},+ {.project = project, .source_id = hub_id, .target_id = callee_id, .type = "CALLS"},+ {.project = project, .source_id = caller_id, .target_id = hub_id, .type = "CALLS"},+ };+ for (size_t i = 0; i < sizeof(edges) / sizeof(edges[0]); i++) {+ ASSERT_GT(cbm_store_insert_edge(store, &edges[i]), 0);+ }++ const char *first_args = "{\"project\":\"trace-visible-page\",\"function_name\":\"hub\","+ "\"direction\":\"both\",\"depth\":1000,\"limit\":1,"+ "\"edge_types\":[\"CALLS\"],\"format\":\"json\"}";+ char *response = cbm_mcp_handle_tool(srv, "trace_path", first_args);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "visible_callee"));+ ASSERT_NULL(strstr(inner, "hidden_test"));+ ASSERT_NULL(strstr(inner, "visible_caller"));+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *next_value = yyjson_obj_get(yyjson_doc_get_root(doc), "next_cursor");+ ASSERT_NOT_NULL(next_value);+ char *next = strdup(yyjson_get_str(next_value));+ ASSERT_NOT_NULL(next);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ /* A cursor is bound to edge_types; changing the traversed graph fails+ * loudly instead of applying the watermark to unrelated rows. */+ char args[768];+ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"function_name\":\"hub\",\"direction\":\"both\","+ "\"depth\":1000,\"limit\":1,\"edge_types\":[\"IMPORTS\"],"+ "\"format\":\"json\",\"cursor\":\"%s\"}",+ project, next);+ response = cbm_mcp_handle_tool(srv, "trace_path", args);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "cursor_params_mismatch"));+ free(inner);+ free(response);++ /* Replaying the same out-of-range depth works because cursor identity is+ * based on the clamped effective value. This exact outbound boundary has+ * zero inbound rows on page one, so it also binds the last-emitted-row+ * watermark (no visited[-1]). */+ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"function_name\":\"hub\",\"direction\":\"both\","+ "\"depth\":1000,\"limit\":1,\"edge_types\":[\"CALLS\"],"+ "\"format\":\"json\",\"cursor\":\"%s\"}",+ project, next);+ response = cbm_mcp_handle_tool(srv, "trace_path", args);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "visible_caller"));+ ASSERT_NULL(strstr(inner, "visible_callee"));+ ASSERT_NULL(strstr(inner, "next_cursor"));+ free(inner);+ free(response);+ free(next);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_trace_budget_never_slices_identifiers) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "trace-byte-budget";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-byte-budget"), CBM_STORE_OK);++ cbm_node_t hub = {.project = project,+ .label = "Function",+ .name = "hub",+ .qualified_name = "trace-byte-budget.hub",+ .file_path = "src/hub.c",+ .start_line = 1,+ .end_line = 3};+ int64_t hub_id = cbm_store_upsert_node(store, &hub);+ ASSERT_GT(hub_id, 0);++ enum { PREFIX_LEN = 7000 };+ char *long_qn = malloc(PREFIX_LEN + sizeof(".leaf"));+ ASSERT_NOT_NULL(long_qn);+ memset(long_qn, 'p', PREFIX_LEN);+ memcpy(long_qn + PREFIX_LEN, ".leaf", sizeof(".leaf"));+ cbm_node_t leaf = {.project = project,+ .label = "Function",+ .name = "leaf",+ .qualified_name = long_qn,+ .file_path = "src/leaf.c",+ .start_line = 4,+ .end_line = 6};+ int64_t leaf_id = cbm_store_upsert_node(store, &leaf);+ ASSERT_GT(leaf_id, 0);+ cbm_edge_t long_edge = {+ .project = project, .source_id = hub_id, .target_id = leaf_id, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(store, &long_edge), 0);++ char *tree_response =+ cbm_mcp_handle_tool(srv, "trace_path",+ "{\"project\":\"trace-byte-budget\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"max_output_tokens\":10000}");+ char *tree = extract_text_content(tree_response);+ ASSERT_NOT_NULL(tree);+ /* One long row is smaller when emitted directly than behind a one-entry+ * group. The complete identifier is still present and never byte-sliced. */+ char *long_prefix = cbm_strndup(long_qn, PREFIX_LEN);+ ASSERT_NOT_NULL(long_prefix);+ ASSERT_NOT_NULL(strstr(tree, long_qn));+ ASSERT_NOT_NULL(strstr(tree, "(cols: qn hop)"));+ ASSERT_NULL(strstr(tree, "qn = group prefix"));++ char *json_response = cbm_mcp_handle_tool(+ srv, "trace_path",+ "{\"project\":\"trace-byte-budget\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"max_output_tokens\":10000,\"format\":\"json\"}");+ char *json = extract_text_content(json_response);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *callees = yyjson_obj_get(yyjson_doc_get_root(doc), "callees");+ yyjson_val *groups = callees ? yyjson_obj_get(callees, "groups") : NULL;+ yyjson_val *group = groups ? yyjson_arr_get(groups, 0) : NULL;+ yyjson_val *rows = group ? yyjson_obj_get(group, "rows") : NULL;+ yyjson_val *row = rows ? yyjson_arr_get(rows, 0) : NULL;+ const char *prefix = group ? yyjson_get_str(yyjson_obj_get(group, "qn_prefix")) : NULL;+ const char *name = row ? yyjson_get_str(yyjson_arr_get(row, 0)) : NULL;+ ASSERT_NOT_NULL(prefix);+ ASSERT_NOT_NULL(name);+ char *reconstructed = malloc(strlen(prefix) + strlen(name) + 2U);+ ASSERT_NOT_NULL(reconstructed);+ snprintf(reconstructed, strlen(prefix) + strlen(name) + 2U, "%s.%s", prefix, name);+ ASSERT_STR_EQ(reconstructed, long_qn);+ free(reconstructed);+ yyjson_doc_free(doc);++ /* A zero-row hard floor still reports what exists and how to continue.+ * It must never mint a cursor from a row that was not actually returned. */+ const char *floor_formats[] = {"tree", "json"};+ for (size_t i = 0; i < sizeof(floor_formats) / sizeof(floor_formats[0]); i++) {+ char floor_args[256];+ snprintf(floor_args, sizeof(floor_args),+ "{\"project\":\"trace-byte-budget\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"max_output_tokens\":128,\"format\":\"%s\"}",+ floor_formats[i]);+ char *floor_response = cbm_mcp_handle_tool(srv, "trace_path", floor_args);+ char *floor = extract_text_content(floor_response);+ ASSERT_NOT_NULL(floor);+ ASSERT_TRUE(strlen(floor) <= 512U);+ ASSERT_NULL(strstr(floor, long_prefix));+ if (strcmp(floor_formats[i], "json") == 0) {+ yyjson_doc *floor_doc = yyjson_read(floor, strlen(floor), 0);+ ASSERT_NOT_NULL(floor_doc);+ yyjson_val *floor_root = yyjson_doc_get_root(floor_doc);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(floor_root, "callees_total")), 1);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(floor_root, "callees_total_relation")),+ "eq");+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(floor_root, "has_more")));+ ASSERT_TRUE(+ yyjson_get_bool(yyjson_obj_get(floor_root, "continuation_requires_higher_budget")));+ ASSERT_TRUE(+ yyjson_get_bool(yyjson_obj_get(floor_root, "output_budget_floor_exceeded")));+ ASSERT_NULL(yyjson_obj_get(floor_root, "next_cursor"));+ yyjson_doc_free(floor_doc);+ } else {+ ASSERT_NOT_NULL(strstr(floor, "callees_total: 1"));+ ASSERT_NOT_NULL(strstr(floor, "callees_total_relation: eq"));+ ASSERT_NOT_NULL(strstr(floor, "has_more: true"));+ ASSERT_NOT_NULL(strstr(floor, "continuation_requires_higher_budget: true"));+ ASSERT_NOT_NULL(strstr(floor, "output_budget_floor_exceeded: true"));+ ASSERT_NULL(strstr(floor, "next: "));+ }+ free(floor);+ free(floor_response);+ }+ free(json);+ free(json_response);+ free(tree);+ free(tree_response);+ free(long_prefix);+ free(long_qn);+ cbm_mcp_server_free(srv);+ PASS();+}++/* A cursor identifies graph position, not presentation budget. Page one can+ * fit a short row, while page two's first identity needs a higher budget. The+ * hard floor emits no fabricated cursor, but retrying the original watermark+ * with more max_output_tokens must resume successfully instead of failing a+ * cursor-params hash check or replaying page one. */+TEST(tool_trace_cursor_survives_output_budget_increase) {+ 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 = "trace-budget-cursor";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-budget-cursor"), CBM_STORE_OK);+ cbm_node_t hub = {.project = project,+ .label = "Function",+ .name = "hub",+ .qualified_name = "trace-budget-cursor.hub",+ .file_path = "src/hub.c",+ .start_line = 1,+ .end_line = 2};+ cbm_node_t short_node = {.project = project,+ .label = "Function",+ .name = "short_row",+ .qualified_name = "trace-budget-cursor.short_row",+ .file_path = "src/short.c",+ .start_line = 3,+ .end_line = 4};+ int64_t hub_id = cbm_store_upsert_node(store, &hub);+ int64_t short_id = cbm_store_upsert_node(store, &short_node);+ ASSERT_GT(hub_id, 0);+ ASSERT_GT(short_id, hub_id);+ enum { LONG_PREFIX = 3000 };+ char *long_qn = malloc(LONG_PREFIX + sizeof(".long_row"));+ ASSERT_NOT_NULL(long_qn);+ memset(long_qn, 'q', LONG_PREFIX);+ memcpy(long_qn + LONG_PREFIX, ".long_row", sizeof(".long_row"));+ cbm_node_t long_node = {.project = project,+ .label = "Function",+ .name = "long_row",+ .qualified_name = long_qn,+ .file_path = "src/long.c",+ .start_line = 5,+ .end_line = 6};+ int64_t long_id = cbm_store_upsert_node(store, &long_node);+ ASSERT_GT(long_id, short_id);+ cbm_edge_t short_edge = {+ .project = project, .source_id = hub_id, .target_id = short_id, .type = "CALLS"};+ cbm_edge_t long_edge = {+ .project = project, .source_id = hub_id, .target_id = long_id, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(store, &short_edge), 0);+ ASSERT_GT(cbm_store_insert_edge(store, &long_edge), 0);++ char *response =+ cbm_mcp_handle_tool(srv, "trace_path",+ "{\"project\":\"trace-budget-cursor\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"limit\":1,\"max_output_tokens\":256,"+ "\"format\":\"json\"}");+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "short_row"));+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *next_value = yyjson_obj_get(yyjson_doc_get_root(doc), "next_cursor");+ ASSERT_NOT_NULL(next_value);+ char *cursor = strdup(yyjson_get_str(next_value));+ ASSERT_NOT_NULL(cursor);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ char args[768];+ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"limit\":1,\"max_output_tokens\":128,"+ "\"format\":\"json\",\"cursor\":\"%s\"}",+ project, cursor);+ response = cbm_mcp_handle_tool(srv, "trace_path", args);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NULL(strstr(inner, "cursor_params_mismatch"));+ ASSERT_NULL(strstr(inner, long_qn));+ doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *floor = yyjson_doc_get_root(doc);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(floor, "continuation_requires_higher_budget")));+ ASSERT_NULL(yyjson_obj_get(floor, "next_cursor"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"limit\":1,\"max_output_tokens\":2000,"+ "\"format\":\"json\",\"cursor\":\"%s\"}",+ project, cursor);+ response = cbm_mcp_handle_tool(srv, "trace_path", args);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NULL(strstr(inner, "cursor_params_mismatch"));+ ASSERT_NULL(strstr(inner, "short_row"));+ doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *callees = yyjson_obj_get(yyjson_doc_get_root(doc), "callees");+ ASSERT_NOT_NULL(callees);+ const char *long_prefix_out = NULL;+ yyjson_val *long_row = trace_grouped_row_named(callees, "long_row", &long_prefix_out);+ ASSERT_NOT_NULL(long_row);+ ASSERT_NOT_NULL(long_prefix_out);+ size_t reconstructed_cap = strlen(long_prefix_out) + sizeof(".long_row");+ char *reconstructed = malloc(reconstructed_cap);+ ASSERT_NOT_NULL(reconstructed);+ snprintf(reconstructed, reconstructed_cap, "%s.long_row", long_prefix_out);+ ASSERT_STR_EQ(reconstructed, long_qn);+ free(reconstructed);+ yyjson_doc_free(doc);+ free(inner);+ free(response);+ free(cursor);+ free(long_qn);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_trace_budget_drops_huge_optional_args_before_graph_row) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "trace-args-budget";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-args-budget"), CBM_STORE_OK);+ cbm_node_t caller = {.project = project,+ .label = "Function",+ .name = "caller",+ .qualified_name = "trace-args-budget.caller",+ .file_path = "src/caller.c",+ .start_line = 1,+ .end_line = 3};+ cbm_node_t callee = {.project = project,+ .label = "Function",+ .name = "callee",+ .qualified_name = "trace-args-budget.callee",+ .file_path = "src/callee.c",+ .start_line = 4,+ .end_line = 6};+ int64_t caller_id = cbm_store_upsert_node(store, &caller);+ int64_t callee_id = cbm_store_upsert_node(store, &callee);+ ASSERT_GT(caller_id, 0);+ ASSERT_GT(callee_id, 0);+ enum { ARG_BYTES = 40000 };+ char *properties = malloc(ARG_BYTES + 32U);+ ASSERT_NOT_NULL(properties);+ memcpy(properties, "{\"args\":[\"", 10U);+ memset(properties + 10U, 'x', ARG_BYTES);+ memcpy(properties + 10U + ARG_BYTES, "\"]}", 4U);+ properties[14U + ARG_BYTES] = '\0';+ cbm_edge_t edge = {.project = project,+ .source_id = caller_id,+ .target_id = callee_id,+ .type = "CALLS",+ .properties_json = properties};+ ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);+ for (int i = 0; i < 20; i++) {+ char name[32];+ char qualified_name[96];+ snprintf(name, sizeof(name), "extra_%d", i);+ snprintf(qualified_name, sizeof(qualified_name), "trace-args-budget.%s", name);+ cbm_node_t extra = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = qualified_name,+ .file_path = "src/extra.c",+ .start_line = 10 + i,+ .end_line = 11 + i};+ int64_t extra_id = cbm_store_upsert_node(store, &extra);+ ASSERT_GT(extra_id, 0);+ cbm_edge_t extra_edge = {+ .project = project, .source_id = caller_id, .target_id = extra_id, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(store, &extra_edge), 0);+ }++ char *response =+ cbm_mcp_handle_tool(srv, "trace_path",+ "{\"project\":\"trace-args-budget\",\"function_name\":\"caller\","+ "\"direction\":\"outbound\",\"mode\":\"data_flow\","+ "\"risk_labels\":true,\"include_evidence\":true,"+ "\"max_output_tokens\":256,\"format\":\"json\"}");+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_TRUE(strlen(inner) <= 1024U);+ ASSERT_NOT_NULL(strstr(inner, "trace-args-budget"));+ ASSERT_NOT_NULL(strstr(inner, "optional_fields_omitted"));+ ASSERT_NULL(strstr(inner, "xxxxxxxxxxxxxxxx"));+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ yyjson_val *callees = yyjson_obj_get(root, "callees");+ ASSERT_NOT_NULL(callees);+ ASSERT_NOT_NULL(trace_grouped_row_named(callees, "callee", NULL));+ yyjson_val *has_more = yyjson_obj_get(root, "has_more");+ ASSERT_NOT_NULL(has_more);+ yyjson_val *next_cursor = yyjson_obj_get(root, "next_cursor");+ if (yyjson_get_bool(has_more)) {+ ASSERT_NOT_NULL(next_cursor);+ } else {+ ASSERT_NULL(next_cursor);+ }+ yyjson_val *omitted = yyjson_obj_get(root, "omitted_optional_fields");+ ASSERT_NOT_NULL(omitted);+ ASSERT_EQ(yyjson_arr_size(omitted), 4);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(omitted, 0)), "risk");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(omitted, 1)), "args");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(omitted, 2)), "strategy");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(omitted, 3)), "confidence");+ yyjson_doc_free(doc);++ free(inner);+ free(response);+ free(properties);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_trace_reports_engine_saturation_as_lower_bound) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "trace-engine-cap";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-engine-cap"), CBM_STORE_OK);+ cbm_node_t hub = {.project = project,+ .label = "Function",+ .name = "hub",+ .qualified_name = "trace-engine-cap.hub",+ .file_path = "src/hub.c",+ .start_line = 1,+ .end_line = 3};+ int64_t hub_id = cbm_store_upsert_node(store, &hub);+ ASSERT_GT(hub_id, 0);+ ASSERT_EQ(cbm_store_begin_bulk(store), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_begin(store), CBM_STORE_OK);+ for (int i = 0; i < 5001; i++) {+ char name[32];+ char qualified_name[64];+ snprintf(name, sizeof(name), "callee_%04d", i);+ snprintf(qualified_name, sizeof(qualified_name), "trace-engine-cap.%s", name);+ char *oversized_qn = NULL;+ const char *node_qn = qualified_name;+ if (i == 0) {+ oversized_qn = malloc(7000U + sizeof(".callee_0000"));+ ASSERT_NOT_NULL(oversized_qn);+ memset(oversized_qn, 'q', 7000U);+ memcpy(oversized_qn + 7000U, ".callee_0000", sizeof(".callee_0000"));+ node_qn = oversized_qn;+ }+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = node_qn,+ .file_path = "src/callees.c",+ .start_line = i + 1,+ .end_line = i + 2};+ int64_t node_id = cbm_store_upsert_node(store, &node);+ free(oversized_qn);+ ASSERT_GT(node_id, 0);+ cbm_edge_t edge = {+ .project = project, .source_id = hub_id, .target_id = node_id, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);+ }+ ASSERT_EQ(cbm_store_commit(store), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_end_bulk(store), CBM_STORE_OK);++ char *response =+ cbm_mcp_handle_tool(srv, "trace_path",+ "{\"project\":\"trace-engine-cap\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"depth\":1,\"limit\":5000,"+ "\"max_output_tokens\":100000,\"format\":\"json\"}");+ 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);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "callees_total")), 5000);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "callees_total_relation")), "gte");+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "engine_saturated")));+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "truncated")));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "truncation_reason")), "engine_limit");+ ASSERT_FALSE(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);++ /* The hard floor preserves the engine's lower-bound relation while+ * withholding the oversized first identity and any self-loop cursor. */+ response = cbm_mcp_handle_tool(srv, "trace_path",+ "{\"project\":\"trace-engine-cap\",\"function_name\":\"hub\","+ "\"direction\":\"outbound\",\"depth\":1,\"limit\":5000,"+ "\"max_output_tokens\":128,\"format\":\"json\"}");+ inner = extract_text_content(response);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "stale_cursor"));+ ASSERT_TRUE(strlen(inner) <= 512U);+ 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, "callees_total")), 5000);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "callees_total_relation")), "gte");+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "has_more")));+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "continuation_requires_higher_budget")));+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "output_budget_floor_exceeded")));+ ASSERT_NULL(yyjson_obj_get(root, "next_cursor"));+ yyjson_doc_free(doc);free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(store_bfs_edge_data_is_skippable_and_bounded) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "trace-edge-budget";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-edge-budget"), CBM_STORE_OK);++ cbm_node_t hub = {.project = project,+ .label = "Function",+ .name = "hub",+ .qualified_name = "trace-edge-budget.hub",+ .file_path = "src/hub.c",+ .start_line = 1,+ .end_line = 3};+ int64_t hub_id = cbm_store_upsert_node(store, &hub);+ ASSERT_GT(hub_id, 0);+ for (int i = 0; i < 2; i++) {+ char name[24];+ char qualified_name[64];+ snprintf(name, sizeof(name), "callee_%d", i);+ snprintf(qualified_name, sizeof(qualified_name), "trace-edge-budget.%s", name);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = name,+ .qualified_name = qualified_name,+ .file_path = "src/callee.c",+ .start_line = i + 1,+ .end_line = i + 2};+ int64_t node_id = cbm_store_upsert_node(store, &node);+ ASSERT_GT(node_id, 0);+ cbm_edge_t edge = {+ .project = project, .source_id = hub_id, .target_id = node_id, .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);+ }++ const char *types[] = {"CALLS"};+ cbm_traverse_result_t traversal = {0};+ ASSERT_EQ(+ cbm_store_bfs_with_edge_limit(store, hub_id, "outbound", types, 1, 1, 10, 0, &traversal),+ CBM_STORE_OK);+ ASSERT_EQ(traversal.visited_count, 2);+ ASSERT_EQ(traversal.edge_count, 0);+ ASSERT_FALSE(traversal.edges_truncated);+ cbm_store_traverse_free(&traversal);++ memset(&traversal, 0, sizeof(traversal));+ ASSERT_EQ(+ cbm_store_bfs_with_edge_limit(store, hub_id, "outbound", types, 1, 1, 10, 1, &traversal),+ CBM_STORE_OK);+ ASSERT_EQ(traversal.visited_count, 2);+ ASSERT_EQ(traversal.edge_count, 1);+ ASSERT_TRUE(traversal.edges_truncated);+ ASSERT_FALSE(traversal.truncated);+ cbm_store_traverse_free(&traversal);cbm_mcp_server_free(srv);PASS();@@ -3781,17 +6082,291 @@ TEST(tool_trace_path_evidence_is_opt_in_and_class_mapped) {ASSERT_NOT_NULL(ev_json);char *ev_json_txt = extract_text_content(ev_json);ASSERT_NOT_NULL(ev_json_txt);- ASSERT_NOT_NULL(strstr(ev_json_txt, "\"strategy\""));- ASSERT_NOT_NULL(strstr(ev_json_txt, "\"confidence\""));- ASSERT_NOT_NULL(strstr(ev_json_txt, "lsp"));- ASSERT_NOT_NULL(strstr(ev_json_txt, "0.95"));+ yyjson_doc *ev_doc = yyjson_read(ev_json_txt, strlen(ev_json_txt), 0);+ ASSERT_NOT_NULL(ev_doc);+ yyjson_val *ev_root = yyjson_doc_get_root(ev_doc);+ yyjson_val *ev_callees = yyjson_obj_get(ev_root, "callees");+ yyjson_val *ev_cols = ev_callees ? yyjson_obj_get(ev_callees, "cols") : NULL;+ ASSERT_NOT_NULL(ev_cols);+ ASSERT_EQ(yyjson_arr_size(ev_cols), 4);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(ev_cols, 0)), "name");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(ev_cols, 1)), "hop");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(ev_cols, 2)), "strategy");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(ev_cols, 3)), "confidence");+ yyjson_val *ev_row = trace_grouped_row_named(ev_callees, "target", NULL);+ ASSERT_NOT_NULL(ev_row);+ ASSERT_EQ(yyjson_arr_size(ev_row), yyjson_arr_size(ev_cols));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(ev_row, 0)), "target");+ ASSERT_EQ(yyjson_get_int(yyjson_arr_get(ev_row, 1)), 1);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(ev_row, 2)), "lsp");+ ASSERT_EQ((int)(yyjson_get_real(yyjson_arr_get(ev_row, 3)) * 100.0), 95);ASSERT_NULL(strstr(ev_json_txt, "lsp_trait_dispatch"));+ yyjson_doc_free(ev_doc);free(ev_json_txt);free(ev_json);cbm_mcp_server_free(srv);PASS();}+/* Edge-data lookup must follow the traversal direction and shortest-path hop.+ * The induced edge set contains a same-hop cross edge whose source is the row+ * node and sorts before its real inbound predecessor. An arbitrary incident-+ * edge scan attaches the decoy args/evidence; canonical predecessor selection+ * must attach the edge that actually reaches the root. */+TEST(tool_trace_path_edge_details_use_canonical_predecessor) {+ 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 = "trace-predecessor";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/trace-predecessor"), CBM_STORE_OK);++ cbm_node_t wrong_target = {.project = project,+ .label = "Function",+ .name = "wrong_target",+ .qualified_name = "trace-predecessor.wrong_target",+ .file_path = "src/wrong.c",+ .start_line = 1,+ .end_line = 2};+ cbm_node_t caller = {.project = project,+ .label = "Function",+ .name = "caller",+ .qualified_name = "trace-predecessor.caller",+ .file_path = "src/caller.c",+ .start_line = 3,+ .end_line = 4};+ cbm_node_t root = {.project = project,+ .label = "Function",+ .name = "root",+ .qualified_name = "trace-predecessor.root",+ .file_path = "src/root.c",+ .start_line = 5,+ .end_line = 6};+ int64_t wrong_id = cbm_store_upsert_node(store, &wrong_target);+ int64_t caller_id = cbm_store_upsert_node(store, &caller);+ int64_t root_id = cbm_store_upsert_node(store, &root);+ ASSERT_GT(wrong_id, 0);+ ASSERT_GT(caller_id, wrong_id);+ ASSERT_GT(root_id, caller_id);++ cbm_edge_t edges[] = {+ {.project = project,+ .source_id = caller_id,+ .target_id = wrong_id,+ .type = "CALLS",+ .properties_json = "{\"args\":[{\"e\":\"decoy\"}],\"strategy\":\"callee_suffix\","+ "\"confidence\":0.1}"},+ {.project = project,+ .source_id = wrong_id,+ .target_id = root_id,+ .type = "CALLS",+ .properties_json = "{\"args\":[{\"e\":\"other\"}],\"strategy\":\"callee_suffix\","+ "\"confidence\":0.2}"},+ {.project = project,+ .source_id = caller_id,+ .target_id = root_id,+ .type = "CALLS",+ .properties_json = "{\"args\":[{\"e\":\"correct\"}],"+ "\"strategy\":\"lsp_trait_dispatch\",\"confidence\":0.9}"},+ };+ for (size_t i = 0; i < sizeof(edges) / sizeof(edges[0]); i++) {+ ASSERT_GT(cbm_store_insert_edge(store, &edges[i]), 0);+ }++ char *response =+ cbm_mcp_handle_tool(srv, "trace_path",+ "{\"project\":\"trace-predecessor\",\"function_name\":\"root\","+ "\"direction\":\"inbound\",\"mode\":\"data_flow\","+ "\"include_evidence\":true,\"format\":\"json\"}");+ 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 *callers = yyjson_obj_get(yyjson_doc_get_root(doc), "callers");+ ASSERT_NOT_NULL(callers);+ yyjson_val *row = trace_grouped_row_named(callers, "caller", NULL);+ ASSERT_NOT_NULL(row);+ ASSERT_EQ(yyjson_get_int(yyjson_arr_get(row, 1)), 1);+ yyjson_val *args = yyjson_arr_get(row, 2);+ ASSERT_TRUE(yyjson_is_arr(args));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(args, 0), "e")), "correct");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(row, 3)), "lsp");+ ASSERT_EQ((int)(yyjson_get_real(yyjson_arr_get(row, 4)) * 10.0), 9);+ ASSERT_NULL(strstr(inner, "decoy"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ PASS();+}++/* Audit contract: every opt-in trace column is positional. In particular,+ * data_flow args must stay under `args`, evidence must appear exactly once at+ * the tail, and the flat tree renderer selected by either risk_labels or+ * data_flow must not discard requested evidence. include_tests exercises the+ * widest flat-table shape and keeps a dotless qualified name in the payload. */+TEST(tool_trace_path_evidence_columns_align_across_optional_modes) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ const char *proj = "ev-align";+ cbm_mcp_server_set_project(srv, proj);+ cbm_store_upsert_project(st, proj, "/tmp/ev-align");+ cbm_node_t caller = {.project = proj,+ .label = "Function",+ .name = "caller",+ .qualified_name = "ev-align.src.caller",+ .file_path = "src/caller.c",+ .start_line = 1,+ .end_line = 5};+ cbm_node_t target = {.project = proj,+ .label = "Function",+ .name = "target",+ .qualified_name = "ev-align.src.target",+ .file_path = "src/target.c",+ .start_line = 10,+ .end_line = 20};+ cbm_node_t dotless_test = {.project = proj,+ .label = "Function",+ .name = "dotless_target",+ .qualified_name = "dotless_target",+ .file_path = "tests/test_target.c",+ .start_line = 1,+ .end_line = 4};+ int64_t caller_id = cbm_store_upsert_node(st, &caller);+ int64_t target_id = cbm_store_upsert_node(st, &target);+ int64_t dotless_id = cbm_store_upsert_node(st, &dotless_test);+ ASSERT_GT(caller_id, 0);+ ASSERT_GT(target_id, 0);+ ASSERT_GT(dotless_id, 0);+ cbm_edge_t target_edge = {.project = proj,+ .source_id = caller_id,+ .target_id = target_id,+ .type = "CALLS",+ .properties_json =+ "{\"args\":[{\"i\":0,\"e\":\"payload\"}],\"confidence\":0.95,"+ "\"strategy\":\"lsp_trait_dispatch\"}"};+ cbm_edge_t dotless_edge = {.project = proj,+ .source_id = caller_id,+ .target_id = dotless_id,+ .type = "CALLS",+ .properties_json =+ "{\"args\":[{\"i\":1,\"e\":\"fixture\"}],\"confidence\":0.5,"+ "\"strategy\":\"callee_suffix\"}"};+ ASSERT_GT(cbm_store_insert_edge(st, &target_edge), 0);+ ASSERT_GT(cbm_store_insert_edge(st, &dotless_edge), 0);++ char *response = cbm_mcp_handle_tool(+ srv, "trace_path",+ "{\"project\":\"ev-align\",\"function_name\":\"caller\",\"direction\":\"outbound\","+ "\"mode\":\"data_flow\",\"risk_labels\":true,\"include_tests\":true,"+ "\"include_evidence\":true,\"format\":\"json\"}");+ 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 *callees = yyjson_obj_get(root, "callees");+ ASSERT_NOT_NULL(callees);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(callees, "qn_rule")),+ "qn = qn_prefix == \"\" ? name : qn_prefix + \".\" + name");+ yyjson_val *cols = yyjson_obj_get(callees, "cols");+ ASSERT_NOT_NULL(cols);+ static const char *const expected_cols[] = {"name", "hop", "risk", "test",+ "args", "strategy", "confidence"};+ ASSERT_EQ(yyjson_arr_size(cols), sizeof(expected_cols) / sizeof(expected_cols[0]));+ for (size_t i = 0; i < sizeof(expected_cols) / sizeof(expected_cols[0]); i++) {+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(cols, i)), expected_cols[i]);+ }+ yyjson_val *target_row = trace_grouped_row_named(callees, "target", NULL);+ ASSERT_NOT_NULL(target_row);+ ASSERT_EQ(yyjson_arr_size(target_row), yyjson_arr_size(cols));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(target_row, 0)), "target");+ ASSERT_EQ(yyjson_get_int(yyjson_arr_get(target_row, 1)), 1);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(target_row, 2)), "CRITICAL");+ ASSERT_FALSE(yyjson_get_bool(yyjson_arr_get(target_row, 3)));+ yyjson_val *target_args = yyjson_arr_get(target_row, 4);+ ASSERT_TRUE(yyjson_is_arr(target_args));+ ASSERT_EQ(yyjson_arr_size(target_args), 1);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(target_args, 0), "e")), "payload");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(target_row, 5)), "lsp");+ ASSERT_EQ((int)(yyjson_get_real(yyjson_arr_get(target_row, 6)) * 100.0), 95);++ const char *dotless_prefix = NULL;+ yyjson_val *dotless_row = trace_grouped_row_named(callees, "dotless_target", &dotless_prefix);+ ASSERT_NOT_NULL(dotless_row);+ ASSERT_NOT_NULL(dotless_prefix);+ ASSERT_STR_EQ(dotless_prefix, "");+ ASSERT_EQ(yyjson_arr_size(dotless_row), yyjson_arr_size(cols));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(dotless_row, 0)), "dotless_target");+ ASSERT_TRUE(yyjson_get_bool(yyjson_arr_get(dotless_row, 3)));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(dotless_row, 5)), "heuristic");+ ASSERT_EQ((int)(yyjson_get_real(yyjson_arr_get(dotless_row, 6)) * 10.0), 5);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ /* risk_labels alone selects the flat tree path without implicitly enabling+ * evidence; the default stays lean even though the risk column is present. */+ response = cbm_mcp_handle_tool(+ srv, "trace_path",+ "{\"project\":\"ev-align\",\"function_name\":\"caller\",\"direction\":\"outbound\","+ "\"risk_labels\":true,\"include_tests\":true}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "(cols: qn hop risk test)"));+ ASSERT_NOT_NULL(strstr(inner, "ev-align.src.target 1 CRITICAL false"));+ ASSERT_NULL(strstr(inner, "strategy"));+ ASSERT_NULL(strstr(inner, "0.95"));+ free(inner);+ free(response);++ /* Combining risk_labels with evidence keeps evidence after risk/test. */+ response = cbm_mcp_handle_tool(+ srv, "trace_path",+ "{\"project\":\"ev-align\",\"function_name\":\"caller\",\"direction\":\"outbound\","+ "\"risk_labels\":true,\"include_tests\":true,\"include_evidence\":true}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "(cols: qn hop risk test strategy confidence)"));+ ASSERT_NOT_NULL(strstr(inner, "ev-align.src.target 1 CRITICAL false lsp 0.95"));+ ASSERT_NOT_NULL(strstr(inner, "dotless_target 1 CRITICAL true heuristic 0.5"));+ free(inner);+ free(response);++ /* data_flow alone reaches the same flat renderer; args retain their+ * established position and evidence follows them. */+ response = cbm_mcp_handle_tool(+ srv, "trace_path",+ "{\"project\":\"ev-align\",\"function_name\":\"caller\",\"direction\":\"outbound\","+ "\"mode\":\"data_flow\",\"include_tests\":true,\"include_evidence\":true}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "(cols: qn hop test args strategy confidence)"));+ ASSERT_NOT_NULL(strstr(inner, "lsp 0.95"));+ ASSERT_NOT_NULL(strstr(inner, "heuristic 0.5"));+ free(inner);+ free(response);++ /* With only two unrelated prefixes, the direct table is smaller than two+ * one-row groups. It keeps full QNs and the promised test marker. */+ response = cbm_mcp_handle_tool(+ srv, "trace_path",+ "{\"project\":\"ev-align\",\"function_name\":\"caller\",\"direction\":\"outbound\","+ "\"include_tests\":true,\"include_evidence\":true}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "(cols: qn hop test strategy confidence)"));+ ASSERT_NOT_NULL(strstr(inner, "ev-align.src.target 1 false lsp 0.95"));+ ASSERT_NOT_NULL(strstr(inner, "dotless_target 1 true heuristic 0.5"));+ ASSERT_NULL(strstr(inner, "qn = group prefix"));+ free(inner);+ free(response);++ cbm_mcp_server_free(srv);+ PASS();+}+/* #1542 leftover: header order is strategy,confidence then args, but json* used to emit args first; tree flat_trace (risk_labels || data_flow) used* to call bfs_to_toon_table without include_evidence. Pin both: every row@@ -4781,52 +7356,413 @@ TEST(tool_search_code_limit_declares_a_minimum_issue1511) {free(resp);cbm_mcp_server_free(srv);- ASSERT_TRUE(declared);+ ASSERT_TRUE(declared);+ PASS();+}++TEST(tool_search_code_no_project) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":34,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_code\","+ "\"arguments\":{\"pattern\":\"func main\","+ "\"project\":\"nonexistent\"}}}");+ ASSERT_NOT_NULL(resp);+ /* No project indexed → error */+ ASSERT_TRUE(strstr(resp, "not found") || strstr(resp, "not indexed") ||+ strstr(resp, "required"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+}++TEST(search_code_multi_word) {+ char tmp[512];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);++ /* Multi-word query "HandleRequest error" — should find the line+ * "func HandleRequest() error {" via regex conversion. */+ char req[512];+ snprintf(req, sizeof(req),+ "{\"jsonrpc\":\"2.0\",\"id\":90,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_code\","+ "\"arguments\":{\"pattern\":\"HandleRequest error\","+ "\"project\":\"test-project\"}}}");++ char *resp = cbm_mcp_server_handle(srv, req);+ ASSERT_NOT_NULL(resp);+ /* Should find at least one result (not zero) */+ ASSERT_TRUE(strstr(resp, "HandleRequest") != NULL);+ /* Should NOT contain an error about "not found" */+ ASSERT_TRUE(strstr(resp, "\"isError\":true") == NULL);+ free(resp);++ cleanup_snippet_dir(tmp);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(search_code_preserves_valid_utf8_source) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_srch_utf8_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char src_path[512];+ snprintf(src_path, sizeof(src_path), "%s/unicode.c", tmp);+ FILE *fp = cbm_fopen(src_path, "wb");+ ASSERT_NOT_NULL(fp);+ fputs("void unicode_needle(void) { /* Gr\xC3\xBC\xC3\x9F"+ "e \xE4\xB8\x96\xE7\x95\x8C */ }\n",+ fp);+ fclose(fp);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "search-utf8";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "unicode_needle",+ .qualified_name = "search-utf8.unicode_needle",+ .file_path = "unicode.c",+ .start_line = 1,+ .end_line = 1};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);++ char *response =+ cbm_mcp_handle_tool(srv, "search_code",+ "{\"pattern\":\"unicode_needle\",\"project\":\"search-utf8\","+ "\"mode\":\"full\",\"format\":\"json\"}");+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "Gr\xC3\xBC\xC3\x9F"+ "e"));+ ASSERT_NOT_NULL(strstr(inner, "\xE4\xB8\x96\xE7\x95\x8C"));+ ASSERT_NULL(strstr(inner, "Gr??e"));++ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cbm_unlink(src_path);+ cbm_rmdir(tmp);+ PASS();+}++TEST(search_code_reports_scan_saturation) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_srch_sat_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char src_path[512];+ snprintf(src_path, sizeof(src_path), "%s/many.c", tmp);+ FILE *fp = cbm_fopen(src_path, "wb");+ ASSERT_NOT_NULL(fp);+ for (int i = 0; i < 501; i++) {+ fprintf(fp, "int saturationneedle_%d = %d;\n", i, i);+ }+ fclose(fp);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "search-saturation";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "many",+ .qualified_name = "search-saturation.many",+ .file_path = "many.c",+ .start_line = 1,+ .end_line = 501};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);++ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":97,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_code\",\"arguments\":{"+ "\"pattern\":\"saturationneedle\",\"project\":\"search-saturation\","+ "\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"total_grep_matches\":500"));+ ASSERT_NOT_NULL(strstr(inner, "\"total_relation\":\"gte\""));+ ASSERT_NOT_NULL(strstr(inner, "\"scan_saturated\":true"));+ ASSERT_NOT_NULL(strstr(inner, "\"truncated\":true"));+ free(inner);+ free(resp);+ cbm_mcp_server_free(srv);+ cbm_unlink(src_path);+ cbm_rmdir(tmp);+ PASS();+}++TEST(search_code_default_budget_limits_raw_rows_before_graph_results) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_srch_budget_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char src_path[512];+ snprintf(src_path, sizeof(src_path), "%s/raw.txt", tmp);+ FILE *fp = cbm_fopen(src_path, "wb");+ ASSERT_NOT_NULL(fp);+ for (int row = 0; row < 20; row++) {+ fprintf(fp, "RAW_NEEDLE_%02d_", row);+ for (int col = 0; col < 850; col++) {+ fputc('a' + row % 26, fp);+ }+ fputc('\n', fp);+ }+ fclose(fp);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "search-budget";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);++ char *response =+ cbm_mcp_handle_tool(srv, "search_code",+ "{\"pattern\":\"RAW_NEEDLE\",\"project\":\"search-budget\","+ "\"format\":\"json\"}");+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_TRUE(strlen(inner) <= 3200U * 4U);+ ASSERT_NOT_NULL(strstr(inner, "\"raw_match_count\":20"));+ ASSERT_NOT_NULL(strstr(inner, "\"raw_returned\":5"));+ ASSERT_NOT_NULL(strstr(inner, "\"raw_has_more\":true"));+ free(inner);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "search_code",+ "{\"pattern\":\"RAW_NEEDLE\",\"project\":\"search-budget\","+ "\"raw_limit\":20,\"max_output_tokens\":20000,\"format\":\"json\"}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"raw_returned\":20"));+ ASSERT_NOT_NULL(strstr(inner, "\"raw_has_more\":false"));+ free(inner);+ free(response);++ cbm_mcp_server_free(srv);+ cbm_unlink(src_path);+ cbm_rmdir(tmp);+ PASS();+}++static char *search_code_long_identity(char fill, bool path) {+ enum { LONG_IDENTITY_LENGTH = 2304, FIRST_DIRECTORY_LENGTH = 200 };+ char *value = malloc(LONG_IDENTITY_LENGTH + 1U);+ if (!value) {+ return NULL;+ }+ memset(value, fill, LONG_IDENTITY_LENGTH);+ if (path) {+ for (size_t i = FIRST_DIRECTORY_LENGTH; i + 16U < LONG_IDENTITY_LENGTH; i += 73U) {+ value[i] = '/';+ }+ static const char suffix[] = "/needle.c";+ memcpy(value + LONG_IDENTITY_LENGTH - (sizeof(suffix) - 1U), suffix, sizeof(suffix) - 1U);+ } else {+ for (size_t i = 61U; i + 16U < LONG_IDENTITY_LENGTH; i += 61U) {+ value[i] = '.';+ }+ static const char suffix[] = ".Needle";+ memcpy(value + LONG_IDENTITY_LENGTH - (sizeof(suffix) - 1U), suffix, sizeof(suffix) - 1U);+ }+ value[LONG_IDENTITY_LENGTH] = '\0';+ return value;+}++TEST(search_code_preserves_multi_kib_identities_and_distinct_long_directories) {+ char *qualified_names[] = {search_code_long_identity('x', false),+ search_code_long_identity('y', false)};+ char *file_paths[] = {search_code_long_identity('a', true),+ search_code_long_identity('z', true)};+ ASSERT_NOT_NULL(qualified_names[0]);+ ASSERT_NOT_NULL(qualified_names[1]);+ ASSERT_NOT_NULL(file_paths[0]);+ ASSERT_NOT_NULL(file_paths[1]);++ const char *qualified_name_view[] = {qualified_names[0], qualified_names[1]};+ const char *file_path_view[] = {file_paths[0], file_paths[1]};+ char *tree =+ cbm_mcp_render_search_rows_for_testing(qualified_name_view, file_path_view, 2, false);+ ASSERT_NOT_NULL(tree);+ ASSERT_NOT_NULL(strstr(tree, qualified_names[0]));+ ASSERT_NOT_NULL(strstr(tree, qualified_names[1]));+ ASSERT_NOT_NULL(strstr(tree, file_paths[0]));+ ASSERT_NOT_NULL(strstr(tree, file_paths[1]));+ ASSERT_NOT_NULL(strstr(tree, "directories_total: 2"));+ free(tree);++ char *json =+ cbm_mcp_render_search_rows_for_testing(qualified_name_view, file_path_view, 2, true);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ yyjson_val *rows = yyjson_obj_get(root, "rows");+ ASSERT_EQ((int)yyjson_arr_size(rows), 2);+ yyjson_val *first = yyjson_arr_get(rows, 0);+ yyjson_val *second = yyjson_arr_get(rows, 1);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(first, 0)), qualified_names[0]);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(first, 2)), file_paths[0]);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(second, 0)), qualified_names[1]);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(second, 2)), file_paths[1]);++ char *first_directory = cbm_strndup(file_paths[0], 201U);+ char *second_directory = cbm_strndup(file_paths[1], 201U);+ ASSERT_NOT_NULL(first_directory);+ ASSERT_NOT_NULL(second_directory);+ yyjson_val *directories = yyjson_obj_get(root, "directories");+ ASSERT_EQ((int)yyjson_obj_size(directories), 2);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(directories, first_directory)), 1);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(directories, second_directory)), 1);++ free(first_directory);+ free(second_directory);+ yyjson_doc_free(doc);+ free(json);+ free(qualified_names[0]);+ free(qualified_names[1]);+ free(file_paths[0]);+ free(file_paths[1]);PASS();}-TEST(tool_search_code_no_project) {+TEST(search_code_long_raw_line_is_one_truthfully_truncated_match) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_srch_long_line_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char source_path[512];+ snprintf(source_path, sizeof(source_path), "%s/long.txt", tmp);+ FILE *source = cbm_fopen(source_path, "wb");+ ASSERT_NOT_NULL(source);+ fputs("LONG_RAW_NEEDLE_", source);+ for (int i = 0; i < 2500; i++) {+ fputc('q', source);+ }+ fputc('\n', source);+ fclose(source);+cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "search-long-raw-line";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);- char *resp =- cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":34,\"method\":\"tools/call\","- "\"params\":{\"name\":\"search_code\","- "\"arguments\":{\"pattern\":\"func main\","- "\"project\":\"nonexistent\"}}}");- ASSERT_NOT_NULL(resp);- /* No project indexed → error */- ASSERT_TRUE(strstr(resp, "not found") || strstr(resp, "not indexed") ||- strstr(resp, "required"));- free(resp);+ char *response =+ cbm_mcp_handle_tool(srv, "search_code",+ "{\"pattern\":\"LONG_RAW_NEEDLE\",\"project\":\"search-long-raw-line\","+ "\"raw_limit\":5,\"max_output_tokens\":10000,\"format\":\"json\"}");+ 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);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "total_grep_matches")), 1);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "raw_match_count")), 1);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "raw_content_truncated")), 1);+ yyjson_val *raw = yyjson_obj_get(root, "raw_matches");+ yyjson_val *rows = yyjson_obj_get(raw, "rows");+ ASSERT_EQ((int)yyjson_arr_size(rows), 1);+ yyjson_val *row = yyjson_arr_get(rows, 0);+ const char *content = yyjson_get_str(yyjson_arr_get(row, 2));+ ASSERT_NOT_NULL(content);+ ASSERT_NOT_NULL(strstr(content, "LONG_RAW_NEEDLE_"));+ ASSERT_EQ((int)strlen(content), CBM_SZ_1K - 1);+ yyjson_doc_free(doc);+ free(inner);+ free(response);cbm_mcp_server_free(srv);+ cbm_unlink(source_path);+ cbm_rmdir(tmp);PASS();}-TEST(search_code_multi_word) {- char tmp[512];- cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+TEST(search_code_match_locations_are_explicitly_bounded_and_expandable) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_srch_match_locations_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char source_path[512];+ snprintf(source_path, sizeof(source_path), "%s/many.c", tmp);+ FILE *source = cbm_fopen(source_path, "wb");+ ASSERT_NOT_NULL(source);+ for (int line = 1; line <= 100; line++) {+ fprintf(source, "MATCH_LOCATION_%03d\n", line);+ }+ fclose(source);++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "search-match-locations";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, tmp), CBM_STORE_OK);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = "many_matches",+ .qualified_name = "search_match_locations.many_matches",+ .file_path = "many.c",+ .start_line = 1,+ .end_line = 100};+ ASSERT_GT(cbm_store_upsert_node(store, &node), 0);- /* Multi-word query "HandleRequest error" — should find the line- * "func HandleRequest() error {" via regex conversion. */- char req[512];- snprintf(req, sizeof(req),- "{\"jsonrpc\":\"2.0\",\"id\":90,\"method\":\"tools/call\","- "\"params\":{\"name\":\"search_code\","- "\"arguments\":{\"pattern\":\"HandleRequest error\","- "\"project\":\"test-project\"}}}");+ char *response = cbm_mcp_handle_tool(+ srv, "search_code",+ "{\"pattern\":\"MATCH_LOCATION\",\"project\":\"search-match-locations\","+ "\"max_output_tokens\":10000,\"format\":\"json\"}");+ 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 *rows = yyjson_obj_get(root, "rows");+ ASSERT_EQ((int)yyjson_arr_size(rows), 1);+ yyjson_val *row = yyjson_arr_get(rows, 0);+ ASSERT_EQ((int)yyjson_arr_size(yyjson_arr_get(row, 4)), 8);+ ASSERT_EQ((int)yyjson_get_int(yyjson_arr_get(row, 5)), 92);+ yyjson_doc_free(doc);+ free(inner);+ free(response);- char *resp = cbm_mcp_server_handle(srv, req);- ASSERT_NOT_NULL(resp);- /* Should find at least one result (not zero) */- ASSERT_TRUE(strstr(resp, "HandleRequest") != NULL);- /* Should NOT contain an error about "not found" */- ASSERT_TRUE(strstr(resp, "\"isError\":true") == NULL);- free(resp);+ response = cbm_mcp_handle_tool(+ srv, "search_code",+ "{\"pattern\":\"MATCH_LOCATION\",\"project\":\"search-match-locations\","+ "\"max_output_tokens\":10000}");+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "matches_omitted"));+ ASSERT_NOT_NULL(strstr(inner, "1;2;3;4;5;6;7;8 92"));+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(+ srv, "search_code",+ "{\"pattern\":\"MATCH_LOCATION\",\"project\":\"search-match-locations\","+ "\"match_limit\":500,\"max_output_tokens\":10000,\"format\":\"json\"}");+ 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);+ row = yyjson_arr_get(yyjson_obj_get(root, "rows"), 0);+ ASSERT_EQ((int)yyjson_arr_size(yyjson_arr_get(row, 4)), 100);+ ASSERT_EQ((int)yyjson_get_int(yyjson_arr_get(row, 5)), 0);+ yyjson_doc_free(doc);+ free(inner);+ free(response);- cleanup_snippet_dir(tmp);cbm_mcp_server_free(srv);+ cbm_unlink(source_path);+ cbm_rmdir(tmp);PASS();}@@ -6614,6 +9550,78 @@ TEST(tool_manage_adr_sections_agrees_with_write_path) {PASS();}+TEST(tool_manage_adr_defaults_to_bounded_outline) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "adr-outline";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/adr-outline"), CBM_STORE_OK);++ char content[CBM_ADR_MAX_LENGTH];+ size_t used = 0;+ for (int i = 0; i < 60; i++) {+ int n = snprintf(content + used, sizeof(content) - used,+ "## Decision %02d\nbody %02d BODY_TAIL_%02d\n", i, i, i);+ ASSERT_GT(n, 0);+ used += (size_t)n;+ }+ ASSERT_EQ(cbm_store_adr_store(store, project, content), CBM_STORE_OK);++ char *resp = cbm_mcp_handle_tool(srv, "manage_adr", "{\"project\":\"adr-outline\"}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "mode: outline"));+ ASSERT_NOT_NULL(strstr(inner, "sections_total: 60"));+ ASSERT_NOT_NULL(strstr(inner, "sections_returned: 50"));+ ASSERT_NOT_NULL(strstr(inner, "next_section_offset: 50"));+ ASSERT_NULL(strstr(inner, "BODY_TAIL_59"));+ ASSERT_LT((int)strlen(inner), 5000);+ free(inner);+ free(resp);++ resp = cbm_mcp_handle_tool(+ srv, "manage_adr", "{\"project\":\"adr-outline\",\"mode\":\"get\",\"format\":\"json\"}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "BODY_TAIL_59"));+ ASSERT_NOT_NULL(strstr(inner, "\"content_complete\":true"));+ free(inner);+ free(resp);+ cbm_mcp_server_free(srv);+ PASS();+}++TEST(tool_manage_adr_rejects_unknown_mode_and_empty_update) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ const char *project = "adr-invalid-mode";+ cbm_mcp_server_set_project(srv, project);+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/adr-invalid-mode"), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_adr_store(store, project, "SECRET_ADR_BODY"), CBM_STORE_OK);++ char *resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-invalid-mode\",\"mode\":\"bogus\"}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "invalid mode"));+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));+ ASSERT_NULL(strstr(resp, "SECRET_ADR_BODY"));+ free(resp);++ resp = cbm_mcp_handle_tool(srv, "manage_adr",+ "{\"project\":\"adr-invalid-mode\",\"mode\":\"update\"}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "content is required"));+ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));+ ASSERT_NULL(strstr(resp, "SECRET_ADR_BODY"));+ free(resp);+ cbm_mcp_server_free(srv);+ PASS();+}+/* CBM_ADR_MAX_LENGTH is enforced on this path — mode='update' bypasses it, so* exposing an incremental writer without the cap would make unbounded growth* cheap. The rejected merge must also roll back to the byte-identical prior@@ -8752,6 +11760,277 @@ TEST(tool_detect_changes_contained_commands_clean_up_error_and_success) {PASS();}+TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget) {+ char repo[CBM_SZ_4K];+ (void)snprintf(repo, sizeof(repo), "%s/cbm-detect-pages-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(repo));+ char cache[CBM_SZ_4K];+ (void)snprintf(cache, sizeof(cache), "%s/cbm-detect-pages-cache-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(cache));++ 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", "[email protected]",+ "-c", "commit.gpgsign=false",+ "commit", "-q",+ "-m", "fixture",+ NULL,+ };+ ASSERT_EQ(mcp_test_git(repo, init_args), 0);+ ASSERT_EQ(mcp_test_git(repo, add_args), 0);+ ASSERT_EQ(mcp_test_git(repo, commit_args), 0);++ const char *filler =+ "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"+ "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";+ for (int i = 0; i < 25; i++) {+ char path[CBM_SZ_4K];+ (void)snprintf(path, sizeof(path), "%s/change-%02d-%s.c", repo, i, filler);+ ASSERT_EQ(th_write_file(path, "int changed;\n"), 0);+ }++ const char *saved_cache = getenv("CBM_CACHE_DIR");+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR", cache, 1), 0);+ 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);+ ASSERT_EQ(cbm_store_upsert_project(store, "detect-pages-project", repo), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, "detect-pages-project");++ char seed_file[512];+ (void)snprintf(seed_file, sizeof(seed_file), "change-00-%s.c", filler);+ cbm_node_t seed = {.project = "detect-pages-project",+ .label = "Function",+ .name = "changed_seed",+ .qualified_name = "fixture.changed_seed",+ .file_path = seed_file,+ .start_line = 1,+ .end_line = 1};+ int64_t seed_id = cbm_store_upsert_node(store, &seed);+ ASSERT_GT(seed_id, 0);+ enum { DETECT_LONG_VALUE = 3072 };+ char *long_detect_qn = malloc(DETECT_LONG_VALUE + 32U);+ char *long_detect_file = malloc(DETECT_LONG_VALUE + 32U);+ ASSERT_NOT_NULL(long_detect_qn);+ ASSERT_NOT_NULL(long_detect_file);+ memcpy(long_detect_qn, "fixture.", 8U);+ memset(long_detect_qn + 8U, 'q', DETECT_LONG_VALUE);+ memcpy(long_detect_qn + 8U + DETECT_LONG_VALUE, ".caller_00", 11U);+ size_t long_file_len = 0;+ for (int part = 0; part < 24; part++) {+ int written =+ snprintf(long_detect_file + long_file_len, DETECT_LONG_VALUE + 32U - long_file_len,+ "segment_%02d_%096d/", part, part);+ ASSERT_GT(written, 0);+ long_file_len += (size_t)written;+ }+ memcpy(long_detect_file + long_file_len, "caller.c", 9U);+ for (int i = 0; i < 25; i++) {+ char name[64];+ char qn[128];+ char file[128];+ (void)snprintf(name, sizeof(name), "caller_%02d", i);+ (void)snprintf(qn, sizeof(qn), "fixture.pkg%02d.sub.caller_%02d", i, i);+ (void)snprintf(file, sizeof(file), "pkg%02d/sub/caller.c", i);+ cbm_node_t caller = {.project = "detect-pages-project",+ .label = "Function",+ .name = name,+ .qualified_name = i == 0 ? long_detect_qn : qn,+ .file_path = i == 0 ? long_detect_file : file,+ .start_line = 1,+ .end_line = 1};+ int64_t caller_id = cbm_store_upsert_node(store, &caller);+ ASSERT_GT(caller_id, 0);+ cbm_edge_t edge = {.project = "detect-pages-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-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"files\",\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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);+ 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_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_doc_free(doc);+ free(inner);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"impact\",\"depth\":1,\"limit\":1,\"changed_limit\":0,"+ "\"max_output_tokens\":100000,\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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_TRUE(+ yyjson_get_bool(yyjson_obj_get(root, "changed_continuation_requires_positive_limit")));+ ASSERT_NULL(yyjson_obj_get(root, "changed_continuation_requires_higher_budget"));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "impacted_total")), 25);+ 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_EQ(yyjson_get_int(yyjson_obj_get(root, "impacted_next_offset")), 1);+ yyjson_val *first_impacted = yyjson_arr_get_first(yyjson_obj_get(root, "impacted"));+ ASSERT_NOT_NULL(first_impacted);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(first_impacted, "qn")), long_detect_qn);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(first_impacted, "file")), long_detect_file);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "module_total")), 25);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "module_total_relation")), "eq");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "module_returned")), 20);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "module_has_more")));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "module_next_offset")), 20);+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "impacted_modules")), 20);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"impact\",\"depth\":1,\"limit\":1,\"changed_limit\":0,"+ "\"module_limit\":0,\"max_output_tokens\":100000}");+ ASSERT_NOT_NULL(response);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ 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_NULL(strstr(inner, "module_continuation_requires_higher_budget"));+ free(inner);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"impact\",\"depth\":1,\"limit\":1,\"impact_offset\":1,"+ "\"changed_limit\":0,\"module_limit\":0,\"max_output_tokens\":100000,"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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, "impacted_shown")), 1);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "impacted_has_more")));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "impacted_next_offset")), 2);+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "impacted")), 1);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(+ srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"impact\",\"depth\":1,\"limit\":1,\"changed_limit\":0,"+ "\"module_offset\":20,\"max_output_tokens\":100000,\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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, "module_returned")), 5);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "module_has_more")));+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "impacted_modules")), 5);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"files\",\"changed_offset\":20,\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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, "changed_returned")), 5);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "changed_has_more")));+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "changed_files")), 5);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response =+ cbm_mcp_handle_tool(srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"files\",\"max_output_tokens\":128,\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_TRUE(strlen(inner) <= 128U * 4U);+ doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ root = yyjson_doc_get_root(doc);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "truncation_reason")), "output_budget");+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_total")), 25);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "changed_returned")), 0);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "changed_has_more")));+ ASSERT_NULL(yyjson_obj_get(root, "changed_next_offset"));+ ASSERT_TRUE(+ yyjson_get_bool(yyjson_obj_get(root, "changed_continuation_requires_higher_budget")));+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "changed_files")), 0);+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ response = cbm_mcp_handle_tool(srv, "detect_changes",+ "{\"project\":\"detect-pages-project\",\"base_branch\":\"HEAD\","+ "\"scope\":\"impact\",\"depth\":1,\"changed_limit\":0,"+ "\"max_output_tokens\":512,\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ 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, "impacted_shown")), 0);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "impacted_has_more")));+ ASSERT_NULL(yyjson_obj_get(root, "impacted_next_offset"));+ ASSERT_TRUE(+ yyjson_get_bool(yyjson_obj_get(root, "impacted_continuation_requires_higher_budget")));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "module_returned")), 0);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "module_has_more")));+ ASSERT_NULL(yyjson_obj_get(root, "module_next_offset"));+ ASSERT_TRUE(+ yyjson_get_bool(yyjson_obj_get(root, "module_continuation_requires_higher_budget")));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ cbm_mcp_server_free(srv);+ free(long_detect_file);+ free(long_detect_qn);+ restore_cache_dir(saved_cache_copy);+ free(saved_cache_copy);+ ASSERT_EQ(th_rmtree(cache), 0);+ ASSERT_EQ(th_rmtree(repo), 0);+ PASS();+}+/* Regression test for issue #1363: detect_changes seeded every definition in* a changed file instead of just the ones whose line range overlaps the diff* hunk. cbm_detect_node_in_hunks is the overlap primitive; this exercises it@@ -10035,7 +13314,19 @@ TEST(tool_compare_graphs_cancel_and_readonly_handles_release_issue525) {/* Call get_code_snippet and extract inner text content.* Caller must free returned string. */static char *call_snippet(cbm_mcp_server_t *srv, const char *args_json) {- char *raw = cbm_mcp_handle_tool(srv, "get_code_snippet", args_json);+ yyjson_doc *input_doc = yyjson_read(args_json, strlen(args_json), 0);+ if (!input_doc) {+ return NULL;+ }+ yyjson_mut_doc *request_doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *request = yyjson_val_mut_copy(request_doc, yyjson_doc_get_root(input_doc));+ yyjson_mut_doc_set_root(request_doc, request);+ yyjson_mut_obj_add_str(request_doc, request, "format", "json");+ char *json_args = yyjson_mut_write(request_doc, 0, NULL);+ yyjson_mut_doc_free(request_doc);+ yyjson_doc_free(input_doc);+ char *raw = cbm_mcp_handle_tool(srv, "get_code_snippet", json_args);+ free(json_args);char *text = extract_text_content(raw);free(raw);return text;@@ -10385,7 +13676,7 @@ TEST(snippet_source_invalid_utf8) {char *raw =cbm_mcp_handle_tool(srv, "get_code_snippet","{\"qualified_name\":\"test-project.cmd.server.main.HandleRequest\","- "\"project\":\"test-project\"}");+ "\"project\":\"test-project\",\"format\":\"json\"}");ASSERT_TRUE(is_valid_json_response(raw));char *resp = extract_text_content(raw);ASSERT_NOT_NULL(resp);@@ -11592,7 +14883,8 @@ static int idx823_supervised_name_override_check(const char *repo_dir, const chafree(resp);if (code == IDX823_OK) {- char *projects = cbm_mcp_handle_tool(srv, "list_projects", "{}");+ char *projects =+ cbm_mcp_handle_tool(srv, "list_projects", "{\"format\":\"json\",\"limit\":500}");char expected[256];snprintf(expected, sizeof(expected), "\"name\":\"%s\"", custom_name);if (!projects || !response_contains_json_fragment(projects, expected)) {@@ -13924,6 +17216,9 @@ SUITE(mcp) {RUN_TEST(jsonrpc_parse_notification);RUN_TEST(jsonrpc_parse_invalid);RUN_TEST(tree_cell_sanitizes_control_and_invalid_utf8);+ RUN_TEST(json_to_tree_uses_header_once_rows_without_losing_metadata);+ RUN_TEST(json_to_tree_keeps_multiline_source_readable);+ 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);RUN_TEST(jsonrpc_format_response_string_id_issue253);@@ -13946,6 +17241,7 @@ SUITE(mcp) {RUN_TEST(mcp_tools_list);RUN_TEST(mcp_tools_help_list_matches_registry);RUN_TEST(mcp_tools_list_latest_metadata);+ RUN_TEST(mcp_metadata_byte_budget);RUN_TEST(mcp_tools_have_behavior_annotations);RUN_TEST(mcp_index_repository_declares_name_override_issue571);RUN_TEST(mcp_tools_array_schemas_have_items);@@ -14021,21 +17317,34 @@ SUITE(mcp) {RUN_TEST(tool_get_file_outline_validates_json_path_limit_and_cancel_issue469);RUN_TEST(tool_search_graph_basic);RUN_TEST(tool_search_graph_semantic_only_skips_structural_results_issue1295);+ RUN_TEST(tool_search_graph_grouped_dotless_qn_round_trips);RUN_TEST(tool_trace_totals_respect_test_filter);RUN_TEST(tool_trace_totals_respect_test_filter_tests_root_subtree_issue1294);RUN_TEST(tool_get_architecture_cycles_detects_scc);RUN_TEST(tool_get_code_snippet_clips_whole_file_node);+ RUN_TEST(tool_get_code_snippet_omits_over_budget_whole_line);+ RUN_TEST(tool_get_code_snippet_pages_outline_rows_to_exact_budget);RUN_TEST(tool_search_graph_includes_node_properties);RUN_TEST(tool_search_graph_toon_never_leaks_internal_fields);RUN_TEST(tool_lean_defaults_schema_and_status);+ RUN_TEST(tool_index_status_keeps_authoritative_ignored_total_when_rows_are_sampled);RUN_TEST(tool_output_regression_gate);RUN_TEST(tool_output_byte_budgets);RUN_TEST(tool_search_graph_query_honors_file_pattern_issue552);+ RUN_TEST(tool_search_graph_bm25_reports_candidate_saturation);+ RUN_TEST(tool_search_graph_budget_preserves_long_values_and_continuation);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_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);+ RUN_TEST(tool_list_projects_tree_uses_one_stable_header_and_keeps_json_direct);+ RUN_TEST(tool_list_projects_preserves_root_beyond_one_kib);RUN_TEST(tool_index_status_no_project);RUN_TEST(tool_check_index_coverage_finds_path_beyond_status_cap);RUN_TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges);+ RUN_TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics);RUN_TEST(tool_check_index_coverage_preserves_multiple_scope_labels);RUN_TEST(tool_check_index_coverage_accepts_truncated_ignored_catalog_for_fresh_path_issue1613);RUN_TEST(tool_check_index_coverage_rejects_stale_generation);@@ -14050,11 +17359,19 @@ SUITE(mcp) {RUN_TEST(tool_trace_call_path_ambiguous);RUN_TEST(tool_trace_union_records_min_hop_across_seeds);RUN_TEST(tool_trace_pagination_exactly_once);+ RUN_TEST(tool_trace_paging_filters_before_window_and_hashes_effective_args);+ RUN_TEST(tool_trace_budget_never_slices_identifiers);+ RUN_TEST(tool_trace_cursor_survives_output_budget_increase);+ RUN_TEST(tool_trace_budget_drops_huge_optional_args_before_graph_row);+ RUN_TEST(tool_trace_reports_engine_saturation_as_lower_bound);+ RUN_TEST(store_bfs_edge_data_is_skippable_and_bounded);RUN_TEST(tool_trace_call_path_prefers_definition);RUN_TEST(trace_evidence_strategy_class_vocabulary_is_closed);RUN_TEST(tool_trace_path_evidence_is_opt_in_and_class_mapped);RUN_TEST(tool_trace_path_evidence_columns_match_header_issue1542);RUN_TEST(tool_trace_path_unreadable_confidence_reports_not_recorded);+ RUN_TEST(tool_trace_path_edge_details_use_canonical_predecessor);+ RUN_TEST(tool_trace_path_evidence_columns_align_across_optional_modes);RUN_TEST(tool_trace_call_path_depth_clamped);RUN_TEST(tool_trace_call_path_distinct_defs_not_over_unioned);RUN_TEST(tool_trace_call_path_dts_stub_unions_with_impl);@@ -14082,6 +17399,12 @@ SUITE(mcp) {RUN_TEST(search_code_raw_match_preserves_utf8_content);RUN_TEST(search_code_context_preserves_utf8_context);RUN_TEST(search_code_invalid_utf8_still_returns_valid_json);+ RUN_TEST(search_code_preserves_valid_utf8_source);+ RUN_TEST(search_code_reports_scan_saturation);+ RUN_TEST(search_code_default_budget_limits_raw_rows_before_graph_results);+ RUN_TEST(search_code_preserves_multi_kib_identities_and_distinct_long_directories);+ RUN_TEST(search_code_long_raw_line_is_one_truthfully_truncated_match);+ RUN_TEST(search_code_match_locations_are_explicitly_bounded_and_expandable);RUN_TEST(search_code_scoped_path_with_spaces_issue687);#ifdef _WIN32RUN_TEST(search_code_scoped_path_with_cjk_root_issue903);@@ -14110,6 +17433,8 @@ SUITE(mcp) {RUN_TEST(tool_detect_changes_no_project);RUN_TEST(tool_manage_adr_no_project);RUN_TEST(tool_manage_adr_get_with_existing_adr);+ RUN_TEST(tool_manage_adr_defaults_to_bounded_outline);+ RUN_TEST(tool_manage_adr_rejects_unknown_mode_and_empty_update);RUN_TEST(tool_manage_adr_unified_backend_issue256);RUN_TEST(tool_manage_adr_rejects_removed_sections_argument);RUN_TEST(tool_manage_adr_set_sections_replaces_only_named);@@ -14144,6 +17469,7 @@ SUITE(mcp) {RUN_TEST(tool_manage_adr_get_accepts_symlink_path);RUN_TEST(tool_detect_changes_not_found_rich_error);RUN_TEST(tool_detect_changes_contained_commands_clean_up_error_and_success);+ RUN_TEST(tool_detect_changes_pages_changed_files_and_honors_semantic_budget);RUN_TEST(detect_changes_node_in_hunks_overlap_issue1363);RUN_TEST(detect_changes_seeds_only_touched_symbol_issue1363);RUN_TEST(detect_changes_zero_overlap_falls_back_issue1363);diff --git a/tests/windows/test_daemon_lifecycle.py b/tests/windows/test_daemon_lifecycle.pyindex 37130dc57..226717fef 100644--- a/tests/windows/test_daemon_lifecycle.py+++ b/tests/windows/test_daemon_lifecycle.py@@ -6,7 +6,8 @@ Guards the PR #1139 daemon-control surface at the product level:* ``daemon start`` launches a PERMANENT daemon: it reports a pid, and thedaemon survives its clients (a one-shot ``cli`` command recycles it withoutprinting the cold-start hint, and the daemon is still active afterwards).-* A cold one-shot ``cli`` command (no daemon) prints the startup-tax hint.+* A cold one-shot ``cli`` command is quiet by default; ``cli --verbose`` opts+ into the startup-tax hint.* ``daemon stop`` on an idle daemon stops it; a second ``stop`` is idempotent.Every path carries a kill-by-pid backstop so a stuck daemon can never hang the@@ -68,11 +69,23 @@ def main():cold = run_cli(binary, cache, ["cli", "list_projects", "{}"])cold_text = output_text(cold)- if cold.returncode != 0 or "daemon start" not in cold_text:- print("RED: a cold one-shot cli command should succeed and hint at "- "`daemon start`:\n%s" % cold_text[:400])+ if cold.returncode != 0 or "daemon start" in cold_text:+ print("RED: a cold one-shot cli command should succeed without default "+ "startup chatter:\n%s" % cold_text[:400])return 1- print("PASS: cold cli one-shot succeeded and printed the startup-tax hint")+ print("PASS: cold cli one-shot succeeded quietly")++ # Use an isolated rendezvous namespace to guarantee a cold verbose call.+ verbose_cache = os.path.join(work, "cache-verbose")+ os.makedirs(verbose_cache, exist_ok=True)+ verbose = run_cli(binary, verbose_cache,+ ["cli", "--verbose", "list_projects", "{}"])+ verbose_text = output_text(verbose)+ if verbose.returncode != 0 or "daemon start" not in verbose_text:+ print("RED: `cli --verbose` should expose the cold-start hint:\n%s"+ % verbose_text[:400])+ return 1+ print("PASS: verbose cold cli exposed the startup-tax hint")start = run_cli(binary, cache, ["daemon", "start"])start_text = output_text(start)diff --git a/tests/windows/test_daemon_stability.py b/tests/windows/test_daemon_stability.pyindex 43b96723b..7bc838182 100644--- a/tests/windows/test_daemon_stability.py+++ b/tests/windows/test_daemon_stability.py@@ -332,9 +332,9 @@ def section_crash_recovery(binary, work):"(`daemon status` kept reporting it)" % daemon_pid)return Falsecold = run_cli(binary, cache, ["cli", "list_projects", "{}"], timeout=90)- if cold.returncode != 0 or "daemon start" not in out_text(cold):- print("RED: a cold one-shot after the daemon crash should succeed with the "- "startup-tax hint:\n%s" % excerpt(out_text(cold)))+ if cold.returncode != 0 or "daemon start" in out_text(cold):+ print("RED: a cold one-shot after the daemon crash should succeed without "+ "default startup chatter:\n%s" % excerpt(out_text(cold)))return Falserestart = run_cli(binary, cache, ["daemon", "start"], timeout=60)second_pid = pid_from(out_text(restart))