Skip to content

Commit a546780

Browse files
committed
fix: 修复分析器识别并加固 MCP 运行边界
借鉴上游 correctness 修复,避免超时被吞、构造器与复杂声明漏收、Git 抢占 stdio、Mermaid 挂起及嵌套仓库越界。
1 parent d8ef71b commit a546780

19 files changed

Lines changed: 1307 additions & 171 deletions

‎codewiki/cli/commands/backfill_note_authors.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ def _git_creator_author(repo_root: Path, note_rel: str) -> str | None:
4848
note_rel,
4949
],
5050
capture_output=True,
51+
stdin=subprocess.DEVNULL,
5152
text=True,
5253
encoding="utf-8",
5354
errors="replace",

‎codewiki/mcp/tools/doc_writer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1497,7 +1497,7 @@ async def handle_write_doc_file(
14971497
mermaid_result = await _validate_mermaid(str(doc_path), filename)
14981498

14991499
# strict mode: block the write if Mermaid validation STILL has errors after auto-fix
1500-
if strict and "syntax errors" in mermaid_result.lower():
1500+
if strict and "mermaid syntax errors found in file:" in mermaid_result.lower():
15011501
try:
15021502
doc_path.unlink()
15031503
except OSError:

‎codewiki/mcp/tools/note_query.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,12 @@ def _last_commit_time(target_path: Path, repo_root: Path) -> Optional[datetime]:
531531
import os
532532
import subprocess
533533

534-
_kw: dict = {"capture_output": True, "text": True, "timeout": 10}
534+
_kw: dict = {
535+
"capture_output": True,
536+
"stdin": subprocess.DEVNULL,
537+
"text": True,
538+
"timeout": 10,
539+
}
535540
if os.name == "nt":
536541
# Console-less parent (IDE-spawned MCP server): without this flag
537542
# every git child allocates a flashing console window.

‎codewiki/mcp/tools/workspace_bootstrap.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,12 @@ def _clone_repo(workspace_p: Path, name: str, url: str, timeout: int) -> dict:
385385
try:
386386
import os
387387

388-
_kw: dict = {"capture_output": True, "text": True, "timeout": timeout}
388+
_kw: dict = {
389+
"capture_output": True,
390+
"stdin": subprocess.DEVNULL,
391+
"text": True,
392+
"timeout": timeout,
393+
}
389394
if os.name == "nt":
390395
# Console-less parent (IDE-spawned MCP server): without this
391396
# flag every git child allocates a flashing console window.

‎codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333
logger = logging.getLogger(__name__)
3434

3535

36-
class TimeoutError(Exception):
37-
"""Raised when file parsing exceeds timeout."""
36+
class TimeoutError(BaseException):
37+
"""必须绕过语言分析器内部的 Exception 捕获,由分派层统一处理。"""
3838

3939
pass
4040

‎codewiki/src/be/dependency_analyzer/analysis/cloning.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ def clone_repository(github_url: str) -> str:
9090
"true",
9191
],
9292
capture_output=True,
93+
stdin=subprocess.DEVNULL,
9394
text=True,
9495
)
9596
except Exception:
@@ -107,6 +108,7 @@ def clone_repository(github_url: str) -> str:
107108
],
108109
check=True,
109110
capture_output=True,
111+
stdin=subprocess.DEVNULL,
110112
text=True,
111113
timeout=300,
112114
)
@@ -123,6 +125,7 @@ def clone_repository(github_url: str) -> str:
123125
"true",
124126
],
125127
capture_output=True,
128+
stdin=subprocess.DEVNULL,
126129
text=True,
127130
)
128131

@@ -146,6 +149,7 @@ def clone_repository(github_url: str) -> str:
146149
"HEAD",
147150
],
148151
capture_output=True,
152+
stdin=subprocess.DEVNULL,
149153
text=True,
150154
)
151155
except Exception:

‎codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py‎

Lines changed: 119 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@
77

88
from __future__ import annotations
99

10+
import configparser
1011
import fnmatch
1112
import logging
13+
import os
1214
import shutil
1315
import subprocess
1416
from pathlib import Path
15-
from typing import Dict, List, Optional
17+
from typing import TYPE_CHECKING, Dict, List, Optional
18+
19+
if TYPE_CHECKING:
20+
from pathspec import GitIgnoreSpec
1621

1722
from codewiki.src.be.dependency_analyzer.utils.patterns import (
1823
DEFAULT_IGNORE_PATTERNS,
@@ -22,6 +27,94 @@
2227
logger = logging.getLogger(__name__)
2328

2429

30+
class RepositoryBoundaryFilter:
31+
"""保留声明的子模块,跳过无关的嵌套 Git checkout。"""
32+
33+
def __init__(self, repo_dir: Path) -> None:
34+
self.root = repo_dir.resolve()
35+
self.owner = next(
36+
(path for path in (self.root, *self.root.parents) if (path / ".git").exists()),
37+
self.root,
38+
)
39+
self._submodules: dict[Path, set[Path]] = {}
40+
41+
@staticmethod
42+
def _config_path(value: str) -> str:
43+
"""解码 Git 配置中的引号、转义与尾随注释。"""
44+
result = []
45+
quoted = False
46+
escaped = False
47+
end = 0
48+
escapes = {"n": "\n", "t": "\t", "b": "\b", '"': '"', "\\": "\\"}
49+
for char in value:
50+
if escaped:
51+
if char not in escapes:
52+
raise ValueError("Invalid escape in submodule path")
53+
result.append(escapes[char])
54+
end = len(result)
55+
escaped = False
56+
elif char == "\\":
57+
escaped = True
58+
elif char == '"':
59+
quoted = not quoted
60+
elif char in "#;" and not quoted:
61+
break
62+
else:
63+
result.append(char)
64+
if quoted or not char.isspace():
65+
end = len(result)
66+
if quoted or escaped:
67+
raise ValueError("Unterminated submodule path")
68+
return "".join(result[:end])
69+
70+
def _declared_submodules(self, owner: Path) -> set[Path]:
71+
if owner in self._submodules:
72+
return self._submodules[owner]
73+
paths: set[Path] = set()
74+
config_path = owner / ".gitmodules"
75+
try:
76+
if config_path.is_symlink() or not config_path.exists():
77+
self._submodules[owner] = paths
78+
return paths
79+
config = configparser.RawConfigParser(strict=False)
80+
config.read_string(config_path.read_text(encoding="utf-8"))
81+
for section in config.sections():
82+
if not section.lower().startswith('submodule "') or not section.endswith('"'):
83+
continue
84+
value = self._config_path(config.get(section, "path", fallback=""))
85+
if not value:
86+
continue
87+
relative = Path(value)
88+
path = (owner / relative).resolve()
89+
if relative.is_absolute() or path == owner or not path.is_relative_to(owner):
90+
logger.warning(
91+
"Skipping escaping submodule path in %s: %s", config_path, value
92+
)
93+
continue
94+
paths.add(path)
95+
except (OSError, UnicodeError, ValueError, configparser.Error) as exc:
96+
logger.warning("Could not read submodule declarations at %s: %s", config_path, exc)
97+
paths.clear()
98+
self._submodules[owner] = paths
99+
return paths
100+
101+
def should_skip(self, path: Path) -> bool:
102+
path = path.resolve()
103+
if path == self.root or not (path / ".git").exists():
104+
return False
105+
owner = self.owner
106+
for parent in path.parents:
107+
if parent == self.root:
108+
break
109+
if (parent / ".git").exists():
110+
owner = parent
111+
break
112+
if path in self._declared_submodules(owner):
113+
return False
114+
logger.debug("Skipping nested Git checkout: %s", path)
115+
return True
116+
117+
25118
class GitIgnoreFilter:
26119
"""Evaluate Git ignore rules once per repository analysis.
27120
@@ -30,8 +123,9 @@ class GitIgnoreFilter:
30123
Plain directories fall back to pathspec-backed ``.gitignore`` evaluation.
31124
"""
32125

33-
def __init__(self, repo_dir: Path) -> None:
126+
def __init__(self, repo_dir: Path, boundaries: RepositoryBoundaryFilter | None = None) -> None:
34127
self.repo_dir = repo_dir.resolve()
128+
self._boundaries = boundaries or RepositoryBoundaryFilter(self.repo_dir)
35129
self._ignored_files: set[str] = set()
36130
self._ignored_dirs: set[str] = set()
37131
self._ignore_all_untracked = False
@@ -120,12 +214,20 @@ def _load_fallback_specs(self) -> None:
120214
return
121215

122216
try:
123-
candidates = sorted(
124-
(
125-
path
126-
for path in self.repo_dir.rglob(".gitignore")
127-
if path.is_file() and not path.is_symlink()
128-
),
217+
candidates: list[Path] = []
218+
for directory, dirs, files in os.walk(self.repo_dir, followlinks=False):
219+
base = Path(directory)
220+
dirs[:] = [
221+
name
222+
for name in dirs
223+
if name != ".git"
224+
and not (base / name).is_symlink()
225+
and not self._boundaries.should_skip(base / name)
226+
]
227+
gitignore = base / ".gitignore"
228+
if ".gitignore" in files and not gitignore.is_symlink():
229+
candidates.append(gitignore)
230+
candidates.sort(
129231
key=lambda path: (len(path.relative_to(self.repo_dir).parts), path.as_posix()),
130232
)
131233
except OSError as exc:
@@ -136,8 +238,8 @@ def _load_fallback_specs(self) -> None:
136238
try:
137239
lines = gitignore_path.read_text(encoding="utf-8").splitlines()
138240
spec = GitIgnoreSpec.from_lines(lines)
139-
base = gitignore_path.parent.relative_to(self.repo_dir).as_posix()
140-
self._fallback_specs.append(("" if base == "." else base, spec))
241+
base_dir = gitignore_path.parent.relative_to(self.repo_dir).as_posix()
242+
self._fallback_specs.append(("" if base_dir == "." else base_dir, spec))
141243
except (OSError, UnicodeError, ValueError) as exc:
142244
logger.warning("Skipping unreadable .gitignore at %s: %s", gitignore_path, exc)
143245

@@ -199,9 +301,13 @@ def __init__(
199301
)
200302
self.use_gitignore = use_gitignore
201303
self._gitignore_filter: Optional[GitIgnoreFilter] = None
304+
self._boundaries: Optional[RepositoryBoundaryFilter] = None
202305

203306
def analyze_repository_structure(self, repo_dir: str) -> Dict:
204-
self._gitignore_filter = GitIgnoreFilter(Path(repo_dir)) if self.use_gitignore else None
307+
self._boundaries = RepositoryBoundaryFilter(Path(repo_dir))
308+
self._gitignore_filter = (
309+
GitIgnoreFilter(Path(repo_dir), self._boundaries) if self.use_gitignore else None
310+
)
205311
file_tree = self._build_file_tree(repo_dir)
206312
return {
207313
"file_tree": file_tree,
@@ -245,6 +351,8 @@ def build_tree(path: Path, base_path: Path) -> Optional[Dict]:
245351
}
246352

247353
elif path.is_dir():
354+
if self._boundaries and self._boundaries.should_skip(path):
355+
return None
248356
children = []
249357
try:
250358
for child in sorted(path.iterdir()):

‎codewiki/src/be/dependency_analyzer/analyzers/c.py‎

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55

66
from tree_sitter import Parser, Language
77
import tree_sitter_c
8+
from codewiki.src.be.dependency_analyzer.analyzers.c_declarators import (
9+
declarator_name,
10+
function_declarator,
11+
split_macro_function_name,
12+
)
813
from codewiki.src.be.dependency_analyzer.models.core import Node, CallRelationship
914

1015
logger = logging.getLogger(__name__)
@@ -73,12 +78,7 @@ def _extract_nodes(self, node, top_level_nodes, lines):
7378

7479
if node.type == "function_definition":
7580
node_type = "function"
76-
# look for function_declarator
77-
declarator = next((c for c in node.children if c.type == "function_declarator"), None)
78-
if declarator:
79-
identifier = next((c for c in declarator.children if c.type == "identifier"), None)
80-
if identifier:
81-
node_name = identifier.text.decode()
81+
node_name = self._function_name(node)
8282
elif node.type == "struct_specifier":
8383
# Extract struct definitions: struct Name { ... }
8484
node_type = "struct"
@@ -218,21 +218,18 @@ def _find_containing_function(self, node, top_level_nodes):
218218
current = node.parent
219219
while current:
220220
if current.type == "function_definition":
221-
# Get function name
222-
declarator = next(
223-
(c for c in current.children if c.type == "function_declarator"), None
224-
)
225-
if declarator:
226-
identifier = next(
227-
(c for c in declarator.children if c.type == "identifier"), None
228-
)
229-
if identifier:
230-
func_name = identifier.text.decode()
231-
if func_name in top_level_nodes:
232-
return func_name
221+
func_name = self._function_name(current)
222+
if func_name in top_level_nodes:
223+
return func_name
233224
current = current.parent
234225
return None
235226

227+
def _function_name(self, definition):
228+
declarator = function_declarator(definition)
229+
if declarator is None:
230+
return split_macro_function_name(definition)
231+
return declarator_name(declarator)
232+
236233

237234
def analyze_c_file(
238235
file_path: str, content: str, repo_path: str = None

0 commit comments

Comments
 (0)