tzero-mcp 10.7.4 → 11.0.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 (127) hide show
  1. package/CHANGELOG.md +56 -29
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -66
  5. package/bin/tzero.js +61 -65
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -88
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -43
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -0,0 +1,368 @@
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero SCIP / LSIF Cross-Language Index Importer.
3
+
4
+ Loads compiler-exact SCIP JSON and LSIF NDJSON symbol indexes into a unified
5
+ cross-file definition/reference call graph without running external paid services.
6
+
7
+ 100% Free, Local, Offline, Zero-Leak Certified.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import urllib.parse
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Dict, Iterator, List, Optional, Set, Tuple
17
+
18
+
19
+ def _read_varint(raw: bytes, offset: int = 0) -> Tuple[int, int]:
20
+ """Reads a varint from raw bytes starting at offset. Returns (value, new_offset)."""
21
+ val = 0
22
+ shift = 0
23
+ length = len(raw)
24
+ while offset < length:
25
+ b = raw[offset]
26
+ offset += 1
27
+ val |= (b & 0x7F) << shift
28
+ if not (b & 0x80):
29
+ return val, offset
30
+ shift += 7
31
+ if shift > 64:
32
+ break
33
+ return val, offset
34
+
35
+
36
+ def _iter_wire_fields(raw: bytes) -> Iterator[Tuple[int, int, Any]]:
37
+ """Iterates (tag, wire_type, value) tuples from protobuf binary wire bytes."""
38
+ offset = 0
39
+ length = len(raw)
40
+ while offset < length:
41
+ key, offset = _read_varint(raw, offset)
42
+ wire_type = key & 0x07
43
+ tag = key >> 3
44
+ if tag == 0:
45
+ break
46
+ if wire_type == 0:
47
+ val, offset = _read_varint(raw, offset)
48
+ yield tag, wire_type, val
49
+ elif wire_type == 1:
50
+ val = raw[offset:offset + 8]
51
+ offset += 8
52
+ yield tag, wire_type, val
53
+ elif wire_type == 2:
54
+ length_delim, offset = _read_varint(raw, offset)
55
+ val = raw[offset:offset + length_delim]
56
+ offset += length_delim
57
+ yield tag, wire_type, val
58
+ elif wire_type == 5:
59
+ val = raw[offset:offset + 4]
60
+ offset += 4
61
+ yield tag, wire_type, val
62
+ else:
63
+ break
64
+
65
+
66
+ @dataclass
67
+ class SymbolLocation:
68
+ symbol: str
69
+ file: str
70
+ line: int
71
+ column: int = 0
72
+ role: str = "reference"
73
+
74
+
75
+ @dataclass
76
+ class ScipIndexGraph:
77
+ format_name: str
78
+ document_count: int
79
+ definitions: Dict[str, List[SymbolLocation]] = field(default_factory=dict)
80
+ references: Dict[str, List[SymbolLocation]] = field(default_factory=dict)
81
+ call_edges: Dict[str, Set[str]] = field(default_factory=dict)
82
+
83
+ def trace_symbol(self, symbol_query: str) -> Dict[str, Any]:
84
+ q = (symbol_query or "").strip().lower()
85
+ matched_defs: List[Dict[str, Any]] = []
86
+ matched_refs: List[Dict[str, Any]] = []
87
+
88
+ for sym, locs in self.definitions.items():
89
+ if not q or q in sym.lower():
90
+ for loc in locs:
91
+ matched_defs.append({
92
+ "symbol": sym,
93
+ "file": loc.file,
94
+ "line": loc.line,
95
+ "column": loc.column,
96
+ })
97
+ for sym, locs in self.references.items():
98
+ if not q or q in sym.lower():
99
+ for loc in locs:
100
+ matched_refs.append({
101
+ "symbol": sym,
102
+ "file": loc.file,
103
+ "line": loc.line,
104
+ "column": loc.column,
105
+ })
106
+
107
+ return {
108
+ "query": symbol_query,
109
+ "format": self.format_name,
110
+ "document_count": self.document_count,
111
+ "definitions": matched_defs,
112
+ "references": matched_refs,
113
+ }
114
+
115
+ def export_tzero_graph(self) -> Dict[str, Any]:
116
+ return {
117
+ "format": self.format_name,
118
+ "documents": self.document_count,
119
+ "symbols_indexed": len(self.definitions) + len(self.references),
120
+ "edges": {src: sorted(dsts) for src, dsts in self.call_edges.items() if dsts},
121
+ }
122
+
123
+
124
+ class ScipIndexImporter:
125
+ """Loads SCIP JSON or LSIF NDJSON indexes into ScipIndexGraph."""
126
+
127
+ @classmethod
128
+ def _uri_to_rel(cls, uri: str) -> str:
129
+ if not uri:
130
+ return ""
131
+ if uri.startswith("file://"):
132
+ p = urllib.parse.unquote(urllib.parse.urlparse(uri).path)
133
+ return p.lstrip("/").replace("\\", "/")
134
+ return uri.replace("\\", "/")
135
+
136
+ @classmethod
137
+ def from_scip_dict(cls, payload: Dict[str, Any]) -> ScipIndexGraph:
138
+ defs: Dict[str, List[SymbolLocation]] = {}
139
+ refs: Dict[str, List[SymbolLocation]] = {}
140
+ docs = payload.get("documents") or []
141
+ edges: Dict[str, Set[str]] = {}
142
+
143
+ for doc in docs:
144
+ rel_path = str(doc.get("relative_path") or "").replace("\\", "/")
145
+ for occ in doc.get("occurrences") or []:
146
+ sym = str(occ.get("symbol") or "")
147
+ if not sym:
148
+ continue
149
+ rng = occ.get("range") or [0, 0]
150
+ ln = int(rng[0]) if len(rng) > 0 else 0
151
+ col = int(rng[1]) if len(rng) > 1 else 0
152
+ roles = int(occ.get("symbol_roles", 0))
153
+ is_def = bool(roles & 1)
154
+ loc = SymbolLocation(
155
+ symbol=sym,
156
+ file=rel_path,
157
+ line=ln,
158
+ column=col,
159
+ role="definition" if is_def else "reference",
160
+ )
161
+ if is_def:
162
+ defs.setdefault(sym, []).append(loc)
163
+ else:
164
+ refs.setdefault(sym, []).append(loc)
165
+
166
+ for sym, ref_locs in refs.items():
167
+ def_files = {d.file for d in defs.get(sym, [])}
168
+ for rloc in ref_locs:
169
+ for df in def_files:
170
+ if df != rloc.file:
171
+ edges.setdefault(rloc.file, set()).add(df)
172
+
173
+ return ScipIndexGraph(
174
+ format_name="scip",
175
+ document_count=len(docs),
176
+ definitions=defs,
177
+ references=refs,
178
+ call_edges=edges,
179
+ )
180
+
181
+ @classmethod
182
+ def from_lsif_lines(cls, lines: List[str]) -> ScipIndexGraph:
183
+ vertices: Dict[Any, Dict[str, Any]] = {}
184
+ doc_by_range: Dict[Any, str] = {}
185
+ moniker_by_range: Dict[Any, str] = {}
186
+ def_result_targets: Dict[Any, List[Any]] = {}
187
+ ref_result_targets: Dict[Any, List[Any]] = {}
188
+ range_to_def_result: Dict[Any, Any] = {}
189
+ range_to_ref_result: Dict[Any, Any] = {}
190
+ docs_seen: Set[str] = set()
191
+
192
+ for raw in lines:
193
+ s = raw.strip()
194
+ if not s:
195
+ continue
196
+ item = json.loads(s)
197
+ if item.get("type") == "vertex":
198
+ vid = item.get("id")
199
+ vertices[vid] = item
200
+ if item.get("label") == "document":
201
+ docs_seen.add(cls._uri_to_rel(str(item.get("uri") or "")))
202
+ elif item.get("type") == "edge":
203
+ label = item.get("label", "")
204
+ out_v = item.get("outV")
205
+ in_vs = item.get("inVs") or ([item.get("inV")] if "inV" in item else [])
206
+ if label == "contains":
207
+ doc_uri = cls._uri_to_rel(str(vertices.get(out_v, {}).get("uri") or ""))
208
+ for rv in in_vs:
209
+ doc_by_range[rv] = doc_uri
210
+ elif label == "moniker":
211
+ for mv in in_vs:
212
+ ident = str(vertices.get(mv, {}).get("identifier") or "")
213
+ if ident:
214
+ moniker_by_range[out_v] = ident
215
+ elif label == "textDocument/definition" and in_vs:
216
+ range_to_def_result[out_v] = in_vs[0]
217
+ elif label == "textDocument/references" and in_vs:
218
+ range_to_ref_result[out_v] = in_vs[0]
219
+ elif label == "item":
220
+ out_label = vertices.get(out_v, {}).get("label", "")
221
+ if out_label == "definitionResult":
222
+ def_result_targets.setdefault(out_v, []).extend(in_vs)
223
+ elif out_label == "referenceResult":
224
+ ref_result_targets.setdefault(out_v, []).extend(in_vs)
225
+
226
+ defs: Dict[str, List[SymbolLocation]] = {}
227
+ refs: Dict[str, List[SymbolLocation]] = {}
228
+ edges: Dict[str, Set[str]] = {}
229
+
230
+ def _range_loc(rv: Any, sym: str, role: str) -> SymbolLocation:
231
+ v = vertices.get(rv, {})
232
+ start = v.get("start") or {}
233
+ return SymbolLocation(
234
+ symbol=sym,
235
+ file=doc_by_range.get(rv, ""),
236
+ line=int(start.get("line", 0)),
237
+ column=int(start.get("character", 0)),
238
+ role=role,
239
+ )
240
+
241
+ for src_r, res_id in range_to_def_result.items():
242
+ sym = moniker_by_range.get(src_r) or f"lsif_sym_{src_r}"
243
+ for def_r in def_result_targets.get(res_id, [src_r]):
244
+ defs.setdefault(sym, []).append(_range_loc(def_r, sym, "definition"))
245
+
246
+ for src_r, res_id in range_to_ref_result.items():
247
+ sym = moniker_by_range.get(src_r) or f"lsif_sym_{src_r}"
248
+ src_doc = doc_by_range.get(src_r, "")
249
+ for ref_r in ref_result_targets.get(res_id, []):
250
+ loc = _range_loc(ref_r, sym, "reference")
251
+ refs.setdefault(sym, []).append(loc)
252
+ if src_doc and loc.file and loc.file != src_doc:
253
+ edges.setdefault(loc.file, set()).add(src_doc)
254
+
255
+ return ScipIndexGraph(
256
+ format_name="lsif",
257
+ document_count=len(docs_seen),
258
+ definitions=defs,
259
+ references=refs,
260
+ call_edges=edges,
261
+ )
262
+
263
+ @classmethod
264
+ def from_scip_protobuf_bytes(cls, raw: bytes) -> ScipIndexGraph:
265
+ if not raw:
266
+ return ScipIndexGraph(format_name="empty", document_count=0)
267
+
268
+ defs: Dict[str, List[SymbolLocation]] = {}
269
+ refs: Dict[str, List[SymbolLocation]] = {}
270
+ edges: Dict[str, Set[str]] = {}
271
+ doc_count = 0
272
+
273
+ # Top-level Index: tag 2 = Document (wire type 2)
274
+ for tag, wtype, doc_data in _iter_wire_fields(raw):
275
+ if tag != 2 or wtype != 2:
276
+ continue
277
+ doc_count += 1
278
+ rel_path = ""
279
+ raw_occurrences: List[bytes] = []
280
+
281
+ # Document fields: tag 1 = relative_path (str), tag 2 = Occurrence
282
+ for d_tag, d_wtype, d_val in _iter_wire_fields(doc_data):
283
+ if d_tag == 1 and d_wtype == 2:
284
+ rel_path = d_val.decode("utf-8", errors="replace").replace("\\", "/")
285
+ elif d_tag == 2 and d_wtype == 2:
286
+ raw_occurrences.append(d_val)
287
+
288
+ for occ_bytes in raw_occurrences:
289
+ occ_range: List[int] = []
290
+ sym = ""
291
+ roles = 0
292
+ for o_tag, o_wtype, o_val in _iter_wire_fields(occ_bytes):
293
+ if o_tag == 1:
294
+ if o_wtype == 2:
295
+ off = 0
296
+ while off < len(o_val):
297
+ n, off = _read_varint(o_val, off)
298
+ occ_range.append(n)
299
+ elif o_wtype == 0:
300
+ occ_range.append(int(o_val))
301
+ elif o_tag == 2 and o_wtype == 2:
302
+ sym = o_val.decode("utf-8", errors="replace")
303
+ elif o_tag == 3 and o_wtype == 0:
304
+ roles = int(o_val)
305
+
306
+ if not sym:
307
+ continue
308
+
309
+ ln = int(occ_range[0]) if len(occ_range) > 0 else 0
310
+ col = int(occ_range[1]) if len(occ_range) > 1 else 0
311
+ is_def = bool(roles & 1)
312
+ loc = SymbolLocation(
313
+ symbol=sym,
314
+ file=rel_path,
315
+ line=ln,
316
+ column=col,
317
+ role="definition" if is_def else "reference",
318
+ )
319
+ if is_def:
320
+ defs.setdefault(sym, []).append(loc)
321
+ else:
322
+ refs.setdefault(sym, []).append(loc)
323
+
324
+ for sym, ref_locs in refs.items():
325
+ def_files = {d.file for d in defs.get(sym, [])}
326
+ for rloc in ref_locs:
327
+ for df in def_files:
328
+ if df != rloc.file:
329
+ edges.setdefault(rloc.file, set()).add(df)
330
+
331
+ return ScipIndexGraph(
332
+ format_name="scip-protobuf",
333
+ document_count=doc_count,
334
+ definitions=defs,
335
+ references=refs,
336
+ call_edges=edges,
337
+ )
338
+
339
+ @classmethod
340
+ def load(cls, path: str) -> ScipIndexGraph:
341
+ if not os.path.isfile(path):
342
+ raise FileNotFoundError(f"SCIP/LSIF index file not found: {path}")
343
+ with open(path, "rb") as f:
344
+ raw = f.read()
345
+ if not raw.strip():
346
+ return ScipIndexGraph(format_name="empty", document_count=0)
347
+
348
+ if path.lower().endswith(".scip") or b"\x00" in raw:
349
+ return cls.from_scip_protobuf_bytes(raw)
350
+
351
+ try:
352
+ text = raw.decode("utf-8")
353
+ try:
354
+ data = json.loads(text)
355
+ if isinstance(data, dict) and "documents" in data:
356
+ return cls.from_scip_dict(data)
357
+ except json.JSONDecodeError:
358
+ pass
359
+ return cls.from_lsif_lines(text.splitlines())
360
+ except Exception:
361
+ return cls.from_scip_protobuf_bytes(raw)
362
+
363
+
364
+ def run_scip_import_cli(path: str, symbol: Optional[str] = None) -> int:
365
+ graph = ScipIndexImporter.load(path)
366
+ out = graph.trace_symbol(symbol) if symbol else graph.export_tzero_graph()
367
+ print(json.dumps(out, indent=2))
368
+ return 0
@@ -443,11 +443,14 @@ class ZeroLeakEngine:
443
443
  }
444
444
 
445
445
  @classmethod
446
- def scan_workspace(cls, workspace_dir: str = ".") -> dict:
446
+ def scan_workspace(cls, workspace_dir: str = ".", exclude_tests: bool = True) -> dict:
447
447
  """Scans a workspace directory for any hardcoded secrets and returns violations dict."""
448
448
  files_map = {}
449
+ ignored_dirs = {"__pycache__", "venv", ".venv", "node_modules", "dist", "build", ".git"}
450
+ if exclude_tests:
451
+ ignored_dirs.update({"tests", "test", "fixtures"})
449
452
  for root, dirs, files in os.walk(workspace_dir):
450
- dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "venv", ".venv", "node_modules", "dist", "build", ".git")]
453
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ignored_dirs]
451
454
  for f in files:
452
455
  if f.endswith((".py", ".js", ".ts", ".json", ".yaml", ".yml", ".env.example", ".sh", ".toml", ".txt")):
453
456
  fp = os.path.join(root, f)
@@ -0,0 +1,189 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Siber Akademi — T-Zero AST Semantic 3-Way Merge & Conflict Healer.
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ License: MIT
6
+
7
+ Performs AST-aware 3-way code merging and automated resolution of git conflict blocks.
8
+ Safely combines independent function additions, deduplicates polyglot imports,
9
+ and eliminates broken syntax markers without relying on external cloud APIs.
10
+ 100% Free, Zero External Dependencies, 100% Zero-Leak Certified.
11
+ """
12
+
13
+ import os
14
+ import sys
15
+ import ast
16
+ import re
17
+ from dataclasses import dataclass, field
18
+ from typing import Dict, List, Optional, Set, Tuple
19
+
20
+
21
+ @dataclass
22
+ class MergeResult:
23
+ success: bool
24
+ merged_code: str
25
+ auto_resolved_conflicts: int
26
+ unresolved_conflicts: int
27
+ symbols_added_ours: List[str] = field(default_factory=list)
28
+ symbols_added_theirs: List[str] = field(default_factory=list)
29
+ details: List[str] = field(default_factory=list)
30
+
31
+
32
+ class ASTSemanticMerger:
33
+ """Semantic AST-aware 3-way merger and git conflict block healer."""
34
+
35
+ CONFLICT_PATTERN = re.compile(
36
+ r'<<<<<<<[^\n]*\n(.*?)=======\n(.*?)>>>>>>>[^\n]*\n',
37
+ re.DOTALL
38
+ )
39
+
40
+ @classmethod
41
+ def has_conflict_markers(cls, text: str) -> bool:
42
+ """Returns True if file contains standard git conflict markers."""
43
+ return bool(cls.CONFLICT_PATTERN.search(text))
44
+
45
+ @classmethod
46
+ def extract_ast_symbols(cls, code: str) -> Dict[str, str]:
47
+ """Extracts top-level functions, classes, and imports as symbol_name -> code string."""
48
+ symbols: Dict[str, str] = {}
49
+ try:
50
+ tree = ast.parse(code)
51
+ except SyntaxError:
52
+ return symbols
53
+
54
+ lines = code.splitlines(keepends=True)
55
+ for node in tree.body:
56
+ name = None
57
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
58
+ name = node.name
59
+ elif isinstance(node, ast.Import):
60
+ name = "import::" + ",".join(a.name for a in node.names)
61
+ elif isinstance(node, ast.ImportFrom):
62
+ name = f"from::{node.module or ''}::" + ",".join(a.name for a in node.names)
63
+
64
+ if name and hasattr(node, "lineno") and hasattr(node, "end_lineno"):
65
+ node_lines = lines[node.lineno - 1:node.end_lineno]
66
+ symbols[name] = "".join(node_lines)
67
+
68
+ return symbols
69
+
70
+ @classmethod
71
+ def heal_conflict_file(cls, content: str) -> MergeResult:
72
+ """
73
+ Scans content for git conflict blocks (<<<<<<< ... ======= ... >>>>>>>)
74
+ and attempts semantic AST healing.
75
+ """
76
+ matches = list(cls.CONFLICT_PATTERN.finditer(content))
77
+ if not matches:
78
+ return MergeResult(
79
+ success=True,
80
+ merged_code=content,
81
+ auto_resolved_conflicts=0,
82
+ unresolved_conflicts=0,
83
+ details=["No conflict markers found in input."]
84
+ )
85
+
86
+ auto_resolved = 0
87
+ unresolved = 0
88
+ details = []
89
+ result_text = content
90
+ added_ours = []
91
+ added_theirs = []
92
+
93
+ # Process each conflict block
94
+ for idx, m in enumerate(matches, 1):
95
+ full_match = m.group(0)
96
+ ours_block = m.group(1)
97
+ theirs_block = m.group(2)
98
+
99
+ ours_syms = cls.extract_ast_symbols(ours_block)
100
+ theirs_syms = cls.extract_ast_symbols(theirs_block)
101
+
102
+ # Check colliding definitions (exclude imports, which are safely unified and deduplicated)
103
+ ours_defs = {k: v for k, v in ours_syms.items() if not k.startswith("import::") and not k.startswith("from::")}
104
+ theirs_defs = {k: v for k, v in theirs_syms.items() if not k.startswith("import::") and not k.startswith("from::")}
105
+ shared_defs = set(ours_defs.keys()).intersection(set(theirs_defs.keys()))
106
+
107
+ # If definitions are disjoint (or purely imports/declarations), merge safely!
108
+ if not shared_defs:
109
+ merged_snippet = ours_block.strip() + "\n\n" + theirs_block.strip() + "\n"
110
+ result_text = result_text.replace(full_match, merged_snippet, 1)
111
+ auto_resolved += 1
112
+ added_ours.extend(list(ours_defs.keys()))
113
+ added_theirs.extend(list(theirs_defs.keys()))
114
+ details.append(
115
+ f"Conflict #{idx}: Auto-healed disjoint AST symbols (Ours: {list(ours_defs.keys())}, Theirs: {list(theirs_defs.keys())})."
116
+ )
117
+ else:
118
+ # True semantic collision on same definition symbol
119
+ safe_block = (
120
+ f"# --- T-ZERO AST MERGE CONFLICT (Shared symbols: {list(shared_defs)}) ---\n"
121
+ f"# [OURS VERSION]:\n{ours_block}\n"
122
+ f"# [THEIRS VERSION]:\n{theirs_block}\n"
123
+ f"# --- END CONFLICT ---\n"
124
+ )
125
+ result_text = result_text.replace(full_match, safe_block, 1)
126
+ unresolved += 1
127
+ details.append(
128
+ f"Conflict #{idx}: Semantic collision on symbol(s) {list(shared_defs)}. Sanitized markers into comments."
129
+ )
130
+
131
+ # Post-process: deduplicate imports if syntactically valid Python
132
+ try:
133
+ tree = ast.parse(result_text)
134
+ # Check for duplicate import lines
135
+ import_lines_seen = set()
136
+ cleaned_lines = []
137
+ for line in result_text.splitlines():
138
+ stripped = line.strip()
139
+ if (stripped.startswith("import ") or stripped.startswith("from ")) and "#" not in stripped:
140
+ if stripped in import_lines_seen:
141
+ continue
142
+ import_lines_seen.add(stripped)
143
+ cleaned_lines.append(line)
144
+ result_text = "\n".join(cleaned_lines)
145
+ if not result_text.endswith("\n"):
146
+ result_text += "\n"
147
+ except SyntaxError:
148
+ pass
149
+
150
+ return MergeResult(
151
+ success=(unresolved == 0),
152
+ merged_code=result_text,
153
+ auto_resolved_conflicts=auto_resolved,
154
+ unresolved_conflicts=unresolved,
155
+ symbols_added_ours=added_ours,
156
+ symbols_added_theirs=added_theirs,
157
+ details=details
158
+ )
159
+
160
+ @classmethod
161
+ def heal_file_on_disk(cls, file_path: str, write_in_place: bool = True) -> MergeResult:
162
+ """Reads a file with git conflict markers, heals it, and optionally overwrites it."""
163
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
164
+ content = f.read()
165
+
166
+ res = cls.heal_conflict_file(content)
167
+ if write_in_place and res.auto_resolved_conflicts > 0:
168
+ with open(file_path, "w", encoding="utf-8") as f:
169
+ f.write(res.merged_code)
170
+
171
+ return res
172
+
173
+ @classmethod
174
+ def render_cli(cls, res: MergeResult, file_hint: str = "file"):
175
+ status_color = "\033[32m" if res.success else "\033[33m"
176
+ print(f"\n🧩 \033[1mT-ZERO AST SEMANTIC MERGE & CONFLICT HEALER\033[0m")
177
+ print("=" * 70)
178
+ print(f"📄 Target: {file_hint}")
179
+ print(f"⚡ Auto-Healed Blocks: \033[32m{res.auto_resolved_conflicts}\033[0m")
180
+ print(f"⚠️ Collisions: {status_color}{res.unresolved_conflicts}\033[0m")
181
+ print("=" * 70)
182
+ for d in res.details:
183
+ print(f" • {d}")
184
+ print("=" * 70)
185
+
186
+
187
+ def heal_conflicts(content: str) -> MergeResult:
188
+ """Convenience functional interface."""
189
+ return ASTSemanticMerger.heal_conflict_file(content)