Open
feat: add evidence-first graph queries #5
AbssyLanAdd on Sep 7
feat: add evidence-first graph queries #5
Open
Total: 10 files changed+1084-21
| @@ -226,7 +226,7 @@ project-brain serve --transport streamable-http \ | |||
| 226 | project-brain --project /path/to/project <command> [options] | 226 | project-brain --project /path/to/project <command> [options] |
| 227 | ``` | 227 | ``` |
| 228 | 228 | ||
| 229 | -**代码查询命令(19 个):** | 229 | +**代码查询命令:** |
| 230 | 230 | ||
| 231 | | 命令 | 说明 | 示例 | | 231 | | 命令 | 说明 | 示例 | |
| 232 | |------|------|------| | 232 | |------|------|------| |
| @@ -234,9 +234,11 @@ project-brain --project /path/to/project <command> [options] | |||
| 234 | | `locate` | 按名定位符号 | `project-brain locate Poll --kind class` | | 234 | | `locate` | 按名定位符号 | `project-brain locate Poll --kind class` | |
| 235 | | `symbol` | 符号详情(含调用关系) | `project-brain symbol Poll --include callers` | | 235 | | `symbol` | 符号详情(含调用关系) | `project-brain symbol Poll --include callers` | |
| 236 | | `calls` | 调用图查询 | `project-brain calls spawn --direction callers --depth 2` | | 236 | | `calls` | 调用图查询 | `project-brain calls spawn --direction callers --depth 2` | |
| 237 | +| `relations` | 带类型和源码证据的关系查询 | `project-brain relations Derived --type IMPLEMENT,OVERRIDES --json` | | ||
| 237 | | `context` | 多维上下文(RAG) | `project-brain context Poll --scope callers` | | 238 | | `context` | 多维上下文(RAG) | `project-brain context Poll --scope callers` | |
| 238 | | `module` | 模块符号列表 | `project-brain module ylong_io --exported-only` | | 239 | | `module` | 模块符号列表 | `project-brain module ylong_io --exported-only` | |
| 239 | | `file` | 文件内符号 | `project-brain file src/poll.rs` | | 240 | | `file` | 文件内符号 | `project-brain file src/poll.rs` | |
| 241 | +| `files` | 已索引代码文件枚举 | `project-brain files --pattern "*.h" --kind header` | | ||
| 240 | | `deps` | 模块依赖 | `project-brain deps ylong_io --direction up` | | 242 | | `deps` | 模块依赖 | `project-brain deps ylong_io --direction up` | |
| 241 | | `tests` | 关联测试 | `project-brain tests Poll` | | 243 | | `tests` | 关联测试 | `project-brain tests Poll` | |
| 242 | | `history` | 修改历史 | `project-brain history src/poll.rs --limit 20` | | 244 | | `history` | 修改历史 | `project-brain history src/poll.rs --limit 20` | |
| @@ -285,6 +287,30 @@ project-brain search "timeout" --json | jq '.results[0]' | |||
| 285 | 287 | ||
| 286 | **常用参数:** `--json`(所有命令)、`--top-k`(search)、`--kind`(locate/code)、`--direction`(calls/deps)、`--depth`(calls/context)、`--include`(symbol)、`--exported-only`(module)、`--limit`(history)、`--format`(diff)、`--scope`/`--pattern`(docs)。 | 288 | **常用参数:** `--json`(所有命令)、`--top-k`(search)、`--kind`(locate/code)、`--direction`(calls/deps)、`--depth`(calls/context)、`--include`(symbol)、`--exported-only`(module)、`--limit`(history)、`--format`(diff)、`--scope`/`--pattern`(docs)。 |
| 287 | 289 | ||
| 290 | +### 证据化查询(0.7.0) | ||
| 291 | + | ||
| 292 | +```bash | ||
| 293 | +# 精确查符号定义,不混入声明、文档或语义搜索结果 | ||
| 294 | +project-brain search smb2_alloc_init --mode exact --domain symbols --definitions-only --json | ||
| 295 | +# 只查看文件顶层符号;默认 file 仍保留所有层级 | ||
| 296 | +project-brain file include/api.h --top-level-only --json | ||
| 297 | +# 查看模板使用关系;关系类型保留图中原始名称 | ||
| 298 | +project-brain relations identity --type TEMPLATE_SPECIALIZATION --direction out --json | ||
| 299 | +# 查看直接调用,或限定回调注册的源码证据文件 | ||
| 300 | +project-brain relations smb2_read_async --type CALL --direct-only --json | ||
| 301 | +project-brain relations smb2_notify_change_async --type CALL --resolution direct_callback_argument --evidence-scope lib/sync.c --json | ||
| 302 | +``` | ||
| 303 | + | ||
| 304 | +`relations` 返回 `source`、`target`、关系类型、`evidence_locations`(已存储的全部调用点)、`resolution`、`provenance` 和原始 `properties`。`--evidence-scope` 按证据路径子串筛选,并在 `matched_evidence_locations` 中列出命中位置;不会删除图中其他证据。旧索引缺少行号时返回 `null`,不会用符号定义行冒充调用点。`IMPLEMENT` 的原始方向是派生类 → 基类,`OVERRIDES` 是基类方法 → 派生类方法。 | ||
| 305 | + | ||
| 306 | +用 `--direction in|out|both` 和 `--depth` 控制邻接关系遍历(最多 10 层),`--max-items` 控制返回上限(默认 1000,最多 10000);若达到输出或内部检查上限,返回 `truncated: true`。这是邻接查询,不是两个符号之间的精确路径查询。`--project-only` 仅保留两端都有项目内相对路径的关系,不等同于标准库识别:仓库中 vendored 的库仍算项目内。`--direct-only` 排除已标记的回调、函数指针及 FFI/宏关系;旧索引未标记的间接调用无法据此识别。 | ||
| 307 | + | ||
| 308 | +`files` 枚举已索引的代码文件,而非实时扫描磁盘;支持 `--pattern`、`--language`、`--kind header|source`、`--exclude-tests`、`--exclude-generated`、`--max-items`。结果带路径、解析状态和覆盖信息;未进入索引的文件不会出现。文件是否为测试/生成文件由已有索引元数据决定。 | ||
| 309 | + | ||
| 310 | +当前语义过滤依据存储的边级 `resolution`;旧索引中合并的多个调用点可能没有各自的解析分类,不能把边级分类当成每个调用点的独立证明。`file --top-level-only` 依据 owner/class 元数据过滤嵌套成员,仍保留真实存在的顶层 typedef 别名,不进行按评测口径的别名合并。 | ||
| 311 | + | ||
| 312 | +`search --domain symbols|documents|code|all` 用于分离符号、文档和代码切片;默认仍为混合排序搜索。`--mode exact` 使用符号定位匹配,不运行语义检索。`locate --definitions-only` 和 `file --definitions-only` 也支持只输出定义;它们仅过滤查询结果,不合并或删除图中的声明节点。所有这些 CLI 查询继续以只读方式使用现有索引;更新源码后请先运行 `project-brain build`。 | ||
| 313 | + | ||
| 288 | ## 与 AI 工具集成 | 314 | ## 与 AI 工具集成 |
| 289 | 315 | ||
| 290 | ### Claude Code | 316 | ### Claude Code |
| @@ -1,6 +1,6 @@ | |||
| 1 | [project] | 1 | [project] |
| 2 | name = "project-brain" | 2 | name = "project-brain" |
| 3 | -version = "0.6.0" | 3 | +version = "0.7.0" |
| 4 | description = "面向研发 Agent 的项目知识图谱引擎" | 4 | description = "面向研发 Agent 的项目知识图谱引擎" |
| 5 | requires-python = ">=3.10" | 5 | requires-python = ">=3.10" |
| 6 | dependencies = [ | 6 | dependencies = [ |
| @@ -674,7 +674,7 @@ def _cmd_info(project_path: Path): | |||
| 674 | 674 | ||
| 675 | 675 | ||
| 676 | # --------------------------------------------------------------------------- # | 676 | # --------------------------------------------------------------------------- # |
| 677 | -# Query commands (18): each maps a CLI subcommand to a QueryEngine method. | 677 | +# Query commands: each maps a CLI subcommand to a QueryEngine/MCP method. |
| 678 | # --------------------------------------------------------------------------- # | 678 | # --------------------------------------------------------------------------- # |
| 679 | # | 679 | # |
| 680 | # _QUERY_SPECS maps subcommand name -> (engine_method, arg_builders). | 680 | # _QUERY_SPECS maps subcommand name -> (engine_method, arg_builders). |
| @@ -853,12 +853,21 @@ _QUERY_SPECS = { | |||
| 853 | {"flags": ["--test-filter"], "opts": {"default": "normal", | 853 | {"flags": ["--test-filter"], "opts": {"default": "normal", |
| 854 | "choices": ["all", "normal", "test"], | 854 | "choices": ["all", "normal", "test"], |
| 855 | "help": "normal (non-test, default), test (tests only), all"}}, | 855 | "help": "normal (non-test, default), test (tests only), all"}}, |
| 856 | + {"flags": ["--domain"], "opts": {"default": "all", | ||
| 857 | + "choices": ["all", "symbols", "documents", "code"]}}, | ||
| 858 | + {"flags": ["--mode"], "opts": {"default": "ranked", | ||
| 859 | + "choices": ["ranked", "exact"]}}, | ||
| 860 | + {"flags": ["--definitions-only"], "opts": { | ||
| 861 | + "action": "store_true", "default": False}}, | ||
| 856 | ], | 862 | ], |
| 857 | "kwargs": { | 863 | "kwargs": { |
| 858 | "query": _arg("query"), | 864 | "query": _arg("query"), |
| 859 | "scope": _arg("scope"), | 865 | "scope": _arg("scope"), |
| 860 | "top_k": _arg("top_k"), | 866 | "top_k": _arg("top_k"), |
| 861 | "test_filter": _arg("test_filter"), | 867 | "test_filter": _arg("test_filter"), |
| 868 | + "domain": _arg("domain"), | ||
| 869 | + "mode": _arg("mode"), | ||
| 870 | + "definitions_only": _arg("definitions_only"), | ||
| 862 | }, | 871 | }, |
| 863 | }, | 872 | }, |
| 864 | "locate": { | 873 | "locate": { |
| @@ -868,8 +877,14 @@ _QUERY_SPECS = { | |||
| 868 | {"flags": ["symbol_name"], "opts": {"help": "symbol name"}}, | 877 | {"flags": ["symbol_name"], "opts": {"help": "symbol name"}}, |
| 869 | {"flags": ["--kind"], "opts": {"default": None, | 878 | {"flags": ["--kind"], "opts": {"default": None, |
| 870 | "help": "class/function/module"}}, | 879 | "help": "class/function/module"}}, |
| 880 | + {"flags": ["--definitions-only"], "opts": { | ||
| 881 | + "action": "store_true", "default": False}}, | ||
| 871 | ], | 882 | ], |
| 872 | - "kwargs": {"symbol_name": _arg("symbol_name"), "kind": _arg("kind")}, | 883 | + "kwargs": { |
| 884 | + "symbol_name": _arg("symbol_name"), | ||
| 885 | + "kind": _arg("kind"), | ||
| 886 | + "definitions_only": _arg("definitions_only"), | ||
| 887 | + }, | ||
| 873 | }, | 888 | }, |
| 874 | "symbol": { | 889 | "symbol": { |
| 875 | "name": "symbol", "tool": "get_symbol_info", | 890 | "name": "symbol", "tool": "get_symbol_info", |
| @@ -896,6 +911,38 @@ _QUERY_SPECS = { | |||
| 896 | "depth": _arg("depth"), | 911 | "depth": _arg("depth"), |
| 897 | }, | 912 | }, |
| 898 | }, | 913 | }, |
| 914 | + "relations": { | ||
| 915 | + "name": "relations", "tool": "get_relations", | ||
| 916 | + "help": "Query typed graph relations with edge evidence", | ||
| 917 | + "args": [ | ||
| 918 | + {"flags": ["target"], "opts": {"help": "symbol id/name/qualified name"}}, | ||
| 919 | + {"flags": ["--type"], "opts": {"dest": "relation_types", "default": None, | ||
| 920 | + "help": "comma/slash-separated edge types"}}, | ||
| 921 | + {"flags": ["--direction"], "opts": {"default": "both", | ||
| 922 | + "choices": ["in", "out", "both"]}}, | ||
| 923 | + {"flags": ["--depth"], "opts": {"type": int, "default": 1}}, | ||
| 924 | + {"flags": ["--project-only"], "opts": {"action": "store_true", | ||
| 925 | + "default": False}}, | ||
| 926 | + {"flags": ["--direct-only"], "opts": {"action": "store_true", | ||
| 927 | + "default": False}}, | ||
| 928 | + {"flags": ["--resolution"], "opts": {"default": None, | ||
| 929 | + "help": "exact resolver classification filter"}}, | ||
| 930 | + {"flags": ["--evidence-scope"], "opts": {"default": None, | ||
| 931 | + "help": "call-site path substring filter"}}, | ||
| 932 | + {"flags": ["--max-items"], "opts": {"type": int, "default": 1000}}, | ||
| 933 | + ], | ||
| 934 | + "kwargs": { | ||
| 935 | + "target": _arg("target"), | ||
| 936 | + "relation_types": _arg("relation_types"), | ||
| 937 | + "direction": _arg("direction"), | ||
| 938 | + "depth": _arg("depth"), | ||
| 939 | + "project_only": _arg("project_only"), | ||
| 940 | + "direct_only": _arg("direct_only"), | ||
| 941 | + "resolution": _arg("resolution"), | ||
| 942 | + "evidence_scope": _arg("evidence_scope"), | ||
| 943 | + "max_items": _arg("max_items"), | ||
| 944 | + }, | ||
| 945 | + }, | ||
| 899 | "context": { | 946 | "context": { |
| 900 | "name": "context", "tool": "get_context", | 947 | "name": "context", "tool": "get_context", |
| 901 | "help": "Get multi-dimensional context (RAG)", | 948 | "help": "Get multi-dimensional context (RAG)", |
| @@ -928,8 +975,45 @@ _QUERY_SPECS = { | |||
| 928 | "file": { | 975 | "file": { |
| 929 | "name": "file", "tool": "get_file_symbols", | 976 | "name": "file", "tool": "get_file_symbols", |
| 930 | "help": "List symbols defined in a file", | 977 | "help": "List symbols defined in a file", |
| 931 | - "args": [{"flags": ["file_path"], "opts": {"help": "file path"}}], | 978 | + "args": [ |
| 932 | - "kwargs": {"file_path": _arg("file_path")}, | 979 | + {"flags": ["file_path"], "opts": {"help": "file path"}}, |
| 980 | + {"flags": ["--top-level-only"], "opts": { | ||
| 981 | + "action": "store_true", "default": False}}, | ||
| 982 | + {"flags": ["--kind"], "opts": {"dest": "kinds", "default": None, | ||
| 983 | + "help": "comma/slash-separated symbol kinds"}}, | ||
| 984 | + {"flags": ["--definitions-only"], "opts": { | ||
| 985 | + "action": "store_true", "default": False}}, | ||
| 986 | + ], | ||
| 987 | + "kwargs": { | ||
| 988 | + "file_path": _arg("file_path"), | ||
| 989 | + "top_level_only": _arg("top_level_only"), | ||
| 990 | + "kinds": _arg("kinds"), | ||
| 991 | + "definitions_only": _arg("definitions_only"), | ||
| 992 | + }, | ||
| 993 | + }, | ||
| 994 | + "files": { | ||
| 995 | + "name": "files", "tool": "list_code_files", | ||
| 996 | + "help": "Enumerate indexed source/header files", | ||
| 997 | + "args": [ | ||
| 998 | + {"flags": ["--pattern"], "opts": {"default": None, | ||
| 999 | + "help": "glob such as *.h or include/**/*.hpp"}}, | ||
| 1000 | + {"flags": ["--language"], "opts": {"default": None}}, | ||
| 1001 | + {"flags": ["--kind"], "opts": {"default": "all", | ||
| 1002 | + "choices": ["all", "header", "source"]}}, | ||
| 1003 | + {"flags": ["--exclude-tests"], "opts": { | ||
| 1004 | + "dest": "include_tests", "action": "store_false", "default": True}}, | ||
| 1005 | + {"flags": ["--exclude-generated"], "opts": { | ||
| 1006 | + "dest": "include_generated", "action": "store_false", "default": True}}, | ||
| 1007 | + {"flags": ["--max-items"], "opts": {"type": int, "default": 10_000}}, | ||
| 1008 | + ], | ||
| 1009 | + "kwargs": { | ||
| 1010 | + "pattern": _arg("pattern"), | ||
| 1011 | + "language": _arg("language"), | ||
| 1012 | + "kind": _arg("kind"), | ||
| 1013 | + "include_tests": _arg("include_tests"), | ||
| 1014 | + "include_generated": _arg("include_generated"), | ||
| 1015 | + "max_items": _arg("max_items"), | ||
| 1016 | + }, | ||
| 933 | }, | 1017 | }, |
| 934 | "deps": { | 1018 | "deps": { |
| 935 | "name": "deps", "tool": "get_dependencies", | 1019 | "name": "deps", "tool": "get_dependencies", |
| @@ -147,6 +147,33 @@ def _format_get_call_graph(r: dict) -> str: | |||
| 147 | return "\n".join(out).rstrip() | 147 | return "\n".join(out).rstrip() |
| 148 | 148 | ||
| 149 | 149 | ||
| 150 | +def _format_get_relations(r: dict) -> str: | ||
| 151 | + relations = r.get("relations", []) | ||
| 152 | + out = [ | ||
| 153 | + f"Relations for: {r.get('target')} ({len(relations)}){_freshness(r)}", | ||
| 154 | + "", | ||
| 155 | + ] | ||
| 156 | + rows = [] | ||
| 157 | + for relation in relations: | ||
| 158 | + source = relation.get("source") or {} | ||
| 159 | + target = relation.get("target") or {} | ||
| 160 | + evidence = relation.get("evidence") or {} | ||
| 161 | + location = evidence.get("file") or "" | ||
| 162 | + if evidence.get("line_start") is not None: | ||
| 163 | + location += f":{evidence['line_start']}" | ||
| 164 | + rows.append([ | ||
| 165 | + relation.get("type", ""), | ||
| 166 | + source.get("qualified_name") or source.get("name") or source.get("id", ""), | ||
| 167 | + target.get("qualified_name") or target.get("name") or target.get("id", ""), | ||
| 168 | + location, | ||
| 169 | + relation.get("resolution") or "", | ||
| 170 | + ]) | ||
| 171 | + out.append(_table(["TYPE", "SOURCE", "TARGET", "EVIDENCE", "RESOLUTION"], rows)) | ||
| 172 | + if r.get("truncated"): | ||
| 173 | + out.append("[truncated] Narrow the query or increase --max-items.") | ||
| 174 | + return "\n".join(out) | ||
| 175 | + | ||
| 176 | + | ||
| 150 | def _format_get_context(r: dict) -> str: | 177 | def _format_get_context(r: dict) -> str: |
| 151 | out = [f"Context for: {r.get('target')}{_freshness(r)}", ""] | 178 | out = [f"Context for: {r.get('target')}{_freshness(r)}", ""] |
| 152 | ctx = r.get("context", {}) | 179 | ctx = r.get("context", {}) |
| @@ -207,6 +234,24 @@ def _format_get_file_symbols(r: dict) -> str: | |||
| 207 | return "\n".join(out) | 234 | return "\n".join(out) |
| 208 | 235 | ||
| 209 | 236 | ||
| 237 | +def _format_list_code_files(r: dict) -> str: | ||
| 238 | + files = r.get("files", []) | ||
| 239 | + total = r.get("total", len(files)) | ||
| 240 | + suffix = ", truncated" if r.get("truncated") else "" | ||
| 241 | + out = [f"Files ({len(files)}/{total}{suffix}){_freshness(r)}", ""] | ||
| 242 | + rows = [ | ||
| 243 | + [ | ||
| 244 | + item.get("kind", ""), | ||
| 245 | + item.get("language") or "", | ||
| 246 | + item.get("path", ""), | ||
| 247 | + item.get("parse_status") or "", | ||
| 248 | + ] | ||
| 249 | + for item in files | ||
| 250 | + ] | ||
| 251 | + out.append(_table(["KIND", "LANGUAGE", "PATH", "PARSE"], rows)) | ||
| 252 | + return "\n".join(out) | ||
| 253 | + | ||
| 254 | + | ||
| 210 | def _format_get_dependencies(r: dict) -> str: | 255 | def _format_get_dependencies(r: dict) -> str: |
| 211 | out = [f"Dependencies for: {r.get('target')}{_freshness(r)}", ""] | 256 | out = [f"Dependencies for: {r.get('target')}{_freshness(r)}", ""] |
| 212 | up = r.get("upstream", []) | 257 | up = r.get("upstream", []) |
| @@ -390,9 +435,11 @@ _FORMATTERS = { | |||
| 390 | "locate_symbol": _format_locate_symbol, | 435 | "locate_symbol": _format_locate_symbol, |
| 391 | "get_symbol_info": _format_get_symbol_info, | 436 | "get_symbol_info": _format_get_symbol_info, |
| 392 | "get_call_graph": _format_get_call_graph, | 437 | "get_call_graph": _format_get_call_graph, |
| 438 | + "get_relations": _format_get_relations, | ||
| 393 | "get_context": _format_get_context, | 439 | "get_context": _format_get_context, |
| 394 | "get_module_contents": _format_get_module_contents, | 440 | "get_module_contents": _format_get_module_contents, |
| 395 | "get_file_symbols": _format_get_file_symbols, | 441 | "get_file_symbols": _format_get_file_symbols, |
| 442 | + "list_code_files": _format_list_code_files, | ||
| 396 | "get_dependencies": _format_get_dependencies, | 443 | "get_dependencies": _format_get_dependencies, |
| 397 | "get_related_tests": _format_get_related_tests, | 444 | "get_related_tests": _format_get_related_tests, |
| 398 | "get_history": _format_get_history, | 445 | "get_history": _format_get_history, |
| @@ -1126,17 +1126,24 @@ class ProjectBrainServer: | |||
| 1126 | """ | 1126 | """ |
| 1127 | # -- sync implementations ------------------------------------------------ | 1127 | # -- sync implementations ------------------------------------------------ |
| 1128 | 1128 | ||
| 1129 | - def _keyword_search(query, scope=None, top_k=20, test_filter="normal"): | 1129 | + def _keyword_search( |
| 1130 | + query, scope=None, top_k=20, test_filter="normal", domain="all", | ||
| 1131 | + definitions_only=False, mode="ranked", | ||
| 1132 | + ): | ||
| 1130 | self._ensure_initialized() | 1133 | self._ensure_initialized() |
| 1131 | - results = self._query_engine.keyword_search(query, scope, top_k, test_filter) | 1134 | + results = self._query_engine.keyword_search( |
| 1135 | + query, scope, top_k, test_filter, domain, definitions_only, mode, | ||
| 1136 | + ) | ||
| 1132 | return json.dumps( | 1137 | return json.dumps( |
| 1133 | {"results": results, "total": len(results), "freshness": self._freshness()}, | 1138 | {"results": results, "total": len(results), "freshness": self._freshness()}, |
| 1134 | ensure_ascii=False, indent=2, | 1139 | ensure_ascii=False, indent=2, |
| 1135 | ) | 1140 | ) |
| 1136 | 1141 | ||
| 1137 | - def _locate_symbol(symbol_name, kind=None): | 1142 | + def _locate_symbol(symbol_name, kind=None, definitions_only=False): |
| 1138 | self._ensure_initialized() | 1143 | self._ensure_initialized() |
| 1139 | - results = self._query_engine.locate_symbol(symbol_name, kind) | 1144 | + results = self._query_engine.locate_symbol( |
| 1145 | + symbol_name, kind, definitions_only, | ||
| 1146 | + ) | ||
| 1140 | return json.dumps( | 1147 | return json.dumps( |
| 1141 | {"symbols": results, "freshness": self._freshness()}, ensure_ascii=False, indent=2 | 1148 | {"symbols": results, "freshness": self._freshness()}, ensure_ascii=False, indent=2 |
| 1142 | ) | 1149 | ) |
| @@ -1159,6 +1166,29 @@ class ProjectBrainServer: | |||
| 1159 | payload["freshness"] = self._freshness() | 1166 | payload["freshness"] = self._freshness() |
| 1160 | return json.dumps(payload, ensure_ascii=False, indent=2) | 1167 | return json.dumps(payload, ensure_ascii=False, indent=2) |
| 1161 | 1168 | ||
| 1169 | + def _get_relations( | ||
| 1170 | + target, relation_types=None, direction="both", depth=1, | ||
| 1171 | + project_only=False, direct_only=False, resolution=None, | ||
| 1172 | + evidence_scope=None, max_items=1000, | ||
| 1173 | + ): | ||
| 1174 | + self._ensure_initialized() | ||
| 1175 | + payload = self._query_engine.get_relations( | ||
| 1176 | + target, | ||
| 1177 | + relation_types=relation_types, | ||
| 1178 | + direction=direction, | ||
| 1179 | + depth=depth, | ||
| 1180 | + project_only=project_only, | ||
| 1181 | + direct_only=direct_only, | ||
| 1182 | + resolution=resolution, | ||
| 1183 | + evidence_scope=evidence_scope, | ||
| 1184 | + max_items=max_items, | ||
| 1185 | + ) | ||
| 1186 | + payload["freshness"] = self._freshness() | ||
| 1187 | + completeness = self._completeness_block("get_relations") | ||
| 1188 | + if completeness: | ||
| 1189 | + payload["completeness"] = completeness | ||
| 1190 | + return json.dumps(payload, ensure_ascii=False, indent=2) | ||
| 1191 | + | ||
| 1162 | def _get_dependencies(module_id, direction="both"): | 1192 | def _get_dependencies(module_id, direction="both"): |
| 1163 | self._ensure_initialized() | 1193 | self._ensure_initialized() |
| 1164 | result = self._query_engine.get_dependencies(module_id, direction) | 1194 | result = self._query_engine.get_dependencies(module_id, direction) |
| @@ -1174,14 +1204,38 @@ class ProjectBrainServer: | |||
| 1174 | return json.dumps(result, ensure_ascii=False, indent=2) | 1204 | return json.dumps(result, ensure_ascii=False, indent=2) |
| 1175 | return json.dumps({"error": f"Module not found: {module_id}"}) | 1205 | return json.dumps({"error": f"Module not found: {module_id}"}) |
| 1176 | 1206 | ||
| 1177 | - def _get_file_symbols(file_path): | 1207 | + def _get_file_symbols( |
| 1208 | + file_path, top_level_only=False, kinds=None, | ||
| 1209 | + definitions_only=False, | ||
| 1210 | + ): | ||
| 1178 | self._ensure_initialized() | 1211 | self._ensure_initialized() |
| 1179 | - results = self._query_engine.get_file_symbols(file_path) | 1212 | + results = self._query_engine.get_file_symbols( |
| 1213 | + file_path, | ||
| 1214 | + top_level_only=top_level_only, | ||
| 1215 | + kinds=kinds, | ||
| 1216 | + definitions_only=definitions_only, | ||
| 1217 | + ) | ||
| 1180 | return json.dumps( | 1218 | return json.dumps( |
| 1181 | {"file": file_path, "symbols": results, "freshness": self._freshness()}, | 1219 | {"file": file_path, "symbols": results, "freshness": self._freshness()}, |
| 1182 | ensure_ascii=False, indent=2, | 1220 | ensure_ascii=False, indent=2, |
| 1183 | ) | 1221 | ) |
| 1184 | 1222 | ||
| 1223 | + def _list_code_files( | ||
| 1224 | + pattern=None, language=None, kind="all", include_tests=True, | ||
| 1225 | + include_generated=True, max_items=10_000, | ||
| 1226 | + ): | ||
| 1227 | + self._ensure_initialized() | ||
| 1228 | + payload = self._query_engine.list_code_files( | ||
| 1229 | + pattern=pattern, | ||
| 1230 | + language=language, | ||
| 1231 | + kind=kind, | ||
| 1232 | + include_tests=include_tests, | ||
| 1233 | + include_generated=include_generated, | ||
| 1234 | + max_items=max_items, | ||
| 1235 | + ) | ||
| 1236 | + payload["freshness"] = self._freshness() | ||
| 1237 | + return json.dumps(payload, ensure_ascii=False, indent=2) | ||
| 1238 | + | ||
| 1185 | def _get_related_tests(symbol_id): | 1239 | def _get_related_tests(symbol_id): |
| 1186 | self._ensure_initialized() | 1240 | self._ensure_initialized() |
| 1187 | unavailable = self._guard_unavailable("get_related_tests") | 1241 | unavailable = self._guard_unavailable("get_related_tests") |
| @@ -1388,9 +1442,11 @@ class ProjectBrainServer: | |||
| 1388 | "locate_symbol": _locate_symbol, | 1442 | "locate_symbol": _locate_symbol, |
| 1389 | "get_symbol_info": _get_symbol_info, | 1443 | "get_symbol_info": _get_symbol_info, |
| 1390 | "get_call_graph": _get_call_graph, | 1444 | "get_call_graph": _get_call_graph, |
| 1445 | + "get_relations": _get_relations, | ||
| 1391 | "get_dependencies": _get_dependencies, | 1446 | "get_dependencies": _get_dependencies, |
| 1392 | "get_module_contents": _get_module_contents, | 1447 | "get_module_contents": _get_module_contents, |
| 1393 | "get_file_symbols": _get_file_symbols, | 1448 | "get_file_symbols": _get_file_symbols, |
| 1449 | + "list_code_files": _list_code_files, | ||
| 1394 | "get_related_tests": _get_related_tests, | 1450 | "get_related_tests": _get_related_tests, |
| 1395 | "get_history": _get_history, | 1451 | "get_history": _get_history, |
| 1396 | "get_owner": _get_owner, | 1452 | "get_owner": _get_owner, |
| @@ -1411,7 +1467,15 @@ class ProjectBrainServer: | |||
| 1411 | # the Uvicorn event loop is not blocked by sync query engine calls. | 1467 | # the Uvicorn event loop is not blocked by sync query engine calls. |
| 1412 | 1468 | ||
| 1413 | @self.mcp.tool() | 1469 | @self.mcp.tool() |
| 1414 | - async def keyword_search(query: str, scope: str = None, top_k: int = 20, test_filter: str = "normal") -> str: | 1470 | + async def keyword_search( |
| 1471 | + query: str, | ||
| 1472 | + scope: str = None, | ||
| 1473 | + top_k: int = 20, | ||
| 1474 | + test_filter: str = "normal", | ||
| 1475 | + domain: str = "all", | ||
| 1476 | + definitions_only: bool = False, | ||
| 1477 | + mode: str = "ranked", | ||
| 1478 | + ) -> str: | ||
| 1415 | """Search project knowledge by keywords: code symbols, document sections, concepts. | 1479 | """Search project knowledge by keywords: code symbols, document sections, concepts. |
| 1416 | 1480 | ||
| 1417 | Works across code and documents. BM25 by default; hybrid (BM25 + | 1481 | Works across code and documents. BM25 by default; hybrid (BM25 + |
| @@ -1425,6 +1489,9 @@ class ProjectBrainServer: | |||
| 1425 | scope: optional path/module substring filter; at most 4096 | 1489 | scope: optional path/module substring filter; at most 4096 |
| 1426 | characters | 1490 | characters |
| 1427 | top_k: max results (default 20, hard limit 100) | 1491 | top_k: max results (default 20, hard limit 100) |
| 1492 | + domain: all, symbols, documents, or code (including fallback chunks). | ||
| 1493 | + definitions_only: Exclude declarations and non-symbol results. | ||
| 1494 | + mode: ranked (default) or exact symbol-name lookup without embeddings. | ||
| 1428 | test_filter: "normal" (non-test only, default), "test" (test | 1495 | test_filter: "normal" (non-test only, default), "test" (test |
| 1429 | functions only), "all" (everything). | 1496 | functions only), "all" (everything). |
| 1430 | 1497 | ||
| @@ -1435,12 +1502,17 @@ class ProjectBrainServer: | |||
| 1435 | return await self._call_tool_async("keyword_search", locals()) | 1502 | return await self._call_tool_async("keyword_search", locals()) |
| 1436 | 1503 | ||
| 1437 | @self.mcp.tool() | 1504 | @self.mcp.tool() |
| 1438 | - async def locate_symbol(symbol_name: str, kind: str = None) -> str: | 1505 | + async def locate_symbol( |
| 1506 | + symbol_name: str, | ||
| 1507 | + kind: str = None, | ||
| 1508 | + definitions_only: bool = False, | ||
| 1509 | + ) -> str: | ||
| 1439 | """Locate symbol definition(s) by exact name (case-insensitive). | 1510 | """Locate symbol definition(s) by exact name (case-insensitive). |
| 1440 | 1511 | ||
| 1441 | Args: | 1512 | Args: |
| 1442 | symbol_name: function/class/module name, e.g. "OrderService", "osalmemfree" | 1513 | symbol_name: function/class/module name, e.g. "OrderService", "osalmemfree" |
| 1443 | kind: optional filter — "function", "class", "module" | 1514 | kind: optional filter — "function", "class", "module" |
| 1515 | + definitions_only: Exclude nodes explicitly marked as declarations. | ||
| 1444 | 1516 | ||
| 1445 | Returns all matches (multiple if the name is ambiguous across files/crates) with id, name, type, kind, class_name, file, line range, signature. | 1517 | Returns all matches (multiple if the name is ambiguous across files/crates) with id, name, type, kind, class_name, file, line range, signature. |
| 1446 | Prefer this over keyword_search when the exact symbol name is known. | 1518 | Prefer this over keyword_search when the exact symbol name is known. |
| @@ -1490,6 +1562,40 @@ class ProjectBrainServer: | |||
| 1490 | """ | 1562 | """ |
| 1491 | return await self._call_tool_async("get_call_graph", locals()) | 1563 | return await self._call_tool_async("get_call_graph", locals()) |
| 1492 | 1564 | ||
| 1565 | + @self.mcp.tool() | ||
| 1566 | + async def get_relations( | ||
| 1567 | + target: str, | ||
| 1568 | + relation_types: str = None, | ||
| 1569 | + direction: str = "both", | ||
| 1570 | + depth: int = 1, | ||
| 1571 | + project_only: bool = False, | ||
| 1572 | + direct_only: bool = False, | ||
| 1573 | + resolution: str = None, | ||
| 1574 | + evidence_scope: str = None, | ||
| 1575 | + max_items: int = 1000, | ||
| 1576 | + ) -> str: | ||
| 1577 | + """Query typed graph relations with complete edge evidence. | ||
| 1578 | + | ||
| 1579 | + Args: | ||
| 1580 | + target: Symbol node id, exact name, or qualified name. | ||
| 1581 | + relation_types: Optional comma/slash-separated edge types, for | ||
| 1582 | + example ``CALL,OVERRIDES,TEMPLATE_SPECIALIZATION``. | ||
| 1583 | + direction: ``in``, ``out``, or ``both``. | ||
| 1584 | + depth: Breadth-first traversal depth, capped at 10. | ||
| 1585 | + project_only: Require both endpoints to have indexed project-relative | ||
| 1586 | + paths. This is not a standard-library name blacklist. | ||
| 1587 | + direct_only: Exclude callback-argument, FFI and macro call | ||
| 1588 | + projections while retaining ordinary direct CALL edges. | ||
| 1589 | + resolution: Optional exact resolver classification filter, | ||
| 1590 | + such as ``direct_callback_argument``. | ||
| 1591 | + evidence_scope: Optional call-site path substring filter. | ||
| 1592 | + max_items: Maximum edges returned, capped at 10000. Check truncated. | ||
| 1593 | + | ||
| 1594 | + Returns endpoint identities and paths, relation type, call-site | ||
| 1595 | + evidence, resolution, provenance, certainty and raw properties. | ||
| 1596 | + """ | ||
| 1597 | + return await self._call_tool_async("get_relations", locals()) | ||
| 1598 | + | ||
| 1493 | @self.mcp.tool() | 1599 | @self.mcp.tool() |
| 1494 | async def get_dependencies(module_id: str, direction: str = "both") -> str: | 1600 | async def get_dependencies(module_id: str, direction: str = "both") -> str: |
| 1495 | """Get module-level dependencies (import relationships). | 1601 | """Get module-level dependencies (import relationships). |
| @@ -1525,16 +1631,50 @@ class ProjectBrainServer: | |||
| 1525 | return await self._call_tool_async("get_module_contents", locals()) | 1631 | return await self._call_tool_async("get_module_contents", locals()) |
| 1526 | 1632 | ||
| 1527 | @self.mcp.tool() | 1633 | @self.mcp.tool() |
| 1528 | - async def get_file_symbols(file_path: str) -> str: | 1634 | + async def get_file_symbols( |
| 1635 | + file_path: str, | ||
| 1636 | + top_level_only: bool = False, | ||
| 1637 | + kinds: str = None, | ||
| 1638 | + definitions_only: bool = False, | ||
| 1639 | + ) -> str: | ||
| 1529 | """List all symbols (functions, classes) defined in a source file. | 1640 | """List all symbols (functions, classes) defined in a source file. |
| 1530 | 1641 | ||
| 1531 | Args: | 1642 | Args: |
| 1532 | file_path: project-relative path; forward and backward slashes are normalized. | 1643 | file_path: project-relative path; forward and backward slashes are normalized. |
| 1533 | 1644 | ||
| 1645 | + top_level_only: Exclude symbols with an indexed owner/class. | ||
| 1646 | + Top-level typedef aliases remain independent symbols. | ||
| 1647 | + kinds: Optional comma/slash-separated symbol kind filter. | ||
| 1648 | + definitions_only: Exclude nodes explicitly marked as declarations. | ||
| 1649 | + | ||
| 1534 | Returns {file, symbols: [{id, name, type, kind, line}]}. Empty list if the file is not indexed. | 1650 | Returns {file, symbols: [{id, name, type, kind, line}]}. Empty list if the file is not indexed. |
| 1535 | """ | 1651 | """ |
| 1536 | return await self._call_tool_async("get_file_symbols", locals()) | 1652 | return await self._call_tool_async("get_file_symbols", locals()) |
| 1537 | 1653 | ||
| 1654 | + @self.mcp.tool() | ||
| 1655 | + async def list_code_files( | ||
| 1656 | + pattern: str = None, | ||
| 1657 | + language: str = None, | ||
| 1658 | + kind: str = "all", | ||
| 1659 | + include_tests: bool = True, | ||
| 1660 | + include_generated: bool = True, | ||
| 1661 | + max_items: int = 10_000, | ||
| 1662 | + ) -> str: | ||
| 1663 | + """Enumerate indexed source/header files. | ||
| 1664 | + | ||
| 1665 | + Args: | ||
| 1666 | + pattern: Optional project-relative glob such as ``*.h`` or | ||
| 1667 | + ``include/**/*.hpp``. | ||
| 1668 | + language: Optional exact parser language filter. | ||
| 1669 | + kind: ``all``, ``header``, or ``source``. | ||
| 1670 | + include_tests: Include files classified as tests. | ||
| 1671 | + include_generated: Include generated files. | ||
| 1672 | + max_items: Maximum returned entries, capped at 100000. | ||
| 1673 | + | ||
| 1674 | + Returns stable file ids, paths, kinds, language and parse status. | ||
| 1675 | + """ | ||
| 1676 | + return await self._call_tool_async("list_code_files", locals()) | ||
| 1677 | + | ||
| 1538 | @self.mcp.tool() | 1678 | @self.mcp.tool() |
| 1539 | async def get_related_tests(symbol_id: str) -> str: | 1679 | async def get_related_tests(symbol_id: str) -> str: |
| 1540 | """Find tests related to a symbol. Combines explicit TEST edges with inferred tests (caller functions flagged is_test that invoke the symbol). | 1680 | """Find tests related to a symbol. Combines explicit TEST edges with inferred tests (caller functions flagged is_test that invoke the symbol). |
| @@ -199,6 +199,7 @@ def _mini_capabilities(plan: BuildPlan) -> dict[str, str]: | |||
| 199 | "locate_symbol": STATUS_AVAILABLE, | 199 | "locate_symbol": STATUS_AVAILABLE, |
| 200 | "get_module_contents": STATUS_AVAILABLE, | 200 | "get_module_contents": STATUS_AVAILABLE, |
| 201 | "get_file_symbols": STATUS_AVAILABLE, | 201 | "get_file_symbols": STATUS_AVAILABLE, |
| 202 | + "list_code_files": STATUS_AVAILABLE, | ||
| 202 | "get_conventions": STATUS_AVAILABLE, | 203 | "get_conventions": STATUS_AVAILABLE, |
| 203 | "get_doc_links": STATUS_AVAILABLE, | 204 | "get_doc_links": STATUS_AVAILABLE, |
| 204 | "list_documents": STATUS_AVAILABLE, | 205 | "list_documents": STATUS_AVAILABLE, |
| @@ -206,6 +207,7 @@ def _mini_capabilities(plan: BuildPlan) -> dict[str, str]: | |||
| 206 | # Partial: the call/dependency graph only spans public symbols. | 207 | # Partial: the call/dependency graph only spans public symbols. |
| 207 | "get_symbol_info": STATUS_PARTIAL, | 208 | "get_symbol_info": STATUS_PARTIAL, |
| 208 | "get_call_graph": STATUS_PARTIAL, | 209 | "get_call_graph": STATUS_PARTIAL, |
| 210 | + "get_relations": STATUS_PARTIAL, | ||
| 209 | "get_dependencies": STATUS_PARTIAL, | 211 | "get_dependencies": STATUS_PARTIAL, |
| 210 | "impact_analysis": STATUS_PARTIAL, | 212 | "impact_analysis": STATUS_PARTIAL, |
| 211 | "get_context": STATUS_PARTIAL, | 213 | "get_context": STATUS_PARTIAL, |
| @@ -242,6 +244,7 @@ def _missing_dimensions(tool_name: str, profile: str) -> list[str]: | |||
| 242 | _MINI_MISSING: dict[str, list[str]] = { | 244 | _MINI_MISSING: dict[str, list[str]] = { |
| 243 | "get_symbol_info": ["private_symbols", "support_type_closure"], | 245 | "get_symbol_info": ["private_symbols", "support_type_closure"], |
| 244 | "get_call_graph": ["private_call_edges"], | 246 | "get_call_graph": ["private_call_edges"], |
| 247 | + "get_relations": ["private_symbols", "private_call_edges"], | ||
| 245 | "get_dependencies": ["private_module_dependencies", "module_dependency_aggregation"], | 248 | "get_dependencies": ["private_module_dependencies", "module_dependency_aggregation"], |
| 246 | "impact_analysis": ["tests", "private_call_edges"], | 249 | "impact_analysis": ["tests", "private_call_edges"], |
| 247 | "get_context": ["private_symbols"], | 250 | "get_context": ["private_symbols"], |
| @@ -11,7 +11,10 @@ import stat | |||
| 11 | import threading | 11 | import threading |
| 12 | import time | 12 | import time |
| 13 | import re | 13 | import re |
| 14 | +from collections import deque | ||
| 15 | +from copy import deepcopy | ||
| 14 | from functools import wraps | 16 | from functools import wraps |
| 17 | +from fnmatch import fnmatchcase | ||
| 15 | from dataclasses import dataclass | 18 | from dataclasses import dataclass |
| 16 | from pathlib import Path, PurePosixPath | 19 | from pathlib import Path, PurePosixPath |
| 17 | from typing import Any | 20 | from typing import Any |
| @@ -0,0 +1,169 @@ | |||
| 1 | +import argparse | ||
| 2 | +import json | ||
| 3 | + | ||
| 4 | +import pytest | ||
| 5 | + | ||
| 6 | +from project_brain.__main__ import _QUERY_SPECS, _register_query_commands | ||
| 7 | +from project_brain.cli.format import format_result | ||
| 8 | +from project_brain.graph.json_store import JsonStore | ||
| 9 | +from project_brain.graph.models import Edge | ||
| 10 | +from project_brain.graph.sqlite_store import SqliteStore | ||
| 11 | +from project_brain.query.engine import QueryEngine | ||
| 12 | +from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +@pytest.fixture(params=[JsonStore, SqliteStore], ids=["json", "sqlite"]) | ||
| 16 | +def query(tmp_path, request): | ||
| 17 | + store = request.param(tmp_path) | ||
| 18 | + symbols = SymbolIndex() | ||
| 19 | + keyword = KeywordIndex() | ||
| 20 | + for i in range(3): | ||
| 21 | + store.add_node({ | ||
| 22 | + "id": f"f{i}", "type": "function", "name": f"f{i}", | ||
| 23 | + "path": f"src/f{i}.py", "line_start": i + 1, | ||
| 24 | + }) | ||
| 25 | + symbols.add(f"f{i}", f"f{i}") | ||
| 26 | + keyword.add(f"f{i}", f"f{i}") | ||
| 27 | + yield QueryEngine(store, keyword, symbols, FileIndex()) | ||
| 28 | + if isinstance(store, SqliteStore): | ||
| 29 | + store.close() | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def test_relations_bounded_cycle_and_self_call(query): | ||
| 33 | + for eid, source, target in [("a", "f0", "f1"), ("b", "f1", "f2"), | ||
| 34 | + ("c", "f2", "f0"), ("d", "f0", "f0")]: | ||
| 35 | + query.store.add_edge(Edge(eid, "CALL", source, target)) | ||
| 36 | + result = query.get_relations("f0", "CALL", "out", depth=10) | ||
| 37 | + assert {item["id"] for item in result["relations"]} == {"a", "b", "c", "d"} | ||
| 38 | + assert not result["truncated"] | ||
| 39 | + limited = query.get_relations("f0", "CALL", "out", depth=10, max_items=2) | ||
| 40 | + assert len(limited["relations"]) == 2 | ||
| 41 | + assert limited["truncated"] | ||
| 42 | + assert "[truncated]" in format_result("get_relations", limited, False) | ||
| 43 | + assert query.get_relations("f0", max_items="bad")["error"] == "invalid_max_items" | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def test_relations_filter_all_sites_without_changing_stored_properties(query): | ||
| 47 | + query.store.add_node({"id": "file_a", "type": "file", "path": "src/a.py"}) | ||
| 48 | + query.store.add_node({"id": "file_b", "type": "file", "path": "tests/b.py"}) | ||
| 49 | + properties = {"file_id": "file_a", "line_start": 10, "locations": [ | ||
| 50 | + {"file_id": "file_a", "line_start": 10, "line_end": 10}, | ||
| 51 | + {"file_id": "file_b", "line_start": 30, "line_end": 31, "evidence_source": "binder"}, | ||
| 52 | + ]} | ||
| 53 | + query.store.add_edge(Edge("multi", "CALL", "f0", "f1", properties)) | ||
| 54 | + record = query.get_relations("f0", evidence_scope="tests\\b.py")["relations"][0] | ||
| 55 | + assert record["evidence"]["file"] == "tests/b.py" | ||
| 56 | + assert record["evidence"]["line_start"] == 30 | ||
| 57 | + assert record["evidence"]["evidence_source"] == "binder" | ||
| 58 | + assert len(record["evidence_locations"]) == 2 | ||
| 59 | + record["properties"]["locations"][0]["line_start"] = 100 | ||
| 60 | + assert properties["locations"][0]["line_start"] == 10 | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def test_callsite_missing_file_uses_caller_not_callee(query): | ||
| 64 | + query.store.add_edge(Edge("call", "CALL", "f0", "f1", {"line_start": 50})) | ||
| 65 | + record = query.get_relations("f0")["relations"][0] | ||
| 66 | + assert record["evidence"]["file"] == "src/f0.py" | ||
| 67 | + assert record["evidence"]["line_start"] == 50 | ||
| 68 | + query.store.add_edge(Edge("legacy", "CALL", "f0", "f2")) | ||
| 69 | + legacy = next(r for r in query.get_relations("f0")["relations"] if r["id"] == "legacy") | ||
| 70 | + assert legacy["evidence"]["line_start"] is None | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def test_unresolved_explicit_evidence_file_is_not_replaced_by_another_file(query): | ||
| 74 | + query.store.add_edge(Edge("broken", "CALL", "f0", "f1", { | ||
| 75 | + "file_id": "deleted_file", "line_start": 12, "certainty": 0, | ||
| 76 | + "locations": [{"file_id": "other_deleted_file", "line_start": 30}], | ||
| 77 | + })) | ||
| 78 | + record = query.get_relations("f0")["relations"][0] | ||
| 79 | + assert record["evidence"]["file"] is None | ||
| 80 | + assert record["certainty"] == 0 | ||
| 81 | + assert query.get_relations("f0", evidence_scope="src/f0.py")["relations"] == [] | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def test_project_scope_does_not_treat_every_persisted_node_as_project(query): | ||
| 85 | + query.store.add_node({"id": "external", "type": "function", "name": "native", | ||
| 86 | + "path": "C:/SDK/native.h"}) | ||
| 87 | + query.store.add_node({"id": "unknown", "type": "function", "name": "unknown"}) | ||
| 88 | + for eid, target in [("a", "f1"), ("b", "external"), ("c", "unknown")]: | ||
| 89 | + query.store.add_edge(Edge(eid, "CALL", "f0", target)) | ||
| 90 | + result = query.get_relations("f0", project_only=True) | ||
| 91 | + assert [r["id"] for r in result["relations"]] == ["a"] | ||
| 92 | + scopes = {r["id"]: r["scope"] for r in query.get_relations("f0")["relations"]} | ||
| 93 | + assert scopes == {"a": "project", "b": "external", "c": "unknown"} | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def test_class_relations_include_methods_and_qualified_identity(query): | ||
| 97 | + query.store.add_node({"id": "cls", "type": "class", "name": "Body", | ||
| 98 | + "module_path": "sync_impl", "methods": ["f0"]}) | ||
| 99 | + query.store.update_node("f0", {"class_name": "Body", "module_path": "sync_impl"}) | ||
| 100 | + query.symbol_index.add("Body", "cls") | ||
| 101 | + query.store.add_edge(Edge("override", "OVERRIDES", "f1", "f0", {"line_start": 1})) | ||
| 102 | + record = query.get_relations("sync_impl::Body", "OVERRIDES")["relations"][0] | ||
| 103 | + assert record["target"]["qualified_name"] == "sync_impl::Body::f0" | ||
| 104 | + assert record["evidence"]["file"] == "src/f0.py" | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +def test_exact_search_never_calls_ranked_or_semantic_retrieval(query, monkeypatch): | ||
| 108 | + monkeypatch.setattr(query, "_retrieve", lambda *_: pytest.fail("ranked retrieval used")) | ||
| 109 | + query.store.update_node("f0", {"is_definition": False}) | ||
| 110 | + assert query.keyword_search("f0", mode="exact", definitions_only=True) == [] | ||
| 111 | + assert query.keyword_search("missing", mode="exact") == [] | ||
| 112 | + assert query.keyword_search("f1", mode="exact")[0]["id"] == "f1" | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def test_ranked_symbol_filter_refills_from_a_bounded_candidate_pool(query, monkeypatch): | ||
| 116 | + query.store.add_node({"id": "doc", "type": "document", "title": "f1"}) | ||
| 117 | + def retrieve(text, top_k, test_filter): | ||
| 118 | + return [("doc", 2.0), ("f1", 1.0)][:top_k] | ||
| 119 | + monkeypatch.setattr(query, "_retrieve", retrieve) | ||
| 120 | + assert query.keyword_search("f1", top_k=1)[0]["id"] == "doc" | ||
| 121 | + assert query.keyword_search("f1", top_k=1, domain="symbols")[0]["id"] == "f1" | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +def test_code_file_globs_match_zero_or_multiple_nested_directories(query): | ||
| 125 | + paths = ["include/a.hpp", "include/one/two/b.hpp", "other/c.hpp", "include/d.h"] | ||
| 126 | + for index, path in enumerate(paths): | ||
| 127 | + query.store.add_node({"id": f"file{index}", "type": "file", "path": path}) | ||
| 128 | + result = query.list_code_files(pattern="include/**/*.hpp") | ||
| 129 | + assert [item["path"] for item in result["files"]] == paths[:2] | ||
| 130 | + assert query.list_code_files(pattern="*.hpp")["total"] == 3 | ||
| 131 | + assert query.list_code_files(pattern="include/*.hpp")["total"] == 1 | ||
| 132 | + assert query.list_code_files(pattern="include\\**\\*.hpp")["total"] == 2 | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +@pytest.mark.parametrize("argv, tool, expected", [ | ||
| 136 | + (["files", "--pattern", "*.h", "--exclude-tests"], "list_code_files", | ||
| 137 | + {"pattern": "*.h", "include_tests": False}), | ||
| 138 | + (["relations", "f0", "--type", "CALL", "--max-items", "5"], "get_relations", | ||
| 139 | + {"relation_types": "CALL", "max_items": 5}), | ||
| 140 | + (["search", "f0", "--mode", "exact", "--definitions-only"], "keyword_search", | ||
| 141 | + {"mode": "exact", "definitions_only": True}), | ||
| 142 | + (["file", "src/a.h", "--top-level-only"], "get_file_symbols", | ||
| 143 | + {"top_level_only": True}), | ||
| 144 | +]) | ||
| 145 | +def test_cli_options_are_forwarded(argv, tool, expected): | ||
| 146 | + parser = argparse.ArgumentParser() | ||
| 147 | + _register_query_commands(parser.add_subparsers(dest="command")) | ||
| 148 | + args = parser.parse_args(argv) | ||
| 149 | + spec = _QUERY_SPECS[args.command] | ||
| 150 | + assert spec["tool"] == tool | ||
| 151 | + kwargs = {key: value(args) for key, value in spec["kwargs"].items()} | ||
| 152 | + for key, value in expected.items(): | ||
| 153 | + assert kwargs[key] == value | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def test_mcp_sync_tools_and_formatters_use_new_contract(query, tmp_path, monkeypatch): | ||
| 157 | + from project_brain.mcp.server import ProjectBrainServer | ||
| 158 | + server = ProjectBrainServer(str(tmp_path)) | ||
| 159 | + monkeypatch.setattr(server, "_ensure_initialized", lambda: None) | ||
| 160 | + monkeypatch.setattr(server, "_freshness", lambda: {"status": "idle"}) | ||
| 161 | + server._query_engine = query | ||
| 162 | + query.store.add_edge(Edge("edge", "CALL", "f0", "f1")) | ||
| 163 | + result = json.loads(server.call_tool_sync("get_relations", {"target": "f0"})) | ||
| 164 | + assert result["relations"][0]["type"] == "CALL" | ||
| 165 | + assert "CALL" in format_result("get_relations", result, False) | ||
| 166 | + files = json.loads(server.call_tool_sync("list_code_files", {})) | ||
| 167 | + assert files["files"] == [] | ||
| 168 | + assert "Files" in format_result("list_code_files", files, False) | ||
| 169 | + server.close() | ||
| @@ -54,6 +54,24 @@ def test_keyword_search(engine): | |||
| 54 | assert any(r["name"] == "create_order" for r in results) | 54 | assert any(r["name"] == "create_order" for r in results) |
| 55 | 55 | ||
| 56 | 56 | ||
| 57 | +def test_keyword_search_domain_and_definition_filters(engine): | ||
| 58 | + engine.store.update_node("fn_1", {"is_definition": False}) | ||
| 59 | + engine.store.add_node({ | ||
| 60 | + "id": "doc_search", "type": "document", "title": "create_order guide", | ||
| 61 | + "path": "docs/create_order.md", | ||
| 62 | + }) | ||
| 63 | + engine.keyword_index.add("doc_search", "create_order guide") | ||
| 64 | + | ||
| 65 | + symbols = engine.keyword_search( | ||
| 66 | + "create_order", domain="symbols", definitions_only=True, | ||
| 67 | + ) | ||
| 68 | + documents = engine.keyword_search("create_order", domain="documents") | ||
| 69 | + | ||
| 70 | + assert all(item["type"] in {"function", "class", "symbol", "module"} for item in symbols) | ||
| 71 | + assert all(item["id"] != "fn_1" for item in symbols) | ||
| 72 | + assert [item["id"] for item in documents] == ["doc_search"] | ||
| 73 | + | ||
| 74 | + | ||
| 57 | def test_query_boundaries_and_direct_id_type_filter(engine): | 75 | def test_query_boundaries_and_direct_id_type_filter(engine): |
| 58 | assert engine.keyword_search("create_order", top_k=0) == [] | 76 | assert engine.keyword_search("create_order", top_k=0) == [] |
| 59 | assert engine.keyword_search("create_order", top_k=-1) == [] | 77 | assert engine.keyword_search("create_order", top_k=-1) == [] |
| @@ -135,6 +153,25 @@ def test_get_symbol_info(engine): | |||
| 135 | assert len(info["tests"]) == 1 | 153 | assert len(info["tests"]) == 1 |
| 136 | 154 | ||
| 137 | 155 | ||
| 156 | +def test_get_symbol_info_prefers_one_exact_case_match(engine): | ||
| 157 | + engine.store.add_node({ | ||
| 158 | + "id": "sym_derived", "type": "symbol", "name": "derived", | ||
| 159 | + "kind": "variable", "path": "src/other.cpp", | ||
| 160 | + }) | ||
| 161 | + engine.symbol_index.add("derived", "sym_derived") | ||
| 162 | + engine.store.add_node({ | ||
| 163 | + "id": "cls_derived", "type": "class", "name": "Derived", | ||
| 164 | + "kind": "class", "path": "src/model.cpp", | ||
| 165 | + }) | ||
| 166 | + engine.symbol_index.add("Derived", "cls_derived") | ||
| 167 | + | ||
| 168 | + info = engine.get_symbol_info("Derived", include="callers") | ||
| 169 | + | ||
| 170 | + assert info is not None | ||
| 171 | + assert info["id"] == "cls_derived" | ||
| 172 | + assert not info.get("ambiguous") | ||
| 173 | + | ||
| 174 | + | ||
| 138 | def test_get_symbol_info_exposes_p2_relation_edges(engine): | 175 | def test_get_symbol_info_exposes_p2_relation_edges(engine): |
| 139 | engine.store.add_node({"id": "cls_user", "type": "class", "name": "User"}) | 176 | engine.store.add_node({"id": "cls_user", "type": "class", "name": "User"}) |
| 140 | engine.store.add_node({"id": "field_name", "type": "symbol", "name": "name"}) | 177 | engine.store.add_node({"id": "field_name", "type": "symbol", "name": "name"}) |
| @@ -194,6 +231,49 @@ def test_get_symbol_info_exposes_p31_relations(engine): | |||
| 194 | assert info["called_macros"] == [{"id": "macro", "name": "TRACE"}] | 231 | assert info["called_macros"] == [{"id": "macro", "name": "TRACE"}] |
| 195 | 232 | ||
| 196 | 233 | ||
| 234 | +def test_get_relations_preserves_type_evidence_and_resolution(engine): | ||
| 235 | + engine.store.add_node({ | ||
| 236 | + "id": "file_order", "type": "file", "path": "src/order.py", | ||
| 237 | + "language": "python", | ||
| 238 | + }) | ||
| 239 | + engine.store.add_edge(Edge( | ||
| 240 | + id="callback", type="CALL", source="fn_1", target="fn_3", | ||
| 241 | + properties={ | ||
| 242 | + "file_id": "file_order", "line_start": 18, "line_end": 18, | ||
| 243 | + "byte_start": 120, "byte_end": 140, | ||
| 244 | + "resolution": "direct_callback_argument", | ||
| 245 | + "provenance": "tree-sitter", | ||
| 246 | + }, | ||
| 247 | + )) | ||
| 248 | + | ||
| 249 | + result = engine.get_relations("create_order", relation_types="CALL", direction="out") | ||
| 250 | + callback = next(item for item in result["relations"] if item["id"] == "callback") | ||
| 251 | + | ||
| 252 | + assert callback["source"]["name"] == "create_order" | ||
| 253 | + assert callback["target"]["name"] == "process_payment" | ||
| 254 | + assert callback["evidence"] == { | ||
| 255 | + "file": "src/order.py", | ||
| 256 | + "line_start": 18, | ||
| 257 | + "line_end": 18, | ||
| 258 | + "byte_start": 120, | ||
| 259 | + "byte_end": 140, | ||
| 260 | + } | ||
| 261 | + assert callback["resolution"] == "direct_callback_argument" | ||
| 262 | + assert callback["provenance"] == "tree-sitter" | ||
| 263 | + | ||
| 264 | + callbacks = engine.get_relations( | ||
| 265 | + "create_order", relation_types="CALL", direction="out", | ||
| 266 | + resolution="direct_callback_argument", evidence_scope="src/order.py", | ||
| 267 | + ) | ||
| 268 | + assert [item["id"] for item in callbacks["relations"]] == ["callback"] | ||
| 269 | + | ||
| 270 | + direct = engine.get_relations( | ||
| 271 | + "create_order", relation_types="CALL", direction="out", direct_only=True, | ||
| 272 | + ) | ||
| 273 | + assert "callback" not in {item["id"] for item in direct["relations"]} | ||
| 274 | + assert {item["id"] for item in direct["relations"]} == {"e1", "e2"} | ||
| 275 | + | ||
| 276 | + | ||
| 197 | def test_locate_symbol_supports_module_and_owner_qualified_names(engine): | 277 | def test_locate_symbol_supports_module_and_owner_qualified_names(engine): |
| 198 | for node in ( | 278 | for node in ( |
| 199 | { | 279 | { |
| @@ -335,6 +415,49 @@ def test_get_file_symbols(engine): | |||
| 335 | assert "OrderService" in names | 415 | assert "OrderService" in names |
| 336 | 416 | ||
| 337 | 417 | ||
| 418 | +def test_get_file_symbols_supports_top_level_kind_and_definition_filters(engine): | ||
| 419 | + engine.store.update_node("fn_1", {"is_definition": False}) | ||
| 420 | + engine.store.update_node("fn_2", {"kind": "function", "is_definition": True}) | ||
| 421 | + engine.store.update_node("cls_1", {"class_name": "Outer"}) | ||
| 422 | + | ||
| 423 | + symbols = engine.get_file_symbols( | ||
| 424 | + "src/order.py", top_level_only=True, kinds="function", | ||
| 425 | + definitions_only=True, | ||
| 426 | + ) | ||
| 427 | + | ||
| 428 | + assert [item["id"] for item in symbols] == ["fn_2"] | ||
| 429 | + | ||
| 430 | + | ||
| 431 | +def test_list_code_files_filters_headers_and_keeps_parse_evidence(engine): | ||
| 432 | + for node in ( | ||
| 433 | + { | ||
| 434 | + "id": "file_header", "type": "file", "path": "include/api.h", | ||
| 435 | + "language": "c", "line_count": 20, "is_test": False, | ||
| 436 | + "is_generated": False, "parse_status": "ok", "parse_coverage": 1.0, | ||
| 437 | + }, | ||
| 438 | + { | ||
| 439 | + "id": "file_source", "type": "file", "path": "src/api.c", | ||
| 440 | + "language": "c", "line_count": 40, "is_test": False, | ||
| 441 | + "is_generated": False, "parse_status": "recovered", "parse_coverage": 0.9, | ||
| 442 | + }, | ||
| 443 | + { | ||
| 444 | + "id": "file_test", "type": "file", "path": "tests/api_test.h", | ||
| 445 | + "language": "c", "line_count": 10, "is_test": True, | ||
| 446 | + "is_generated": False, "parse_status": "ok", "parse_coverage": 1.0, | ||
| 447 | + }, | ||
| 448 | + ): | ||
| 449 | + engine.store.add_node(node) | ||
| 450 | + | ||
| 451 | + result = engine.list_code_files( | ||
| 452 | + pattern="*.h", kind="header", language="C", include_tests=False, | ||
| 453 | + ) | ||
| 454 | + | ||
| 455 | + assert result["total"] == 1 | ||
| 456 | + assert result["files"][0]["path"] == "include/api.h" | ||
| 457 | + assert result["files"][0]["kind"] == "header_file" | ||
| 458 | + assert result["files"][0]["parse_coverage"] == 1.0 | ||
| 459 | + | ||
| 460 | + | ||
| 338 | def test_get_related_tests(engine): | 461 | def test_get_related_tests(engine): |
| 339 | tests = engine.get_related_tests("fn_1") | 462 | tests = engine.get_related_tests("fn_1") |
| 340 | assert len(tests) == 1 | 463 | assert len(tests) == 1 |
| @@ -1448,7 +1448,7 @@ wheels = [ | |||
| 1448 | 1448 | ||
| 1449 | [[package]] | 1449 | [[package]] |
| 1450 | name = "project-brain" | 1450 | name = "project-brain" |
| 1451 | -version = "0.6.0" | 1451 | +version = "0.7.0" |
| 1452 | source = { editable = "." } | 1452 | source = { editable = "." } |
| 1453 | dependencies = [ | 1453 | dependencies = [ |
| 1454 | { name = "faiss-cpu" }, | 1454 | { name = "faiss-cpu" }, |