codegraphcontext-rust 0.9.24__cp314-cp314-win_amd64.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.
Files changed (112) hide show
  1. codegraphcontext/__init__.py +2 -0
  2. codegraphcontext/__main__.py +5 -0
  3. codegraphcontext/_cgc_rust.cp314-win_amd64.pyd +4 -0
  4. codegraphcontext/cli/__init__.py +1 -0
  5. codegraphcontext/cli/cli_helpers.py +774 -0
  6. codegraphcontext/cli/config_manager.py +1051 -0
  7. codegraphcontext/cli/entry.py +21 -0
  8. codegraphcontext/cli/main.py +2386 -0
  9. codegraphcontext/cli/registry_commands.py +404 -0
  10. codegraphcontext/cli/setup_macos.py +93 -0
  11. codegraphcontext/cli/setup_wizard.py +991 -0
  12. codegraphcontext/cli/visualizer.py +50 -0
  13. codegraphcontext/core/__init__.py +165 -0
  14. codegraphcontext/core/bundle_registry.py +181 -0
  15. codegraphcontext/core/cgc_bundle.py +858 -0
  16. codegraphcontext/core/cgcignore.py +118 -0
  17. codegraphcontext/core/database.py +273 -0
  18. codegraphcontext/core/database_falkordb.py +480 -0
  19. codegraphcontext/core/database_falkordb_remote.py +199 -0
  20. codegraphcontext/core/database_kuzu.py +636 -0
  21. codegraphcontext/core/falkor_worker.py +132 -0
  22. codegraphcontext/core/jobs.py +132 -0
  23. codegraphcontext/core/watcher.py +260 -0
  24. codegraphcontext/prompts.py +125 -0
  25. codegraphcontext/server.py +471 -0
  26. codegraphcontext/tool_definitions.py +220 -0
  27. codegraphcontext/tools/__init__.py +0 -0
  28. codegraphcontext/tools/advanced_language_query_tool.py +103 -0
  29. codegraphcontext/tools/code_finder.py +1160 -0
  30. codegraphcontext/tools/graph_builder.py +337 -0
  31. codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
  32. codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
  33. codegraphcontext/tools/handlers/management_handlers.py +339 -0
  34. codegraphcontext/tools/handlers/query_handlers.py +83 -0
  35. codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
  36. codegraphcontext/tools/indexing/__init__.py +1 -0
  37. codegraphcontext/tools/indexing/angular_routes.py +396 -0
  38. codegraphcontext/tools/indexing/cgc_wiki_cli.py +1334 -0
  39. codegraphcontext/tools/indexing/constants.py +70 -0
  40. codegraphcontext/tools/indexing/context_generator.py +461 -0
  41. codegraphcontext/tools/indexing/discovery.py +64 -0
  42. codegraphcontext/tools/indexing/engine.py +114 -0
  43. codegraphcontext/tools/indexing/execution_flows.py +355 -0
  44. codegraphcontext/tools/indexing/module_grouping.py +551 -0
  45. codegraphcontext/tools/indexing/noise_filter.py +131 -0
  46. codegraphcontext/tools/indexing/op_param_extraction.py +287 -0
  47. codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
  48. codegraphcontext/tools/indexing/persistence/duckdb_writer.py +1116 -0
  49. codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
  50. codegraphcontext/tools/indexing/persistence/writer.py +1562 -0
  51. codegraphcontext/tools/indexing/pipeline.py +171 -0
  52. codegraphcontext/tools/indexing/pre_scan.py +105 -0
  53. codegraphcontext/tools/indexing/rationale_extraction.py +154 -0
  54. codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
  55. codegraphcontext/tools/indexing/resolution/calls.py +253 -0
  56. codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
  57. codegraphcontext/tools/indexing/route_extraction.py +659 -0
  58. codegraphcontext/tools/indexing/sanitize.py +41 -0
  59. codegraphcontext/tools/indexing/schema.py +79 -0
  60. codegraphcontext/tools/indexing/schema_contract.py +44 -0
  61. codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
  62. codegraphcontext/tools/languages/c.py +563 -0
  63. codegraphcontext/tools/languages/cpp.py +616 -0
  64. codegraphcontext/tools/languages/csharp.py +551 -0
  65. codegraphcontext/tools/languages/dart.py +378 -0
  66. codegraphcontext/tools/languages/elixir.py +460 -0
  67. codegraphcontext/tools/languages/go.py +499 -0
  68. codegraphcontext/tools/languages/haskell.py +426 -0
  69. codegraphcontext/tools/languages/java.py +500 -0
  70. codegraphcontext/tools/languages/javascript.py +589 -0
  71. codegraphcontext/tools/languages/kotlin.py +640 -0
  72. codegraphcontext/tools/languages/perl.py +260 -0
  73. codegraphcontext/tools/languages/php.py +519 -0
  74. codegraphcontext/tools/languages/python.py +578 -0
  75. codegraphcontext/tools/languages/ruby.py +537 -0
  76. codegraphcontext/tools/languages/rust.py +295 -0
  77. codegraphcontext/tools/languages/scala.py +519 -0
  78. codegraphcontext/tools/languages/swift.py +491 -0
  79. codegraphcontext/tools/languages/typescript.py +606 -0
  80. codegraphcontext/tools/languages/typescriptjsx.py +151 -0
  81. codegraphcontext/tools/package_resolver.py +472 -0
  82. codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
  83. codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
  84. codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
  85. codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
  86. codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
  87. codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
  88. codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
  89. codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
  90. codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
  91. codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
  92. codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
  93. codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
  94. codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
  95. codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
  96. codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
  97. codegraphcontext/tools/scip_indexer.py +467 -0
  98. codegraphcontext/tools/scip_pb2.py +2455 -0
  99. codegraphcontext/tools/system.py +133 -0
  100. codegraphcontext/tools/tree_sitter_parser.py +103 -0
  101. codegraphcontext/utils/debug_log.py +90 -0
  102. codegraphcontext/utils/path_ignore.py +55 -0
  103. codegraphcontext/utils/repo_path.py +27 -0
  104. codegraphcontext/utils/tree_sitter_manager.py +285 -0
  105. codegraphcontext/utils/visualize_graph.py +0 -0
  106. codegraphcontext/viz/server.py +282 -0
  107. codegraphcontext_rust-0.9.24.dist-info/METADATA +543 -0
  108. codegraphcontext_rust-0.9.24.dist-info/RECORD +112 -0
  109. codegraphcontext_rust-0.9.24.dist-info/WHEEL +4 -0
  110. codegraphcontext_rust-0.9.24.dist-info/entry_points.txt +4 -0
  111. codegraphcontext_rust-0.9.24.dist-info/licenses/LICENSE +21 -0
  112. codegraphcontext_rust-0.9.24.dist-info/sboms/cgc-python.cyclonedx.json +2302 -0
@@ -0,0 +1,551 @@
1
+ """Auto-group source files into logical modules using graph structure.
2
+
3
+ Replaces LLM-based grouping (Phase 1 of llm-wiki) with deterministic
4
+ graph-based clustering. No LLM cost.
5
+
6
+ Grouping strategy:
7
+ 1. Primary: directory structure (src/auth/ → "authentication")
8
+ 2. Secondary: class_context clustering (files sharing classes)
9
+ 3. Tertiary: import graph communities (files importing each other)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import logging
16
+ import os
17
+ import re
18
+ from collections import defaultdict, Counter
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List, Set, Tuple
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # Directories to skip when naming modules
25
+ _SKIP_DIR_NAMES = {
26
+ "src", "app", "lib", "libs", "core", "main", "java", "kotlin",
27
+ "python", "typescript", "javascript", "resources", "static",
28
+ "com", "org", "net", "io", "vn", "controllers", "services",
29
+ "models", "dto", "entities", "repositories", "utils", "helpers",
30
+ "common", "shared", "internal", "pkg", "cmd",
31
+ }
32
+
33
+ # Name cleanup patterns
34
+ _CLEANUP_RE = re.compile(r"[-_.]")
35
+
36
+
37
+ def _humanize_dir(name: str) -> str:
38
+ """Convert directory name to human-readable module name."""
39
+ name = _CLEANUP_RE.sub(" ", name)
40
+ return name.strip().title()
41
+
42
+
43
+ def auto_group_modules(
44
+ parsed_results: List[Dict[str, Any]],
45
+ repo_path: str,
46
+ max_files_per_module: int = 30,
47
+ min_files_per_module: int = 2,
48
+ ) -> List[Dict[str, Any]]:
49
+ """Group source files into logical modules.
50
+
51
+ Returns list of:
52
+ {
53
+ name: str, # human-readable module name
54
+ slug: str, # file-safe slug
55
+ files: [str], # relative file paths
56
+ primary_lang: str, # dominant language
57
+ classes: [str], # class names in this module
58
+ entry_functions: [str], # key functions
59
+ }
60
+ """
61
+ # Build file → data map
62
+ file_data: Dict[str, Dict] = {}
63
+ for r in parsed_results:
64
+ if "error" in r:
65
+ continue
66
+ fp = r.get("path", "")
67
+ try:
68
+ rel = os.path.relpath(fp, repo_path)
69
+ except ValueError:
70
+ rel = Path(fp).name
71
+ file_data[rel] = r
72
+
73
+ if not file_data:
74
+ return []
75
+
76
+ all_rel_paths = list(file_data.keys())
77
+
78
+ # ── Strategy 0: Detect build manifest modules ─────────────
79
+ # Maven: top-level dirs with pom.xml or build.gradle
80
+ # Node: package.json workspaces
81
+ manifest_modules: Dict[str, List[str]] = {}
82
+
83
+ repo = Path(repo_path)
84
+ # Check for Maven/Gradle multi-module
85
+ for pom in repo.glob("*/pom.xml"):
86
+ mod_dir = pom.parent.name
87
+ manifest_modules[mod_dir] = []
88
+ for gradle in repo.glob("*/build.gradle"):
89
+ mod_dir = gradle.parent.name
90
+ if mod_dir not in manifest_modules:
91
+ manifest_modules[mod_dir] = []
92
+ for gradle in repo.glob("*/build.gradle.kts"):
93
+ mod_dir = gradle.parent.name
94
+ if mod_dir not in manifest_modules:
95
+ manifest_modules[mod_dir] = []
96
+
97
+ # Check for Node.js workspaces (apps/*, libs/*, packages/*)
98
+ pkg_json = repo / "package.json"
99
+ if pkg_json.exists():
100
+ try:
101
+ pkg = json.loads(pkg_json.read_text())
102
+ workspaces = pkg.get("workspaces", [])
103
+ if isinstance(workspaces, dict):
104
+ workspaces = workspaces.get("packages", [])
105
+ for ws in workspaces:
106
+ ws_base = ws.replace("/*", "").replace("*", "")
107
+ for ws_dir in repo.glob(f"{ws_base}/*/package.json"):
108
+ mod_dir = str(ws_dir.parent.relative_to(repo))
109
+ manifest_modules[mod_dir] = []
110
+ except (json.JSONDecodeError, OSError):
111
+ pass
112
+
113
+ # NX: check nx.json or project.json in subdirs
114
+ for proj_json in repo.glob("*/project.json"):
115
+ mod_dir = str(proj_json.parent.relative_to(repo))
116
+ if mod_dir not in manifest_modules:
117
+ manifest_modules[mod_dir] = []
118
+ for proj_json in repo.glob("*/*/project.json"):
119
+ mod_dir = str(proj_json.parent.relative_to(repo))
120
+ if mod_dir not in manifest_modules:
121
+ manifest_modules[mod_dir] = []
122
+
123
+ # If manifest modules found, use them for grouping
124
+ if manifest_modules:
125
+ for rel_path in all_rel_paths:
126
+ assigned = False
127
+ for mod_dir in sorted(manifest_modules.keys(), key=len, reverse=True):
128
+ if rel_path.startswith(mod_dir + "/") or rel_path.startswith(mod_dir + os.sep):
129
+ manifest_modules[mod_dir].append(rel_path)
130
+ assigned = True
131
+ break
132
+ if not assigned:
133
+ manifest_modules.setdefault("(root)", []).append(rel_path)
134
+
135
+ # Remove empty modules, use TOP-LEVEL dir as slug (not "src")
136
+ manifest_modules = {k: v for k, v in manifest_modules.items() if v}
137
+
138
+ if manifest_modules:
139
+ logger.info("Detected %d manifest-based modules: %s",
140
+ len(manifest_modules), list(manifest_modules.keys()))
141
+
142
+ # Threshold above which a manifest-based module is sub-split by
143
+ # the next directory level. Prevents single-NX-app monorepos
144
+ # (e.g. apps/app with 1000+ files) from collapsing into one giant
145
+ # module that wiki cannot navigate.
146
+ _SUBSPLIT_THRESHOLD = max_files_per_module * 3 # e.g. 90
147
+
148
+ def _common_prefix_len(file_list: List[str]) -> int:
149
+ """Length (in path parts) of the common directory prefix of files."""
150
+ if not file_list:
151
+ return 0
152
+ split_parts = [Path(f).parts[:-1] for f in file_list] # drop filename
153
+ n = min(len(p) for p in split_parts)
154
+ i = 0
155
+ while i < n and all(p[i] == split_parts[0][i] for p in split_parts):
156
+ i += 1
157
+ return i
158
+
159
+ def _subsplit(files: List[str], skip_depth: int, depth: int = 0) -> Dict[str, List[str]]:
160
+ """Split files by the first non-generic directory beyond skip_depth.
161
+ Recursively sub-splits groups that are still above threshold (up to
162
+ depth 3 to prevent explosion). Returns {sub_label -> files}."""
163
+ groups: Dict[str, List[str]] = defaultdict(list)
164
+ for f in files:
165
+ parts = Path(f).parts
166
+ start = skip_depth
167
+ sub = None
168
+ while start < len(parts) - 1:
169
+ candidate = parts[start]
170
+ if candidate.lower() in _SKIP_DIR_NAMES or candidate.startswith("."):
171
+ start += 1
172
+ continue
173
+ sub = candidate
174
+ break
175
+ if not sub:
176
+ sub = "(misc)"
177
+ groups[sub].append(f)
178
+
179
+ # Recursively sub-split oversized groups (stop at depth 3)
180
+ if depth < 3:
181
+ expanded: Dict[str, List[str]] = {}
182
+ for k, v in groups.items():
183
+ if len(v) > _SUBSPLIT_THRESHOLD and k != "(misc)":
184
+ # Find the actual common prefix length for this subgroup
185
+ # (could be deeper than the matched `k` if src/app wrappers exist)
186
+ subgroup_prefix = _common_prefix_len(v)
187
+ deeper = _subsplit(v, subgroup_prefix, depth + 1)
188
+ for dk, dv in deeper.items():
189
+ label = f"{k}/{dk}" if dk != "(misc)" else k
190
+ expanded[label] = dv
191
+ else:
192
+ expanded[k] = v
193
+ groups = expanded
194
+
195
+ # Merge tiny sub-groups into (misc)
196
+ merged: Dict[str, List[str]] = {}
197
+ misc: List[str] = []
198
+ for k, v in groups.items():
199
+ if len(v) >= min_files_per_module:
200
+ merged[k] = v
201
+ else:
202
+ misc.extend(v)
203
+ if misc:
204
+ merged["(misc)"] = misc
205
+ return merged
206
+
207
+ modules = []
208
+ for mod_dir, files in sorted(manifest_modules.items(), key=lambda x: -len(x[1])):
209
+ mod_base = _humanize_dir(mod_dir.split("/")[0])
210
+ mod_slug_base = re.sub(r"[^a-z0-9]+", "-", mod_dir.lower()).strip("-") or "root"
211
+
212
+ if len(files) > _SUBSPLIT_THRESHOLD:
213
+ sub_groups = _subsplit(files, _common_prefix_len(files))
214
+ logger.info("Sub-splitting %s (%d files) into %d sub-modules",
215
+ mod_dir, len(files), len(sub_groups))
216
+ for sub_name, sub_files in sub_groups.items():
217
+ lang_counts = Counter(); classes = set()
218
+ for f in sub_files:
219
+ data = file_data.get(f, {})
220
+ if (lang := data.get("lang", "")): lang_counts[lang] += 1
221
+ for cls in data.get("classes", []):
222
+ classes.add(cls.get("name", ""))
223
+ sub_humanized = _humanize_dir(sub_name.split("/")[-1]) if sub_name != "(misc)" else "(misc)"
224
+ sub_slug_tail = re.sub(r"[^a-z0-9]+", "-", sub_name.lower()).strip("-") or "misc"
225
+ modules.append({
226
+ "name": f"{mod_base} / {sub_humanized}",
227
+ "slug": f"{mod_slug_base}-{sub_slug_tail}",
228
+ "dir": f"{mod_dir}/{sub_name}" if sub_name != "(misc)" else mod_dir,
229
+ "files": sorted(sub_files),
230
+ "file_count": len(sub_files),
231
+ "primary_lang": lang_counts.most_common(1)[0][0] if lang_counts else "",
232
+ "classes": sorted(classes - {""}),
233
+ "entry_functions": [],
234
+ })
235
+ else:
236
+ lang_counts = Counter(); classes = set()
237
+ for f in files:
238
+ data = file_data.get(f, {})
239
+ if (lang := data.get("lang", "")): lang_counts[lang] += 1
240
+ for cls in data.get("classes", []):
241
+ classes.add(cls.get("name", ""))
242
+ modules.append({
243
+ "name": mod_base,
244
+ "slug": mod_slug_base,
245
+ "dir": mod_dir,
246
+ "files": sorted(files),
247
+ "file_count": len(files),
248
+ "primary_lang": lang_counts.most_common(1)[0][0] if lang_counts else "",
249
+ "classes": sorted(classes - {""}),
250
+ "entry_functions": [],
251
+ })
252
+
253
+ return modules
254
+
255
+ # ── Strategy 1: Group by meaningful directory ──────────────
256
+ dir_groups: Dict[str, List[str]] = defaultdict(list)
257
+
258
+ for rel_path in file_data:
259
+ parts = Path(rel_path).parts
260
+
261
+ # Find first meaningful directory (skip generic ones)
262
+ meaningful_dir = None
263
+ for i, part in enumerate(parts[:-1]): # skip filename
264
+ if part.lower() not in _SKIP_DIR_NAMES and not part.startswith("."):
265
+ meaningful_dir = part
266
+ # If next dir is also meaningful, use both
267
+ if i + 1 < len(parts) - 1:
268
+ next_part = parts[i + 1]
269
+ if next_part.lower() not in _SKIP_DIR_NAMES:
270
+ meaningful_dir = f"{part}/{next_part}"
271
+ break
272
+
273
+ if not meaningful_dir:
274
+ # Use parent directory
275
+ parent = Path(rel_path).parent.name
276
+ if parent and parent != ".":
277
+ meaningful_dir = parent
278
+ else:
279
+ meaningful_dir = "(root)"
280
+
281
+ dir_groups[meaningful_dir].append(rel_path)
282
+
283
+ # ── Split oversized groups (recursive by directory depth) ──
284
+ def _dir_split(files: List[str], after_dir: str, depth: int = 0) -> Dict[str, List[str]]:
285
+ """Split files by the directory immediately after `after_dir` in each
286
+ file's path. Recurses on oversized sub-groups (max depth 3)."""
287
+ last_seg = after_dir.rsplit("/", 1)[-1]
288
+ sub: Dict[str, List[str]] = defaultdict(list)
289
+ for f in files:
290
+ parts = Path(f).parts
291
+ try:
292
+ idx = len(parts) - 1 - list(reversed(parts)).index(last_seg)
293
+ except ValueError:
294
+ sub[after_dir].append(f)
295
+ continue
296
+ if idx + 1 < len(parts) - 1:
297
+ sub_dir = parts[idx + 1]
298
+ # Skip generic wrapper dirs transparently
299
+ if sub_dir.lower() in _SKIP_DIR_NAMES and idx + 2 < len(parts) - 1:
300
+ sub_dir = parts[idx + 2]
301
+ sub[f"{after_dir}/{sub_dir}"].append(f)
302
+ else:
303
+ sub[after_dir].append(f)
304
+ if depth < 3:
305
+ expanded: Dict[str, List[str]] = {}
306
+ for k, v in sub.items():
307
+ if len(v) > max_files_per_module * 3 and k != after_dir:
308
+ deeper = _dir_split(v, k, depth + 1)
309
+ expanded.update(deeper)
310
+ else:
311
+ expanded[k] = v
312
+ sub = expanded
313
+ return dict(sub)
314
+
315
+ final_groups: Dict[str, List[str]] = {}
316
+ for dir_name, files in dir_groups.items():
317
+ if len(files) <= max_files_per_module * 3:
318
+ final_groups[dir_name] = files
319
+ else:
320
+ for sub_name, sub_files in _dir_split(files, dir_name).items():
321
+ final_groups[sub_name] = sub_files
322
+
323
+ # ── Merge tiny groups ──────────────────────────────────────
324
+ merged: Dict[str, List[str]] = {}
325
+ tiny: List[Tuple[str, List[str]]] = []
326
+
327
+ for name, files in final_groups.items():
328
+ if len(files) >= min_files_per_module:
329
+ merged[name] = files
330
+ else:
331
+ tiny.append((name, files))
332
+
333
+ # Merge tiny groups into "(other)" or nearest parent
334
+ if tiny:
335
+ other_files = []
336
+ for name, files in tiny:
337
+ other_files.extend(files)
338
+ if other_files:
339
+ merged["other"] = other_files
340
+
341
+ # ── Build module metadata ──────────────────────────────────
342
+ modules: List[Dict[str, Any]] = []
343
+
344
+ for dir_name, files in sorted(merged.items(), key=lambda x: -len(x[1])):
345
+ # Detect primary language
346
+ lang_counts = Counter()
347
+ classes = set()
348
+ entry_funcs = []
349
+
350
+ for f in files:
351
+ data = file_data.get(f, {})
352
+ lang = data.get("lang", "")
353
+ if lang:
354
+ lang_counts[lang] += 1
355
+ for cls in data.get("classes", []):
356
+ classes.add(cls.get("name", ""))
357
+ for fn in data.get("functions", []):
358
+ name = fn.get("name", "")
359
+ # Heuristic: entry functions are top-level, exported, or handlers
360
+ if name and not name.startswith("_"):
361
+ ctx = fn.get("class_context", "")
362
+ if not ctx: # top-level
363
+ entry_funcs.append(name)
364
+
365
+ primary_lang = lang_counts.most_common(1)[0][0] if lang_counts else ""
366
+
367
+ # Generate human-readable name
368
+ name = _humanize_dir(dir_name.split("/")[-1])
369
+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
370
+
371
+ modules.append({
372
+ "name": name,
373
+ "slug": slug,
374
+ "dir": dir_name,
375
+ "files": sorted(files),
376
+ "file_count": len(files),
377
+ "primary_lang": primary_lang,
378
+ "classes": sorted(classes - {""}),
379
+ "entry_functions": entry_funcs[:10],
380
+ })
381
+
382
+ # ── Disambiguate duplicate slugs (Next.js app/ vs components/ etc.) ──
383
+ # When two modules have same slug (e.g. src/app/admin and src/components/admin),
384
+ # prepend parent dir segment so each gets a unique slug + distinguishable name.
385
+ # Next.js route groups like (dashboard), (public) are kept (with parens stripped)
386
+ # as meaningful disambiguators when they are the only parent segment available.
387
+ slug_counts: Counter = Counter(m["slug"] for m in modules)
388
+ for m in modules:
389
+ if slug_counts[m["slug"]] > 1:
390
+ raw_parts = [p for p in m["dir"].split("/") if p]
391
+ # Strip parens from route groups but keep them as semantic parents
392
+ cleaned_parts = [
393
+ p[1:-1] if p.startswith("(") and p.endswith(")") else p
394
+ for p in raw_parts
395
+ ]
396
+ if len(cleaned_parts) >= 2:
397
+ full_slug = re.sub(r"[^a-z0-9]+", "-", "-".join(cleaned_parts).lower()).strip("-")
398
+ parent_seg = _humanize_dir(cleaned_parts[-2])
399
+ m["slug"] = full_slug
400
+ m["name"] = f"{m['name']} ({parent_seg})"
401
+
402
+ logger.info("Auto-grouped %d files into %d modules", len(file_data), len(modules))
403
+ return modules
404
+
405
+
406
+ def _build_module_metadata(
407
+ groups: Dict[str, List[str]],
408
+ file_data: Dict[str, Dict],
409
+ min_files: int = 2,
410
+ ) -> List[Dict[str, Any]]:
411
+ """Build module metadata from grouped files."""
412
+ # Merge tiny groups
413
+ merged: Dict[str, List[str]] = {}
414
+ tiny_files = []
415
+ for name, files in groups.items():
416
+ if len(files) >= min_files:
417
+ merged[name] = files
418
+ else:
419
+ tiny_files.extend(files)
420
+ if tiny_files:
421
+ merged["other"] = tiny_files
422
+
423
+ modules = []
424
+ for dir_name, files in sorted(merged.items(), key=lambda x: -len(x[1])):
425
+ lang_counts = Counter()
426
+ classes = set()
427
+ for f in files:
428
+ data = file_data.get(f, {})
429
+ lang = data.get("lang", "")
430
+ if lang:
431
+ lang_counts[lang] += 1
432
+ for cls in data.get("classes", []):
433
+ classes.add(cls.get("name", ""))
434
+
435
+ primary_lang = lang_counts.most_common(1)[0][0] if lang_counts else ""
436
+
437
+ # Use full dir path for name (not just last segment)
438
+ # e.g., "gateway-api/src" → "Gateway Api" with slug "gateway-api"
439
+ dir_parts = dir_name.split("/")
440
+ # For manifest modules, use top-level dir (gateway-api, service-pet, etc.)
441
+ name_source = dir_parts[0] if dir_parts[0].lower() not in _SKIP_DIR_NAMES else dir_name
442
+ name = _humanize_dir(name_source)
443
+ slug = re.sub(r"[^a-z0-9]+", "-", name_source.lower()).strip("-")
444
+
445
+ # Ensure unique slugs
446
+ existing_slugs = {m["slug"] for m in modules}
447
+ if slug in existing_slugs:
448
+ if len(dir_parts) > 1:
449
+ full = "-".join(dir_parts)
450
+ slug = re.sub(r"[^a-z0-9]+", "-", full.lower()).strip("-")
451
+ name = _humanize_dir(full)
452
+ else:
453
+ slug = f"{slug}-{len(modules)}"
454
+
455
+ modules.append({
456
+ "name": name,
457
+ "slug": slug,
458
+ "dir": dir_name,
459
+ "files": sorted(files),
460
+ "file_count": len(files),
461
+ "primary_lang": primary_lang,
462
+ "classes": sorted(classes - {""}),
463
+ "entry_functions": [],
464
+ })
465
+
466
+ logger.info("Built %d modules from manifest", len(modules))
467
+ return modules
468
+
469
+
470
+ def group_parents(
471
+ modules: List[Dict[str, Any]],
472
+ threshold: int = 10,
473
+ ) -> List[Dict[str, Any]]:
474
+ """Group modules into parent categories when count >= threshold.
475
+
476
+ Uses the first meaningful directory segment shared by module files
477
+ to cluster modules into 3-7 parent groups.
478
+
479
+ Returns list of:
480
+ {name, slug, children: [module_slug, ...]}
481
+ Returns empty list if module count < threshold.
482
+ """
483
+ if len(modules) < threshold:
484
+ return []
485
+
486
+ # Group by first directory segment of the module's dir field
487
+ parent_map: Dict[str, List[str]] = defaultdict(list)
488
+
489
+ for mod in modules:
490
+ mod_dir = mod.get("dir", "")
491
+ files = mod.get("files", [])
492
+ slug = mod.get("slug", "")
493
+
494
+ # Find common parent from dir or first file path
495
+ if mod_dir:
496
+ parts = Path(mod_dir).parts
497
+ parent_name = None
498
+ for part in parts:
499
+ if part.lower() not in _SKIP_DIR_NAMES and not part.startswith("."):
500
+ parent_name = part
501
+ break
502
+ if not parent_name and parts:
503
+ parent_name = parts[0]
504
+ elif files:
505
+ parts = Path(files[0]).parts
506
+ parent_name = parts[0] if parts else "(root)"
507
+ else:
508
+ parent_name = "(other)"
509
+
510
+ parent_map[parent_name or "(other)"].append(slug)
511
+
512
+ # If only 1-2 parents, try splitting further
513
+ if len(parent_map) < 3:
514
+ return []
515
+
516
+ # Merge tiny parents (< 2 modules) into "(other)"
517
+ merged: Dict[str, List[str]] = {}
518
+ other: List[str] = []
519
+ for name, children in parent_map.items():
520
+ if len(children) < 2:
521
+ other.extend(children)
522
+ else:
523
+ merged[name] = children
524
+ if other:
525
+ merged["Other"] = other
526
+
527
+ # Quality check: if "Other" has > 50% of modules, grouping isn't natural → skip
528
+ total_modules = len(modules)
529
+ other_count = len(merged.get("Other", []))
530
+ if other_count > total_modules * 0.5:
531
+ logger.info("Parent grouping skipped: %d/%d modules in 'Other' (> 50%%)",
532
+ other_count, total_modules)
533
+ return []
534
+
535
+ # Also skip if too few real groups (excluding Other)
536
+ real_groups = len([k for k in merged if k != "Other"])
537
+ if real_groups < 2:
538
+ logger.info("Parent grouping skipped: only %d real groups", real_groups)
539
+ return []
540
+
541
+ parents = []
542
+ for name, children in sorted(merged.items()):
543
+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "other"
544
+ parents.append({
545
+ "name": _humanize_dir(name),
546
+ "slug": slug,
547
+ "children": sorted(children),
548
+ })
549
+
550
+ logger.info("Grouped %d modules into %d parents", len(modules), len(parents))
551
+ return parents
@@ -0,0 +1,131 @@
1
+ """Shared god-node noise filter for graph reports and visualization.
2
+
3
+ Used by both CGC (cgc_wiki_cli.py) and llm-wiki-v3 (cgc_bridge.py)
4
+ to filter out accessors, test DSL, stdlib, and other noisy function
5
+ names from top-connected / god-node reports.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ # Function names that are noise in call graphs (not real architectural hubs)
12
+ GOD_NODE_NOISE = frozenset({
13
+ # Java/generic accessors
14
+ "get", "set", "of", "put", "add", "remove", "size", "isEmpty",
15
+ "equals", "hashCode", "toString", "compareTo", "valueOf", "values",
16
+ "build", "builder", "clone", "close", "read", "write",
17
+ "from", "apply", "accept", "test", "run", "call",
18
+ # Lombok-style getters/setters
19
+ "getId", "getName", "getStatus", "getType", "getValue", "getCode",
20
+ "getCreatedAt", "getUpdatedAt", "getPath", "getMessage",
21
+ "setId", "setName", "setStatus", "setType", "setValue",
22
+ # Jackson / JSON
23
+ "asText", "asLong", "asInt", "asBoolean", "isMissingNode", "isArray",
24
+ "path", "jsonPath", "readTree", "readValue", "writeValueAsString",
25
+ # Test DSL (JUnit, MockMvc, Jest, Vitest, Testing Library)
26
+ "it", "describe", "expect", "toBe", "toEqual", "assert",
27
+ "andExpect", "assertThat", "verify", "mock", "when", "given",
28
+ "mockResolvedValue", "mockReturnValue", "waitForTimeout",
29
+ "perform", "isOk", "content", "header", "value",
30
+ "toHaveBeenCalled", "toHaveBeenCalledWith", "toContain",
31
+ "toBeTruthy", "toBeFalsy", "toBeDefined", "toBeNull",
32
+ "render", "screen", "fireEvent", "waitFor", "userEvent",
33
+ "vi", "beforeEach", "afterEach", "beforeAll", "afterAll",
34
+ # HTTP / response
35
+ "status", "ok", "body", "json", "parse", "stringify",
36
+ # Logging
37
+ "log", "error", "warn", "info", "debug", "println", "printf",
38
+ # Java stdlib
39
+ "format", "trim", "split", "join", "replace", "contains",
40
+ "append", "insert", "delete", "substring", "length",
41
+ "stream", "map", "filter", "collect", "forEach", "reduce",
42
+ "Optional", "orElse", "orElseThrow", "isPresent", "ifPresent",
43
+ "currentTimeMillis", "nanoTime", "now",
44
+ # TS/JS stdlib built-ins
45
+ "String", "Date", "Number", "Boolean", "Array", "Object",
46
+ "Error", "Float32Array", "Int32Array", "Uint8Array", "Math",
47
+ "Promise", "Symbol", "Set", "Map", "JSON",
48
+ # Tailwind / className utilities
49
+ "cn", "clsx", "cx", "tw", "twMerge",
50
+ # React hooks (too noisy to count as hub)
51
+ "useState", "useEffect", "useCallback", "useMemo", "useRef",
52
+ "useContext", "useReducer", "useLayoutEffect",
53
+ # Python stdlib + test DSL
54
+ "uuid4", "uuid1", "print", "len", "str", "int", "float", "dict",
55
+ "list", "tuple", "range", "isinstance", "hasattr", "getattr",
56
+ "setattr", "type", "enumerate", "zip", "sorted", "reversed",
57
+ "MagicMock", "AsyncMock", "Mock", "patch",
58
+ "pytest", "fixture", "raises", "mark",
59
+ # SQLAlchemy declarative noise
60
+ "Column", "String", "Integer", "Text", "Boolean", "DateTime",
61
+ "ForeignKey", "Index", "UniqueConstraint", "Table",
62
+ # Go testing + testify + gomock + stdlib
63
+ "T", "B", "M", "Helper", "Logf", "Skip", "SkipNow", "FailNow",
64
+ "Errorf", "Fatalf", "Error", "Fatal", "Log",
65
+ "NoError", "Equal", "NotEqual", "Nil", "NotNil", "True", "False",
66
+ "Empty", "NotEmpty", "Len", "Contains", "NotContains",
67
+ "Greater", "Less", "InDelta", "ElementsMatch", "Subset",
68
+ "EXPECT", "DoAndReturn", "Return", "Times", "AnyTimes", "Do",
69
+ "Finish", "NewController", "Call",
70
+ "Background", "TODO", "WithValue", "WithCancel", "WithTimeout",
71
+ "Printf", "Println", "Sprintf", "Sprintln",
72
+ "Make", "Append", "Copy", "Close", "Open", "Read", "Write",
73
+ # Go logger levels + HTTP response primitives
74
+ "Info", "Warn", "Debug", "Trace",
75
+ "WriteString", "SendString", "WriteJSON", "SendStatus",
76
+ "Next", "Locals", "Param", "Params", "Query", "QueryParser",
77
+ "BodyParser", "ParamsParser",
78
+ # Go testing extra
79
+ "Parallel", "Cleanup", "Deadline",
80
+ # Angular reactive forms
81
+ "FormControl", "FormGroup", "FormArray", "FormBuilder", "Validators",
82
+ "AbstractControl", "ControlValueAccessor",
83
+ # Angular testing
84
+ "TestBed", "inject", "fakeAsync", "tick", "flush", "waitForAsync",
85
+ "ComponentFixture", "DebugElement",
86
+ # RxJS
87
+ "Subject", "BehaviorSubject", "ReplaySubject", "Observable",
88
+ "of", "from", "pipe", "tap", "switchMap",
89
+ "mergeMap", "catchError", "take", "takeUntil", "subscribe",
90
+ # Ionic
91
+ "ModalController", "ToastController", "AlertController",
92
+ "LoadingController", "NavController",
93
+ })
94
+
95
+ # Regex patterns for accessor detection
96
+ ACCESSOR_RE = re.compile(r"^(get|set|is|has)[A-Z]")
97
+ RECORD_ACCESSOR_RE = re.compile(r"^[a-z][a-zA-Z]*$")
98
+ REACT_HOOK_RE = re.compile(r"^use[A-Z]\w*$")
99
+
100
+ # Functions that look like record accessors but are meaningful
101
+ MEANINGFUL_NAMES = frozenset({
102
+ "main", "run", "start", "execute", "init", "setup", "configure",
103
+ "handle", "process", "validate", "create", "update", "delete",
104
+ "save", "load", "find", "search", "index", "render", "dispatch",
105
+ "schedule", "publish", "subscribe", "connect", "disconnect",
106
+ "authenticate", "authorize", "transform", "convert", "migrate",
107
+ "fetch", "post", "get", "put", "patch",
108
+ })
109
+
110
+
111
+ def is_noise_node(name: str, call_count: int = 0) -> bool:
112
+ """Return True if this function name is noise (not a real architectural hub).
113
+
114
+ Args:
115
+ name: Function/class name.
116
+ call_count: Number of times this function is called (for record accessor heuristic).
117
+ """
118
+ if name in GOD_NODE_NOISE:
119
+ return True
120
+ # React hooks are meaningful — keep
121
+ if REACT_HOOK_RE.match(name):
122
+ return False
123
+ if ACCESSOR_RE.match(name):
124
+ return True
125
+ # Record accessor heuristic: short camelCase name, not meaningful, high call count
126
+ if (RECORD_ACCESSOR_RE.match(name)
127
+ and name not in MEANINGFUL_NAMES
128
+ and len(name) <= 20
129
+ and call_count >= 5):
130
+ return True
131
+ return False