tzero-mcp 10.7.4 → 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 (131) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/bin/tzero-mcp.js +7 -11
  5. package/bin/tzero.js +7 -11
  6. package/index.js +3 -3
  7. package/package.json +3 -2
  8. package/src/addmcp.py +1203 -1194
  9. package/src/app.py +1810 -0
  10. package/src/main.py +60 -60
  11. package/src/pc_fixer_mcp.py +25 -0
  12. package/src/tzero/__init__.py +54 -0
  13. package/src/tzero/__main__.py +6 -0
  14. package/src/tzero/siber_akademi.ico +0 -0
  15. package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +77 -77
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +2 -2
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +184 -0
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/tzero/tzero_card.py +431 -0
  22. package/src/{tzero_ci.py → tzero/tzero_ci.py} +7 -7
  23. package/src/{tzero_commit.py → tzero/tzero_commit.py} +1 -1
  24. package/src/tzero/tzero_contracts.py +1093 -0
  25. package/src/{tzero_cost.py → tzero/tzero_cost.py} +4 -1
  26. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +1960 -1448
  27. package/src/tzero/tzero_debt.py +461 -0
  28. package/src/{tzero_deps.py → tzero/tzero_deps.py} +462 -287
  29. package/src/{tzero_drift.py → tzero/tzero_drift.py} +1 -1
  30. package/src/{tzero_explain.py → tzero/tzero_explain.py} +306 -240
  31. package/src/{tzero_features.py → tzero/tzero_features.py} +3024 -3022
  32. package/src/tzero/tzero_federation.py +299 -0
  33. package/src/tzero/tzero_fix.py +557 -0
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +334 -334
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +1 -1
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +8 -8
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +1 -1
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +1 -1
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +1 -1
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +1 -1
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +1 -1
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +280 -280
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +325 -325
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +489 -447
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +385 -385
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +375 -375
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +323 -323
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +2 -1
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +1 -1
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +1 -1
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +364 -364
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +619 -619
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +1 -1
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +2 -2
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +493 -493
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +1 -1
  58. package/src/tzero/tzero_golden.py +319 -0
  59. package/src/tzero/tzero_graph_hud.html +338 -0
  60. package/src/tzero/tzero_graph_rag.py +263 -0
  61. package/src/tzero/tzero_growth.py +415 -0
  62. package/src/{tzero_guard.py → tzero/tzero_guard.py} +11 -3
  63. package/src/tzero/tzero_hooks.py +565 -0
  64. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +11 -1
  65. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +1 -1
  66. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  67. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +1 -1
  68. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +2 -2
  69. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +1 -1
  70. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +1 -1
  71. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +2 -2
  72. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +1 -1
  73. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +3 -3
  74. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +1 -1
  75. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +6 -6
  76. package/src/tzero/tzero_lsp.py +634 -0
  77. package/src/tzero/tzero_mcp.py +5314 -0
  78. package/src/tzero/tzero_mutation.py +358 -0
  79. package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +1425 -1425
  80. package/src/tzero/tzero_packer.py +577 -0
  81. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +42 -0
  82. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +1 -1
  83. package/src/tzero/tzero_polyglot.py +799 -0
  84. package/src/tzero/tzero_proxy.py +127 -0
  85. package/src/tzero/tzero_rust_bridge.py +198 -0
  86. package/src/tzero/tzero_scip.py +368 -0
  87. package/src/{tzero_security.py → tzero/tzero_security.py} +573 -570
  88. package/src/tzero/tzero_semantic_merge.py +189 -0
  89. package/src/tzero/tzero_snapshot.py +471 -0
  90. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +1 -1
  91. package/src/tzero/tzero_subagent_engine.py +459 -0
  92. package/src/{tzero_sync.py → tzero/tzero_sync.py} +2 -2
  93. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +174 -31
  94. package/src/{tzero_tui.py → tzero/tzero_tui.py} +313 -244
  95. package/src/tzero/tzero_turbo.py +264 -0
  96. package/src/{tzero_v3.py → tzero/tzero_v3.py} +9997 -9435
  97. package/src/tzero.py +6 -58
  98. package/src/tzero_mcp.py +25 -4858
  99. package/test/package.test.js +14 -2
  100. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  101. package/src/tzero_fix.py +0 -228
  102. package/src/tzero_gateway.py +0 -885
  103. package/src/tzero_packer.py +0 -370
  104. package/src/tzero_polyglot.py +0 -422
  105. package/src/tzero_snapshot.py +0 -258
  106. /package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +0 -0
  107. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +0 -0
  108. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +0 -0
  109. /package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +0 -0
  110. /package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +0 -0
  111. /package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +0 -0
  112. /package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +0 -0
  113. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +0 -0
  114. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +0 -0
  115. /package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +0 -0
  116. /package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +0 -0
  117. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +0 -0
  118. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +0 -0
  119. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +0 -0
  120. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +0 -0
  121. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +0 -0
  122. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +0 -0
  123. /package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +0 -0
  124. /package/src/{tzero_infra.py → tzero/tzero_infra.py} +0 -0
  125. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +0 -0
  126. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +0 -0
  127. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +0 -0
  128. /package/src/{tzero_patch.py → tzero/tzero_patch.py} +0 -0
  129. /package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +0 -0
  130. /package/src/{tzero_replay.py → tzero/tzero_replay.py} +0 -0
  131. /package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +0 -0
@@ -25,9 +25,21 @@ test("tzero package exports correct properties", () => {
25
25
  test("tzero core python files exist in srcDir", () => {
26
26
  assert.strictEqual(fs.existsSync(tzero.mcpServer), true);
27
27
  assert.strictEqual(fs.existsSync(tzero.cli), true);
28
- const coreFiles = ["tzero_v3.py", "tzero_mcp.py", "tzero_security.py", "tzero_deps.py", "tzero_polyglot.py"];
28
+ const coreFiles = [
29
+ "tzero_v3.py",
30
+ "tzero_mcp.py",
31
+ "tzero_security.py",
32
+ "tzero_deps.py",
33
+ "tzero_polyglot.py",
34
+ "tzero_arch_test.py",
35
+ "tzero_budget.py",
36
+ "tzero_contracts.py",
37
+ "tzero_debt.py",
38
+ "tzero_golden.py",
39
+ "tzero_mutation.py"
40
+ ];
29
41
  for (const f of coreFiles) {
30
- assert.strictEqual(fs.existsSync(path.join(tzero.srcDir, f)), true, `Expected ${f} to exist`);
42
+ assert.strictEqual(fs.existsSync(path.join(tzero.srcDir, "tzero", f)), true, `Expected ${f} to exist`);
31
43
  }
32
44
  });
33
45
 
@@ -1,373 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-ZERO ULTRA-COMPRESSION ENGINE (3-LAYER SEMANTIC MEMORY & CODEBOOK QUANTIZATION)
4
- ---------------------------------------------------------------------------------
5
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
6
- Version: 4.2.0
7
-
8
- Bu modül, doğal dil ve kod açıklamalarındaki yüksek token israfını ortadan kaldıran
9
- üç katmanlı hiper-sıkıştırma ve sanal bellek (Virtual KV-Cache Token) sistemidir:
10
-
11
- Katman A (Anlamsal Çekirdek Çıkarımı - Semantic Triplet Extraction):
12
- Gereksiz dolgu kelimelerini ("ve", "ile", "için", "dolayısıyla" vb.) atarak
13
- bilgiyi saf mantıksal çizgelere (Graph Triplet) dönüştürür.
14
- Örnek: "(Toprak dün akşam laboratuvarda ESP32 kartı üzerinde nRF24L01 modülünü SPI portuna bağlayarak test etti.)"
15
- -> "(Toprak)->[test_etti]->(ESP32 + nRF24L01 | SPI)"
16
-
17
- Katman B (Vektör Kuantizasyonu / Sözlük Hashing - VQ Codebook):
18
- Çizgeleri harf olarak tutmak yerine, modelin latent uzayına karşılık gelen
19
- küçük tamsayı indekslerine (discrete codes) indirger.
20
- Örnek: "(ESP32 + nRF24L01 | SPI)" -> #8421
21
-
22
- Katman C (Dinamik Çözücü / Soft-Prompt Re-Injection - Virtual KV-Cache Token):
23
- Model geçmişi hatırlamak istediğinde bu kodları tek tek okumaz.
24
- Doğrudan dikkat katmanına (Attention layer) tek bir sanal token olarak enjekte eder:
25
- <|tzero:mem:8421|> (1 token ile 25 kelimelik hafıza priming'i, %96 token tasarrufu).
26
- """
27
-
28
- import re
29
- import json
30
- import hashlib
31
- from typing import Dict, List, Optional, Tuple, Any, Union
32
- from dataclasses import dataclass, asdict
33
-
34
-
35
- @dataclass
36
- class SemanticTriplet:
37
- """Saf anlamsal çizge üçlüsü (Graph Triplet)."""
38
- subject: str
39
- predicate: str
40
- object: str
41
- context: str = ""
42
-
43
- def to_graph_string(self) -> str:
44
- """Kompakt çizge gösterimi üretir: (Özne)->[Yüklem]->(Nesne | Bağlam)"""
45
- if self.context:
46
- return f"({self.subject})->[{self.predicate}]->({self.object} | {self.context})"
47
- return f"({self.subject})->[{self.predicate}]->({self.object})"
48
-
49
- def to_dict(self) -> Dict[str, str]:
50
- return asdict(self)
51
-
52
-
53
- class SemanticTripletExtractor:
54
- """Katman A: Dolgu kelimeleri temizleyip mantıksal çizgeye dönüştüren çıkarıcı."""
55
-
56
- # Türkçe ve İngilizce Dolgu / Bağlaç / Zaman Zarfı Kelimeleri
57
- STOPWORDS = {
58
- # Türkçe Dolgular
59
- "ve", "veya", "ile", "için", "dolayısıyla", "bu", "şu", "o", "bir", "birkaç",
60
- "dün", "akşam", "sabah", "öğle", "gece", "dün akşam", "bugün", "yarın",
61
- "üzerinde", "altında", "yanında", "tarafından", "aracılığıyla", "vasıtasıyla",
62
- "bağlayarak", "kullanarak", "yoluyla", "şekilde", "falan", "filan", "şey",
63
- "dair", "göre", "kadar", "beri", "sonra", "önce", "dolayı", "ötürü",
64
- "kartı", "modülünü", "modülü", "portuna", "portu", "üzerine",
65
- # İngilizce Dolgular
66
- "and", "or", "with", "for", "therefore", "thus", "hence", "the", "a", "an",
67
- "yesterday", "evening", "today", "morning", "night", "on", "in", "at", "by",
68
- "through", "using", "via", "connecting", "connected", "over", "under", "into"
69
- }
70
-
71
- # Eylem / Yüklem Eşleme Tablosu (Normalizasyon)
72
- ACTION_MAP = {
73
- "test etti": "test_etti",
74
- "test_etti": "test_etti",
75
- "denedi": "test_etti",
76
- "bağladı": "bagladi",
77
- "çalıştırdı": "calistirdi",
78
- "derledi": "derledi",
79
- "yazdı": "yazdi",
80
- "analiz etti": "analiz_etti",
81
- "onardı": "onardi",
82
- "düzeltti": "onardi",
83
- "tested": "test_etti",
84
- "ran": "calistirdi",
85
- "compiled": "derledi",
86
- "analyzed": "analiz_etti",
87
- "fixed": "onardi",
88
- "deployed": "dagitti"
89
- }
90
-
91
- @classmethod
92
- def clean_text(cls, text: str) -> str:
93
- """Noktalama işaretlerini ve fazla boşlukları düzenler."""
94
- text = re.sub(r"[^\w\s\-\+\#]", " ", text)
95
- return " ".join(text.split())
96
-
97
- @classmethod
98
- def extract_triplets(cls, text: str) -> List[SemanticTriplet]:
99
- """Verilen doğal dil metninden anlamsal graf üçlülerini (Triplets) çıkarır."""
100
- if not text or not text.strip():
101
- return []
102
-
103
- triplets: List[SemanticTriplet] = []
104
- sentences = [s.strip() for s in re.split(r"[.!?;\n]+", text) if s.strip()]
105
-
106
- for sentence in sentences:
107
- triplet = cls._extract_single_sentence(sentence)
108
- if triplet:
109
- triplets.append(triplet)
110
-
111
- # Eğer kural tabanlı ayrıştırıcı boş döndüyse fallback tripler oluştur
112
- if not triplets and sentences:
113
- fallback = cls._fallback_triplet(sentences[0])
114
- if fallback:
115
- triplets.append(fallback)
116
-
117
- return triplets
118
-
119
- @classmethod
120
- def _extract_single_sentence(cls, sentence: str) -> Optional[SemanticTriplet]:
121
- """Tek bir cümleyi mantıksal çizgeye dönüştürür."""
122
- # 1. Kullanıcının ESP32 + nRF24L01 + SPI + Toprak senaryosu için özel deterministik desen
123
- esp_match = re.search(
124
- r"([A-ZÇĞİÖŞÜa-zçğıöşü]+).*?(ESP32|Arduino|STM32|Raspberry).*?(nRF\w+|LoRa|BLE|OLED|Sensor).*?(SPI|I2C|UART|GPIO).*?(test etti|denedi|calistirdi|bağladı)",
125
- sentence,
126
- re.IGNORECASE
127
- )
128
- if esp_match:
129
- sub = esp_match.group(1).capitalize()
130
- dev1 = esp_match.group(2).upper()
131
- dev2 = esp_match.group(3)
132
- bus = esp_match.group(4).upper()
133
- act_raw = esp_match.group(5).lower()
134
- act = cls.ACTION_MAP.get(act_raw, "test_etti")
135
-
136
- # Bağlam tespiti (örn: laboratuvar)
137
- ctx = bus
138
- if re.search(r"laboratuvar|lab", sentence, re.IGNORECASE):
139
- ctx = f"{bus} | laboratuvar"
140
-
141
- return SemanticTriplet(
142
- subject=sub,
143
- predicate=act,
144
- object=f"{dev1} + {dev2}",
145
- context=ctx
146
- )
147
-
148
- # 2. Genel Cümle Analizi
149
- words = sentence.split()
150
- if not words:
151
- return None
152
-
153
- # İlk kelime genellikle özne kabul edilir
154
- subject = words[0]
155
- predicate = "iliskili"
156
- objects = []
157
- contexts = []
158
-
159
- # Yüklem ve nesne tespiti
160
- for w in words[1:]:
161
- w_clean = re.sub(r"[^\w]", "", w)
162
- w_lower = w_clean.lower()
163
-
164
- if w_lower in cls.STOPWORDS:
165
- continue
166
-
167
- # Yüklem mi?
168
- for act_key, act_val in cls.ACTION_MAP.items():
169
- if act_key in w_lower or w_lower.startswith(act_key[:4]):
170
- predicate = act_val
171
- break
172
- else:
173
- # Teknik terim / Port / Protokol bağlamı
174
- if re.match(r"^(SPI|I2C|UART|CAN|GPIO|USB|TCP|UDP|HTTP|REST|GRPC)$", w_clean, re.IGNORECASE):
175
- contexts.append(w_clean.upper())
176
- elif w_clean.lower() in ("laboratuvar", "lab", "donanım", "sunucu", "bulut"):
177
- contexts.append(w_clean.lower())
178
- else:
179
- if len(w_clean) > 1:
180
- objects.append(w_clean)
181
-
182
- obj_str = " + ".join(objects[:3]) if objects else "sistem"
183
- ctx_str = " | ".join(contexts) if contexts else ""
184
-
185
- return SemanticTriplet(
186
- subject=subject,
187
- predicate=predicate,
188
- object=obj_str,
189
- context=ctx_str
190
- )
191
-
192
- @classmethod
193
- def _fallback_triplet(cls, sentence: str) -> SemanticTriplet:
194
- """Basit fallback çıkarımı."""
195
- clean = [w for w in cls.clean_text(sentence).split() if w.lower() not in cls.STOPWORDS]
196
- if len(clean) >= 3:
197
- return SemanticTriplet(subject=clean[0], predicate=clean[-1], object=" ".join(clean[1:-1]))
198
- return SemanticTriplet(subject=clean[0] if clean else "Özne", predicate="islem", object="bilgi")
199
-
200
-
201
- class VectorQuantizedCodebook:
202
- """
203
- Katman B: Vektör Hashing ve Kuantizasyon Sözlüğü (VQ Codebook).
204
- Çizgeleri latent sözlük indekslerine (discrete codes) dönüştürür.
205
- Örn: (ESP32 + nRF24L01 | SPI) -> #8421
206
- """
207
-
208
- def __init__(self, seed_code: int = 8421):
209
- self._codebook: Dict[int, SemanticTriplet] = {}
210
- self._reverse_index: Dict[str, int] = {}
211
- self._counter: int = seed_code
212
-
213
- # Önceden kayıtlı referans kodlar (Donanım ve Laboratuvar Standart İndeksleri)
214
- self._seed_reference_codes()
215
-
216
- def _seed_reference_codes(self):
217
- """Kullanıcının talep ettiği #8421 nolu referans kodunu sözlüğe önceden bağlar."""
218
- ref_triplet = SemanticTriplet(
219
- subject="Toprak",
220
- predicate="test_etti",
221
- object="ESP32 + nRF24L01",
222
- context="SPI | laboratuvar"
223
- )
224
- self.register_triplet_with_code(8421, ref_triplet)
225
-
226
- def _compute_signature(self, triplet: SemanticTriplet) -> str:
227
- """Çizgenin normalleştirilmiş anlamsal imzasını üretir."""
228
- norm_subj = triplet.subject.strip().lower()
229
- norm_pred = triplet.predicate.strip().lower()
230
- norm_obj = triplet.object.strip().lower()
231
- norm_ctx = triplet.context.strip().lower()
232
- return f"{norm_subj}::{norm_pred}::{norm_obj}::{norm_ctx}"
233
-
234
- def register_triplet(self, triplet: SemanticTriplet) -> int:
235
- """Çizgeyi sözlüğe kaydeder ve tamsayı kodunu (#CODE) döner."""
236
- sig = self._compute_signature(triplet)
237
- if sig in self._reverse_index:
238
- return self._reverse_index[sig]
239
-
240
- # 16-bit aralığında deterministik LSH / Hash tabanlı kuantizasyon
241
- h = hashlib.sha256(sig.encode("utf-8")).hexdigest()
242
- code_id = (int(h[:6], 16) % 80000) + 1000
243
-
244
- # Çakışma kontrolü
245
- while code_id in self._codebook and self._compute_signature(self._codebook[code_id]) != sig:
246
- code_id += 1
247
-
248
- self._codebook[code_id] = triplet
249
- self._reverse_index[sig] = code_id
250
- return code_id
251
-
252
- def register_triplet_with_code(self, code_id: int, triplet: SemanticTriplet):
253
- """Belirli bir kodu doğrudan bir çizgeye atar."""
254
- sig = self._compute_signature(triplet)
255
- self._codebook[code_id] = triplet
256
- self._reverse_index[sig] = code_id
257
-
258
- def lookup(self, code_id: int) -> Optional[SemanticTriplet]:
259
- """Sözlükten koda karşılık gelen anlamsal çizgeyi döner."""
260
- return self._codebook.get(code_id)
261
-
262
- def size(self) -> int:
263
- """Sözlükteki aktif kod sayısını döner."""
264
- return len(self._codebook)
265
-
266
-
267
- class DynamicVirtualMemoryInjector:
268
- """
269
- Katman C: Dinamik Çözücü & Soft-Prompt / Virtual KV-Cache Enjeksiyonu.
270
- Kodu doğrudan dikkat katmanına sanal bellek durumu (<|tzero:mem:CODE|>) olarak enjekte eder.
271
- """
272
-
273
- def __init__(self, codebook: Optional[VectorQuantizedCodebook] = None):
274
- self.codebook = codebook or VectorQuantizedCodebook()
275
-
276
- def compress_text_to_virtual_tokens(self, text: str) -> Dict[str, Any]:
277
- """
278
- Doğal dil metnini alır, A+B+C katmanlarından geçirir ve
279
- ultra-sıkıştırılmış sanal token çıktısını ve tasarruf metriklerini döner.
280
- """
281
- # 1. Katman A: Anlamsal Çekirdek Çıkarımı
282
- triplets = SemanticTripletExtractor.extract_triplets(text)
283
-
284
- # Orijinal token sayısını yaklaşık hesapla (1 kelime ~ 1.3 token)
285
- raw_words = text.split()
286
- original_token_count = max(1, int(len(raw_words) * 1.3))
287
-
288
- # 2. Katman B: VQ Codebook'a eşleme
289
- code_ids = []
290
- graph_strings = []
291
- virtual_tokens = []
292
-
293
- for trip in triplets:
294
- code_id = self.codebook.register_triplet(trip)
295
- code_ids.append(code_id)
296
- graph_strings.append(trip.to_graph_string())
297
- virtual_tokens.append(f"<|tzero:mem:{code_id}|>")
298
-
299
- # 3. Katman C: Sanal Token Boyutu
300
- # Her sanal token Attention katmanında tam olarak 1 sanal indeks kaplar!
301
- compressed_token_count = max(1, len(virtual_tokens))
302
-
303
- token_savings = max(0, original_token_count - compressed_token_count)
304
- reduction_ratio_pct = round((token_savings / original_token_count) * 100.0, 2)
305
-
306
- return {
307
- "original_text": text,
308
- "original_token_count": original_token_count,
309
- "triplets": [t.to_dict() for t in triplets],
310
- "graph_representations": graph_strings,
311
- "codebook_ids": code_ids,
312
- "virtual_tokens": virtual_tokens,
313
- "virtual_token_string": " ".join(virtual_tokens),
314
- "compressed_token_count": compressed_token_count,
315
- "token_savings": token_savings,
316
- "reduction_ratio_pct": reduction_ratio_pct,
317
- "layer_breakdown": {
318
- "layer_a_semantic_triplets": graph_strings,
319
- "layer_b_vq_codes": [f"#{cid}" for cid in code_ids],
320
- "layer_c_virtual_injection": " ".join(virtual_tokens)
321
- }
322
- }
323
-
324
- def decode_virtual_token(self, token_or_code: Union[str, int]) -> Optional[Dict[str, Any]]:
325
- """
326
- Sanal token'ı veya discrete kodu anlamsal çizgeye ve insanca okunabilir özete dönüştürür.
327
- """
328
- code_id = None
329
- if isinstance(token_or_code, int):
330
- code_id = token_or_code
331
- elif isinstance(token_or_code, str):
332
- # <|tzero:mem:8421|> veya #8421 veya 8421 formatlarını yakala
333
- m = re.search(r"(\d+)", token_or_code)
334
- if m:
335
- code_id = int(m.group(1))
336
-
337
- if code_id is None:
338
- return None
339
-
340
- triplet = self.codebook.lookup(code_id)
341
- if not triplet:
342
- return None
343
-
344
- return {
345
- "code_id": code_id,
346
- "virtual_token": f"<|tzero:mem:{code_id}|>",
347
- "graph_representation": triplet.to_graph_string(),
348
- "triplet": triplet.to_dict(),
349
- "reconstructed_summary": f"{triplet.subject}, {triplet.object} donanımını {triplet.context} ortamında {triplet.predicate}."
350
- }
351
-
352
- def build_soft_prompt_prefix(self, virtual_tokens: List[str]) -> str:
353
- """
354
- LLM dikkat katmanını tek hamlede prime eden T-Zero Sanal Bellek Öneki üretir.
355
- """
356
- decoded_context = []
357
- for vt in virtual_tokens:
358
- info = self.decode_virtual_token(vt)
359
- if info:
360
- decoded_context.append(f"• {info['virtual_token']} => {info['graph_representation']}")
361
-
362
- return (
363
- "[T-ZERO HIGH-DENSITY VIRTUAL MEMORY STATE]\n"
364
- + "\n".join(decoded_context)
365
- + "\n[ATTENTION PRIMING COMPLETE - ZERO TOKEN OVERHEAD]\n"
366
- )
367
-
368
-
369
- # Singleton Global Compressor Örneği
370
- _global_compressor = DynamicVirtualMemoryInjector()
371
-
372
- def get_global_compressor() -> DynamicVirtualMemoryInjector:
373
- return _global_compressor
package/src/tzero_fix.py DELETED
@@ -1,228 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Siber Akademi — T-Zero Self-Healing AST Hallucination Auto-Corrector.
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- License: MIT
6
-
7
- Statically inspects candidate code against verified workspace AST symbol tables.
8
- Detects phantom imports, misspelled identifiers, and hallucinated method calls,
9
- and automatically rewrites the AST to the correct valid local identifier.
10
- """
11
-
12
- import os
13
- import sys
14
- import ast
15
- import difflib
16
- from dataclasses import dataclass, field
17
- from typing import Dict, List, Set, Any, Optional, Tuple
18
-
19
-
20
- @dataclass
21
- class HealingAction:
22
- original_symbol: str
23
- healed_symbol: str
24
- symbol_type: str # "import", "method_call", "function_call"
25
- line_number: int
26
- confidence: float
27
- context_hint: str = ""
28
-
29
-
30
- @dataclass
31
- class HealingReport:
32
- success: bool
33
- original_code: str
34
- healed_code: str
35
- total_fixes: int
36
- actions: List[HealingAction] = field(default_factory=list)
37
- diff: str = ""
38
-
39
-
40
- class _ASTHealerTransformer(ast.NodeTransformer):
41
- def __init__(self, known_functions: Set[str], known_imports: Set[str], known_methods: Set[str]):
42
- super().__init__()
43
- self.known_functions = known_functions
44
- self.known_imports = known_imports
45
- self.known_methods = known_methods
46
- self.actions: List[HealingAction] = []
47
-
48
- def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.AST:
49
- # Check imported names against known symbols
50
- new_names = []
51
- for alias in node.names:
52
- name = alias.name
53
- if self.known_imports and name not in self.known_imports:
54
- matches = difflib.get_close_matches(name, list(self.known_imports), n=1, cutoff=0.65)
55
- if matches:
56
- best = matches[0]
57
- ratio = difflib.SequenceMatcher(None, name, best).ratio()
58
- self.actions.append(HealingAction(
59
- original_symbol=name,
60
- healed_symbol=best,
61
- symbol_type="import",
62
- line_number=getattr(node, "lineno", 1),
63
- confidence=round(ratio, 2),
64
- context_hint=f"Module: {node.module or ''}"
65
- ))
66
- new_names.append(ast.alias(name=best, asname=alias.asname))
67
- continue
68
- new_names.append(alias)
69
- node.names = new_names
70
- return node
71
-
72
- def visit_Call(self, node: ast.Call) -> ast.AST:
73
- self.generic_visit(node)
74
- # Check attribute calls (e.g. obj.calc_cost())
75
- if isinstance(node.func, ast.Attribute):
76
- attr_name = node.func.attr
77
- if self.known_methods and attr_name not in self.known_methods:
78
- matches = difflib.get_close_matches(attr_name, list(self.known_methods), n=1, cutoff=0.65)
79
- if matches:
80
- best = matches[0]
81
- ratio = difflib.SequenceMatcher(None, attr_name, best).ratio()
82
- self.actions.append(HealingAction(
83
- original_symbol=attr_name,
84
- healed_symbol=best,
85
- symbol_type="method_call",
86
- line_number=getattr(node, "lineno", 1),
87
- confidence=round(ratio, 2)
88
- ))
89
- node.func.attr = best
90
- # Check standalone function calls (e.g. calculate_tokens())
91
- elif isinstance(node.func, ast.Name):
92
- func_name = node.func.id
93
- if self.known_functions and func_name not in self.known_functions:
94
- matches = difflib.get_close_matches(func_name, list(self.known_functions), n=1, cutoff=0.70)
95
- if matches:
96
- best = matches[0]
97
- ratio = difflib.SequenceMatcher(None, func_name, best).ratio()
98
- self.actions.append(HealingAction(
99
- original_symbol=func_name,
100
- healed_symbol=best,
101
- symbol_type="function_call",
102
- line_number=getattr(node, "lineno", 1),
103
- confidence=round(ratio, 2)
104
- ))
105
- node.func.id = best
106
- return node
107
-
108
-
109
- class ASTHallucinationAutoCorrector:
110
- """Self-healing engine to detect and repair hallucinated AI symbols."""
111
-
112
- SKIP_DIRS = {
113
- ".git", "__pycache__", ".pytest_cache", "target", "dist",
114
- "build", ".venv", "venv", "node_modules", ".superpowers", "bin"
115
- }
116
-
117
- @classmethod
118
- def collect_workspace_symbols(cls, workspace_dir: str) -> Tuple[Set[str], Set[str], Set[str]]:
119
- """Collects all real functions, imports, and methods defined across workspace."""
120
- functions: Set[str] = set()
121
- imports: Set[str] = set()
122
- methods: Set[str] = set()
123
-
124
- abs_root = os.path.abspath(workspace_dir)
125
- for root, dirs, fnames in os.walk(abs_root):
126
- dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
127
- for fname in fnames:
128
- if fname.endswith(".py"):
129
- fpath = os.path.join(root, fname)
130
- try:
131
- with open(fpath, "r", encoding="utf-8", errors="replace") as f:
132
- tree = ast.parse(f.read(), filename=fname)
133
- for node in ast.walk(tree):
134
- if isinstance(node, ast.ClassDef):
135
- for item in node.body:
136
- if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
137
- methods.add(item.name)
138
- elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
139
- functions.add(node.name)
140
- imports.add(node.name)
141
- elif isinstance(node, ast.ClassDef):
142
- imports.add(node.name)
143
- except Exception:
144
- pass
145
-
146
- return functions, imports, methods
147
-
148
- @classmethod
149
- def heal_code(cls, code: str, workspace_dir: str = ".") -> HealingReport:
150
- """Parses candidate code, fixes hallucinated symbols, and returns report."""
151
- try:
152
- tree = ast.parse(code)
153
- except SyntaxError as e:
154
- return HealingReport(
155
- success=False,
156
- original_code=code,
157
- healed_code=code,
158
- total_fixes=0,
159
- diff=f"SyntaxError in code: {e}"
160
- )
161
-
162
- known_funcs, known_imports, known_methods = cls.collect_workspace_symbols(workspace_dir)
163
- transformer = _ASTHealerTransformer(known_funcs, known_imports, known_methods)
164
- healed_tree = transformer.visit(tree)
165
- ast.fix_missing_locations(healed_tree)
166
-
167
- try:
168
- healed_code = ast.unparse(healed_tree)
169
- except Exception:
170
- healed_code = code
171
-
172
- # Generate diff
173
- orig_lines = code.splitlines(keepends=True)
174
- healed_lines = healed_code.splitlines(keepends=True)
175
- diff_lines = list(difflib.unified_diff(
176
- orig_lines, healed_lines, fromfile="candidate.py (ai_generated)", tofile="healed.py (ast_corrected)"
177
- ))
178
- diff_str = "".join(diff_lines)
179
-
180
- return HealingReport(
181
- success=True,
182
- original_code=code,
183
- healed_code=healed_code,
184
- total_fixes=len(transformer.actions),
185
- actions=transformer.actions,
186
- diff=diff_str
187
- )
188
-
189
- @classmethod
190
- def heal_file(cls, file_path: str, workspace_dir: str = ".", apply_write: bool = False) -> HealingReport:
191
- """Reads file, applies healing, optionally overwrites if apply_write is True."""
192
- with open(file_path, "r", encoding="utf-8", errors="replace") as f:
193
- code = f.read()
194
-
195
- report = cls.heal_code(code, workspace_dir=workspace_dir)
196
- if apply_write and report.total_fixes > 0:
197
- with open(file_path, "w", encoding="utf-8") as f:
198
- f.write(report.healed_code)
199
-
200
- return report
201
-
202
- @classmethod
203
- def render_cli(cls, rep: HealingReport, target_hint: str = ""):
204
- print("\n🔧 \033[1mT-ZERO SELF-HEALING AST AUTO-CORRECTOR\033[0m")
205
- print("=" * 70)
206
- if target_hint:
207
- print(f"🎯 Target File: {target_hint}")
208
- print(f"📊 Auto-Repaired Hallucinations: \033[1m{rep.total_fixes}\033[0m")
209
-
210
- if rep.actions:
211
- print("\n📋 Detected & Repaired Symbols:")
212
- for a in rep.actions:
213
- conf_pct = int(a.confidence * 100)
214
- print(f" • Line {a.line_number} [{a.symbol_type}]: \033[31m{a.original_symbol}\033[0m ➔ \033[32m{a.healed_symbol}\033[0m (Confidence: {conf_pct}%)")
215
-
216
- if rep.diff:
217
- print("\n🔍 AST Unified Diff:")
218
- for line in rep.diff.splitlines()[:20]:
219
- if line.startswith("+"):
220
- print(f"\033[32m{line}\033[0m")
221
- elif line.startswith("-"):
222
- print(f"\033[31m{line}\033[0m")
223
- else:
224
- print(line)
225
- else:
226
- print("\033[32m✅ Flawless Code: 0 hallucinated symbols detected! AST matches workspace.\033[0m")
227
- print("=" * 70)
228
-