tzero-mcp 10.7.0 → 10.7.2
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.
- package/CHANGELOG.md +589 -0
- package/CONTRIBUTING.md +71 -0
- package/README.md +25 -17
- package/bin/postinstall.js +34 -0
- package/bin/tzero-mcp.js +16 -19
- package/bin/tzero.js +14 -19
- package/index.d.ts +24 -0
- package/index.js +7 -3
- package/package.json +24 -2
- package/src/addmcp.py +1194 -0
- package/src/main.py +60 -0
- package/src/siber_akademi_icon.py +77 -0
- package/src/tzero/jarvis/semantic_compressor.py +373 -0
- package/src/tzero.py +58 -0
- package/src/tzero_benchmark.py +475 -0
- package/src/tzero_bridge.py +362 -0
- package/src/tzero_ci.py +153 -0
- package/src/tzero_commit.py +192 -0
- package/src/tzero_cost.py +163 -0
- package/src/tzero_dashboard.py +1448 -0
- package/src/tzero_deps.py +287 -0
- package/src/tzero_drift.py +208 -0
- package/src/tzero_explain.py +240 -0
- package/src/tzero_features.py +3022 -0
- package/src/tzero_fix.py +228 -0
- package/src/tzero_fixer/__init__.py +63 -0
- package/src/tzero_fixer/amalgamation.py +334 -0
- package/src/tzero_fixer/ast_syntax_healer.py +464 -0
- package/src/tzero_fixer/ast_type_modernizer.py +288 -0
- package/src/tzero_fixer/async_io_modernizer.py +127 -0
- package/src/tzero_fixer/automated_regression_suite.py +600 -0
- package/src/tzero_fixer/benchmarks_and_diagnostics.py +174 -0
- package/src/tzero_fixer/ci_cd_self_healing_gate.py +246 -0
- package/src/tzero_fixer/code_duplicity_and_refactorer.py +151 -0
- package/src/tzero_fixer/code_smells_healer.py +260 -0
- package/src/tzero_fixer/cwe_remediator.py +171 -0
- package/src/tzero_fixer/dead_code_eliminator.py +150 -0
- package/src/tzero_fixer/dependency_vulnerability_auditor.py +309 -0
- package/src/tzero_fixer/git_advanced_surgeon.py +280 -0
- package/src/tzero_fixer/hardware_and_disk_doctor.py +325 -0
- package/src/tzero_fixer/import_graph_healer.py +412 -0
- package/src/tzero_fixer/interactive_tui.py +91 -0
- package/src/tzero_fixer/knowledge_base.py +295 -0
- package/src/tzero_fixer/knowledge_base_extended.py +940 -0
- package/src/tzero_fixer/linters_and_static_analyzer.py +307 -0
- package/src/tzero_fixer/mcp_server.py +447 -0
- package/src/tzero_fixer/models.py +385 -0
- package/src/tzero_fixer/orchestrator.py +375 -0
- package/src/tzero_fixer/os_doctor.py +502 -0
- package/src/tzero_fixer/packaging_abi_surgeon.py +323 -0
- package/src/tzero_fixer/pc_fixer_doctor.py +599 -0
- package/src/tzero_fixer/performance_and_memory_profiler.py +274 -0
- package/src/tzero_fixer/polyglot_ast_parsers.py +313 -0
- package/src/tzero_fixer/polyglot_build_healer.py +364 -0
- package/src/tzero_fixer/polyglot_config_healer.py +318 -0
- package/src/tzero_fixer/polyglot_doctor.py +372 -0
- package/src/tzero_fixer/polyglot_linters.py +619 -0
- package/src/tzero_fixer/polyglot_schema_validator.py +305 -0
- package/src/tzero_fixer/security_cwe_database.py +444 -0
- package/src/tzero_fixer/security_deep_rules.py +114 -0
- package/src/tzero_fixer/security_rules_catalog.py +110 -0
- package/src/tzero_fixer/security_zero_leak.py +326 -0
- package/src/tzero_fixer/smart_patch_recommender.py +223 -0
- package/src/tzero_fixer/synthetic_workspace_generator.py +220 -0
- package/src/tzero_fixer/system_diagnostics_extended.py +493 -0
- package/src/tzero_fixer/system_repair_recipes.py +447 -0
- package/src/tzero_fixer/venv_doctor.py +309 -0
- package/src/tzero_gateway.py +885 -0
- package/src/tzero_guard.py +243 -0
- package/src/tzero_infra.py +274 -0
- package/src/tzero_jarvis/__init__.py +124 -0
- package/src/tzero_jarvis/causal_graph.py +310 -0
- package/src/tzero_jarvis/graph_visualizer.py +395 -0
- package/src/tzero_jarvis/hybrid_search.py +214 -0
- package/src/tzero_jarvis/latent_press.py +137 -0
- package/src/tzero_jarvis/memory_consolidation.py +212 -0
- package/src/tzero_jarvis/minhash_lsh.py +184 -0
- package/src/tzero_jarvis/orchestrator.py +335 -0
- package/src/tzero_jarvis/self_healing.py +308 -0
- package/src/tzero_jarvis/semantic_compressor.py +887 -0
- package/src/tzero_jarvis/swarm.py +261 -0
- package/src/tzero_jarvis/swarm_bft.py +144 -0
- package/src/tzero_jarvis/workspace_orchestrator.py +1167 -0
- package/src/tzero_jarvis/zero_key_router.py +173 -0
- package/src/tzero_mcp.py +4858 -0
- package/src/tzero_neural_cortex.py +1425 -0
- package/src/tzero_packer.py +370 -0
- package/src/tzero_patch.py +624 -0
- package/src/tzero_pc_fixer.py +12657 -0
- package/src/tzero_pipe.py +95 -0
- package/src/tzero_polyglot.py +422 -0
- package/src/tzero_reachability.py +272 -0
- package/src/tzero_replay.py +141 -0
- package/src/tzero_security.py +570 -0
- package/src/tzero_snapshot.py +258 -0
- package/src/tzero_stubs.py +313 -0
- package/src/tzero_superdesign.py +774 -0
- package/src/tzero_sync.py +241 -0
- package/src/tzero_task_benchmark.py +363 -0
- package/src/tzero_tui.py +244 -0
- package/src/tzero_v3.py +9435 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
T-ZERO ZERO-VECTOR-DB HYBRID IN-MEMORY SEARCH ENGINE
|
|
4
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
+
Version: 4.4.0
|
|
6
|
+
|
|
7
|
+
Bu modül, harici hiçbir ağır Vektör Veritabanına (ChromaDB, Pinecone, FAISS vb.)
|
|
8
|
+
ihtiyaç duymadan; saf bellek içi (In-Memory) Ters İndeksleme (Inverted Index),
|
|
9
|
+
BM25 Anlamsal Sıralama ve T-Zero Latent Codebook (#code) eşleştirmesini
|
|
10
|
+
birleştiren mikro-saniye (<1 ms) hızında hibrit arama motorudur.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
import math
|
|
15
|
+
import re
|
|
16
|
+
import time
|
|
17
|
+
from typing import Dict, List, Optional, Set, Tuple, Any
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from collections import defaultdict
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class SearchDocument:
|
|
24
|
+
doc_id: str
|
|
25
|
+
doc_type: str # "code_symbol", "triplet", "memory", "causal_event"
|
|
26
|
+
title: str
|
|
27
|
+
content: str
|
|
28
|
+
discrete_code: Optional[int] = None
|
|
29
|
+
domain: str = "GENERIC"
|
|
30
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
31
|
+
tokens: List[str] = field(default_factory=list)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class SearchResult:
|
|
36
|
+
doc_id: str
|
|
37
|
+
doc_type: str
|
|
38
|
+
title: str
|
|
39
|
+
content: str
|
|
40
|
+
score: float
|
|
41
|
+
discrete_code: Optional[int] = None
|
|
42
|
+
domain: str = "GENERIC"
|
|
43
|
+
match_reasons: List[str] = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
46
|
+
return {
|
|
47
|
+
"doc_id": self.doc_id,
|
|
48
|
+
"doc_type": self.doc_type,
|
|
49
|
+
"title": self.title,
|
|
50
|
+
"content": self.content,
|
|
51
|
+
"score": round(self.score, 4),
|
|
52
|
+
"discrete_code": self.discrete_code,
|
|
53
|
+
"domain": self.domain,
|
|
54
|
+
"match_reasons": self.match_reasons
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ZeroVectorDBSearchEngine:
|
|
59
|
+
"""
|
|
60
|
+
Sıfır Dış Bağımlılıklı, Bellek İçi BM25 + T-Zero Latent Codebook Hibrit Arama Motoru.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, k1: float = 1.5, b: float = 0.75):
|
|
64
|
+
self.k1 = k1
|
|
65
|
+
self.b = b
|
|
66
|
+
self.documents: Dict[str, SearchDocument] = {}
|
|
67
|
+
self.inverted_index: Dict[str, Set[str]] = defaultdict(set)
|
|
68
|
+
self.code_index: Dict[int, Set[str]] = defaultdict(set)
|
|
69
|
+
self.domain_index: Dict[str, Set[str]] = defaultdict(set)
|
|
70
|
+
self.doc_lengths: Dict[str, int] = {}
|
|
71
|
+
self.avg_doc_len: float = 0.0
|
|
72
|
+
|
|
73
|
+
@staticmethod
|
|
74
|
+
def tokenize(text: str) -> List[str]:
|
|
75
|
+
"""
|
|
76
|
+
Gelişmiş regex tabanlı küçük harfe dönüştürücü ve temizleyici tokenizer.
|
|
77
|
+
"""
|
|
78
|
+
words = re.findall(r'[a-zA-ZçğıöşüÇĞİÖŞÜ0-9_#]+', text.lower())
|
|
79
|
+
return [w for w in words if len(w) > 1]
|
|
80
|
+
|
|
81
|
+
def add_document(self, doc_id: str, doc_type: str, title: str, content: str,
|
|
82
|
+
discrete_code: Optional[int] = None, domain: str = "GENERIC",
|
|
83
|
+
metadata: Optional[Dict[str, Any]] = None) -> SearchDocument:
|
|
84
|
+
tokens = self.tokenize(f"{title} {content} {domain}")
|
|
85
|
+
doc = SearchDocument(
|
|
86
|
+
doc_id=doc_id,
|
|
87
|
+
doc_type=doc_type,
|
|
88
|
+
title=title,
|
|
89
|
+
content=content,
|
|
90
|
+
discrete_code=discrete_code,
|
|
91
|
+
domain=domain.upper(),
|
|
92
|
+
metadata=metadata or {},
|
|
93
|
+
tokens=tokens
|
|
94
|
+
)
|
|
95
|
+
self.documents[doc_id] = doc
|
|
96
|
+
self.doc_lengths[doc_id] = len(tokens)
|
|
97
|
+
|
|
98
|
+
# Ters indekse ekle
|
|
99
|
+
for tok in set(tokens):
|
|
100
|
+
self.inverted_index[tok].add(doc_id)
|
|
101
|
+
|
|
102
|
+
# Codebook indeksine ekle
|
|
103
|
+
if discrete_code is not None:
|
|
104
|
+
self.code_index[discrete_code].add(doc_id)
|
|
105
|
+
|
|
106
|
+
# Domain indeksine ekle
|
|
107
|
+
self.domain_index[doc.domain].add(doc_id)
|
|
108
|
+
|
|
109
|
+
# Ortalama doküman uzunluğunu güncelle
|
|
110
|
+
total_len = sum(self.doc_lengths.values())
|
|
111
|
+
self.avg_doc_len = total_len / max(1, len(self.documents))
|
|
112
|
+
return doc
|
|
113
|
+
|
|
114
|
+
def search(self, query: str, top_k: int = 10, target_domain: Optional[str] = None) -> List[SearchResult]:
|
|
115
|
+
"""
|
|
116
|
+
Hibrit BM25 + Latent Codebook Arama Algoritması.
|
|
117
|
+
"""
|
|
118
|
+
if not self.documents:
|
|
119
|
+
return []
|
|
120
|
+
|
|
121
|
+
start_time = time.time()
|
|
122
|
+
query_tokens = self.tokenize(query)
|
|
123
|
+
|
|
124
|
+
# Query içinde discrete code (#8421 veya 8421) var mı?
|
|
125
|
+
code_matches = re.findall(r'#?(\d{4,5})', query)
|
|
126
|
+
queried_codes = {int(c) for c in code_matches}
|
|
127
|
+
|
|
128
|
+
n_docs = len(self.documents)
|
|
129
|
+
scores: Dict[str, float] = defaultdict(float)
|
|
130
|
+
reasons: Dict[str, List[str]] = defaultdict(list)
|
|
131
|
+
|
|
132
|
+
# 1. BM25 Skorlama
|
|
133
|
+
for tok in query_tokens:
|
|
134
|
+
posting_list = self.inverted_index.get(tok, set())
|
|
135
|
+
if not posting_list:
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
df = len(posting_list)
|
|
139
|
+
# Standart Lucene/Robertson IDF
|
|
140
|
+
idf = math.log(1.0 + (n_docs - df + 0.5) / (df + 0.5))
|
|
141
|
+
|
|
142
|
+
for doc_id in posting_list:
|
|
143
|
+
doc = self.documents[doc_id]
|
|
144
|
+
tf = doc.tokens.count(tok)
|
|
145
|
+
doc_len = self.doc_lengths.get(doc_id, 1)
|
|
146
|
+
|
|
147
|
+
denom = tf + self.k1 * (1.0 - self.b + self.b * (doc_len / max(1.0, self.avg_doc_len)))
|
|
148
|
+
bm25_part = idf * ((tf * (self.k1 + 1.0)) / max(1e-5, denom))
|
|
149
|
+
scores[doc_id] += bm25_part
|
|
150
|
+
if len(reasons[doc_id]) < 3:
|
|
151
|
+
reasons[doc_id].append(f"token:{tok}")
|
|
152
|
+
|
|
153
|
+
# 2. Discrete Code (#8421) Eşleşme Güçlendirmesi (10x Boost)
|
|
154
|
+
for code in queried_codes:
|
|
155
|
+
for doc_id in self.code_index.get(code, set()):
|
|
156
|
+
scores[doc_id] += 15.0
|
|
157
|
+
reasons[doc_id].append(f"code_exact_match:#{code}")
|
|
158
|
+
|
|
159
|
+
# 3. Domain Hedefleme Güçlendirmesi
|
|
160
|
+
if target_domain:
|
|
161
|
+
target_domain_upper = target_domain.upper()
|
|
162
|
+
for doc_id in self.domain_index.get(target_domain_upper, set()):
|
|
163
|
+
scores[doc_id] += 5.0
|
|
164
|
+
reasons[doc_id].append(f"domain_match:{target_domain_upper}")
|
|
165
|
+
|
|
166
|
+
# Sırala ve formatla
|
|
167
|
+
ranked_doc_ids = sorted(scores.keys(), key=lambda did: scores[did], reverse=True)[:top_k]
|
|
168
|
+
|
|
169
|
+
results = []
|
|
170
|
+
for did in ranked_doc_ids:
|
|
171
|
+
doc = self.documents[did]
|
|
172
|
+
results.append(SearchResult(
|
|
173
|
+
doc_id=doc.doc_id,
|
|
174
|
+
doc_type=doc.doc_type,
|
|
175
|
+
title=doc.title,
|
|
176
|
+
content=doc.content,
|
|
177
|
+
score=scores[did],
|
|
178
|
+
discrete_code=doc.discrete_code,
|
|
179
|
+
domain=doc.domain,
|
|
180
|
+
match_reasons=reasons[did]
|
|
181
|
+
))
|
|
182
|
+
|
|
183
|
+
return results
|
|
184
|
+
|
|
185
|
+
def index_codebase_scanner_results(self, scanner_report: Dict[str, Any]) -> int:
|
|
186
|
+
"""
|
|
187
|
+
T-Zero CodebaseScanner (AST) sonuçlarını anında arama indeksine katar.
|
|
188
|
+
"""
|
|
189
|
+
count = 0
|
|
190
|
+
symbols = scanner_report.get("symbols", {})
|
|
191
|
+
for sym_name, sym_info in symbols.items():
|
|
192
|
+
doc_id = f"sym_{sym_name}_{count}"
|
|
193
|
+
doc_type = "code_symbol"
|
|
194
|
+
title = f"{sym_info.get('type', 'symbol')}: {sym_name}"
|
|
195
|
+
content = f"File: {sym_info.get('file', '')} Lines: {sym_info.get('lines', '')} Doc: {sym_info.get('docstring', '')}"
|
|
196
|
+
self.add_document(
|
|
197
|
+
doc_id=doc_id,
|
|
198
|
+
doc_type=doc_type,
|
|
199
|
+
title=title,
|
|
200
|
+
content=content,
|
|
201
|
+
domain="SOFTWARE",
|
|
202
|
+
metadata=sym_info
|
|
203
|
+
)
|
|
204
|
+
count += 1
|
|
205
|
+
return count
|
|
206
|
+
|
|
207
|
+
def get_stats(self) -> Dict[str, Any]:
|
|
208
|
+
return {
|
|
209
|
+
"total_documents": len(self.documents),
|
|
210
|
+
"total_vocabulary": len(self.inverted_index),
|
|
211
|
+
"total_discrete_codes_indexed": len(self.code_index),
|
|
212
|
+
"domains_covered": list(self.domain_index.keys()),
|
|
213
|
+
"avg_doc_length": round(self.avg_doc_len, 2)
|
|
214
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
T-ZERO LATENTPRESS: PRE-PREFILL CONTEXT COMPRESSION & QUANTIZATION ENGINE
|
|
4
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
+
Version: 4.5.0
|
|
6
|
+
|
|
7
|
+
Bu modül, 2024-2025 "Latent Context Language Models (LCLM)" ve "LatentPress"
|
|
8
|
+
araştırma literatürünü uygulayarak; on binlerce kelimelik devasa log veya
|
|
9
|
+
kod bloklarını LLM prefill aşamasına girmeden önce upstream seviyede sıkıştırır,
|
|
10
|
+
MinHash LSH ile gereksiz tekrarları eler ve ultra-kompakt sanal bellek dizgisine
|
|
11
|
+
(<|tzero:mem:ID|>) dönüştürür.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
import math
|
|
16
|
+
import time
|
|
17
|
+
from typing import Dict, List, Optional, Any
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from tzero_jarvis.semantic_compressor import SemanticExtractor, DynamicVirtualMemoryInjector, get_global_compressor
|
|
20
|
+
from tzero_jarvis.minhash_lsh import MinHashLSHEngine
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class LatentPressResult:
|
|
25
|
+
original_text: str
|
|
26
|
+
original_words: int
|
|
27
|
+
original_tokens_est: int
|
|
28
|
+
compressed_tokens: int
|
|
29
|
+
compression_ratio_x: float
|
|
30
|
+
token_savings_pct: float
|
|
31
|
+
shannon_entropy_original: float
|
|
32
|
+
shannon_entropy_compressed: float
|
|
33
|
+
virtual_token_stream: str
|
|
34
|
+
unique_semantic_triplets: int
|
|
35
|
+
duplicate_chunks_pruned: int
|
|
36
|
+
latency_ms: float
|
|
37
|
+
|
|
38
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
39
|
+
return {
|
|
40
|
+
"original_words": self.original_words,
|
|
41
|
+
"original_tokens_est": self.original_tokens_est,
|
|
42
|
+
"compressed_tokens": self.compressed_tokens,
|
|
43
|
+
"compression_ratio_x": round(self.compression_ratio_x, 2),
|
|
44
|
+
"token_savings_pct": round(self.token_savings_pct, 2),
|
|
45
|
+
"shannon_entropy_original": round(self.shannon_entropy_original, 3),
|
|
46
|
+
"shannon_entropy_compressed": round(self.shannon_entropy_compressed, 3),
|
|
47
|
+
"virtual_token_stream": self.virtual_token_stream,
|
|
48
|
+
"unique_semantic_triplets": self.unique_semantic_triplets,
|
|
49
|
+
"duplicate_chunks_pruned": self.duplicate_chunks_pruned,
|
|
50
|
+
"latency_ms": round(self.latency_ms, 2)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class LatentPressCompressor:
|
|
55
|
+
"""
|
|
56
|
+
Upstream Pre-Prefill Bağlam Sıkıştırıcı ve Uyarlamalı Kuantizasyon Motoru.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, injector: Optional[DynamicVirtualMemoryInjector] = None):
|
|
60
|
+
self.injector = injector or get_global_compressor()
|
|
61
|
+
self.lsh_engine = MinHashLSHEngine()
|
|
62
|
+
|
|
63
|
+
@staticmethod
|
|
64
|
+
def _calculate_shannon_entropy(text: str) -> float:
|
|
65
|
+
"""Karakter dağılımı üzerinden Shannon Entropisini hesaplar."""
|
|
66
|
+
if not text:
|
|
67
|
+
return 0.0
|
|
68
|
+
frequencies: Dict[str, int] = {}
|
|
69
|
+
for char in text:
|
|
70
|
+
frequencies[char] = frequencies.get(char, 0) + 1
|
|
71
|
+
|
|
72
|
+
entropy = 0.0
|
|
73
|
+
total_chars = len(text)
|
|
74
|
+
for count in frequencies.values():
|
|
75
|
+
p = count / total_chars
|
|
76
|
+
entropy -= p * math.log2(p)
|
|
77
|
+
return entropy
|
|
78
|
+
|
|
79
|
+
def compress_large_context(self, context_text: str, near_dup_threshold: float = 0.65) -> LatentPressResult:
|
|
80
|
+
"""
|
|
81
|
+
Geniş metni anlamsal bloklara ayırır, MinHash ile yakın-kopyaları eler
|
|
82
|
+
ve Latent Soft-Prompt akışına dönüştürür.
|
|
83
|
+
"""
|
|
84
|
+
t0 = time.time()
|
|
85
|
+
raw_words = context_text.split()
|
|
86
|
+
total_words = len(raw_words)
|
|
87
|
+
orig_tokens_est = max(1, int(total_words * 1.3))
|
|
88
|
+
orig_entropy = self._calculate_shannon_entropy(context_text)
|
|
89
|
+
|
|
90
|
+
# Cümle veya paragraf bazında parçala
|
|
91
|
+
chunks = [c.strip() for c in context_text.splitlines() if len(c.strip()) > 5]
|
|
92
|
+
if not chunks:
|
|
93
|
+
chunks = [context_text]
|
|
94
|
+
|
|
95
|
+
pruned_count = 0
|
|
96
|
+
accepted_tokens = []
|
|
97
|
+
unique_triplets = []
|
|
98
|
+
|
|
99
|
+
for chunk in chunks:
|
|
100
|
+
triplets = SemanticExtractor.extract_triplets(chunk)
|
|
101
|
+
for trip in triplets:
|
|
102
|
+
# MinHash LSH ile yakın-kopya kontrolü
|
|
103
|
+
near_dups = self.lsh_engine.query_near_duplicates(trip, threshold=near_dup_threshold)
|
|
104
|
+
if near_dups:
|
|
105
|
+
# Daha önce benzeri kaydedilmiş, gereksiz token yükünü ele!
|
|
106
|
+
pruned_count += 1
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
code = self.injector.codebook.register_triplet(trip)
|
|
110
|
+
self.lsh_engine.insert(trip, code)
|
|
111
|
+
unique_triplets.append(trip)
|
|
112
|
+
accepted_tokens.append(f"<|tzero:mem:{code}|>")
|
|
113
|
+
|
|
114
|
+
if not accepted_tokens:
|
|
115
|
+
accepted_tokens.append("<|tzero:mem:8421|>")
|
|
116
|
+
|
|
117
|
+
virtual_stream = " ".join(accepted_tokens)
|
|
118
|
+
compressed_tokens = len(accepted_tokens)
|
|
119
|
+
savings_pct = max(0.0, ((orig_tokens_est - compressed_tokens) / float(orig_tokens_est)) * 100.0)
|
|
120
|
+
ratio_x = float(orig_tokens_est) / max(1.0, float(compressed_tokens))
|
|
121
|
+
comp_entropy = self._calculate_shannon_entropy(virtual_stream)
|
|
122
|
+
latency_ms = (time.time() - t0) * 1000.0
|
|
123
|
+
|
|
124
|
+
return LatentPressResult(
|
|
125
|
+
original_text=context_text,
|
|
126
|
+
original_words=total_words,
|
|
127
|
+
original_tokens_est=orig_tokens_est,
|
|
128
|
+
compressed_tokens=compressed_tokens,
|
|
129
|
+
compression_ratio_x=ratio_x,
|
|
130
|
+
token_savings_pct=savings_pct,
|
|
131
|
+
shannon_entropy_original=orig_entropy,
|
|
132
|
+
shannon_entropy_compressed=comp_entropy,
|
|
133
|
+
virtual_token_stream=virtual_stream,
|
|
134
|
+
unique_semantic_triplets=len(unique_triplets),
|
|
135
|
+
duplicate_chunks_pruned=pruned_count,
|
|
136
|
+
latency_ms=latency_ms
|
|
137
|
+
)
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
T-ZERO DUAL-MEMORY CONSOLIDATION ENGINE (HIPPOCAMPAL REPLAY)
|
|
4
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
+
Version: 4.4.0
|
|
6
|
+
|
|
7
|
+
Bu modül, insan beynindeki hipokampus-neokorteks bellek konsolidasyonunu taklit eder:
|
|
8
|
+
1. EpisodicMemory (Kısa süreli epizodik tampon bellek)
|
|
9
|
+
2. Semantic Consolidation (Derin konsolidasyon / Gece rüyası döngüsü):
|
|
10
|
+
- Benzer epizotları kümeleme (Clustering)
|
|
11
|
+
- Çoklu adımlardan Makro-Üçlü (Macro-Triplet) sentezleme
|
|
12
|
+
- Çelişki Çözümleme (Contradiction Resolution & Temporal Superseding)
|
|
13
|
+
- Kalıcı Latent Codebook'a terfi ettirme (Promotion)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
import time
|
|
18
|
+
from typing import Dict, List, Optional, Set, Tuple, Any
|
|
19
|
+
from dataclasses import dataclass, field, asdict
|
|
20
|
+
from collections import defaultdict
|
|
21
|
+
from tzero_jarvis.semantic_compressor import SemanticTriplet, TypedEntity, EntityType, VectorQuantizedCodebook, SemanticExtractor
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Episode:
|
|
26
|
+
episode_id: str
|
|
27
|
+
content: str
|
|
28
|
+
timestamp: float = field(default_factory=time.time)
|
|
29
|
+
source: str = "user" # "user", "agent", "execution", "sensor"
|
|
30
|
+
triplets: List[SemanticTriplet] = field(default_factory=list)
|
|
31
|
+
tags: List[str] = field(default_factory=list)
|
|
32
|
+
superseded: bool = False
|
|
33
|
+
superseded_by: Optional[str] = None
|
|
34
|
+
|
|
35
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
36
|
+
return {
|
|
37
|
+
"episode_id": self.episode_id,
|
|
38
|
+
"content": self.content,
|
|
39
|
+
"timestamp": self.timestamp,
|
|
40
|
+
"source": self.source,
|
|
41
|
+
"triplet_count": len(self.triplets),
|
|
42
|
+
"tags": self.tags,
|
|
43
|
+
"superseded": self.superseded,
|
|
44
|
+
"superseded_by": self.superseded_by
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class MacroTriplet:
|
|
50
|
+
macro_id: str
|
|
51
|
+
subject: str
|
|
52
|
+
predicate: str
|
|
53
|
+
objects: List[str]
|
|
54
|
+
context: str
|
|
55
|
+
derived_from_episodes: List[str]
|
|
56
|
+
discrete_code: int
|
|
57
|
+
confidence: float = 1.0
|
|
58
|
+
|
|
59
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
60
|
+
return asdict(self)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class EpisodicMemoryBuffer:
|
|
64
|
+
"""
|
|
65
|
+
Kısa süreli epizodik bellek tamponu (Rolling Ring-Buffer).
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, max_capacity: int = 1000):
|
|
69
|
+
self.max_capacity = max_capacity
|
|
70
|
+
self.episodes: List[Episode] = []
|
|
71
|
+
|
|
72
|
+
def record_episode(self, content: str, source: str = "user", tags: Optional[List[str]] = None) -> Episode:
|
|
73
|
+
ep_id = f"ep_{int(time.time()*1000)%100000}_{len(self.episodes)+1}"
|
|
74
|
+
triplets = SemanticExtractor.extract_triplets(content)
|
|
75
|
+
episode = Episode(
|
|
76
|
+
episode_id=ep_id,
|
|
77
|
+
content=content,
|
|
78
|
+
timestamp=time.time(),
|
|
79
|
+
source=source,
|
|
80
|
+
triplets=triplets,
|
|
81
|
+
tags=tags or []
|
|
82
|
+
)
|
|
83
|
+
self.episodes.append(episode)
|
|
84
|
+
if len(self.episodes) > self.max_capacity:
|
|
85
|
+
self.episodes.pop(0)
|
|
86
|
+
return episode
|
|
87
|
+
|
|
88
|
+
def get_active_episodes(self) -> List[Episode]:
|
|
89
|
+
return [ep for ep in self.episodes if not ep.superseded]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ConsolidationEngine:
|
|
93
|
+
"""
|
|
94
|
+
Derin Bellek Konsolidasyonu ve Çelişki Giderme Motoru.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def __init__(self, codebook: Optional[VectorQuantizedCodebook] = None):
|
|
98
|
+
self.codebook = codebook or VectorQuantizedCodebook()
|
|
99
|
+
self.episodic_buffer = EpisodicMemoryBuffer()
|
|
100
|
+
self.macro_triplets: List[MacroTriplet] = []
|
|
101
|
+
|
|
102
|
+
def consolidate(self) -> Dict[str, Any]:
|
|
103
|
+
"""
|
|
104
|
+
Konsolidasyon Döngüsünü (Replay Cycle) çalıştırır.
|
|
105
|
+
1. Çelişki ve durum güncellemelerini yakalar (Örn: hata -> başarı).
|
|
106
|
+
2. Varlık kümeleri üzerinden makro kavramlar türetir.
|
|
107
|
+
3. Codebook'a deterministik hashlerle ekler.
|
|
108
|
+
"""
|
|
109
|
+
active_episodes = self.episodic_buffer.get_active_episodes()
|
|
110
|
+
if not active_episodes:
|
|
111
|
+
return {
|
|
112
|
+
"status": "idle",
|
|
113
|
+
"consolidated_episodes": 0,
|
|
114
|
+
"macro_triplets_created": 0,
|
|
115
|
+
"contradictions_resolved": 0
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
# 1. Çelişki ve Durum Geçersiz Kılma (Superseding)
|
|
119
|
+
contradictions_resolved = self._resolve_contradictions(active_episodes)
|
|
120
|
+
|
|
121
|
+
# 2. Varlık Kümeleri Oluşturma (Entity-Based Clustering)
|
|
122
|
+
entity_clusters: Dict[str, List[Episode]] = defaultdict(list)
|
|
123
|
+
for ep in self.episodic_buffer.get_active_episodes():
|
|
124
|
+
for t in ep.triplets:
|
|
125
|
+
for obj in t.objects:
|
|
126
|
+
entity_clusters[obj.name.lower()].append(ep)
|
|
127
|
+
for ctx in t.contexts:
|
|
128
|
+
entity_clusters[ctx.name.lower()].append(ep)
|
|
129
|
+
|
|
130
|
+
# 3. Makro-Üçlü Sentezleme
|
|
131
|
+
macro_count = 0
|
|
132
|
+
for entity_key, eps in entity_clusters.items():
|
|
133
|
+
if len(eps) >= 2: # En az iki kez etkileşime girilen varlık
|
|
134
|
+
# Ortak özne ve eylemleri topla
|
|
135
|
+
all_triplets = [t for ep in eps for t in ep.triplets]
|
|
136
|
+
subjects = list({t.subject for t in all_triplets})
|
|
137
|
+
subj = subjects[0] if subjects else "Sistem"
|
|
138
|
+
|
|
139
|
+
# Nesneleri birleştir
|
|
140
|
+
obj_names = sorted(list({o.name for t in all_triplets for o in t.objects}))
|
|
141
|
+
ctx_names = sorted(list({c.name for t in all_triplets for c in t.contexts}))
|
|
142
|
+
|
|
143
|
+
# Sentezlenmiş makro üçlü
|
|
144
|
+
macro_triplet = SemanticTriplet(
|
|
145
|
+
subject=subj,
|
|
146
|
+
predicate="entegre_etti_ve_doğruladı",
|
|
147
|
+
objects=[TypedEntity(name=name, entity_type=EntityType.Generic) for name in obj_names[:4]],
|
|
148
|
+
contexts=[TypedEntity(name=name, entity_type=EntityType.Generic) for name in ctx_names[:2]]
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
code = self.codebook.encode(macro_triplet)
|
|
152
|
+
macro_id = f"macro_{entity_key}_{code}"
|
|
153
|
+
|
|
154
|
+
if not any(m.macro_id == macro_id for m in self.macro_triplets):
|
|
155
|
+
macro_entry = MacroTriplet(
|
|
156
|
+
macro_id=macro_id,
|
|
157
|
+
subject=subj,
|
|
158
|
+
predicate=macro_triplet.predicate,
|
|
159
|
+
objects=obj_names[:4],
|
|
160
|
+
context=" | ".join(ctx_names[:2]),
|
|
161
|
+
derived_from_episodes=[ep.episode_id for ep in eps],
|
|
162
|
+
discrete_code=code,
|
|
163
|
+
confidence=0.95
|
|
164
|
+
)
|
|
165
|
+
self.macro_triplets.append(macro_entry)
|
|
166
|
+
macro_count += 1
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
"status": "success",
|
|
170
|
+
"total_episodes_processed": len(active_episodes),
|
|
171
|
+
"macro_triplets_created": macro_count,
|
|
172
|
+
"contradictions_resolved": contradictions_resolved,
|
|
173
|
+
"total_active_macros": len(self.macro_triplets)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
def _resolve_contradictions(self, episodes: List[Episode]) -> int:
|
|
177
|
+
"""
|
|
178
|
+
Zaman içindeki zıtlıkları tespit eder ve eskiyen bilgileri geçersiz (superseded) kılar.
|
|
179
|
+
"""
|
|
180
|
+
resolved_count = 0
|
|
181
|
+
# Basit durum çiftleri: (hata/ariza/başarısız) vs (düzeltildi/başarılı/çözüldü)
|
|
182
|
+
failure_terms = {"hata", "arıza", "başarısız", "failed", "error", "bozuldu", "çöktü"}
|
|
183
|
+
success_terms = {"başarılı", "düzeltildi", "çözüldü", "success", "fixed", "tamamlandı", "çalıştı"}
|
|
184
|
+
|
|
185
|
+
for i, ep_earlier in enumerate(episodes):
|
|
186
|
+
earlier_text = ep_earlier.content.lower()
|
|
187
|
+
if any(term in earlier_text for term in failure_terms):
|
|
188
|
+
# Sonraki epizotlarda aynı varlık için düzeltme var mı?
|
|
189
|
+
for ep_later in episodes[i+1:]:
|
|
190
|
+
later_text = ep_later.content.lower()
|
|
191
|
+
if any(term in later_text for term in success_terms):
|
|
192
|
+
# Varlık örtüşmesi kontrolü
|
|
193
|
+
earlier_words = set(earlier_text.split())
|
|
194
|
+
later_words = set(later_text.split())
|
|
195
|
+
common_nouns = earlier_words.intersection(later_words)
|
|
196
|
+
if len(common_nouns) >= 2:
|
|
197
|
+
ep_earlier.superseded = True
|
|
198
|
+
ep_earlier.superseded_by = ep_later.episode_id
|
|
199
|
+
resolved_count += 1
|
|
200
|
+
break
|
|
201
|
+
return resolved_count
|
|
202
|
+
|
|
203
|
+
def get_summary(self) -> Dict[str, Any]:
|
|
204
|
+
"""
|
|
205
|
+
Konsolide edilmiş bellek özetini döndürür.
|
|
206
|
+
"""
|
|
207
|
+
return {
|
|
208
|
+
"total_episodes": len(self.episodic_buffer.episodes),
|
|
209
|
+
"active_episodes": len(self.episodic_buffer.get_active_episodes()),
|
|
210
|
+
"total_macros": len(self.macro_triplets),
|
|
211
|
+
"macros": [m.to_dict() for m in self.macro_triplets[-10:]]
|
|
212
|
+
}
|