agent-efficiency 1.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_efficiency/__init__.py +15 -0
- agent_efficiency/_bundle/mcp/server.py +519 -0
- agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
- agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
- agent_efficiency/_bundle/scripts/ae_init.py +267 -0
- agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
- agent_efficiency/_bundle/scripts/install.py +308 -0
- agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
- agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
- agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
- agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
- agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
- agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
- agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
- agent_efficiency/cli.py +23 -0
- agent_efficiency/mcp_entry.py +25 -0
- agent_efficiency-1.4.2.dist-info/METADATA +267 -0
- agent_efficiency-1.4.2.dist-info/RECORD +64 -0
- agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
- agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
- agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
"""Multi-language symbol & import extraction, summary generation, and import-edge resolution."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import ast
|
|
5
|
+
import posixpath
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
|
9
|
+
|
|
10
|
+
from _ae_core import redact_secrets, sanitize_inline
|
|
11
|
+
from idx_workspace import resolve_workspace_import
|
|
12
|
+
|
|
13
|
+
_TREESITTER_BACKEND: Optional[str] = None
|
|
14
|
+
_TS_LANG_MAP = {
|
|
15
|
+
"js": "javascript", "jsx": "javascript", "mjs": "javascript", "cjs": "javascript",
|
|
16
|
+
"ts": "typescript", "mts": "typescript", "cts": "typescript", "tsx": "tsx",
|
|
17
|
+
"go": "go", "rs": "rust", "java": "java", "rb": "ruby", "c": "c", "cpp": "cpp",
|
|
18
|
+
"kt": "kotlin", "kts": "kotlin", "swift": "swift", "cs": "csharp", "php": "php", "scala": "scala",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def treesitter_backend() -> str:
|
|
23
|
+
"""Return installed tree-sitter backend ('tree-sitter-language-pack', 'tree-sitter-languages', or 'stdlib')."""
|
|
24
|
+
global _TREESITTER_BACKEND
|
|
25
|
+
if _TREESITTER_BACKEND is None:
|
|
26
|
+
for mod_name, label in (
|
|
27
|
+
("tree_sitter_language_pack", "tree-sitter-language-pack"),
|
|
28
|
+
("tree_sitter_languages", "tree-sitter-languages"),
|
|
29
|
+
):
|
|
30
|
+
try:
|
|
31
|
+
__import__(mod_name)
|
|
32
|
+
_TREESITTER_BACKEND = label
|
|
33
|
+
break
|
|
34
|
+
except Exception:
|
|
35
|
+
continue
|
|
36
|
+
if _TREESITTER_BACKEND is None:
|
|
37
|
+
_TREESITTER_BACKEND = "stdlib"
|
|
38
|
+
return _TREESITTER_BACKEND
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def treesitter_available() -> bool:
|
|
42
|
+
"""Return True if optional `tree-sitter-language-pack` or `tree_sitter_languages` backend is installed."""
|
|
43
|
+
return treesitter_backend() != "stdlib"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _get_ts_parser(lang: str) -> Any:
|
|
47
|
+
backend = treesitter_backend()
|
|
48
|
+
ts_lang = _TS_LANG_MAP.get(lang)
|
|
49
|
+
if backend == "stdlib" or not ts_lang:
|
|
50
|
+
return None
|
|
51
|
+
try:
|
|
52
|
+
if backend == "tree-sitter-language-pack":
|
|
53
|
+
from tree_sitter_language_pack import get_parser # type: ignore[import-not-found]
|
|
54
|
+
else:
|
|
55
|
+
from tree_sitter_languages import get_parser # type: ignore[import-not-found]
|
|
56
|
+
return get_parser(ts_lang)
|
|
57
|
+
except Exception:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _node_text(node: Any, raw: bytes) -> str:
|
|
62
|
+
return raw[node.start_byte : node.end_byte].decode("utf-8", errors="replace").strip()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _try_treesitter_extract(text: str, lang: str) -> Optional[List[SymbolRow]]:
|
|
66
|
+
"""Optional tree-sitter AST symbol extractor supporting classes, methods, arrows, Go receivers & Rust impls."""
|
|
67
|
+
parser = _get_ts_parser(lang)
|
|
68
|
+
if parser is None:
|
|
69
|
+
return None
|
|
70
|
+
try:
|
|
71
|
+
raw = text.encode("utf-8", errors="replace")
|
|
72
|
+
tree = parser.parse(raw)
|
|
73
|
+
lines = text.splitlines()
|
|
74
|
+
syms: List[SymbolRow] = []
|
|
75
|
+
|
|
76
|
+
def walk(node: Any, cls_stack: List[str]) -> None:
|
|
77
|
+
ntype = node.type
|
|
78
|
+
# Rust `impl [Trait for] Struct { ... }`
|
|
79
|
+
if ntype == "impl_item":
|
|
80
|
+
t_node = node.child_by_field_name("type")
|
|
81
|
+
owner = _node_text(t_node, raw).split("<", 1)[0].split("::")[-1] if t_node else ""
|
|
82
|
+
next_stack = cls_stack + [owner] if owner else cls_stack
|
|
83
|
+
for ch in node.children:
|
|
84
|
+
walk(ch, next_stack)
|
|
85
|
+
return
|
|
86
|
+
# JS/TS `const foo = (...) => ...` / `const foo = function(...) {}`
|
|
87
|
+
if ntype == "variable_declarator":
|
|
88
|
+
name_node = node.child_by_field_name("name")
|
|
89
|
+
val_node = node.child_by_field_name("value")
|
|
90
|
+
if name_node is not None and val_node is not None and val_node.type in ("arrow_function", "function_expression", "function"):
|
|
91
|
+
name = _node_text(name_node, raw)
|
|
92
|
+
if name and name not in _CTRL_KW:
|
|
93
|
+
start_ln = node.start_point[0] + 1
|
|
94
|
+
end_ln = node.end_point[0] + 1
|
|
95
|
+
sig = redact_secrets(sanitize_inline(lines[start_ln - 1]))[:240] if 0 < start_ln <= len(lines) else name
|
|
96
|
+
syms.append((name, name, "function", start_ln, end_ln, sig, ""))
|
|
97
|
+
return
|
|
98
|
+
# Go receiver method `func (s *Struct) Method(...)`
|
|
99
|
+
if ntype == "method_declaration" and lang == "go":
|
|
100
|
+
name_node = node.child_by_field_name("name")
|
|
101
|
+
recv_node = node.child_by_field_name("receiver")
|
|
102
|
+
if name_node is not None:
|
|
103
|
+
name = _node_text(name_node, raw)
|
|
104
|
+
recv_txt = _node_text(recv_node, raw) if recv_node else ""
|
|
105
|
+
m_r = re.search(r"\*?\s*([A-Za-z_]\w*)(?:\[[^\]]*\])?\s*\)", recv_txt)
|
|
106
|
+
owner = m_r.group(1) if m_r else ""
|
|
107
|
+
qname = f"{owner}.{name}" if owner else name
|
|
108
|
+
start_ln, end_ln = node.start_point[0] + 1, node.end_point[0] + 1
|
|
109
|
+
sig = redact_secrets(sanitize_inline(lines[start_ln - 1]))[:240] if 0 < start_ln <= len(lines) else name
|
|
110
|
+
syms.append((name, qname, "method" if owner else "function", start_ln, end_ln, sig, ""))
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
is_cls = ntype in ("class_declaration", "class_definition", "class", "struct_item", "trait_item", "interface_declaration", "enum_declaration", "type_spec", "type_alias_declaration")
|
|
114
|
+
is_fn = ntype in ("function_declaration", "method_definition", "method_declaration", "function_item", "method", "function_definition")
|
|
115
|
+
if is_cls or is_fn:
|
|
116
|
+
name_node = node.child_by_field_name("name")
|
|
117
|
+
if name_node is not None:
|
|
118
|
+
name = _node_text(name_node, raw)
|
|
119
|
+
if name and name not in _CTRL_KW:
|
|
120
|
+
start_ln = node.start_point[0] + 1
|
|
121
|
+
end_ln = node.end_point[0] + 1
|
|
122
|
+
kind = "method" if (is_fn and cls_stack) else ("class" if is_cls else "function")
|
|
123
|
+
qname = ".".join(cls_stack + [name]) if (is_fn and cls_stack) else name
|
|
124
|
+
sig = redact_secrets(sanitize_inline(lines[start_ln - 1]))[:240] if 0 < start_ln <= len(lines) else name
|
|
125
|
+
syms.append((name, qname, kind, start_ln, end_ln, sig, ""))
|
|
126
|
+
next_stack = cls_stack + [name] if is_cls else cls_stack
|
|
127
|
+
for ch in node.children:
|
|
128
|
+
walk(ch, next_stack)
|
|
129
|
+
return
|
|
130
|
+
for ch in node.children:
|
|
131
|
+
walk(ch, cls_stack)
|
|
132
|
+
|
|
133
|
+
walk(tree.root_node, [])
|
|
134
|
+
return syms if syms else None
|
|
135
|
+
except Exception:
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _try_treesitter_calls(text: str, lang: str, syms: Sequence[SymbolRow]) -> Optional[List[CallRow]]:
|
|
140
|
+
"""AST-accurate call/JSX/decorator extraction when tree-sitter is installed."""
|
|
141
|
+
parser = _get_ts_parser(lang)
|
|
142
|
+
if parser is None:
|
|
143
|
+
return None
|
|
144
|
+
try:
|
|
145
|
+
raw = text.encode("utf-8", errors="replace")
|
|
146
|
+
tree = parser.parse(raw)
|
|
147
|
+
fn_spans = [(s[0], s[1], s[3], s[4]) for s in syms if s[2] in ("function", "async_function", "method", "class")]
|
|
148
|
+
fn_spans.sort(key=lambda x: (x[3] - x[2], x[2]))
|
|
149
|
+
|
|
150
|
+
def enclosing_sym(ln: int) -> Tuple[str, str]:
|
|
151
|
+
for nm, qn, lo, hi in fn_spans:
|
|
152
|
+
if lo <= ln <= hi:
|
|
153
|
+
return nm, qn
|
|
154
|
+
return "", "<module>"
|
|
155
|
+
|
|
156
|
+
calls: List[CallRow] = []
|
|
157
|
+
seen: Set[Tuple[str, str, int]] = set()
|
|
158
|
+
|
|
159
|
+
def record(ln: int, callee: str) -> None:
|
|
160
|
+
clean = callee.strip().rsplit(".", 1)[-1].rsplit("::", 1)[-1]
|
|
161
|
+
if not clean or clean in _CALL_SKIP_KW or not re.fullmatch(r"[A-Za-z_$][\w$]*", clean):
|
|
162
|
+
return
|
|
163
|
+
src_nm, src_q = enclosing_sym(ln)
|
|
164
|
+
if clean == src_nm:
|
|
165
|
+
return
|
|
166
|
+
key = (src_q, clean, ln)
|
|
167
|
+
if key not in seen:
|
|
168
|
+
seen.add(key)
|
|
169
|
+
calls.append((src_q, clean, ln))
|
|
170
|
+
|
|
171
|
+
def walk(node: Any) -> None:
|
|
172
|
+
nt = node.type
|
|
173
|
+
ln = node.start_point[0] + 1
|
|
174
|
+
if nt in ("call_expression", "new_expression"):
|
|
175
|
+
fn_node = node.child_by_field_name("function") or node.child_by_field_name("constructor")
|
|
176
|
+
if fn_node is not None:
|
|
177
|
+
record(ln, _node_text(fn_node, raw))
|
|
178
|
+
elif nt == "method_invocation":
|
|
179
|
+
nm = node.child_by_field_name("name")
|
|
180
|
+
if nm is not None:
|
|
181
|
+
record(ln, _node_text(nm, raw))
|
|
182
|
+
elif nt in ("jsx_opening_element", "jsx_self_closing_element"):
|
|
183
|
+
nm = node.child_by_field_name("name")
|
|
184
|
+
if nm is not None:
|
|
185
|
+
txt = _node_text(nm, raw)
|
|
186
|
+
if txt and txt[0].isupper():
|
|
187
|
+
record(ln, txt)
|
|
188
|
+
elif nt == "decorator":
|
|
189
|
+
txt = _node_text(node, raw).lstrip("@").split("(", 1)[0]
|
|
190
|
+
if txt:
|
|
191
|
+
record(ln, txt)
|
|
192
|
+
for ch in node.children:
|
|
193
|
+
walk(ch)
|
|
194
|
+
|
|
195
|
+
walk(tree.root_node)
|
|
196
|
+
return calls
|
|
197
|
+
except Exception:
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
CallRow = Tuple[str, str, int] # (src_qualified_symbol, callee_name, line)
|
|
202
|
+
_CALL_IDENT_RE = re.compile(r"\b([A-Za-z_]\w*)\s*\(")
|
|
203
|
+
_DECORATOR_RE = re.compile(r"^\s*@([A-Za-z_][\w.]*)")
|
|
204
|
+
_JSX_COMP_RE = re.compile(r"<([A-Z][A-Za-z0-9_]*)\b")
|
|
205
|
+
_DI_ARG_RE = re.compile(r"\b(?:Depends|inject|provide|register|use|UseGuards|UseInterceptors|add_route|include_router)\s*\(([^)]+)\)")
|
|
206
|
+
_CALL_SKIP_KW = {
|
|
207
|
+
"if", "for", "foreach", "while", "switch", "catch", "return", "else", "synchronized", "using",
|
|
208
|
+
"lock", "try", "do", "new", "throw", "case",
|
|
209
|
+
"def", "class", "function", "func", "fn", "import", "from", "export", "const", "let", "var",
|
|
210
|
+
"type", "struct", "interface", "enum", "trait", "impl", "async", "await", "yield", "typeof",
|
|
211
|
+
"sizeof", "match", "select", "defer", "go", "print", "len", "str", "int", "float", "bool",
|
|
212
|
+
"dict", "list", "set", "tuple", "range", "enumerate", "sorted", "isinstance", "getattr",
|
|
213
|
+
"setattr", "hasattr", "super", "require", "console", "log", "println", "fmt", "make", "append",
|
|
214
|
+
"True", "False", "None", "self", "cls", "this", "null", "undefined",
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _py_expr_leaf(node: ast.AST) -> str:
|
|
219
|
+
if isinstance(node, ast.Name):
|
|
220
|
+
return node.id
|
|
221
|
+
if isinstance(node, ast.Attribute):
|
|
222
|
+
return node.attr
|
|
223
|
+
if isinstance(node, ast.Call):
|
|
224
|
+
return _py_expr_leaf(node.func)
|
|
225
|
+
return ""
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def extract_calls(text: str, lang: str, syms: Sequence[SymbolRow]) -> List[CallRow]:
|
|
229
|
+
"""Extract function/method calls, decorators, base classes, JSX components, and DI/callback references."""
|
|
230
|
+
calls: List[CallRow] = []
|
|
231
|
+
if lang in ("py", "pyi"):
|
|
232
|
+
try:
|
|
233
|
+
tree = ast.parse(text)
|
|
234
|
+
except Exception:
|
|
235
|
+
return calls
|
|
236
|
+
|
|
237
|
+
seen_global: Set[Tuple[str, str, int]] = set()
|
|
238
|
+
|
|
239
|
+
def add_call(src_q: str, src_name: str, cname: str, ln: int) -> None:
|
|
240
|
+
if cname and cname not in _CALL_SKIP_KW and cname != src_name:
|
|
241
|
+
key = (src_q, cname, ln)
|
|
242
|
+
if key not in seen_global:
|
|
243
|
+
seen_global.add(key)
|
|
244
|
+
calls.append(key)
|
|
245
|
+
|
|
246
|
+
def record_call_node(src_q: str, src_name: str, call_node: ast.Call, fallback_ln: int) -> None:
|
|
247
|
+
ln = getattr(call_node, "lineno", fallback_ln)
|
|
248
|
+
add_call(src_q, src_name, _py_expr_leaf(call_node.func), ln)
|
|
249
|
+
# Capture callback & dependency-injection symbol references passed as args/kwargs (e.g. Depends(verify_token))
|
|
250
|
+
for arg in list(call_node.args) + [kw.value for kw in call_node.keywords]:
|
|
251
|
+
if isinstance(arg, (ast.Name, ast.Attribute)):
|
|
252
|
+
ref_name = _py_expr_leaf(arg)
|
|
253
|
+
if ref_name and len(ref_name) >= 3:
|
|
254
|
+
add_call(src_q, src_name, ref_name, getattr(arg, "lineno", ln))
|
|
255
|
+
|
|
256
|
+
def walk_body(nodes: Sequence[ast.stmt], stack: List[str]) -> None:
|
|
257
|
+
for n in nodes:
|
|
258
|
+
if isinstance(n, ast.ClassDef):
|
|
259
|
+
cls_q = ".".join(stack + [n.name])
|
|
260
|
+
for dec in n.decorator_list:
|
|
261
|
+
add_call(cls_q, n.name, _py_expr_leaf(dec), getattr(dec, "lineno", n.lineno))
|
|
262
|
+
if isinstance(dec, ast.Call):
|
|
263
|
+
record_call_node(cls_q, n.name, dec, n.lineno)
|
|
264
|
+
for base in n.bases:
|
|
265
|
+
add_call(cls_q, n.name, _py_expr_leaf(base), getattr(base, "lineno", n.lineno))
|
|
266
|
+
walk_body(n.body, stack + [n.name])
|
|
267
|
+
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
268
|
+
src_q = ".".join(stack + [n.name])
|
|
269
|
+
for dec in n.decorator_list:
|
|
270
|
+
add_call(src_q, n.name, _py_expr_leaf(dec), getattr(dec, "lineno", n.lineno))
|
|
271
|
+
if isinstance(dec, ast.Call):
|
|
272
|
+
record_call_node(src_q, n.name, dec, n.lineno)
|
|
273
|
+
for sub in ast.walk(n):
|
|
274
|
+
if isinstance(sub, ast.Call):
|
|
275
|
+
record_call_node(src_q, n.name, sub, n.lineno)
|
|
276
|
+
elif not stack:
|
|
277
|
+
# Module-level wiring calls (e.g. register(Handler), app.include_router(router))
|
|
278
|
+
for sub in ast.walk(n):
|
|
279
|
+
if isinstance(sub, ast.Call):
|
|
280
|
+
record_call_node("<module>", "", sub, getattr(n, "lineno", 1))
|
|
281
|
+
|
|
282
|
+
walk_body(tree.body, [])
|
|
283
|
+
return calls
|
|
284
|
+
|
|
285
|
+
if f".{lang}" not in CODE_EXTS:
|
|
286
|
+
return calls
|
|
287
|
+
|
|
288
|
+
ts_calls = _try_treesitter_calls(text, lang, syms)
|
|
289
|
+
if ts_calls is not None:
|
|
290
|
+
return ts_calls
|
|
291
|
+
|
|
292
|
+
lines = text.splitlines()
|
|
293
|
+
for name, qname, kind, start_ln, end_ln, _sig, _doc in syms:
|
|
294
|
+
if kind not in ("function", "async_function", "method", "class"):
|
|
295
|
+
continue
|
|
296
|
+
seen_local: Set[Tuple[str, int]] = set()
|
|
297
|
+
# Check up to 3 lines immediately above symbol for decorators (@UseGuards(AuthGuard), @Injectable)
|
|
298
|
+
for dln in range(max(1, start_ln - 3), start_ln):
|
|
299
|
+
dm = _DECORATOR_RE.match(lines[dln - 1])
|
|
300
|
+
if dm:
|
|
301
|
+
dname = dm.group(1).rsplit(".", 1)[-1]
|
|
302
|
+
if dname and dname not in _CALL_SKIP_KW and (dname, dln) not in seen_local:
|
|
303
|
+
seen_local.add((dname, dln))
|
|
304
|
+
calls.append((qname, dname, dln))
|
|
305
|
+
for di_m in _DI_ARG_RE.finditer(lines[dln - 1]):
|
|
306
|
+
for tok in re.findall(r"\b([A-Za-z_]\w{2,})\b", di_m.group(1)):
|
|
307
|
+
if tok not in _CALL_SKIP_KW and tok != name and (tok, dln) not in seen_local:
|
|
308
|
+
seen_local.add((tok, dln))
|
|
309
|
+
calls.append((qname, tok, dln))
|
|
310
|
+
if kind == "class":
|
|
311
|
+
continue
|
|
312
|
+
for ln in range(max(1, start_ln + 1), min(len(lines), end_ln) + 1):
|
|
313
|
+
raw_line = lines[ln - 1]
|
|
314
|
+
code_part = raw_line.split("//", 1)[0]
|
|
315
|
+
if code_part.lstrip().startswith(("#", "*", "/*")):
|
|
316
|
+
continue
|
|
317
|
+
code_part = re.sub(r"""(['"`])(?:\\.|(?!\1).)*\1""", " ", code_part)
|
|
318
|
+
for m in _CALL_IDENT_RE.finditer(code_part):
|
|
319
|
+
callee = m.group(1)
|
|
320
|
+
if callee and callee not in _CALL_SKIP_KW and callee != name and (callee, ln) not in seen_local:
|
|
321
|
+
seen_local.add((callee, ln))
|
|
322
|
+
calls.append((qname, callee, ln))
|
|
323
|
+
# JSX component invocations (<AuthModal .../>)
|
|
324
|
+
if lang in ("jsx", "tsx", "vue", "svelte", "astro"):
|
|
325
|
+
for jm in _JSX_COMP_RE.finditer(code_part):
|
|
326
|
+
comp = jm.group(1)
|
|
327
|
+
if comp and comp != name and (comp, ln) not in seen_local:
|
|
328
|
+
seen_local.add((comp, ln))
|
|
329
|
+
calls.append((qname, comp, ln))
|
|
330
|
+
# DI / callback identifiers passed to wiring calls
|
|
331
|
+
for di_m in _DI_ARG_RE.finditer(code_part):
|
|
332
|
+
for tok in re.findall(r"\b([A-Za-z_]\w{2,})\b", di_m.group(1)):
|
|
333
|
+
if tok not in _CALL_SKIP_KW and tok != name and (tok, ln) not in seen_local:
|
|
334
|
+
seen_local.add((tok, ln))
|
|
335
|
+
calls.append((qname, tok, ln))
|
|
336
|
+
return calls
|
|
337
|
+
|
|
338
|
+
CODE_EXTS: Set[str] = {
|
|
339
|
+
".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts",
|
|
340
|
+
".java", ".kt", ".kts", ".go", ".rs", ".c", ".h", ".cpp", ".hpp", ".cc", ".hh",
|
|
341
|
+
".cs", ".php", ".rb", ".swift", ".scala",
|
|
342
|
+
".vue", ".svelte", ".astro", ".dart", ".zig", ".lua", ".ex", ".exs", ".sol", ".groovy",
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
_JS_TS_SYM: Tuple[Tuple[str, re.Pattern[str]], ...] = (
|
|
346
|
+
("class", re.compile(r"^\s*(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)")),
|
|
347
|
+
("interface", re.compile(r"^\s*(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)")),
|
|
348
|
+
("type", re.compile(r"^\s*(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*=")),
|
|
349
|
+
("enum", re.compile(r"^\s*(?:export\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)")),
|
|
350
|
+
("function", re.compile(r"^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\*?\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(")),
|
|
351
|
+
("function", re.compile(r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:<[^>]*>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^=>{]+)?=>")),
|
|
352
|
+
)
|
|
353
|
+
_JS_TS_METHOD_RE = re.compile(
|
|
354
|
+
r"^\s+(?:(?:public|private|protected|static|readonly|override|abstract|async|get|set)\s+)*([A-Za-z_$#][\w$]*)\s*(?:<[^>]*>)?\s*\([^;]*\)\s*(?::\s*[^\{;]+)?\s*\{"
|
|
355
|
+
)
|
|
356
|
+
_JS_TS_IMP = re.compile(r"""(?:import\s+(?:[\s\S]*?\s+from\s+)?|import\s*\(\s*|require\s*\(\s*|export\s+[\s\S]*?\s+from\s+)['"]([^'"]+)['"]""")
|
|
357
|
+
|
|
358
|
+
_GO_METHOD_RE = re.compile(r"^func\s+\([^)]*?\*?\s*([A-Za-z_]\w*)(?:\[[^\]]*\])?\s*\)\s*([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*\(")
|
|
359
|
+
_GO_FUNC_RE = re.compile(r"^func\s+([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*\(")
|
|
360
|
+
_GO_TYPE_RE = re.compile(r"^type\s+([A-Za-z_]\w*)(?:\[[^\]]*\])?\s+(?:struct|interface|=|[A-Za-z_\[*])")
|
|
361
|
+
_GO_IMP = re.compile(r'^\s*(?:[A-Za-z_.]\w*\s+)?"([^"]+)"')
|
|
362
|
+
|
|
363
|
+
_RUST_IMPL_RE = re.compile(r"^\s*(?:unsafe\s+)?impl(?:<[^>]*>)?\s+(?:[A-Za-z_][\w:<>]*\s+for\s+)?([A-Za-z_]\w*)")
|
|
364
|
+
_RUST_SYM: Tuple[Tuple[str, re.Pattern[str]], ...] = (
|
|
365
|
+
("function", re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)")),
|
|
366
|
+
("struct", re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_]\w*)")),
|
|
367
|
+
("enum", re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+([A-Za-z_]\w*)")),
|
|
368
|
+
("trait", re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+([A-Za-z_]\w*)")),
|
|
369
|
+
)
|
|
370
|
+
_RUST_USE = re.compile(r"^\s*(?:pub\s+)?(?:use|mod)\s+([A-Za-z0-9_:]+)")
|
|
371
|
+
|
|
372
|
+
_C_LIKE_SYM = (
|
|
373
|
+
("class", re.compile(r"^\s*(?:public|private|protected|internal|final|abstract|sealed|data|open|static|\s)*(?:class|interface|struct|enum|protocol|record|actor)\s+([A-Za-z_]\w*)")),
|
|
374
|
+
("function", re.compile(r"^\s*(?:(?:public|private|protected|internal|static|final|override|virtual|inline|extern|async|suspend|fun|func|def|fn)\s+)*[A-Za-z_][\w<>,\[\]*&?:]*\s+([A-Za-z_]\w*)\s*\([^;]*\)\s*(?:->\s*[^\{]+)?\s*\{")),
|
|
375
|
+
)
|
|
376
|
+
_CTRL_KW = {"if", "for", "foreach", "while", "switch", "catch", "return", "else", "synchronized", "using", "lock", "try", "do", "new", "throw", "case"}
|
|
377
|
+
_MD_RE = re.compile(r"^(#{1,4})\s+(.+?)\s*#*$")
|
|
378
|
+
_FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")
|
|
379
|
+
_JSON_RE, _YAML_RE, _TOML_RE = re.compile(r'^ "([^"]+)":'), re.compile(r"^([A-Za-z0-9_.-]+)\s*:"), re.compile(r"^\[([^\]]+)\]")
|
|
380
|
+
|
|
381
|
+
_RUBY_OPEN_RE = re.compile(r"^\s*(?:class|module|def|if|unless|case|while|until|for|begin)\b|\bdo\s*(?:\|[^|]*\|)?\s*(?:#.*)?$")
|
|
382
|
+
_RUBY_END_RE = re.compile(r"^\s*end\b")
|
|
383
|
+
|
|
384
|
+
SymbolRow = Tuple[str, str, str, int, int, str, str]
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _unparse(node: ast.AST) -> str:
|
|
388
|
+
if hasattr(ast, "unparse"):
|
|
389
|
+
try:
|
|
390
|
+
return ast.unparse(node)
|
|
391
|
+
except Exception:
|
|
392
|
+
return ""
|
|
393
|
+
return ""
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _py_start_line(node: ast.AST) -> int:
|
|
397
|
+
lineno = getattr(node, "lineno", 1)
|
|
398
|
+
decs = getattr(node, "decorator_list", None) or []
|
|
399
|
+
if decs:
|
|
400
|
+
return min([lineno] + [getattr(d, "lineno", lineno) for d in decs])
|
|
401
|
+
return lineno
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _extract_python(text: str) -> Tuple[List[SymbolRow], List[Tuple[str, str]], Optional[str]]:
|
|
405
|
+
try:
|
|
406
|
+
tree = ast.parse(text)
|
|
407
|
+
except (SyntaxError, ValueError, TypeError):
|
|
408
|
+
return [], [], None
|
|
409
|
+
mod_doc = ast.get_docstring(tree)
|
|
410
|
+
syms: List[SymbolRow] = []
|
|
411
|
+
imports: List[Tuple[str, str]] = []
|
|
412
|
+
|
|
413
|
+
def visit(nodes: Sequence[ast.stmt], stack: List[str]) -> None:
|
|
414
|
+
for n in nodes:
|
|
415
|
+
if isinstance(n, ast.Import):
|
|
416
|
+
imports.extend((a.name, "import") for a in n.names)
|
|
417
|
+
elif isinstance(n, ast.ImportFrom):
|
|
418
|
+
mod = f"{'.' * (n.level or 0)}{n.module or ''}"
|
|
419
|
+
if mod:
|
|
420
|
+
imports.append((mod, "import_from"))
|
|
421
|
+
for a in n.names:
|
|
422
|
+
if a.name != "*":
|
|
423
|
+
imports.append((f"{mod}.{a.name}" if mod and not mod.endswith(".") else f"{mod}{a.name}", "import_from_member"))
|
|
424
|
+
elif isinstance(n, ast.ClassDef):
|
|
425
|
+
qname = ".".join(stack + [n.name])
|
|
426
|
+
bases = [b for b in (_unparse(x) for x in n.bases) if b]
|
|
427
|
+
sig = f"class {n.name}({', '.join(bases)})" if bases else f"class {n.name}"
|
|
428
|
+
doc = (ast.get_docstring(n) or "").splitlines()
|
|
429
|
+
first_doc = redact_secrets(sanitize_inline(doc[0]))[:160] if doc else ""
|
|
430
|
+
start, end = _py_start_line(n), getattr(n, "end_lineno", None) or getattr(n, "lineno", 1)
|
|
431
|
+
syms.append((n.name, qname, "class", start, end, redact_secrets(sanitize_inline(sig))[:240], first_doc))
|
|
432
|
+
visit(n.body, stack + [n.name])
|
|
433
|
+
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
434
|
+
is_async = isinstance(n, ast.AsyncFunctionDef)
|
|
435
|
+
kind = "method" if stack else ("async_function" if is_async else "function")
|
|
436
|
+
ret = _unparse(n.returns) if n.returns else ""
|
|
437
|
+
sig = f"{'async ' if is_async else ''}def {n.name}({_unparse(n.args)})" + (f" -> {ret}" if ret else "")
|
|
438
|
+
doc = (ast.get_docstring(n) or "").splitlines()
|
|
439
|
+
first_doc = redact_secrets(sanitize_inline(doc[0]))[:160] if doc else ""
|
|
440
|
+
start, end = _py_start_line(n), getattr(n, "end_lineno", None) or getattr(n, "lineno", 1)
|
|
441
|
+
syms.append((n.name, ".".join(stack + [n.name]), kind, start, end, redact_secrets(sanitize_inline(sig))[:240], first_doc))
|
|
442
|
+
|
|
443
|
+
visit(tree.body, [])
|
|
444
|
+
return syms, imports, mod_doc
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _brace_end(lines: List[str], start_idx: int) -> int:
|
|
448
|
+
"""Count `{` / `}` depth while skipping single/double/backtick strings and `//` or `/* */` comments."""
|
|
449
|
+
depth = 0
|
|
450
|
+
seen_open = False
|
|
451
|
+
in_block_comment = False
|
|
452
|
+
quote: Optional[str] = None
|
|
453
|
+
|
|
454
|
+
for idx in range(start_idx, min(len(lines), start_idx + 500)):
|
|
455
|
+
line = lines[idx]
|
|
456
|
+
i = 0
|
|
457
|
+
n = len(line)
|
|
458
|
+
while i < n:
|
|
459
|
+
ch = line[i]
|
|
460
|
+
nxt = line[i + 1] if i + 1 < n else ""
|
|
461
|
+
if in_block_comment:
|
|
462
|
+
if ch == "*" and nxt == "/":
|
|
463
|
+
in_block_comment = False
|
|
464
|
+
i += 2
|
|
465
|
+
continue
|
|
466
|
+
i += 1
|
|
467
|
+
continue
|
|
468
|
+
if quote is not None:
|
|
469
|
+
if ch == "\\" and quote != "`":
|
|
470
|
+
i += 2
|
|
471
|
+
continue
|
|
472
|
+
if ch == "\\" and quote == "`":
|
|
473
|
+
i += 2
|
|
474
|
+
continue
|
|
475
|
+
if ch == quote:
|
|
476
|
+
quote = None
|
|
477
|
+
i += 1
|
|
478
|
+
continue
|
|
479
|
+
if ch == "/" and nxt == "/":
|
|
480
|
+
break
|
|
481
|
+
if ch == "/" and nxt == "*":
|
|
482
|
+
in_block_comment = True
|
|
483
|
+
i += 2
|
|
484
|
+
continue
|
|
485
|
+
if ch in ("'", '"', "`"):
|
|
486
|
+
# Rust lifetime like `'a` is not a char literal unless closed with `'` after 1-2 chars
|
|
487
|
+
if ch == "'" and i + 2 < n and line[i + 1].isalpha() and line[i + 2] != "'":
|
|
488
|
+
i += 1
|
|
489
|
+
continue
|
|
490
|
+
quote = ch
|
|
491
|
+
i += 1
|
|
492
|
+
continue
|
|
493
|
+
if ch == "{":
|
|
494
|
+
depth += 1
|
|
495
|
+
seen_open = True
|
|
496
|
+
elif ch == "}":
|
|
497
|
+
depth -= 1
|
|
498
|
+
if seen_open and depth <= 0:
|
|
499
|
+
return idx + 1
|
|
500
|
+
i += 1
|
|
501
|
+
# Single-line quotes don't span lines (except JS/Go backticks)
|
|
502
|
+
if quote in ("'", '"'):
|
|
503
|
+
quote = None
|
|
504
|
+
if not seen_open and idx > start_idx + 3 and line.rstrip().endswith(";"):
|
|
505
|
+
return idx + 1
|
|
506
|
+
return min(len(lines), start_idx + 1)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _ruby_end(lines: List[str], start_idx: int) -> int:
|
|
510
|
+
depth = 0
|
|
511
|
+
for idx in range(start_idx, min(len(lines), start_idx + 500)):
|
|
512
|
+
stripped = lines[idx].strip()
|
|
513
|
+
if not stripped or stripped.startswith("#"):
|
|
514
|
+
continue
|
|
515
|
+
if _RUBY_OPEN_RE.search(lines[idx]):
|
|
516
|
+
depth += 1
|
|
517
|
+
if _RUBY_END_RE.match(lines[idx]):
|
|
518
|
+
depth -= 1
|
|
519
|
+
if depth <= 0:
|
|
520
|
+
return idx + 1
|
|
521
|
+
return min(len(lines), start_idx + 1)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _extract_js_ts(text: str, lines: List[str]) -> Tuple[List[SymbolRow], List[Tuple[str, str]]]:
|
|
525
|
+
syms: List[SymbolRow] = []
|
|
526
|
+
imports = [(m.group(1), "import") for m in _JS_TS_IMP.finditer(text)]
|
|
527
|
+
active_classes: List[Tuple[str, int]] = [] # (class_name, end_line)
|
|
528
|
+
|
|
529
|
+
for idx, line in enumerate(lines):
|
|
530
|
+
lineno = idx + 1
|
|
531
|
+
active_classes = [(cname, cend) for cname, cend in active_classes if lineno <= cend]
|
|
532
|
+
matched_top = False
|
|
533
|
+
for kind, pat in _JS_TS_SYM:
|
|
534
|
+
m = pat.match(line)
|
|
535
|
+
if m and m.group(1) not in _CTRL_KW:
|
|
536
|
+
name = m.group(1)
|
|
537
|
+
end_ln = _brace_end(lines, idx)
|
|
538
|
+
syms.append((name, name, kind, lineno, end_ln, redact_secrets(sanitize_inline(line))[:240], ""))
|
|
539
|
+
if kind == "class":
|
|
540
|
+
active_classes.append((name, end_ln))
|
|
541
|
+
matched_top = True
|
|
542
|
+
break
|
|
543
|
+
if matched_top:
|
|
544
|
+
continue
|
|
545
|
+
if active_classes:
|
|
546
|
+
mm = _JS_TS_METHOD_RE.match(line)
|
|
547
|
+
if mm and mm.group(1) not in _CTRL_KW:
|
|
548
|
+
mname = mm.group(1)
|
|
549
|
+
cls = active_classes[-1][0]
|
|
550
|
+
end_ln = _brace_end(lines, idx)
|
|
551
|
+
syms.append((mname, f"{cls}.{mname}", "method", lineno, end_ln, redact_secrets(sanitize_inline(line))[:240], ""))
|
|
552
|
+
return syms, imports
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _extract_go(lines: List[str]) -> Tuple[List[SymbolRow], List[Tuple[str, str]]]:
|
|
556
|
+
syms: List[SymbolRow] = []
|
|
557
|
+
imports: List[Tuple[str, str]] = []
|
|
558
|
+
in_blk = False
|
|
559
|
+
for idx, line in enumerate(lines):
|
|
560
|
+
s = line.strip()
|
|
561
|
+
if s.startswith("import ("):
|
|
562
|
+
in_blk = True
|
|
563
|
+
elif in_blk:
|
|
564
|
+
if s == ")":
|
|
565
|
+
in_blk = False
|
|
566
|
+
else:
|
|
567
|
+
m_imp = _GO_IMP.match(line)
|
|
568
|
+
if m_imp:
|
|
569
|
+
imports.append((m_imp.group(1), "import"))
|
|
570
|
+
elif s.startswith("import "):
|
|
571
|
+
m_single = re.search(r'"([^"]+)"', s)
|
|
572
|
+
if m_single:
|
|
573
|
+
imports.append((m_single.group(1), "import"))
|
|
574
|
+
|
|
575
|
+
mm = _GO_METHOD_RE.match(line)
|
|
576
|
+
if mm:
|
|
577
|
+
recv, mname = mm.group(1), mm.group(2)
|
|
578
|
+
syms.append((mname, f"{recv}.{mname}", "method", idx + 1, _brace_end(lines, idx), redact_secrets(sanitize_inline(line))[:240], ""))
|
|
579
|
+
continue
|
|
580
|
+
mf = _GO_FUNC_RE.match(line)
|
|
581
|
+
if mf:
|
|
582
|
+
fname = mf.group(1)
|
|
583
|
+
syms.append((fname, fname, "function", idx + 1, _brace_end(lines, idx), redact_secrets(sanitize_inline(line))[:240], ""))
|
|
584
|
+
continue
|
|
585
|
+
mt = _GO_TYPE_RE.match(line)
|
|
586
|
+
if mt:
|
|
587
|
+
tname = mt.group(1)
|
|
588
|
+
end_ln = _brace_end(lines, idx) if "{" in line else idx + 1
|
|
589
|
+
syms.append((tname, tname, "type", idx + 1, end_ln, redact_secrets(sanitize_inline(line))[:240], ""))
|
|
590
|
+
return syms, imports
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _extract_rust(lines: List[str]) -> Tuple[List[SymbolRow], List[Tuple[str, str]]]:
|
|
594
|
+
syms: List[SymbolRow] = []
|
|
595
|
+
imports = [(m.group(1), "use") for l in lines for m in [_RUST_USE.match(l)] if m]
|
|
596
|
+
active_impls: List[Tuple[str, int]] = []
|
|
597
|
+
|
|
598
|
+
for idx, line in enumerate(lines):
|
|
599
|
+
lineno = idx + 1
|
|
600
|
+
active_impls = [(sname, send) for sname, send in active_impls if lineno <= send]
|
|
601
|
+
mi = _RUST_IMPL_RE.match(line)
|
|
602
|
+
if mi:
|
|
603
|
+
target = mi.group(1)
|
|
604
|
+
end_ln = _brace_end(lines, idx)
|
|
605
|
+
syms.append((target, target, "impl", lineno, end_ln, redact_secrets(sanitize_inline(line))[:240], ""))
|
|
606
|
+
active_impls.append((target, end_ln))
|
|
607
|
+
continue
|
|
608
|
+
for kind, pat in _RUST_SYM:
|
|
609
|
+
m = pat.match(line)
|
|
610
|
+
if m and m.group(1) not in _CTRL_KW:
|
|
611
|
+
name = m.group(1)
|
|
612
|
+
end_ln = _brace_end(lines, idx) if ("{" in line or kind == "function") else idx + 1
|
|
613
|
+
if kind == "function" and active_impls:
|
|
614
|
+
owner = active_impls[-1][0]
|
|
615
|
+
syms.append((name, f"{owner}.{name}", "method", lineno, end_ln, redact_secrets(sanitize_inline(line))[:240], ""))
|
|
616
|
+
else:
|
|
617
|
+
syms.append((name, name, kind, lineno, end_ln, redact_secrets(sanitize_inline(line))[:240], ""))
|
|
618
|
+
break
|
|
619
|
+
return syms, imports
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _extract_non_python(text: str, lang: str) -> Tuple[List[SymbolRow], List[Tuple[str, str]]]:
|
|
623
|
+
lines, syms, imports = text.splitlines(), [], []
|
|
624
|
+
if lang in ("md", "mdx", "rst"):
|
|
625
|
+
hd: List[Tuple[int, int, str]] = []
|
|
626
|
+
in_fence: Optional[str] = None
|
|
627
|
+
for i, l in enumerate(lines):
|
|
628
|
+
fm = _FENCE_RE.match(l)
|
|
629
|
+
if fm:
|
|
630
|
+
tok = fm.group(1)[0]
|
|
631
|
+
if in_fence is None:
|
|
632
|
+
in_fence = tok
|
|
633
|
+
elif in_fence == tok:
|
|
634
|
+
in_fence = None
|
|
635
|
+
continue
|
|
636
|
+
if in_fence is not None:
|
|
637
|
+
continue
|
|
638
|
+
m = _MD_RE.match(l)
|
|
639
|
+
if m:
|
|
640
|
+
hd.append((i + 1, len(m.group(1)), sanitize_inline(m.group(2))))
|
|
641
|
+
for i, (ln, lvl, title) in enumerate(hd):
|
|
642
|
+
end = next((nln - 1 for nln, nlvl, _ in hd[i + 1 :] if nlvl <= lvl), len(lines))
|
|
643
|
+
ct = redact_secrets(title)
|
|
644
|
+
syms.append((ct[:80], ct[:120], f"h{lvl}", ln, max(ln, end), f"{'#' * lvl} {ct}"[:240], ""))
|
|
645
|
+
return syms, imports
|
|
646
|
+
if lang in ("json", "yaml", "yml", "toml"):
|
|
647
|
+
rx, kind, fmt = (_JSON_RE, "key", '"{}"') if lang == "json" else ((_TOML_RE, "section", "[{}]") if lang == "toml" else (_YAML_RE, "key", "{}:"))
|
|
648
|
+
for idx, line in enumerate(lines[:500]):
|
|
649
|
+
m = rx.match(line.strip() if lang == "toml" else line)
|
|
650
|
+
if m:
|
|
651
|
+
k = sanitize_inline(m.group(1))
|
|
652
|
+
syms.append((k, k, kind, idx + 1, idx + 1, fmt.format(k), ""))
|
|
653
|
+
return syms, imports
|
|
654
|
+
|
|
655
|
+
if lang in ("js", "jsx", "mjs", "cjs", "ts", "tsx", "mts", "cts", "vue", "svelte", "astro"):
|
|
656
|
+
return _extract_js_ts(text, lines)
|
|
657
|
+
if lang == "go":
|
|
658
|
+
return _extract_go(lines)
|
|
659
|
+
if lang == "rs":
|
|
660
|
+
return _extract_rust(lines)
|
|
661
|
+
if lang == "rb":
|
|
662
|
+
rb_pats = (
|
|
663
|
+
("class", re.compile(r"^\s*(?:class|module)\s+([A-Za-z_][\w:]*)")),
|
|
664
|
+
("function", re.compile(r"^\s*def\s+(?:self\.)?([A-Za-z_]\w*[!?=]?)")),
|
|
665
|
+
)
|
|
666
|
+
for idx, line in enumerate(lines):
|
|
667
|
+
for kind, pat in rb_pats:
|
|
668
|
+
m = pat.match(line)
|
|
669
|
+
if m and m.group(1) not in _CTRL_KW:
|
|
670
|
+
syms.append((m.group(1), m.group(1), kind, idx + 1, _ruby_end(lines, idx), redact_secrets(sanitize_inline(line))[:240], ""))
|
|
671
|
+
break
|
|
672
|
+
return syms, imports
|
|
673
|
+
|
|
674
|
+
if lang in ("java", "kt", "kts", "cs", "swift", "cpp", "cc", "c", "h", "hpp", "php", "scala", "dart", "sol", "groovy"):
|
|
675
|
+
imports.extend((m.group(1), "import") for l in lines for m in [re.match(r'^\s*(?:import|using|#include)\s+[<"]?([A-Za-z0-9_./:-]+)[>"]?', l)] if m)
|
|
676
|
+
patterns = _C_LIKE_SYM
|
|
677
|
+
elif lang in ("sh", "bash", "zsh"):
|
|
678
|
+
patterns = (("function", re.compile(r"^\s*(?:function\s+)?([A-Za-z_]\w*)\s*\(\)\s*\{")),)
|
|
679
|
+
else:
|
|
680
|
+
return syms, imports
|
|
681
|
+
|
|
682
|
+
for idx, line in enumerate(lines):
|
|
683
|
+
for kind, pat in patterns:
|
|
684
|
+
m = pat.match(line)
|
|
685
|
+
if m and m.group(1) not in _CTRL_KW:
|
|
686
|
+
syms.append((m.group(1), m.group(1), kind, idx + 1, _brace_end(lines, idx), redact_secrets(sanitize_inline(line))[:240], ""))
|
|
687
|
+
break
|
|
688
|
+
return syms, imports
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def extract_symbols_and_imports(text: str, lang: str) -> Tuple[List[SymbolRow], List[Tuple[str, str]]]:
|
|
692
|
+
if lang in ("py", "pyi"):
|
|
693
|
+
syms, imps, _ = _extract_python(text)
|
|
694
|
+
return syms, imps
|
|
695
|
+
syms, imps = _extract_non_python(text, lang)
|
|
696
|
+
ts_syms = _try_treesitter_extract(text, lang)
|
|
697
|
+
return (ts_syms if ts_syms else syms), imps
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def extract_file_metadata(text: str, lang: str) -> Tuple[List[SymbolRow], List[Tuple[str, str]], str]:
|
|
701
|
+
"""Single-pass extraction of symbols, imports, and summary (uses tree-sitter when installed, else stdlib)."""
|
|
702
|
+
if lang in ("py", "pyi"):
|
|
703
|
+
syms, imps, mod_doc = _extract_python(text)
|
|
704
|
+
return syms, imps, make_summary(text, lang, syms, precomputed_py_doc=mod_doc)
|
|
705
|
+
syms, imps = _extract_non_python(text, lang)
|
|
706
|
+
ts_syms = _try_treesitter_extract(text, lang)
|
|
707
|
+
eff_syms = ts_syms if ts_syms else syms
|
|
708
|
+
return eff_syms, imps, make_summary(text, lang, eff_syms)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def make_summary(text: str, lang: str, syms: Sequence[SymbolRow], *, precomputed_py_doc: Optional[str] = None) -> str:
|
|
712
|
+
lines = [x.strip() for x in text.splitlines() if x.strip()]
|
|
713
|
+
if not lines:
|
|
714
|
+
return f"Empty {lang} file."
|
|
715
|
+
if lang in ("py", "pyi"):
|
|
716
|
+
doc = precomputed_py_doc
|
|
717
|
+
if doc is None:
|
|
718
|
+
try:
|
|
719
|
+
doc = ast.get_docstring(ast.parse(text))
|
|
720
|
+
except Exception:
|
|
721
|
+
doc = None
|
|
722
|
+
if doc:
|
|
723
|
+
first = sanitize_inline(" ".join(doc.strip().splitlines()[:2]))
|
|
724
|
+
if first:
|
|
725
|
+
return redact_secrets(first)[:220]
|
|
726
|
+
if lang in ("md", "mdx"):
|
|
727
|
+
for ln in lines[:15]:
|
|
728
|
+
if ln.startswith("#"):
|
|
729
|
+
return redact_secrets(sanitize_inline(ln.lstrip("# ")))[:220]
|
|
730
|
+
cmts = [sanitize_inline(x.lstrip("#/* ")) for x in lines[:40] if x.startswith(("#", "//", "/*", "*")) and not x.startswith("#!")]
|
|
731
|
+
cmts = [c for c in cmts if c and not c.startswith(("eslint", "type:"))][:2]
|
|
732
|
+
if cmts:
|
|
733
|
+
return redact_secrets(" ".join(cmts))[:220]
|
|
734
|
+
if syms:
|
|
735
|
+
return f"{len(lines)} lines ({lang}); defines {', '.join(sanitize_inline(s[0]) for s in syms[:5])}"[:220]
|
|
736
|
+
return f"{len(lines)} lines ({lang})"
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def resolve_import_edge(
|
|
740
|
+
src_path: str,
|
|
741
|
+
raw_target: str,
|
|
742
|
+
all_paths: Set[str],
|
|
743
|
+
code_stem_index: Dict[str, List[str]],
|
|
744
|
+
workspace_aliases: Optional[Dict[str, Any]] = None,
|
|
745
|
+
) -> Optional[str]:
|
|
746
|
+
src_dir = Path(src_path).parent
|
|
747
|
+
if raw_target.startswith(".") and "/" in raw_target:
|
|
748
|
+
base = posixpath.normpath((src_dir / raw_target).as_posix())
|
|
749
|
+
return next((base + s for s in ("", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".py", "/index.ts", "/index.tsx", "/index.js") if (base + s) in all_paths), None)
|
|
750
|
+
if raw_target.startswith("."):
|
|
751
|
+
dots = len(raw_target) - len(raw_target.lstrip("."))
|
|
752
|
+
rest, base_dir = raw_target[dots:].replace(".", "/"), src_dir
|
|
753
|
+
for _ in range(max(0, dots - 1)):
|
|
754
|
+
base_dir = base_dir.parent
|
|
755
|
+
rel_base = posixpath.normpath((base_dir / rest).as_posix() if rest else base_dir.as_posix())
|
|
756
|
+
return next((rel_base + s for s in (".py", "/__init__.py") if (rel_base + s) in all_paths), None)
|
|
757
|
+
ws_hit = resolve_workspace_import(src_path, raw_target, all_paths, workspace_aliases)
|
|
758
|
+
if ws_hit:
|
|
759
|
+
return ws_hit
|
|
760
|
+
slash = raw_target.replace(".", "/").replace("::", "/")
|
|
761
|
+
direct = next((c for c in (raw_target, slash + ".py", slash + "/__init__.py", slash + ".ts", slash + ".tsx", slash + ".js", slash + "/index.ts", slash + "/index.js", slash + ".go", slash + ".rs", f"src/{slash}.py", f"src/{slash}.ts", f"src/{slash}.js") if c in all_paths), None)
|
|
762
|
+
if direct:
|
|
763
|
+
return direct
|
|
764
|
+
leaf = slash.split("/")[-1]
|
|
765
|
+
if leaf:
|
|
766
|
+
cands = [p for p in code_stem_index.get(leaf, []) if p != src_path]
|
|
767
|
+
same = [p for p in cands if Path(p).suffix.lower() == Path(src_path).suffix.lower()]
|
|
768
|
+
return same[0] if len(same) == 1 else (cands[0] if len(cands) == 1 else None)
|
|
769
|
+
return None
|