tzero-mcp 11.0.0 → 11.11.0

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 (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -1,263 +1,263 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Vectorless Semantic Graph & Local Code-RAG Engine (100% Offline, Zero-Cost).
3
-
4
- Combines lexical BM25 token relevance, AST structural symbols, and PageRank
5
- graph centrality into a unified hybrid retrieval pipeline without external embeddings.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import collections
11
- import dataclasses
12
- import math
13
- import os
14
- import re
15
- from typing import Any, Dict, List, Optional, Set, Tuple
16
-
17
-
18
- @dataclasses.dataclass
19
- class GraphRagChunk:
20
- chunk_id: str
21
- file_path: str
22
- name: str
23
- kind: str # function, class, interface, module
24
- signature: str
25
- content: str
26
- docstring: str
27
- line_start: int
28
- line_end: int
29
- dependencies: List[str] = dataclasses.field(default_factory=list)
30
- tokens: List[str] = dataclasses.field(default_factory=list)
31
- bm25_score: float = 0.0
32
- graph_centrality: float = 0.0
33
- hybrid_score: float = 0.0
34
-
35
-
36
- class VectorlessGraphRAG:
37
- """100% Offline, private Graph RAG combining BM25, AST Call Graph, and Centrality."""
38
-
39
- def __init__(self, workspace_dir: str):
40
- self.workspace_dir = os.path.abspath(workspace_dir)
41
- self.chunks: List[GraphRagChunk] = []
42
- self.doc_freqs: Dict[str, int] = collections.defaultdict(int)
43
- self.total_docs: int = 0
44
- self.avg_doc_len: float = 0.0
45
- self.call_graph: Dict[str, Set[str]] = collections.defaultdict(set)
46
- self.reverse_call_graph: Dict[str, Set[str]] = collections.defaultdict(set)
47
- self.centrality_scores: Dict[str, float] = {}
48
-
49
- @staticmethod
50
- def tokenize(text: str) -> List[str]:
51
- """Sub-word aware identifier tokenization."""
52
- if not text:
53
- return []
54
- raw_words = re.findall(r"[A-Za-z0-9_]+", text)
55
- tokens: List[str] = []
56
- for word in raw_words:
57
- tokens.append(word.lower())
58
- # split camelCase and PascalCase
59
- parts = re.findall(r"[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\d|\W|$)|\d+", word)
60
- if len(parts) > 1:
61
- for p in parts:
62
- clean = p.lower().strip("_")
63
- if len(clean) >= 2:
64
- tokens.append(clean)
65
- # split snake_case
66
- if "_" in word:
67
- for sub in word.split("_"):
68
- clean = sub.lower()
69
- if len(clean) >= 2:
70
- tokens.append(clean)
71
- return [t for t in tokens if len(t) >= 2]
72
-
73
- def index_workspace(self, file_limit: int = 500) -> int:
74
- """Scan workspace and index code structures into graph RAG nodes."""
75
- from tzero.tzero_snapshot import SnapshotEngine
76
-
77
- snap = SnapshotEngine.create_snapshot(self.workspace_dir)
78
- self.chunks.clear()
79
- self.doc_freqs.clear()
80
- self.call_graph.clear()
81
- self.reverse_call_graph.clear()
82
-
83
- total_tokens = 0
84
- file_count = 0
85
-
86
- for rel_path, file_snap in sorted(snap.files.items()):
87
- file_count += 1
88
- if file_count > file_limit:
89
- break
90
-
91
- full_path = os.path.join(self.workspace_dir, rel_path)
92
- # 1. Module chunk
93
- mod_text = f"{rel_path} " + " ".join(file_snap.imports)
94
- mod_tokens = self.tokenize(mod_text)
95
- mod_chunk = GraphRagChunk(
96
- chunk_id=f"mod::{rel_path}",
97
- file_path=rel_path,
98
- name=os.path.basename(rel_path),
99
- kind="module",
100
- signature=f"module {rel_path}",
101
- content=mod_text,
102
- docstring="",
103
- line_start=1,
104
- line_end=1,
105
- dependencies=list(file_snap.imports),
106
- tokens=mod_tokens,
107
- )
108
- self.chunks.append(mod_chunk)
109
- total_tokens += len(mod_tokens)
110
-
111
- # Record dependency edges
112
- for imp in file_snap.imports:
113
- imp_stem = os.path.splitext(os.path.basename(imp))[0]
114
- self.call_graph[rel_path].add(imp_stem)
115
- self.reverse_call_graph[imp_stem].add(rel_path)
116
-
117
- # 2. Function / Class chunks
118
- for fn_name in file_snap.functions:
119
- sig_text = f"def {fn_name}() in {rel_path}"
120
- fn_tokens = self.tokenize(f"{fn_name} {rel_path}")
121
- fn_chunk = GraphRagChunk(
122
- chunk_id=f"fn::{rel_path}::{fn_name}",
123
- file_path=rel_path,
124
- name=fn_name,
125
- kind="function",
126
- signature=sig_text,
127
- content=sig_text,
128
- docstring="",
129
- line_start=1,
130
- line_end=1,
131
- dependencies=list(file_snap.imports),
132
- tokens=fn_tokens,
133
- )
134
- self.chunks.append(fn_chunk)
135
- total_tokens += len(fn_tokens)
136
-
137
- for cls_name in file_snap.classes:
138
- sig_text = f"class {cls_name} in {rel_path}"
139
- cls_tokens = self.tokenize(f"{cls_name} {rel_path}")
140
- cls_chunk = GraphRagChunk(
141
- chunk_id=f"cls::{rel_path}::{cls_name}",
142
- file_path=rel_path,
143
- name=cls_name,
144
- kind="class",
145
- signature=sig_text,
146
- content=sig_text,
147
- docstring="",
148
- line_start=1,
149
- line_end=1,
150
- dependencies=list(file_snap.imports),
151
- tokens=cls_tokens,
152
- )
153
- self.chunks.append(cls_chunk)
154
- total_tokens += len(cls_tokens)
155
-
156
- self.total_docs = len(self.chunks)
157
- self.avg_doc_len = (total_tokens / self.total_docs) if self.total_docs > 0 else 1.0
158
-
159
- # Build Document Frequency
160
- for chunk in self.chunks:
161
- seen_terms = set(chunk.tokens)
162
- for term in seen_terms:
163
- self.doc_freqs[term] += 1
164
-
165
- # Compute PageRank Centrality across nodes
166
- self._compute_graph_centrality()
167
- return self.total_docs
168
-
169
- def _compute_graph_centrality(self, damping: float = 0.85, iterations: int = 25) -> None:
170
- """Compute node centrality for connected files."""
171
- nodes = list(self.call_graph.keys() | self.reverse_call_graph.keys())
172
- if not nodes:
173
- return
174
- n = len(nodes)
175
- scores = {node: 1.0 / n for node in nodes}
176
-
177
- for _ in range(iterations):
178
- new_scores = {}
179
- for node in nodes:
180
- incoming_sum = 0.0
181
- for pred in self.reverse_call_graph.get(node, set()):
182
- out_deg = len(self.call_graph.get(pred, set()))
183
- if out_deg > 0:
184
- incoming_sum += scores.get(pred, 0.0) / out_deg
185
- new_scores[node] = (1.0 - damping) / n + damping * incoming_sum
186
- scores = new_scores
187
-
188
- self.centrality_scores = scores
189
- for chunk in self.chunks:
190
- stem = os.path.splitext(os.path.basename(chunk.file_path))[0]
191
- chunk.graph_centrality = self.centrality_scores.get(stem, self.centrality_scores.get(chunk.file_path, 0.05))
192
-
193
- def _score_bm25(self, query_tokens: List[str], chunk_tokens: List[str], k1: float = 1.2, b: float = 0.75) -> float:
194
- """Standard BM25 scoring for query tokens against chunk tokens."""
195
- if not query_tokens or not chunk_tokens:
196
- return 0.0
197
- doc_len = len(chunk_tokens)
198
- counts = collections.Counter(chunk_tokens)
199
- score = 0.0
200
-
201
- for q in query_tokens:
202
- if q not in counts:
203
- continue
204
- df = self.doc_freqs.get(q, 0)
205
- idf = math.log(1.0 + (self.total_docs - df + 0.5) / (df + 0.5))
206
- tf = counts[q]
207
- denom = tf + k1 * (1.0 - b + b * (doc_len / (self.avg_doc_len or 1.0)))
208
- score += idf * (tf * (k1 + 1.0)) / denom
209
- return max(0.0, score)
210
-
211
- def query(
212
- self,
213
- query_text: str,
214
- top_k: int = 5,
215
- graph_weight: float = 0.35,
216
- bm25_weight: float = 0.65,
217
- ) -> List[Dict[str, Any]]:
218
- """Execute hybrid search combining BM25 and graph centrality ranking."""
219
- if not self.chunks:
220
- self.index_workspace()
221
-
222
- q_tokens = self.tokenize(query_text)
223
- if not q_tokens:
224
- return []
225
-
226
- scored_chunks: List[GraphRagChunk] = []
227
- max_bm25 = 0.0001
228
- for chunk in self.chunks:
229
- b_score = self._score_bm25(q_tokens, chunk.tokens)
230
- chunk.bm25_score = b_score
231
- if b_score > max_bm25:
232
- max_bm25 = b_score
233
-
234
- # Normalize and blend
235
- for chunk in self.chunks:
236
- norm_bm25 = chunk.bm25_score / max_bm25
237
- # Graph centrality boost
238
- hybrid = (norm_bm25 * bm25_weight) + (chunk.graph_centrality * graph_weight)
239
- # Exact symbol name match boost
240
- if any(q == chunk.name.lower() for q in q_tokens):
241
- hybrid += 0.5
242
- chunk.hybrid_score = hybrid
243
- if chunk.bm25_score > 0.0 or chunk.hybrid_score > 0.2:
244
- scored_chunks.append(chunk)
245
-
246
- scored_chunks.sort(key=lambda c: c.hybrid_score, reverse=True)
247
- top = scored_chunks[:top_k]
248
-
249
- return [
250
- {
251
- "chunk_id": c.chunk_id,
252
- "file_path": c.file_path,
253
- "name": c.name,
254
- "kind": c.kind,
255
- "signature": c.signature,
256
- "hybrid_score": round(c.hybrid_score, 4),
257
- "bm25_score": round(c.bm25_score, 4),
258
- "centrality": round(c.graph_centrality, 4),
259
- "dependencies": c.dependencies[:5],
260
- }
261
- for c in top
262
- ]
263
-
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Vectorless Semantic Graph & Local Code-RAG Engine (100% Offline, Zero-Cost).
3
+
4
+ Combines lexical BM25 token relevance, AST structural symbols, and PageRank
5
+ graph centrality into a unified hybrid retrieval pipeline without external embeddings.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import collections
11
+ import dataclasses
12
+ import math
13
+ import os
14
+ import re
15
+ from typing import Any, Dict, List, Optional, Set, Tuple
16
+
17
+
18
+ @dataclasses.dataclass
19
+ class GraphRagChunk:
20
+ chunk_id: str
21
+ file_path: str
22
+ name: str
23
+ kind: str # function, class, interface, module
24
+ signature: str
25
+ content: str
26
+ docstring: str
27
+ line_start: int
28
+ line_end: int
29
+ dependencies: List[str] = dataclasses.field(default_factory=list)
30
+ tokens: List[str] = dataclasses.field(default_factory=list)
31
+ bm25_score: float = 0.0
32
+ graph_centrality: float = 0.0
33
+ hybrid_score: float = 0.0
34
+
35
+
36
+ class VectorlessGraphRAG:
37
+ """100% Offline, private Graph RAG combining BM25, AST Call Graph, and Centrality."""
38
+
39
+ def __init__(self, workspace_dir: str):
40
+ self.workspace_dir = os.path.abspath(workspace_dir)
41
+ self.chunks: List[GraphRagChunk] = []
42
+ self.doc_freqs: Dict[str, int] = collections.defaultdict(int)
43
+ self.total_docs: int = 0
44
+ self.avg_doc_len: float = 0.0
45
+ self.call_graph: Dict[str, Set[str]] = collections.defaultdict(set)
46
+ self.reverse_call_graph: Dict[str, Set[str]] = collections.defaultdict(set)
47
+ self.centrality_scores: Dict[str, float] = {}
48
+
49
+ @staticmethod
50
+ def tokenize(text: str) -> List[str]:
51
+ """Sub-word aware identifier tokenization."""
52
+ if not text:
53
+ return []
54
+ raw_words = re.findall(r"[A-Za-z0-9_]+", text)
55
+ tokens: List[str] = []
56
+ for word in raw_words:
57
+ tokens.append(word.lower())
58
+ # split camelCase and PascalCase
59
+ parts = re.findall(r"[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\d|\W|$)|\d+", word)
60
+ if len(parts) > 1:
61
+ for p in parts:
62
+ clean = p.lower().strip("_")
63
+ if len(clean) >= 2:
64
+ tokens.append(clean)
65
+ # split snake_case
66
+ if "_" in word:
67
+ for sub in word.split("_"):
68
+ clean = sub.lower()
69
+ if len(clean) >= 2:
70
+ tokens.append(clean)
71
+ return [t for t in tokens if len(t) >= 2]
72
+
73
+ def index_workspace(self, file_limit: int = 500) -> int:
74
+ """Scan workspace and index code structures into graph RAG nodes."""
75
+ from tzero.tzero_snapshot import SnapshotEngine
76
+
77
+ snap = SnapshotEngine.create_snapshot(self.workspace_dir)
78
+ self.chunks.clear()
79
+ self.doc_freqs.clear()
80
+ self.call_graph.clear()
81
+ self.reverse_call_graph.clear()
82
+
83
+ total_tokens = 0
84
+ file_count = 0
85
+
86
+ for rel_path, file_snap in sorted(snap.files.items()):
87
+ file_count += 1
88
+ if file_count > file_limit:
89
+ break
90
+
91
+ full_path = os.path.join(self.workspace_dir, rel_path)
92
+ # 1. Module chunk
93
+ mod_text = f"{rel_path} " + " ".join(file_snap.imports)
94
+ mod_tokens = self.tokenize(mod_text)
95
+ mod_chunk = GraphRagChunk(
96
+ chunk_id=f"mod::{rel_path}",
97
+ file_path=rel_path,
98
+ name=os.path.basename(rel_path),
99
+ kind="module",
100
+ signature=f"module {rel_path}",
101
+ content=mod_text,
102
+ docstring="",
103
+ line_start=1,
104
+ line_end=1,
105
+ dependencies=list(file_snap.imports),
106
+ tokens=mod_tokens,
107
+ )
108
+ self.chunks.append(mod_chunk)
109
+ total_tokens += len(mod_tokens)
110
+
111
+ # Record dependency edges
112
+ for imp in file_snap.imports:
113
+ imp_stem = os.path.splitext(os.path.basename(imp))[0]
114
+ self.call_graph[rel_path].add(imp_stem)
115
+ self.reverse_call_graph[imp_stem].add(rel_path)
116
+
117
+ # 2. Function / Class chunks
118
+ for fn_name in file_snap.functions:
119
+ sig_text = f"def {fn_name}() in {rel_path}"
120
+ fn_tokens = self.tokenize(f"{fn_name} {rel_path}")
121
+ fn_chunk = GraphRagChunk(
122
+ chunk_id=f"fn::{rel_path}::{fn_name}",
123
+ file_path=rel_path,
124
+ name=fn_name,
125
+ kind="function",
126
+ signature=sig_text,
127
+ content=sig_text,
128
+ docstring="",
129
+ line_start=1,
130
+ line_end=1,
131
+ dependencies=list(file_snap.imports),
132
+ tokens=fn_tokens,
133
+ )
134
+ self.chunks.append(fn_chunk)
135
+ total_tokens += len(fn_tokens)
136
+
137
+ for cls_name in file_snap.classes:
138
+ sig_text = f"class {cls_name} in {rel_path}"
139
+ cls_tokens = self.tokenize(f"{cls_name} {rel_path}")
140
+ cls_chunk = GraphRagChunk(
141
+ chunk_id=f"cls::{rel_path}::{cls_name}",
142
+ file_path=rel_path,
143
+ name=cls_name,
144
+ kind="class",
145
+ signature=sig_text,
146
+ content=sig_text,
147
+ docstring="",
148
+ line_start=1,
149
+ line_end=1,
150
+ dependencies=list(file_snap.imports),
151
+ tokens=cls_tokens,
152
+ )
153
+ self.chunks.append(cls_chunk)
154
+ total_tokens += len(cls_tokens)
155
+
156
+ self.total_docs = len(self.chunks)
157
+ self.avg_doc_len = (total_tokens / self.total_docs) if self.total_docs > 0 else 1.0
158
+
159
+ # Build Document Frequency
160
+ for chunk in self.chunks:
161
+ seen_terms = set(chunk.tokens)
162
+ for term in seen_terms:
163
+ self.doc_freqs[term] += 1
164
+
165
+ # Compute PageRank Centrality across nodes
166
+ self._compute_graph_centrality()
167
+ return self.total_docs
168
+
169
+ def _compute_graph_centrality(self, damping: float = 0.85, iterations: int = 25) -> None:
170
+ """Compute node centrality for connected files."""
171
+ nodes = list(self.call_graph.keys() | self.reverse_call_graph.keys())
172
+ if not nodes:
173
+ return
174
+ n = len(nodes)
175
+ scores = {node: 1.0 / n for node in nodes}
176
+
177
+ for _ in range(iterations):
178
+ new_scores = {}
179
+ for node in nodes:
180
+ incoming_sum = 0.0
181
+ for pred in self.reverse_call_graph.get(node, set()):
182
+ out_deg = len(self.call_graph.get(pred, set()))
183
+ if out_deg > 0:
184
+ incoming_sum += scores.get(pred, 0.0) / out_deg
185
+ new_scores[node] = (1.0 - damping) / n + damping * incoming_sum
186
+ scores = new_scores
187
+
188
+ self.centrality_scores = scores
189
+ for chunk in self.chunks:
190
+ stem = os.path.splitext(os.path.basename(chunk.file_path))[0]
191
+ chunk.graph_centrality = self.centrality_scores.get(stem, self.centrality_scores.get(chunk.file_path, 0.05))
192
+
193
+ def _score_bm25(self, query_tokens: List[str], chunk_tokens: List[str], k1: float = 1.2, b: float = 0.75) -> float:
194
+ """Standard BM25 scoring for query tokens against chunk tokens."""
195
+ if not query_tokens or not chunk_tokens:
196
+ return 0.0
197
+ doc_len = len(chunk_tokens)
198
+ counts = collections.Counter(chunk_tokens)
199
+ score = 0.0
200
+
201
+ for q in query_tokens:
202
+ if q not in counts:
203
+ continue
204
+ df = self.doc_freqs.get(q, 0)
205
+ idf = math.log(1.0 + (self.total_docs - df + 0.5) / (df + 0.5))
206
+ tf = counts[q]
207
+ denom = tf + k1 * (1.0 - b + b * (doc_len / (self.avg_doc_len or 1.0)))
208
+ score += idf * (tf * (k1 + 1.0)) / denom
209
+ return max(0.0, score)
210
+
211
+ def query(
212
+ self,
213
+ query_text: str,
214
+ top_k: int = 5,
215
+ graph_weight: float = 0.35,
216
+ bm25_weight: float = 0.65,
217
+ ) -> List[Dict[str, Any]]:
218
+ """Execute hybrid search combining BM25 and graph centrality ranking."""
219
+ if not self.chunks:
220
+ self.index_workspace()
221
+
222
+ q_tokens = self.tokenize(query_text)
223
+ if not q_tokens:
224
+ return []
225
+
226
+ scored_chunks: List[GraphRagChunk] = []
227
+ max_bm25 = 0.0001
228
+ for chunk in self.chunks:
229
+ b_score = self._score_bm25(q_tokens, chunk.tokens)
230
+ chunk.bm25_score = b_score
231
+ if b_score > max_bm25:
232
+ max_bm25 = b_score
233
+
234
+ # Normalize and blend
235
+ for chunk in self.chunks:
236
+ norm_bm25 = chunk.bm25_score / max_bm25
237
+ # Graph centrality boost
238
+ hybrid = (norm_bm25 * bm25_weight) + (chunk.graph_centrality * graph_weight)
239
+ # Exact symbol name match boost
240
+ if any(q == chunk.name.lower() for q in q_tokens):
241
+ hybrid += 0.5
242
+ chunk.hybrid_score = hybrid
243
+ if chunk.bm25_score > 0.0 or chunk.hybrid_score > 0.2:
244
+ scored_chunks.append(chunk)
245
+
246
+ scored_chunks.sort(key=lambda c: c.hybrid_score, reverse=True)
247
+ top = scored_chunks[:top_k]
248
+
249
+ return [
250
+ {
251
+ "chunk_id": c.chunk_id,
252
+ "file_path": c.file_path,
253
+ "name": c.name,
254
+ "kind": c.kind,
255
+ "signature": c.signature,
256
+ "hybrid_score": round(c.hybrid_score, 4),
257
+ "bm25_score": round(c.bm25_score, 4),
258
+ "centrality": round(c.graph_centrality, 4),
259
+ "dependencies": c.dependencies[:5],
260
+ }
261
+ for c in top
262
+ ]
263
+