featuregraph-cli 0.1.0__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.
- featuregraph/__init__.py +6 -0
- featuregraph/cli.py +758 -0
- featuregraph/core/annotator.py +491 -0
- featuregraph/core/dependency_resolver.py +480 -0
- featuregraph/core/graph.py +123 -0
- featuregraph/core/lexmask.py +264 -0
- featuregraph/core/parser_generic.py +233 -0
- featuregraph/core/parser_protocol.py +18 -0
- featuregraph/core/parser_py.py +243 -0
- featuregraph/core/parser_ts.py +350 -0
- featuregraph/core/scanner.py +429 -0
- featuregraph/core/tags.py +51 -0
- featuregraph/formatters/json_formatter.py +164 -0
- featuregraph/formatters/markdown_formatter.py +110 -0
- featuregraph/hooks/git_hook.py +82 -0
- featuregraph/skills/__init__.py +3 -0
- featuregraph/skills/featuregraph/SKILL.md +211 -0
- featuregraph/skills/skill_manager.py +51 -0
- featuregraph_cli-0.1.0.dist-info/METADATA +338 -0
- featuregraph_cli-0.1.0.dist-info/RECORD +23 -0
- featuregraph_cli-0.1.0.dist-info/WHEEL +4 -0
- featuregraph_cli-0.1.0.dist-info/entry_points.txt +2 -0
- featuregraph_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
from collections import Counter, defaultdict
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from . import lexmask
|
|
10
|
+
|
|
11
|
+
# Common keywords/builtins to ignore during dependency resolution
|
|
12
|
+
IGNORED_SYMBOLS = {
|
|
13
|
+
# Python builtins & common keywords
|
|
14
|
+
"str", "int", "float", "bool", "list", "dict", "set", "tuple", "len",
|
|
15
|
+
"print", "range", "enumerate", "isinstance", "issubclass", "getattr",
|
|
16
|
+
"setattr", "hasattr", "open", "super", "min", "max", "sum", "any", "all",
|
|
17
|
+
"filter", "map", "sorted", "reversed", "zip", "type", "id", "self", "cls",
|
|
18
|
+
"None", "True", "False", "Exception", "ValueError", "TypeError", "KeyError",
|
|
19
|
+
"router", "app", "get", "post", "put", "delete", "patch", "response", "request",
|
|
20
|
+
# JS/TS builtins
|
|
21
|
+
"console", "log", "error", "warn", "info", "window", "document", "React",
|
|
22
|
+
"useState", "useEffect", "useCallback", "useMemo", "useRef", "useContext",
|
|
23
|
+
# Go / Rust / Java / C#
|
|
24
|
+
"fmt", "println", "printf", "err", "ctx", "nil", "ok", "Vec", "String",
|
|
25
|
+
"Option", "Result", "System", "out", "Console", "WriteLine", "Task",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
# Dependency-injection wrappers: their arguments name the real dependency.
|
|
29
|
+
DI_WRAPPERS = {
|
|
30
|
+
"Depends", "Security", "Body", "Header", "Cookie",
|
|
31
|
+
"fastapi.Depends", "fastapi.Security",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
# Non-Python extraction: only real references, never bare identifier tokens.
|
|
35
|
+
CALL_SITE_REGEX = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)\s*\(")
|
|
36
|
+
JSX_TAG_REGEX = re.compile(r"<([A-Z][A-Za-z0-9_]*)\b")
|
|
37
|
+
INHERIT_REGEX = re.compile(r"\b(?:extends|implements)\s+([A-Za-z_][A-Za-z0-9_]*)")
|
|
38
|
+
IMPORT_FROM_REGEX = re.compile(r"\bimport\s+(?:type\s+)?([^;'\"]+?)\s+from\s+['\"]")
|
|
39
|
+
REQUIRE_REGEX = re.compile(
|
|
40
|
+
r"\b(?:const|let|var)\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s*=\s*require\s*\("
|
|
41
|
+
)
|
|
42
|
+
NAMED_IMPORT_REGEX = re.compile(r"\{([^}]*)\}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _clean(part: str) -> str:
|
|
46
|
+
return re.sub(r"[^A-Za-z0-9_]", "_", part)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _scope(feat: dict[str, Any], include_filename: bool = False) -> str:
|
|
50
|
+
raw = str(feat.get("rel_path") or feat.get("file") or "")
|
|
51
|
+
if not raw:
|
|
52
|
+
return ""
|
|
53
|
+
path = Path(raw)
|
|
54
|
+
path = path.with_suffix("") if include_filename else path.parent
|
|
55
|
+
parts = [p for p in path.as_posix().split("/") if p not in ("", ".")]
|
|
56
|
+
return ".".join(_clean(p) for p in parts)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _module_aliases(tree: ast.Module) -> dict[str, str]:
|
|
60
|
+
"""Local name -> imported name for `import X as Y` and `from M import A as B`."""
|
|
61
|
+
aliases: dict[str, str] = {}
|
|
62
|
+
for node in ast.walk(tree):
|
|
63
|
+
if isinstance(node, ast.Import):
|
|
64
|
+
for alias in node.names:
|
|
65
|
+
if alias.asname:
|
|
66
|
+
aliases[alias.asname] = alias.name
|
|
67
|
+
elif isinstance(node, ast.ImportFrom):
|
|
68
|
+
for alias in node.names:
|
|
69
|
+
if alias.name == "*":
|
|
70
|
+
continue
|
|
71
|
+
local = alias.asname or alias.name
|
|
72
|
+
if local != alias.name:
|
|
73
|
+
aliases[local] = alias.name
|
|
74
|
+
return aliases
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _canonical_name(name: str, aliases: dict[str, str]) -> str:
|
|
78
|
+
seen: set[str] = set()
|
|
79
|
+
while name in aliases and name not in seen:
|
|
80
|
+
seen.add(name)
|
|
81
|
+
name = aliases[name]
|
|
82
|
+
return name
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _canonical_dotted(dotted: str, aliases: dict[str, str]) -> str:
|
|
86
|
+
head, sep, tail = dotted.partition(".")
|
|
87
|
+
return f"{_canonical_name(head, aliases)}{sep}{tail}" if sep else _canonical_name(dotted, aliases)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def assign_symbol_ids(features_data: list[dict[str, Any]]):
|
|
91
|
+
"""Bare symbol when unique; deterministic path qualification on collision."""
|
|
92
|
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
93
|
+
for feat in features_data:
|
|
94
|
+
symbol = str(feat.get("symbol", "")).strip()
|
|
95
|
+
if symbol:
|
|
96
|
+
groups[symbol.casefold()].append(feat)
|
|
97
|
+
|
|
98
|
+
for group in groups.values():
|
|
99
|
+
symbol = min(_clean(str(feat.get("symbol", ""))) for feat in group)
|
|
100
|
+
if len(group) == 1:
|
|
101
|
+
group[0]["symbol_id"] = symbol
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
for feat in group:
|
|
105
|
+
scope = _scope(feat)
|
|
106
|
+
feat["_symbol_id"] = f"{scope}.{symbol}" if scope else symbol
|
|
107
|
+
|
|
108
|
+
counts = Counter(f["_symbol_id"] for f in group)
|
|
109
|
+
for feat in group:
|
|
110
|
+
if counts[feat["_symbol_id"]] > 1:
|
|
111
|
+
scope = _scope(feat, include_filename=True)
|
|
112
|
+
feat["_symbol_id"] = f"{scope}.{symbol}" if scope else symbol
|
|
113
|
+
|
|
114
|
+
counts = Counter(f["_symbol_id"] for f in group)
|
|
115
|
+
for feat in group:
|
|
116
|
+
if counts[feat["_symbol_id"]] > 1:
|
|
117
|
+
fid = _clean(str(feat.get("feature_id", ""))).lower() or "feature"
|
|
118
|
+
feat["_symbol_id"] = f"{feat['_symbol_id']}.{fid}"
|
|
119
|
+
|
|
120
|
+
counts = Counter(f["_symbol_id"] for f in group)
|
|
121
|
+
for feat in group:
|
|
122
|
+
if counts[feat["_symbol_id"]] > 1:
|
|
123
|
+
start = feat.get("start_line") or (feat.get("lines") or [0])[0]
|
|
124
|
+
feat["_symbol_id"] = f"{feat['_symbol_id']}.{start}"
|
|
125
|
+
|
|
126
|
+
for feat in group:
|
|
127
|
+
feat["symbol_id"] = feat.pop("_symbol_id")
|
|
128
|
+
|
|
129
|
+
used: set[str] = set()
|
|
130
|
+
for feat in features_data:
|
|
131
|
+
symbol_id = feat.get("symbol_id")
|
|
132
|
+
if not symbol_id:
|
|
133
|
+
continue
|
|
134
|
+
base = symbol_id
|
|
135
|
+
n = 2
|
|
136
|
+
while symbol_id.casefold() in used:
|
|
137
|
+
symbol_id = f"{base}_{n}"
|
|
138
|
+
n += 1
|
|
139
|
+
feat["symbol_id"] = symbol_id
|
|
140
|
+
used.add(symbol_id.casefold())
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def build_symbol_aliases(
|
|
144
|
+
features: dict[str, dict[str, Any]]
|
|
145
|
+
) -> tuple[dict[str, str], dict[str, list[tuple[str, str, str]]]]:
|
|
146
|
+
"""Map persisted locations to symbol-id and bare-symbol aliases for CLI lookup."""
|
|
147
|
+
records: list[dict[str, Any]] = []
|
|
148
|
+
for feat_id, feat in features.items():
|
|
149
|
+
for loc in feat.get("locations", []):
|
|
150
|
+
lines = loc.get("lines") or [loc.get("start_line", 1), loc.get("end_line", 1)]
|
|
151
|
+
records.append({
|
|
152
|
+
"feature_id": feat_id,
|
|
153
|
+
"symbol": loc.get("symbol", ""),
|
|
154
|
+
"symbol_id": loc.get("symbol_id"),
|
|
155
|
+
"rel_path": loc.get("file", ""),
|
|
156
|
+
"start_line": lines[0] if lines else 1,
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
if not all(rec.get("symbol_id") for rec in records):
|
|
160
|
+
assign_symbol_ids(records)
|
|
161
|
+
by_id: dict[str, str] = {}
|
|
162
|
+
by_symbol: dict[str, list[tuple[str, str, str]]] = defaultdict(list)
|
|
163
|
+
seen: set[tuple[str, str]] = set()
|
|
164
|
+
for rec in records:
|
|
165
|
+
symbol_id = rec.get("symbol_id")
|
|
166
|
+
if not symbol_id:
|
|
167
|
+
continue
|
|
168
|
+
feat_id = rec["feature_id"]
|
|
169
|
+
by_id[symbol_id.casefold()] = feat_id
|
|
170
|
+
key = (symbol_id, feat_id)
|
|
171
|
+
if key not in seen:
|
|
172
|
+
seen.add(key)
|
|
173
|
+
by_symbol[str(rec.get("symbol", "")).casefold()].append(
|
|
174
|
+
(symbol_id, feat_id, rec["rel_path"])
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
for candidates in by_symbol.values():
|
|
178
|
+
candidates.sort()
|
|
179
|
+
return by_id, by_symbol
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# @feature [DEP_RESOLVER-01] Dependency Resolver
|
|
183
|
+
class DependencyResolver:
|
|
184
|
+
"""Analyzes AST call-sites and token references to automatically infer cross-feature dependencies."""
|
|
185
|
+
|
|
186
|
+
def __init__(self):
|
|
187
|
+
# symbol_name -> feature_id (unique names only)
|
|
188
|
+
self.symbol_to_feature: dict[str, str] = {}
|
|
189
|
+
# "Class.method" -> feature_id (unique qualified names only)
|
|
190
|
+
self.qualname_to_feature: dict[str, str] = {}
|
|
191
|
+
# symbol_name -> [{symbol_id, feature_id, file}] for collision-aware resolution
|
|
192
|
+
self.symbol_candidates: dict[str, list[dict[str, str]]] = {}
|
|
193
|
+
self._qual_seen: dict[str, str] = {}
|
|
194
|
+
|
|
195
|
+
# @feature [DEP_RESOLVER-02] Register symbols
|
|
196
|
+
def register_feature_symbols(self, features_data: list[dict[str, Any]], assign: bool = True):
|
|
197
|
+
"""Registers all definitions after parsing so collisions can be qualified globally."""
|
|
198
|
+
if assign:
|
|
199
|
+
assign_symbol_ids(features_data)
|
|
200
|
+
for feat in features_data:
|
|
201
|
+
feat_id = feat.get("feature_id", "").upper()
|
|
202
|
+
symbol = feat.get("symbol", "").strip()
|
|
203
|
+
if not feat_id or not symbol or symbol in IGNORED_SYMBOLS:
|
|
204
|
+
continue
|
|
205
|
+
qual = feat.get("qualname") or symbol
|
|
206
|
+
self.symbol_candidates.setdefault(symbol, []).append({
|
|
207
|
+
"symbol_id": feat.get("symbol_id") or symbol,
|
|
208
|
+
"feature_id": feat_id,
|
|
209
|
+
"file": str(feat.get("file") or feat.get("rel_path") or ""),
|
|
210
|
+
})
|
|
211
|
+
self._register_qualname(qual, feat_id)
|
|
212
|
+
|
|
213
|
+
for symbol, candidates in self.symbol_candidates.items():
|
|
214
|
+
feature_ids = {c["feature_id"] for c in candidates}
|
|
215
|
+
if len(feature_ids) == 1:
|
|
216
|
+
self.symbol_to_feature[symbol] = next(iter(feature_ids))
|
|
217
|
+
|
|
218
|
+
def _register_qualname(self, name: str, feat_id: str):
|
|
219
|
+
"""Qualified names stay unique; competing definitions resolve only by exact name."""
|
|
220
|
+
if name in self._qual_seen:
|
|
221
|
+
if self._qual_seen[name] != feat_id:
|
|
222
|
+
self.qualname_to_feature.pop(name, None)
|
|
223
|
+
else:
|
|
224
|
+
self._qual_seen[name] = feat_id
|
|
225
|
+
self.qualname_to_feature[name] = feat_id
|
|
226
|
+
|
|
227
|
+
def _resolve_bare(self, symbol: str, caller_file: str) -> set[str]:
|
|
228
|
+
"""Resolve a bare name to the closest definitions; ties keep all, never dropped."""
|
|
229
|
+
target = self.symbol_to_feature.get(symbol)
|
|
230
|
+
if target:
|
|
231
|
+
return {target}
|
|
232
|
+
candidates = self.symbol_candidates.get(symbol)
|
|
233
|
+
if not candidates:
|
|
234
|
+
return set()
|
|
235
|
+
|
|
236
|
+
caller = Path(caller_file)
|
|
237
|
+
|
|
238
|
+
def rank(candidate: dict[str, str]) -> tuple[int, int]:
|
|
239
|
+
candidate_file = Path(candidate["file"])
|
|
240
|
+
if candidate_file == caller:
|
|
241
|
+
return (2, 0)
|
|
242
|
+
if candidate_file.parent == caller.parent:
|
|
243
|
+
return (1, 0)
|
|
244
|
+
common = 0
|
|
245
|
+
for a, b in zip(candidate_file.parent.parts, caller.parent.parts, strict=False):
|
|
246
|
+
if a != b:
|
|
247
|
+
break
|
|
248
|
+
common += 1
|
|
249
|
+
return (0, common)
|
|
250
|
+
|
|
251
|
+
by_feature: dict[str, tuple[tuple[int, int], dict[str, str]]] = {}
|
|
252
|
+
for candidate in candidates:
|
|
253
|
+
feat_id = candidate["feature_id"]
|
|
254
|
+
score = rank(candidate)
|
|
255
|
+
existing = by_feature.get(feat_id)
|
|
256
|
+
if existing is None or (score, candidate["symbol_id"]) > (existing[0], existing[1]["symbol_id"]):
|
|
257
|
+
by_feature[feat_id] = (score, candidate)
|
|
258
|
+
|
|
259
|
+
ranked = sorted(
|
|
260
|
+
by_feature.values(),
|
|
261
|
+
key=lambda item: (item[0], item[1]["symbol_id"]),
|
|
262
|
+
reverse=True,
|
|
263
|
+
)
|
|
264
|
+
best_score = ranked[0][0]
|
|
265
|
+
if best_score == (0, 0):
|
|
266
|
+
return set()
|
|
267
|
+
return {
|
|
268
|
+
candidate["feature_id"]
|
|
269
|
+
for score, candidate in ranked
|
|
270
|
+
if score == best_score
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
@staticmethod
|
|
274
|
+
def _dotted(node: ast.AST) -> str:
|
|
275
|
+
"""Builds the dotted name of an Attribute chain, e.g. Outer.Inner.method."""
|
|
276
|
+
parts: list[str] = []
|
|
277
|
+
while isinstance(node, ast.Attribute):
|
|
278
|
+
parts.append(node.attr)
|
|
279
|
+
node = node.value
|
|
280
|
+
if not isinstance(node, ast.Name):
|
|
281
|
+
return ""
|
|
282
|
+
parts.append(node.id)
|
|
283
|
+
return ".".join(reversed(parts))
|
|
284
|
+
|
|
285
|
+
# @feature [DEP_RESOLVER-03] Resolve dependencies for file
|
|
286
|
+
def resolve_file_dependencies(
|
|
287
|
+
self, file_path: Path, features_in_file: list[dict[str, Any]]
|
|
288
|
+
) -> dict[str, set[str]]:
|
|
289
|
+
"""
|
|
290
|
+
Infers dependencies for each feature in the given file.
|
|
291
|
+
Returns: {feature_id: set(dependent_feature_ids)}
|
|
292
|
+
"""
|
|
293
|
+
if not features_in_file:
|
|
294
|
+
return {}
|
|
295
|
+
|
|
296
|
+
results: dict[str, set[str]] = {f["feature_id"]: set() for f in features_in_file}
|
|
297
|
+
ext = file_path.suffix.lower()
|
|
298
|
+
|
|
299
|
+
try:
|
|
300
|
+
content = file_path.read_text(encoding="utf-8", errors="replace")
|
|
301
|
+
except (UnicodeDecodeError, OSError):
|
|
302
|
+
return results
|
|
303
|
+
|
|
304
|
+
if ext == ".py":
|
|
305
|
+
self._resolve_python(content, features_in_file, results, file_path)
|
|
306
|
+
else:
|
|
307
|
+
self._resolve_tokens(content, features_in_file, results, file_path, lexmask.lang_for_suffix(ext))
|
|
308
|
+
|
|
309
|
+
self._drop_containment_edges(results, features_in_file)
|
|
310
|
+
return results
|
|
311
|
+
|
|
312
|
+
@staticmethod
|
|
313
|
+
def _drop_containment_edges(
|
|
314
|
+
results: dict[str, set[str]], features_in_file: list[dict[str, Any]]
|
|
315
|
+
) -> None:
|
|
316
|
+
"""Never wire a feature to the feature whose span encloses it (same file).
|
|
317
|
+
|
|
318
|
+
A tagged method lives inside a tagged class body, so every call inside the
|
|
319
|
+
method also falls inside the class span. Keeping those edges creates a fake
|
|
320
|
+
class <-> method cycle that is pure span overlap, not a real dependency.
|
|
321
|
+
"""
|
|
322
|
+
spans = {
|
|
323
|
+
feat["feature_id"]: (feat["start_line"], feat["end_line"])
|
|
324
|
+
for feat in features_in_file
|
|
325
|
+
}
|
|
326
|
+
for feat_id, deps in results.items():
|
|
327
|
+
outer = spans.get(feat_id)
|
|
328
|
+
if not outer:
|
|
329
|
+
continue
|
|
330
|
+
for dep in list(deps):
|
|
331
|
+
inner = spans.get(dep)
|
|
332
|
+
if not inner or inner == outer:
|
|
333
|
+
continue
|
|
334
|
+
encloses = (
|
|
335
|
+
outer[0] <= inner[0] and inner[1] <= outer[1]
|
|
336
|
+
) or (
|
|
337
|
+
inner[0] <= outer[0] and outer[1] <= inner[1]
|
|
338
|
+
)
|
|
339
|
+
if encloses:
|
|
340
|
+
deps.discard(dep)
|
|
341
|
+
|
|
342
|
+
def _resolve_python(
|
|
343
|
+
self, content: str, features_in_file: list[dict[str, Any]], results: dict[str, set[str]],
|
|
344
|
+
file_path: Path,
|
|
345
|
+
):
|
|
346
|
+
"""Uses Python AST to extract exact call-sites in a single pass."""
|
|
347
|
+
try:
|
|
348
|
+
tree = ast.parse(content)
|
|
349
|
+
except Exception:
|
|
350
|
+
# Fallback to token matching on syntax error; keep path affinity.
|
|
351
|
+
self._resolve_tokens(content, features_in_file, results, file_path, "python")
|
|
352
|
+
return
|
|
353
|
+
|
|
354
|
+
aliases = _module_aliases(tree)
|
|
355
|
+
# Single AST walk per file: (lineno, bare symbol, qualified symbol or "")
|
|
356
|
+
line_symbols: list[tuple[int, str, str]] = []
|
|
357
|
+
# Decorators sit above node.lineno, outside the parsed feature span.
|
|
358
|
+
decorator_start: dict[int, int] = {}
|
|
359
|
+
|
|
360
|
+
def add_ref(node: ast.AST, lineno: int | None):
|
|
361
|
+
if lineno is None:
|
|
362
|
+
return
|
|
363
|
+
if isinstance(node, ast.Name):
|
|
364
|
+
symbol = _canonical_name(node.id, aliases)
|
|
365
|
+
if symbol and symbol not in IGNORED_SYMBOLS:
|
|
366
|
+
line_symbols.append((lineno, symbol, symbol))
|
|
367
|
+
elif isinstance(node, ast.Attribute):
|
|
368
|
+
dotted = _canonical_dotted(self._dotted(node), aliases)
|
|
369
|
+
if dotted:
|
|
370
|
+
line_symbols.append((lineno, node.attr, dotted))
|
|
371
|
+
root = node.value
|
|
372
|
+
while isinstance(root, ast.Attribute):
|
|
373
|
+
root = root.value
|
|
374
|
+
if isinstance(root, ast.Name):
|
|
375
|
+
symbol = _canonical_name(root.id, aliases)
|
|
376
|
+
if symbol and symbol not in IGNORED_SYMBOLS:
|
|
377
|
+
line_symbols.append((lineno, symbol, symbol))
|
|
378
|
+
|
|
379
|
+
def callee_name(node: ast.AST) -> str:
|
|
380
|
+
if isinstance(node, ast.Name):
|
|
381
|
+
return _canonical_name(node.id, aliases)
|
|
382
|
+
if isinstance(node, ast.Attribute):
|
|
383
|
+
return _canonical_dotted(self._dotted(node), aliases)
|
|
384
|
+
return ""
|
|
385
|
+
|
|
386
|
+
for node in ast.walk(tree):
|
|
387
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
388
|
+
if node.decorator_list:
|
|
389
|
+
first = getattr(node.decorator_list[0], "lineno", node.lineno)
|
|
390
|
+
decorator_start[node.lineno] = min(node.lineno, first)
|
|
391
|
+
for dec in node.decorator_list:
|
|
392
|
+
target = dec.func if isinstance(dec, ast.Call) else dec
|
|
393
|
+
add_ref(target, getattr(dec, "lineno", None))
|
|
394
|
+
if isinstance(node, ast.ClassDef):
|
|
395
|
+
for base in node.bases:
|
|
396
|
+
add_ref(base, getattr(base, "lineno", None))
|
|
397
|
+
|
|
398
|
+
if not isinstance(node, ast.Call):
|
|
399
|
+
continue
|
|
400
|
+
lineno = getattr(node, "lineno", None)
|
|
401
|
+
if lineno is None:
|
|
402
|
+
continue
|
|
403
|
+
add_ref(node.func, lineno)
|
|
404
|
+
# Dependency injection: the argument names the real dependency.
|
|
405
|
+
if callee_name(node.func) in DI_WRAPPERS:
|
|
406
|
+
for arg in node.args:
|
|
407
|
+
add_ref(arg, lineno)
|
|
408
|
+
|
|
409
|
+
for feat in features_in_file:
|
|
410
|
+
feat_id = feat["feature_id"]
|
|
411
|
+
start_line = feat["start_line"]
|
|
412
|
+
end_line = feat["end_line"]
|
|
413
|
+
span_start = min(start_line, decorator_start.get(start_line, start_line))
|
|
414
|
+
|
|
415
|
+
for lineno, sym, qual in line_symbols:
|
|
416
|
+
if span_start <= lineno <= end_line:
|
|
417
|
+
target_feat = self.qualname_to_feature.get(qual) if qual else None
|
|
418
|
+
targets = {target_feat} if target_feat else self._resolve_bare(sym, str(file_path))
|
|
419
|
+
results[feat_id].update(t for t in targets if t != feat_id)
|
|
420
|
+
|
|
421
|
+
@staticmethod
|
|
422
|
+
def _import_bindings(content: str) -> set[str]:
|
|
423
|
+
"""Local names bound by explicit ES imports or CommonJS require()."""
|
|
424
|
+
bindings: set[str] = set()
|
|
425
|
+
for match in IMPORT_FROM_REGEX.finditer(content):
|
|
426
|
+
clause = match.group(1).strip()
|
|
427
|
+
named = NAMED_IMPORT_REGEX.search(clause)
|
|
428
|
+
if named:
|
|
429
|
+
clause = clause[: named.start()]
|
|
430
|
+
for part in named.group(1).split(","):
|
|
431
|
+
pieces = part.split()
|
|
432
|
+
if len(pieces) == 3 and pieces[1] == "as":
|
|
433
|
+
bindings.add(pieces[2])
|
|
434
|
+
elif len(pieces) == 1:
|
|
435
|
+
bindings.add(pieces[0])
|
|
436
|
+
for part in clause.split(","):
|
|
437
|
+
pieces = part.split()
|
|
438
|
+
if len(pieces) == 1 and pieces[0] != "*":
|
|
439
|
+
bindings.add(pieces[0])
|
|
440
|
+
elif len(pieces) == 3 and pieces[0] == "*" and pieces[1] == "as":
|
|
441
|
+
bindings.add(pieces[2])
|
|
442
|
+
for match in REQUIRE_REGEX.finditer(content):
|
|
443
|
+
target = match.group(1).strip()
|
|
444
|
+
if target.startswith("{"):
|
|
445
|
+
for part in target.strip("{}").split(","):
|
|
446
|
+
key = part.split(":")[0].strip()
|
|
447
|
+
if re.fullmatch(r"[A-Za-z_$][\w$]*", key):
|
|
448
|
+
bindings.add(key)
|
|
449
|
+
else:
|
|
450
|
+
bindings.add(target)
|
|
451
|
+
return bindings
|
|
452
|
+
|
|
453
|
+
def _resolve_tokens(
|
|
454
|
+
self,
|
|
455
|
+
content: str,
|
|
456
|
+
features_in_file: list[dict[str, Any]],
|
|
457
|
+
results: dict[str, set[str]],
|
|
458
|
+
file_path: Path,
|
|
459
|
+
lang: str = "other",
|
|
460
|
+
):
|
|
461
|
+
"""Extracts explicit references (calls, JSX, imports, inheritance) across languages."""
|
|
462
|
+
lines = lexmask.code_only(content, lang).splitlines()
|
|
463
|
+
# ponytail: bare identifier tokens minted edges from local variables and params;
|
|
464
|
+
# only call-sites, JSX tags, explicit imports and inheritance count now.
|
|
465
|
+
imported = self._import_bindings(content)
|
|
466
|
+
|
|
467
|
+
for feat in features_in_file:
|
|
468
|
+
feat_id = feat["feature_id"]
|
|
469
|
+
start_idx = max(0, feat["start_line"] - 1)
|
|
470
|
+
end_idx = min(len(lines), feat["end_line"])
|
|
471
|
+
|
|
472
|
+
chunk = "\n".join(lines[start_idx:end_idx])
|
|
473
|
+
tokens = set(CALL_SITE_REGEX.findall(chunk))
|
|
474
|
+
tokens.update(JSX_TAG_REGEX.findall(chunk))
|
|
475
|
+
tokens.update(INHERIT_REGEX.findall(chunk))
|
|
476
|
+
tokens.update(name for name in imported if re.search(rf"\b{re.escape(name)}\b", chunk))
|
|
477
|
+
|
|
478
|
+
for tok in tokens:
|
|
479
|
+
targets = self._resolve_bare(tok, str(file_path))
|
|
480
|
+
results[feat_id].update(t for t in targets if t != feat_id)
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _loc_key(loc: dict):
|
|
8
|
+
return (loc.get("file"), tuple(loc.get("lines") or [loc.get("start_line", 1), loc.get("end_line", 1)]), loc.get("symbol"))
|
|
9
|
+
|
|
10
|
+
# @feature [GRAPH-01] Feature graph
|
|
11
|
+
class FeatureGraph:
|
|
12
|
+
"""Manages the feature dependency graph, reverse edges, and orphan detection."""
|
|
13
|
+
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.nodes: dict[str, dict[str, Any]] = {}
|
|
16
|
+
self.edges: dict[str, set[str]] = {} # node -> set(dependencies)
|
|
17
|
+
self.reverse_edges: dict[str, set[str]] = {} # node -> set(dependents)
|
|
18
|
+
# Reused IDs merged across locations: the warning is not lost after printing.
|
|
19
|
+
self.duplicate_ids: list[dict[str, Any]] = []
|
|
20
|
+
|
|
21
|
+
# @feature [GRAPH-02] Add feature
|
|
22
|
+
def add_feature(self, feature_id: str, data: dict[str, Any]):
|
|
23
|
+
feat_id = feature_id.upper()
|
|
24
|
+
if feat_id not in self.nodes:
|
|
25
|
+
self.nodes[feat_id] = data
|
|
26
|
+
if feat_id not in self.edges:
|
|
27
|
+
self.edges[feat_id] = set()
|
|
28
|
+
if feat_id not in self.reverse_edges:
|
|
29
|
+
self.reverse_edges[feat_id] = set()
|
|
30
|
+
else:
|
|
31
|
+
# Merge locations, but never silently: a reused ID across files is almost always a mistake
|
|
32
|
+
existing_locs = self.nodes[feat_id].get("locations", [])
|
|
33
|
+
new_locs = data.get("locations", [])
|
|
34
|
+
existing_keys = {_loc_key(loc) for loc in existing_locs}
|
|
35
|
+
added = [loc for loc in new_locs if _loc_key(loc) not in existing_keys]
|
|
36
|
+
for loc in added:
|
|
37
|
+
print(
|
|
38
|
+
f"⚠ Feature ID [{feat_id}] defined in multiple locations — merging: "
|
|
39
|
+
f"{loc.get('file')} (symbol: {loc.get('symbol')})",
|
|
40
|
+
file=sys.stderr,
|
|
41
|
+
)
|
|
42
|
+
if added:
|
|
43
|
+
files = sorted({
|
|
44
|
+
str(loc.get("file"))
|
|
45
|
+
for loc in existing_locs + added
|
|
46
|
+
if loc.get("file")
|
|
47
|
+
})
|
|
48
|
+
self.duplicate_ids.append({"feature_id": feat_id, "files": files})
|
|
49
|
+
self.nodes[feat_id]["locations"] = existing_locs + new_locs
|
|
50
|
+
if not self.nodes[feat_id].get("name") and data.get("name"):
|
|
51
|
+
self.nodes[feat_id]["name"] = data.get("name")
|
|
52
|
+
|
|
53
|
+
for dep in data.get("depends_on", []):
|
|
54
|
+
dep_clean = dep.strip().upper()
|
|
55
|
+
if dep_clean:
|
|
56
|
+
self.edges[feat_id].add(dep_clean)
|
|
57
|
+
if dep_clean not in self.reverse_edges:
|
|
58
|
+
self.reverse_edges[dep_clean] = set()
|
|
59
|
+
self.reverse_edges[dep_clean].add(feat_id)
|
|
60
|
+
|
|
61
|
+
# Contract/security metadata: merged across duplicate locations, dropped when empty.
|
|
62
|
+
for tag_key in ("boundaries", "invariants", "tests"):
|
|
63
|
+
values = [value for value in (data.get(tag_key) or []) if value]
|
|
64
|
+
if not values:
|
|
65
|
+
continue
|
|
66
|
+
bucket = self.nodes[feat_id].setdefault(tag_key, [])
|
|
67
|
+
bucket.extend(value for value in values if value not in bucket)
|
|
68
|
+
|
|
69
|
+
# @feature [GRAPH-05] Find dependency cycles
|
|
70
|
+
def find_cycles(self) -> list[list[str]]:
|
|
71
|
+
"""Deterministic simple cycles as closed chains, e.g. ["A", "B", "A"]."""
|
|
72
|
+
nodes = sorted(self.nodes)
|
|
73
|
+
rank = {node: i for i, node in enumerate(nodes)}
|
|
74
|
+
cycles: set[tuple[str, ...]] = set()
|
|
75
|
+
for start in nodes:
|
|
76
|
+
stack: list[tuple[str, list[str]]] = [(start, [start])]
|
|
77
|
+
while stack:
|
|
78
|
+
node, path = stack.pop()
|
|
79
|
+
for dep in sorted(self.edges.get(node, ())):
|
|
80
|
+
if dep not in rank or rank[dep] < rank[start]:
|
|
81
|
+
continue
|
|
82
|
+
if dep == start:
|
|
83
|
+
cycles.add(tuple(path + [start]))
|
|
84
|
+
elif dep not in path:
|
|
85
|
+
stack.append((dep, path + [dep]))
|
|
86
|
+
return [list(cycle) for cycle in sorted(cycles)]
|
|
87
|
+
|
|
88
|
+
# @feature [GRAPH-03] Get orphans
|
|
89
|
+
def get_orphans(self) -> list[str]:
|
|
90
|
+
"""Returns features that have no callers/dependents and are not root features."""
|
|
91
|
+
orphans = []
|
|
92
|
+
for feat_id in self.nodes:
|
|
93
|
+
if not self.edges.get(feat_id) and not self.reverse_edges.get(feat_id):
|
|
94
|
+
orphans.append(feat_id)
|
|
95
|
+
return orphans
|
|
96
|
+
|
|
97
|
+
# @feature [GRAPH-04] To dict
|
|
98
|
+
def to_dict(self) -> dict[str, Any]:
|
|
99
|
+
output = {}
|
|
100
|
+
for feat_id, data in self.nodes.items():
|
|
101
|
+
entry: dict[str, Any] = {
|
|
102
|
+
"name": data.get("name", feat_id),
|
|
103
|
+
}
|
|
104
|
+
if data.get("category") and data.get("category") != "General":
|
|
105
|
+
entry["category"] = data.get("category")
|
|
106
|
+
if data.get("description"):
|
|
107
|
+
entry["description"] = data.get("description")
|
|
108
|
+
|
|
109
|
+
deps = sorted(list(self.edges.get(feat_id, set())))
|
|
110
|
+
if deps:
|
|
111
|
+
entry["depends_on"] = deps
|
|
112
|
+
|
|
113
|
+
callers = sorted(list(self.reverse_edges.get(feat_id, set())))
|
|
114
|
+
if callers:
|
|
115
|
+
entry["called_by"] = callers
|
|
116
|
+
|
|
117
|
+
for tag_key in ("boundaries", "invariants", "tests"):
|
|
118
|
+
if data.get(tag_key):
|
|
119
|
+
entry[tag_key] = data[tag_key]
|
|
120
|
+
|
|
121
|
+
entry["locations"] = data.get("locations", [])
|
|
122
|
+
output[feat_id] = entry
|
|
123
|
+
return output
|