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,70 @@
1
+ """Shared constants for the indexing pipeline."""
2
+
3
+ DEFAULT_IGNORE_PATTERNS = [
4
+ # OS metadata
5
+ "__MACOSX/",
6
+ ".DS_Store",
7
+ # CGC / wiki output
8
+ ".cgc-index/",
9
+ ".wiki-tmp/",
10
+ "wiki-output/",
11
+ # Dependency / build directories
12
+ "node_modules/",
13
+ "venv/",
14
+ ".venv/",
15
+ "env/",
16
+ ".env/",
17
+ "dist/",
18
+ "build/",
19
+ "target/",
20
+ "out/",
21
+ ".git/",
22
+ "__pycache__/",
23
+ # Auto-generated migrations (Alembic, Django, Prisma, etc.)
24
+ # Noise in god-nodes (SQLAlchemy Column/Table declarations).
25
+ # Migrations themselves are important but not source code — keep in source
26
+ # control, exclude from graph index.
27
+ "alembic/versions/",
28
+ "migrations/",
29
+ "prisma/migrations/",
30
+ "db/migrate/",
31
+ # Vendor / bundled code (not project source)
32
+ "vendor/",
33
+ ".next/",
34
+ "bower_components/",
35
+ # Binary / media assets
36
+ "*.png",
37
+ "*.jpg",
38
+ "*.jpeg",
39
+ "*.gif",
40
+ "*.svg",
41
+ "*.mp4",
42
+ "*.mp3",
43
+ "*.zip",
44
+ "*.tar",
45
+ "*.gz",
46
+ "*.woff",
47
+ "*.woff2",
48
+ "*.ttf",
49
+ "*.eot",
50
+ "*.ico",
51
+ "*.pdf",
52
+ # Minified / bundled JS/CSS (noise, not project source)
53
+ "*.min.js",
54
+ "*.min.css",
55
+ "*.bundle.js",
56
+ "*.chunk.js",
57
+ # Source maps
58
+ "*.map",
59
+ # Lock files
60
+ "package-lock.json",
61
+ "yarn.lock",
62
+ "pnpm-lock.yaml",
63
+ "bun.lock",
64
+ "Cargo.lock",
65
+ "poetry.lock",
66
+ "Pipfile.lock",
67
+ "composer.lock",
68
+ "Gemfile.lock",
69
+ "go.sum",
70
+ ]
@@ -0,0 +1,461 @@
1
+ """Generate per-module context files for AI IDE wiki generation.
2
+
3
+ Incorporates patterns from:
4
+ - llm-wiki-v3 cgc_bridge.py (path normalization, structured queries)
5
+ - gen.py (dual path patterns, class categorization, architecture Mermaid)
6
+
7
+ Each module_contexts/{slug}.md is self-contained — AI IDE reads it
8
+ and generates one wiki document. Same data = same quality as server.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import os
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _MAX_SOURCE_CHARS = 12000
22
+
23
+
24
+ def _rel(path: str, repo_path: str) -> str:
25
+ """Normalize any path to repo-relative."""
26
+ if not path:
27
+ return path
28
+ try:
29
+ return os.path.relpath(path, repo_path)
30
+ except ValueError:
31
+ return Path(path).name
32
+
33
+
34
+ def _classify_class(rel_path: str) -> str:
35
+ """Classify a class by its file path pattern."""
36
+ p = rel_path.lower()
37
+ if "controller" in p or "/api/" in p:
38
+ return "controller"
39
+ if "/service/" in p or "service.java" in p or "service.ts" in p:
40
+ return "service"
41
+ if "/model/" in p or "/domain/" in p or "/entity/" in p or "/entities/" in p:
42
+ return "model"
43
+ if "/repository/" in p or "repository.java" in p:
44
+ return "repository"
45
+ if "/event/" in p or "event.java" in p or "event.ts" in p:
46
+ return "event"
47
+ if "/dto/" in p or "dto.java" in p or "dto.ts" in p:
48
+ return "dto"
49
+ if "/guard/" in p or "/middleware/" in p:
50
+ return "middleware"
51
+ if "/config/" in p or "/configuration/" in p:
52
+ return "config"
53
+ if ".spec." in p or ".test." in p or "test" in p.split("/")[-1].lower():
54
+ return "test"
55
+ return "other"
56
+
57
+
58
+ def _build_arch_mermaid(layers: Dict[str, List[str]]) -> str:
59
+ """Generate architecture Mermaid diagram from detected layers."""
60
+ if not any(layers.values()):
61
+ return ""
62
+
63
+ lines = ["```mermaid", "graph LR"]
64
+
65
+ if layers.get("controller"):
66
+ lines.append(" Client[HTTP Client] --> Ctrl[Controllers]")
67
+ if layers.get("service"):
68
+ lines.append(" Ctrl --> Svc[Services]")
69
+ elif layers.get("service"):
70
+ lines.append(" Caller --> Svc[Services]")
71
+
72
+ if layers.get("repository"):
73
+ lines.append(" Svc --> Repo[Repositories]")
74
+ lines.append(" Repo --> DB[(Database)]")
75
+
76
+ if layers.get("event"):
77
+ lines.append(" Svc --> Events[[Domain Events]]")
78
+
79
+ if layers.get("middleware"):
80
+ lines.append(" Middleware[Guards/Middleware] -.-> Ctrl")
81
+
82
+ lines.append("```")
83
+ return "\n".join(lines)
84
+
85
+
86
+ def generate_module_contexts(
87
+ modules: List[Dict[str, Any]],
88
+ parsed_results: List[Dict[str, Any]],
89
+ repo_path: str,
90
+ output_dir: str,
91
+ call_groups: tuple = None,
92
+ routes: List[Dict] = None,
93
+ flows: List[Dict] = None,
94
+ rationales: List[Dict] = None,
95
+ op_params: List[Dict] = None,
96
+ ) -> int:
97
+ """Generate module_contexts/{slug}.md for each module."""
98
+ os.makedirs(output_dir, exist_ok=True)
99
+
100
+ # Build lookup maps
101
+ file_data_map: Dict[str, Dict] = {} # rel_path → parsed data
102
+ abs_to_rel: Dict[str, str] = {} # absolute → relative
103
+
104
+ for r in parsed_results:
105
+ if "error" in r:
106
+ continue
107
+ fp = r.get("path", "")
108
+ rel = _rel(fp, repo_path)
109
+ file_data_map[rel] = r
110
+ abs_to_rel[fp] = rel
111
+
112
+ # Build call edges with NORMALIZED paths
113
+ all_edges = []
114
+ if call_groups:
115
+ for group in call_groups:
116
+ for e in group:
117
+ caller_path = _rel(e.get("caller_file_path", ""), repo_path)
118
+ called_path = _rel(e.get("called_file_path", ""), repo_path)
119
+ same_file = caller_path == called_path
120
+ all_edges.append({
121
+ "caller_name": e.get("caller_name", ""),
122
+ "caller_file": caller_path,
123
+ "called_name": e.get("called_name", ""),
124
+ "called_file": called_path,
125
+ "confidence": e.get("confidence") or ("EXTRACTED" if same_file else "INFERRED"),
126
+ })
127
+
128
+ # Normalize route paths
129
+ norm_routes = []
130
+ if routes:
131
+ for r in routes:
132
+ nr = dict(r)
133
+ # Routes already have relative paths from extract
134
+ norm_routes.append(nr)
135
+
136
+ # Normalize flow paths
137
+ norm_flows = []
138
+ if flows:
139
+ for f in flows:
140
+ nf = dict(f)
141
+ nf["entry_file"] = _rel(f.get("entry_file", ""), repo_path)
142
+ if "steps" in nf:
143
+ for s in nf["steps"]:
144
+ if "file" in s:
145
+ s["file"] = _rel(s["file"], repo_path)
146
+ norm_flows.append(nf)
147
+
148
+ # Normalize rationale paths
149
+ norm_rationales = []
150
+ if rationales:
151
+ for r in rationales:
152
+ nr = dict(r)
153
+ # Rationales already relative from extract
154
+ norm_rationales.append(nr)
155
+
156
+ count = 0
157
+
158
+ for module in modules:
159
+ slug = module["slug"]
160
+ name = module["name"]
161
+ files = module["files"]
162
+ file_set = set(files)
163
+
164
+ # Also match by path pattern (for DuckDB queries with absolute paths)
165
+ # gen.py pattern: files might be under module dir
166
+ module_dir = module.get("dir", slug)
167
+
168
+ lines = []
169
+ lines.append(f"# Module: {name}")
170
+ lines.append("")
171
+
172
+ # ── Stats ─────────────────────────────────────────────
173
+ total_funcs = sum(len(file_data_map.get(f, {}).get("functions", [])) for f in files)
174
+ total_classes = sum(len(file_data_map.get(f, {}).get("classes", [])) for f in files)
175
+ module_routes = [r for r in norm_routes if r.get("file", "") in file_set
176
+ or any(r.get("file", "").startswith(f.rsplit("/", 1)[0]) for f in files[:3])]
177
+ module_flows = [f for f in norm_flows if f.get("entry_file", "") in file_set
178
+ or any(f.get("entry_file", "").startswith(fp.rsplit("/", 1)[0]) for fp in files[:3])]
179
+ module_rationales = [r for r in norm_rationales if r.get("file", "") in file_set]
180
+
181
+ lines.append(f"**Stats:** {len(files)} files · {total_funcs} functions · {total_classes} classes · {len(module_routes)} routes")
182
+ lines.append("")
183
+
184
+ # ── Files ──────────────────────────────────────────────
185
+ lines.append("## Files")
186
+ lines.append("")
187
+ for f in files[:40]:
188
+ data = file_data_map.get(f, {})
189
+ fn_count = len(data.get("functions", []))
190
+ cls_count = len(data.get("classes", []))
191
+ lines.append(f"- `{f}` ({fn_count} functions, {cls_count} classes)")
192
+ if len(files) > 40:
193
+ lines.append(f"- ... and {len(files) - 40} more")
194
+ lines.append("")
195
+
196
+ # ── Class categorization (gen.py pattern) ──────────────
197
+ layers: Dict[str, List[str]] = {
198
+ "controller": [], "service": [], "model": [],
199
+ "repository": [], "event": [], "dto": [],
200
+ "middleware": [], "config": [], "test": [], "other": [],
201
+ }
202
+
203
+ all_classes_in_module = []
204
+ for f in files:
205
+ data = file_data_map.get(f, {})
206
+ for cls in data.get("classes", []):
207
+ cls_name = cls.get("name", "")
208
+ if not cls_name:
209
+ continue
210
+ category = _classify_class(f)
211
+ layers[category].append(cls_name)
212
+ # Count methods
213
+ methods = [fn.get("name", "") for fn in data.get("functions", [])
214
+ if fn.get("class_context") == cls_name]
215
+ bases = cls.get("bases", [])
216
+ bases_str = f" extends {', '.join(str(b) for b in bases)}" if bases else ""
217
+ all_classes_in_module.append({
218
+ "name": cls_name, "file": f, "category": category,
219
+ "methods": methods, "bases_str": bases_str,
220
+ "method_count": len(methods),
221
+ })
222
+
223
+ # ── Architecture Mermaid ────────────────────────────────
224
+ arch = _build_arch_mermaid(layers)
225
+ if arch:
226
+ lines.append("## Architecture")
227
+ lines.append("")
228
+ lines.append(arch)
229
+ lines.append("")
230
+
231
+ # ── Controllers ────────────────────────────────────────
232
+ controllers = [c for c in all_classes_in_module if c["category"] == "controller"]
233
+ if controllers:
234
+ lines.append("## Controllers")
235
+ lines.append("")
236
+ for c in controllers:
237
+ lines.append(f"- **`{c['name']}`**{c['bases_str']} — `{c['file']}` ({c['method_count']} methods)")
238
+ if c["methods"][:8]:
239
+ lines.append(f" Methods: {', '.join(c['methods'][:8])}")
240
+ lines.append("")
241
+
242
+ # ── Services ───────────────────────────────────────────
243
+ services = [c for c in all_classes_in_module if c["category"] == "service"]
244
+ if services:
245
+ lines.append("## Services")
246
+ lines.append("")
247
+ for c in sorted(services, key=lambda x: -x["method_count"])[:20]:
248
+ lines.append(f"- **`{c['name']}`**{c['bases_str']} — {c['method_count']} methods")
249
+ lines.append("")
250
+
251
+ # ── Models / DTOs ──────────────────────────────────────
252
+ models = [c for c in all_classes_in_module if c["category"] in ("model", "dto")]
253
+ if models:
254
+ lines.append("## Models & DTOs")
255
+ lines.append("")
256
+ for c in models[:20]:
257
+ lines.append(f"- `{c['name']}`{c['bases_str']} — `{c['file']}`")
258
+ lines.append("")
259
+
260
+ # ── API Routes ─────────────────────────────────────────
261
+ if module_routes:
262
+ lines.append("## API Routes / Endpoints")
263
+ lines.append("")
264
+ lines.append("| Method | Path | Handler | File |")
265
+ lines.append("|--------|------|---------|------|")
266
+ for r in module_routes:
267
+ handler = r.get("handler", "-") or "-"
268
+ lines.append(f"| {r['method']} | `{r['path']}` | `{handler}` | `{r.get('file', '')}` |")
269
+ lines.append("")
270
+
271
+ # ── Key Functions ──────────────────────────────────────
272
+ lines.append("## Key Functions")
273
+ lines.append("")
274
+ sig_count = 0
275
+ for f in files:
276
+ data = file_data_map.get(f, {})
277
+ for fn in data.get("functions", []):
278
+ if sig_count >= 30:
279
+ break
280
+ fn_name = fn.get("name", "")
281
+ if not fn_name or fn_name.startswith("_"):
282
+ continue
283
+ ctx = fn.get("class_context", "")
284
+ args = fn.get("args", [])
285
+ line_no = fn.get("line_number", 0)
286
+ prefix = f"{ctx}." if ctx else ""
287
+ args_str = ", ".join(str(a) for a in args[:5]) if args else ""
288
+ lines.append(f"- `{prefix}{fn_name}({args_str})` — `{f}:{line_no}`")
289
+ sig_count += 1
290
+ lines.append("")
291
+
292
+ # ── Call Graph ──────────────────────────────────────────
293
+ intra = []
294
+ outgoing = []
295
+ incoming = []
296
+
297
+ for e in all_edges:
298
+ caller_in = e["caller_file"] in file_set
299
+ called_in = e["called_file"] in file_set
300
+ if caller_in and called_in:
301
+ intra.append(e)
302
+ elif caller_in:
303
+ outgoing.append(e)
304
+ elif called_in:
305
+ incoming.append(e)
306
+
307
+ lines.append("## Call Graph")
308
+ lines.append("")
309
+
310
+ if intra:
311
+ lines.append("**Internal calls:**")
312
+ seen = set()
313
+ for e in intra[:25]:
314
+ key = f"{e['caller_name']}→{e['called_name']}"
315
+ if key not in seen:
316
+ seen.add(key)
317
+ lines.append(f" {e['caller_name']} → {e['called_name']} [{e['confidence']}]")
318
+ if len(intra) > 25:
319
+ lines.append(f" ... and {len(intra) - 25} more")
320
+ lines.append("")
321
+
322
+ if outgoing:
323
+ lines.append("**Outgoing (this module calls):**")
324
+ seen = set()
325
+ for e in [x for x in outgoing if x.get("confidence") != "AMBIGUOUS"][:15]:
326
+ key = f"{e['caller_name']}→{e['called_name']}"
327
+ if key not in seen:
328
+ seen.add(key)
329
+ lines.append(f" {e['caller_name']} → {e['called_name']} (`{e['called_file']}`) [{e.get('confidence', 'INFERRED')}]")
330
+ lines.append("")
331
+
332
+ if incoming:
333
+ lines.append("**Incoming (called by other modules):**")
334
+ seen = set()
335
+ for e in [x for x in incoming if x.get("confidence") != "AMBIGUOUS"][:15]:
336
+ key = f"{e['caller_name']}→{e['called_name']}"
337
+ if key not in seen:
338
+ seen.add(key)
339
+ lines.append(f" {e['caller_name']} (`{e['caller_file']}`) → {e['called_name']} [{e.get('confidence', 'INFERRED')}]")
340
+ lines.append("")
341
+
342
+ # ── Execution Flows ─────────────────────────────────────
343
+ if module_flows:
344
+ lines.append("## Execution Flows")
345
+ lines.append("")
346
+ for f in module_flows[:6]:
347
+ steps = f.get("steps", [])
348
+ lines.append(f"### `{f['name']}` ({f.get('step_count', len(steps))} steps, depth {f.get('depth', 0)})")
349
+ lines.append(f"Entry: `{f.get('entry_file', '')}`")
350
+ lines.append("")
351
+ for i, s in enumerate(steps[:10], 1):
352
+ nm = s.get("name", str(s)) if isinstance(s, dict) else str(s)
353
+ lines.append(f"{i}. `{nm}`")
354
+ if len(steps) > 10:
355
+ lines.append(f"... ({len(steps) - 10} more steps)")
356
+ lines.append("")
357
+
358
+ # ── Design Rationale ────────────────────────────────────
359
+ if module_rationales:
360
+ lines.append("## Design Rationale")
361
+ lines.append("")
362
+ for r in module_rationales:
363
+ ctx = f" in `{r['context']}`" if r.get("context") else ""
364
+ lines.append(f"- **[{r['tag']}]**{ctx}: {r['text']}")
365
+ lines.append(f" — `{r['file']}:{r['line']}`")
366
+ lines.append("")
367
+
368
+ # ── Operational Parameters ─────────────────────────────
369
+ module_op_params = [p for p in (op_params or []) if p.get("path") in file_set]
370
+ if module_op_params:
371
+ lines.append("## Operational Parameters")
372
+ lines.append("")
373
+ lines.append("| Name | Value | Category | File | Line |")
374
+ lines.append("|------|-------|----------|------|------|")
375
+ for p in module_op_params[:30]:
376
+ lines.append(
377
+ f"| `{p['name']}` | `{p['value']}` | {p['category']} "
378
+ f"| `{p['path']}` | {p['line_number']} |"
379
+ )
380
+ lines.append("")
381
+
382
+ # ── Source Code (key files only) ────────────────────────
383
+ lines.append("## Source Code (key files)")
384
+ lines.append("")
385
+ chars = 0
386
+ for f in files:
387
+ if chars >= _MAX_SOURCE_CHARS:
388
+ break
389
+ data = file_data_map.get(f, {})
390
+ fp = data.get("path", "")
391
+ if not fp or not os.path.exists(fp):
392
+ continue
393
+ # Skip test files for source excerpts
394
+ if _classify_class(f) == "test":
395
+ continue
396
+ try:
397
+ content = open(fp, "r", encoding="utf-8", errors="replace").read()
398
+ except OSError:
399
+ continue
400
+ if len(content) > 3000:
401
+ content = content[:3000] + f"\n// ... ({len(content)} chars total)"
402
+ ext = Path(f).suffix.lstrip(".")
403
+ lines.append(f"### `{f}`")
404
+ lines.append(f"```{ext}")
405
+ lines.append(content)
406
+ lines.append("```")
407
+ lines.append("")
408
+ chars += len(content)
409
+
410
+ # ── Instructions ────────────────────────────────────────
411
+ lines.extend([
412
+ "", "---", "",
413
+ "## Instructions for AI Wiki Generator", "",
414
+ "Write comprehensive documentation for this module covering:",
415
+ "1. **Purpose** — what this module does and why",
416
+ "2. **Architecture** — key classes and how they relate (use/enhance the Mermaid diagram)",
417
+ "3. **API Endpoints** — document each route with request/response if available",
418
+ "4. **Execution Flows** — describe what happens when key functions are called",
419
+ "5. **Design Decisions** — include rationale from source comments",
420
+ "6. **Dependencies** — what this module depends on and what depends on it",
421
+ "",
422
+ "Use confidence tags: EXTRACTED = certain (same file, explicit import or enclosing class), INFERRED = resolved via the receiver's type or inheritance. AMBIGUOUS edges are omitted.",
423
+ "When mentioning another module, use: [[module-slug]]",
424
+ ])
425
+
426
+ # Write
427
+ ctx_path = os.path.join(output_dir, f"{slug}.md")
428
+ with open(ctx_path, "w") as fh:
429
+ fh.write("\n".join(lines))
430
+ count += 1
431
+
432
+ # ── index.md ────────────────────────────────────────────────
433
+ idx_lines = [
434
+ "# Wiki Generation Index", "",
435
+ f"**{len(modules)} modules** ready for wiki generation.", "",
436
+ "| Module | Files | Functions | Classes | Routes | Slug |",
437
+ "|--------|-------|-----------|---------|--------|------|",
438
+ ]
439
+ for m in modules:
440
+ fs = set(m["files"])
441
+ fn_c = sum(len(file_data_map.get(f, {}).get("functions", [])) for f in m["files"])
442
+ cl_c = sum(len(file_data_map.get(f, {}).get("classes", [])) for f in m["files"])
443
+ rt_c = sum(1 for r in (norm_routes or []) if r.get("file", "") in fs)
444
+ idx_lines.append(f"| {m['name']} | {m['file_count']} | {fn_c} | {cl_c} | {rt_c} | `{m['slug']}` |")
445
+
446
+ idx_lines.extend([
447
+ "", "## Generate Wiki", "",
448
+ "For each module: read `module_contexts/{slug}.md` → generate `wiki-output/{slug}.md`",
449
+ "After all modules: generate `wiki-output/overview.md`",
450
+ ])
451
+
452
+ with open(os.path.join(output_dir, "index.md"), "w") as fh:
453
+ fh.write("\n".join(idx_lines))
454
+ count += 1
455
+
456
+ # Save modules.json
457
+ with open(os.path.join(os.path.dirname(output_dir), "modules.json"), "w") as fh:
458
+ json.dump(modules, fh, indent=2)
459
+
460
+ logger.info("Generated %d module context files", count)
461
+ return count
@@ -0,0 +1,64 @@
1
+ """Enumerate files to index with ignore rules."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Optional, Tuple
5
+
6
+ from ...core.cgcignore import build_ignore_spec
7
+ from ...utils.debug_log import debug_log, warning_logger
8
+ from .constants import DEFAULT_IGNORE_PATTERNS
9
+
10
+
11
+ def discover_files_to_index(
12
+ path: Path,
13
+ cgcignore_path: Optional[str] = None,
14
+ ) -> Tuple[List[Path], Path]:
15
+ """
16
+ Returns (files, ignore_root). *ignore_root* is used for .cgcignore relative matching.
17
+ """
18
+ ignore_root = path.resolve() if path.is_dir() else path.resolve().parent
19
+
20
+ spec = None
21
+ try:
22
+ spec, resolved_cgcignore = build_ignore_spec(
23
+ ignore_root=ignore_root,
24
+ default_patterns=DEFAULT_IGNORE_PATTERNS,
25
+ explicit_path=cgcignore_path,
26
+ )
27
+ if resolved_cgcignore:
28
+ debug_log(f"Using .cgcignore at {resolved_cgcignore} (filtering relative to {ignore_root})")
29
+ except OSError as e:
30
+ warning_logger(f"Could not load/create .cgcignore: {e}")
31
+
32
+ all_files = path.rglob("*") if path.is_dir() else [path]
33
+ files = [f for f in all_files if f.is_file()]
34
+
35
+ from ...cli.config_manager import get_config_value
36
+
37
+ ignore_dirs_str = get_config_value("IGNORE_DIRS") or ""
38
+ if ignore_dirs_str and path.is_dir():
39
+ ignore_dirs = {d.strip().lower() for d in ignore_dirs_str.split(",") if d.strip()}
40
+ if ignore_dirs:
41
+ kept_files = []
42
+ for f in files:
43
+ try:
44
+ parts = set(p.lower() for p in f.relative_to(path).parent.parts)
45
+ if not parts.intersection(ignore_dirs):
46
+ kept_files.append(f)
47
+ except ValueError:
48
+ kept_files.append(f)
49
+ files = kept_files
50
+
51
+ if spec:
52
+ filtered_files = []
53
+ for f in files:
54
+ try:
55
+ rel_path = f.relative_to(ignore_root).as_posix()
56
+ if not spec.match_file(rel_path):
57
+ filtered_files.append(f)
58
+ else:
59
+ debug_log(f"Ignored file based on .cgcignore: {rel_path}")
60
+ except ValueError:
61
+ filtered_files.append(f)
62
+ files = filtered_files
63
+
64
+ return files, ignore_root