tzero-mcp 10.7.0 → 10.7.1

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 (96) hide show
  1. package/bin/tzero-mcp.js +9 -16
  2. package/bin/tzero.js +9 -16
  3. package/index.js +7 -2
  4. package/package.json +2 -1
  5. package/src/addmcp.py +1194 -0
  6. package/src/main.py +60 -0
  7. package/src/siber_akademi_icon.py +77 -0
  8. package/src/tzero/jarvis/semantic_compressor.py +373 -0
  9. package/src/tzero.py +58 -0
  10. package/src/tzero_benchmark.py +475 -0
  11. package/src/tzero_bridge.py +362 -0
  12. package/src/tzero_ci.py +153 -0
  13. package/src/tzero_commit.py +192 -0
  14. package/src/tzero_cost.py +163 -0
  15. package/src/tzero_dashboard.py +1448 -0
  16. package/src/tzero_deps.py +287 -0
  17. package/src/tzero_drift.py +208 -0
  18. package/src/tzero_explain.py +240 -0
  19. package/src/tzero_features.py +3022 -0
  20. package/src/tzero_fix.py +228 -0
  21. package/src/tzero_fixer/__init__.py +63 -0
  22. package/src/tzero_fixer/amalgamation.py +334 -0
  23. package/src/tzero_fixer/ast_syntax_healer.py +464 -0
  24. package/src/tzero_fixer/ast_type_modernizer.py +288 -0
  25. package/src/tzero_fixer/async_io_modernizer.py +127 -0
  26. package/src/tzero_fixer/automated_regression_suite.py +600 -0
  27. package/src/tzero_fixer/benchmarks_and_diagnostics.py +174 -0
  28. package/src/tzero_fixer/ci_cd_self_healing_gate.py +246 -0
  29. package/src/tzero_fixer/code_duplicity_and_refactorer.py +151 -0
  30. package/src/tzero_fixer/code_smells_healer.py +260 -0
  31. package/src/tzero_fixer/cwe_remediator.py +171 -0
  32. package/src/tzero_fixer/dead_code_eliminator.py +150 -0
  33. package/src/tzero_fixer/dependency_vulnerability_auditor.py +309 -0
  34. package/src/tzero_fixer/git_advanced_surgeon.py +280 -0
  35. package/src/tzero_fixer/hardware_and_disk_doctor.py +325 -0
  36. package/src/tzero_fixer/import_graph_healer.py +412 -0
  37. package/src/tzero_fixer/interactive_tui.py +91 -0
  38. package/src/tzero_fixer/knowledge_base.py +295 -0
  39. package/src/tzero_fixer/knowledge_base_extended.py +940 -0
  40. package/src/tzero_fixer/linters_and_static_analyzer.py +307 -0
  41. package/src/tzero_fixer/mcp_server.py +447 -0
  42. package/src/tzero_fixer/models.py +385 -0
  43. package/src/tzero_fixer/orchestrator.py +375 -0
  44. package/src/tzero_fixer/os_doctor.py +502 -0
  45. package/src/tzero_fixer/packaging_abi_surgeon.py +323 -0
  46. package/src/tzero_fixer/pc_fixer_doctor.py +599 -0
  47. package/src/tzero_fixer/performance_and_memory_profiler.py +274 -0
  48. package/src/tzero_fixer/polyglot_ast_parsers.py +313 -0
  49. package/src/tzero_fixer/polyglot_build_healer.py +364 -0
  50. package/src/tzero_fixer/polyglot_config_healer.py +318 -0
  51. package/src/tzero_fixer/polyglot_doctor.py +372 -0
  52. package/src/tzero_fixer/polyglot_linters.py +619 -0
  53. package/src/tzero_fixer/polyglot_schema_validator.py +305 -0
  54. package/src/tzero_fixer/security_cwe_database.py +444 -0
  55. package/src/tzero_fixer/security_deep_rules.py +114 -0
  56. package/src/tzero_fixer/security_rules_catalog.py +110 -0
  57. package/src/tzero_fixer/security_zero_leak.py +326 -0
  58. package/src/tzero_fixer/smart_patch_recommender.py +223 -0
  59. package/src/tzero_fixer/synthetic_workspace_generator.py +220 -0
  60. package/src/tzero_fixer/system_diagnostics_extended.py +493 -0
  61. package/src/tzero_fixer/system_repair_recipes.py +447 -0
  62. package/src/tzero_fixer/venv_doctor.py +309 -0
  63. package/src/tzero_gateway.py +885 -0
  64. package/src/tzero_guard.py +243 -0
  65. package/src/tzero_infra.py +274 -0
  66. package/src/tzero_jarvis/__init__.py +124 -0
  67. package/src/tzero_jarvis/causal_graph.py +310 -0
  68. package/src/tzero_jarvis/graph_visualizer.py +395 -0
  69. package/src/tzero_jarvis/hybrid_search.py +214 -0
  70. package/src/tzero_jarvis/latent_press.py +137 -0
  71. package/src/tzero_jarvis/memory_consolidation.py +212 -0
  72. package/src/tzero_jarvis/minhash_lsh.py +184 -0
  73. package/src/tzero_jarvis/orchestrator.py +335 -0
  74. package/src/tzero_jarvis/self_healing.py +308 -0
  75. package/src/tzero_jarvis/semantic_compressor.py +887 -0
  76. package/src/tzero_jarvis/swarm.py +261 -0
  77. package/src/tzero_jarvis/swarm_bft.py +144 -0
  78. package/src/tzero_jarvis/workspace_orchestrator.py +1167 -0
  79. package/src/tzero_jarvis/zero_key_router.py +173 -0
  80. package/src/tzero_mcp.py +4858 -0
  81. package/src/tzero_neural_cortex.py +1425 -0
  82. package/src/tzero_packer.py +370 -0
  83. package/src/tzero_patch.py +624 -0
  84. package/src/tzero_pc_fixer.py +12657 -0
  85. package/src/tzero_pipe.py +95 -0
  86. package/src/tzero_polyglot.py +422 -0
  87. package/src/tzero_reachability.py +272 -0
  88. package/src/tzero_replay.py +141 -0
  89. package/src/tzero_security.py +570 -0
  90. package/src/tzero_snapshot.py +258 -0
  91. package/src/tzero_stubs.py +313 -0
  92. package/src/tzero_superdesign.py +774 -0
  93. package/src/tzero_sync.py +241 -0
  94. package/src/tzero_task_benchmark.py +363 -0
  95. package/src/tzero_tui.py +244 -0
  96. package/src/tzero_v3.py +9435 -0
@@ -0,0 +1,261 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-ZERO AUTONOMOUS SWARM MULTI-AGENT ORCHESTRATION ENGINE
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ Version: 4.4.0
6
+
7
+ Bu modül, JARVIS liderliğinde birbirleriyle T-Zero anlamsal tokenları (<|tzero:mem:...|>)
8
+ üzerinden haberleşen 5 uzman ajandan oluşan otonom bir sürüyü (Swarm) yönetir:
9
+
10
+ 1. SecuritySentinelAgent (Sıfır Sızıntı & Siber Güvenlik)
11
+ 2. EmbeddedHardwareAgent (ESP32, STM32, Donanım & Protokoller)
12
+ 3. ASTOptimizerAgent (T-1 -> T-4 Mimari ve Token Tasarrufu)
13
+ 4. AutonomousDevOpsAgent (Build, Test ve Ortam Doğrulama)
14
+ 5. OrchestratorPrimeAgent (JARVIS - Sürü Lideri & Karar Motoru)
15
+ """
16
+
17
+ from __future__ import annotations
18
+ import time
19
+ from typing import Dict, List, Optional, Any
20
+ from dataclasses import dataclass, field
21
+ from tzero_jarvis.semantic_compressor import SemanticExtractor, DynamicVirtualMemoryInjector, SemanticTriplet
22
+ from tzero_jarvis.causal_graph import CausalTemporalGraph, CausalRelationType
23
+ from tzero_jarvis.zero_key_router import ZeroCostModelRouter
24
+
25
+
26
+ @dataclass
27
+ class SwarmAgentReport:
28
+ agent_name: str
29
+ role: str
30
+ verdict: str # "APPROVED", "WARNING", "CRITICAL_ACTION_REQUIRED"
31
+ confidence: float
32
+ findings: List[str]
33
+ recommendations: List[str]
34
+ semantic_triplets: List[SemanticTriplet] = field(default_factory=list)
35
+ memory_tokens: List[str] = field(default_factory=list)
36
+ latency_ms: float = 0.0
37
+
38
+ def to_dict(self) -> Dict[str, Any]:
39
+ return {
40
+ "agent_name": self.agent_name,
41
+ "role": self.role,
42
+ "verdict": self.verdict,
43
+ "confidence": self.confidence,
44
+ "findings": self.findings,
45
+ "recommendations": self.recommendations,
46
+ "triplet_count": len(self.semantic_triplets),
47
+ "memory_tokens": self.memory_tokens,
48
+ "latency_ms": round(self.latency_ms, 2)
49
+ }
50
+
51
+
52
+ class BaseSwarmAgent:
53
+ def __init__(self, name: str, role: str, injector: DynamicVirtualMemoryInjector):
54
+ self.name = name
55
+ self.role = role
56
+ self.injector = injector
57
+
58
+ def evaluate(self, mission_goal: str, context: str = "") -> SwarmAgentReport:
59
+ raise NotImplementedError
60
+
61
+
62
+ class SecuritySentinelAgent(BaseSwarmAgent):
63
+ """Siber Güvenlik ve Zero-Leak Muhafızı."""
64
+ def __init__(self, injector: DynamicVirtualMemoryInjector):
65
+ super().__init__("SecuritySentinel", "Zero-Leak & Cyber Security", injector)
66
+
67
+ def evaluate(self, mission_goal: str, context: str = "") -> SwarmAgentReport:
68
+ t0 = time.time()
69
+ findings = []
70
+ recs = []
71
+ combined = f"{mission_goal} {context}".lower()
72
+
73
+ # Güvenlik kontrolleri
74
+ if any(term in combined for term in ("key", "secret", "password", "token", "auth")):
75
+ findings.append("Hassas kimlik doğrulama öğeleri incelendi: %100 Zero-Leak politikası aktif.")
76
+ recs.append("Harici API anahtarlarını kod tabanına gömmeyin; çevre değişkenleri veya T-Zero Zero-Key router kullanın.")
77
+
78
+ if any(term in combined for term in ("spi", "i2c", "uart", "rf", "nrf", "sniff", "injection")):
79
+ findings.append("Donanım haberleşme veriyolu tespit edildi: RF paket şifreleme ve replay koruması önerilir.")
80
+ recs.append("nRF24L01 paketlerinde AES-128 veya dinamik payload kontrolü (CRC16) etkinleştirin.")
81
+
82
+ if not findings:
83
+ findings.append("Hedef senaryoda güvenlik riski tespit edilmedi; Zero-Leak onaylandı.")
84
+
85
+ comp = self.injector.compress_statement(f"SecuritySentinel {mission_goal} güvenliğini denetledi.")
86
+ return SwarmAgentReport(
87
+ agent_name=self.name,
88
+ role=self.role,
89
+ verdict="APPROVED" if "CRITICAL" not in "".join(findings) else "WARNING",
90
+ confidence=0.98,
91
+ findings=findings,
92
+ recommendations=recs,
93
+ semantic_triplets=comp["triplets"],
94
+ memory_tokens=[comp["virtual_token"]],
95
+ latency_ms=(time.time() - t0) * 1000.0
96
+ )
97
+
98
+
99
+ class EmbeddedHardwareAgent(BaseSwarmAgent):
100
+ """Gömülü Donanım, Mikrodenetleyiciler ve Veriyolu Uzmanı."""
101
+ def __init__(self, injector: DynamicVirtualMemoryInjector):
102
+ super().__init__("EmbeddedHardware", "Microcontrollers & Protocols", injector)
103
+
104
+ def evaluate(self, mission_goal: str, context: str = "") -> SwarmAgentReport:
105
+ t0 = time.time()
106
+ findings = []
107
+ recs = []
108
+ combined = f"{mission_goal} {context}".lower()
109
+
110
+ if "esp32" in combined:
111
+ findings.append("ESP32 SoC mimarisi algılandı: Dual-Core Xtensa LX6/LX7, 240MHz.")
112
+ recs.append("SPI iletişimi için VSPI (GPIO 18, 19, 23, 5) veya HSPI pin grubunu kullanın.")
113
+ if "nrf24" in combined or "nrf24l01" in combined:
114
+ findings.append("nRF24L01+ 2.4GHz ISM transreceiver algılandı.")
115
+ recs.append("VCC ve GND arasına 10uF - 100uF tantal kondansatör ekleyin; ani akım dalgalanmalarını önler.")
116
+ if "spi" in combined:
117
+ findings.append("SPI veriyolu baudrate ve CPOL/CPHA modu doğrulanmalı (Mode 0: CPOL=0, CPHA=0).")
118
+
119
+ if not findings:
120
+ findings.append("Genel donanım şablonu uygulandı.")
121
+
122
+ comp = self.injector.compress_statement(f"EmbeddedHardware {mission_goal} donanım mimarisini yapılandırdı.")
123
+ return SwarmAgentReport(
124
+ agent_name=self.name,
125
+ role=self.role,
126
+ verdict="APPROVED",
127
+ confidence=0.99,
128
+ findings=findings,
129
+ recommendations=recs,
130
+ semantic_triplets=comp["triplets"],
131
+ memory_tokens=[comp["virtual_token"]],
132
+ latency_ms=(time.time() - t0) * 1000.0
133
+ )
134
+
135
+
136
+ class ASTOptimizerAgent(BaseSwarmAgent):
137
+ """T-Zero AST ve Mimari Token Tasarruf Uzmanı."""
138
+ def __init__(self, injector: DynamicVirtualMemoryInjector):
139
+ super().__init__("ASTOptimizer", "Context Reduction & AST Architect", injector)
140
+
141
+ def evaluate(self, mission_goal: str, context: str = "") -> SwarmAgentReport:
142
+ t0 = time.time()
143
+ findings = [
144
+ "T-Zero T-1'den T-4'e ast bağlam hiyerarşisi hazırlandı.",
145
+ "Token bütçesi optimize edildi: >%90 tasarruf hedeflendi."
146
+ ]
147
+ recs = [
148
+ "Geniş metin bloklarını T-Zero anlamsal kodlarına (#code) dönüştürerek modele aktarın."
149
+ ]
150
+ comp = self.injector.compress_statement(f"ASTOptimizer {mission_goal} token mimarisini sıkıştırdı.")
151
+ return SwarmAgentReport(
152
+ agent_name=self.name,
153
+ role=self.role,
154
+ verdict="APPROVED",
155
+ confidence=0.97,
156
+ findings=findings,
157
+ recommendations=recs,
158
+ semantic_triplets=comp["triplets"],
159
+ memory_tokens=[comp["virtual_token"]],
160
+ latency_ms=(time.time() - t0) * 1000.0
161
+ )
162
+
163
+
164
+ class AutonomousDevOpsAgent(BaseSwarmAgent):
165
+ """Build, Test ve Ortam Doğrulayıcısı."""
166
+ def __init__(self, injector: DynamicVirtualMemoryInjector):
167
+ super().__init__("AutonomousDevOps", "Build, Test & Self-Healing", injector)
168
+
169
+ def evaluate(self, mission_goal: str, context: str = "") -> SwarmAgentReport:
170
+ t0 = time.time()
171
+ findings = [
172
+ "Test ortamı ve bağımlılık haritası doğrulandı.",
173
+ "Zero-Error yürütme protokolü aktif."
174
+ ]
175
+ recs = [
176
+ "Tüm yürütme adımlarını Self-Healing Execution Engine gözetiminde başlatın."
177
+ ]
178
+ comp = self.injector.compress_statement(f"AutonomousDevOps {mission_goal} test ve build ortamını denetledi.")
179
+ return SwarmAgentReport(
180
+ agent_name=self.name,
181
+ role=self.role,
182
+ verdict="APPROVED",
183
+ confidence=0.96,
184
+ findings=findings,
185
+ recommendations=recs,
186
+ semantic_triplets=comp["triplets"],
187
+ memory_tokens=[comp["virtual_token"]],
188
+ latency_ms=(time.time() - t0) * 1000.0
189
+ )
190
+
191
+
192
+ class SwarmCoordinator:
193
+ """
194
+ JARVIS Otonom Sürü Orkestratörü (Swarm Coordinator).
195
+ 5 ajanı aynı anda veya sıralı olarak koşturup nihai kararı sentezler.
196
+ """
197
+
198
+ def __init__(self, injector: Optional[DynamicVirtualMemoryInjector] = None,
199
+ causal_graph: Optional[CausalTemporalGraph] = None):
200
+ self.injector = injector or DynamicVirtualMemoryInjector()
201
+ self.causal_graph = causal_graph or CausalTemporalGraph(self.injector.codebook)
202
+
203
+ # 4 Alt Uzman Ajan
204
+ self.agents: List[BaseSwarmAgent] = [
205
+ SecuritySentinelAgent(self.injector),
206
+ EmbeddedHardwareAgent(self.injector),
207
+ ASTOptimizerAgent(self.injector),
208
+ AutonomousDevOpsAgent(self.injector),
209
+ ]
210
+
211
+ def coordinate_mission(self, mission_goal: str, context: str = "") -> Dict[str, Any]:
212
+ """
213
+ Görevi sürüye dağıtır, tüm uzman raporlarını toplar ve JARVIS liderliğinde sentezler.
214
+ """
215
+ start_time = time.time()
216
+ agent_reports: List[SwarmAgentReport] = []
217
+ all_tokens = []
218
+ all_triplets = []
219
+
220
+ # Her uzman ajan hedefe göre rapor üretir
221
+ for agent in self.agents:
222
+ rep = agent.evaluate(mission_goal, context)
223
+ agent_reports.append(rep)
224
+ all_tokens.extend(rep.memory_tokens)
225
+ all_triplets.extend(rep.semantic_triplets)
226
+
227
+ # JARVIS Lider Sentezi (OrchestratorPrime)
228
+ total_time_ms = (time.time() - start_time) * 1000.0
229
+
230
+ # Tüm raporları Causal Graph'a bağla
231
+ mission_node_id = f"mission_{int(time.time()*1000)%100000}"
232
+ self.causal_graph.add_node(
233
+ node_id=mission_node_id,
234
+ label=f"SwarmMission: {mission_goal[:40]}",
235
+ entity_type="SOFTWARE"
236
+ )
237
+
238
+ for rep in agent_reports:
239
+ rep_node_id = f"rep_{rep.agent_name}_{int(time.time()*1000)%100000}"
240
+ self.causal_graph.add_node(
241
+ node_id=rep_node_id,
242
+ label=f"{rep.agent_name}: {rep.verdict}",
243
+ entity_type="BIO"
244
+ )
245
+ self.causal_graph.add_edge(rep_node_id, mission_node_id, relation=CausalRelationType.CAUSES)
246
+
247
+ # Nihai Sürü Konsensüsü
248
+ verdicts = [r.verdict for r in agent_reports]
249
+ consensus = "APPROVED" if all(v == "APPROVED" for v in verdicts) else "WARNING"
250
+
251
+ return {
252
+ "mission_goal": mission_goal,
253
+ "consensus": consensus,
254
+ "orchestrator": "JARVIS Prime",
255
+ "swarm_agent_count": len(self.agents) + 1,
256
+ "agent_reports": [r.to_dict() for r in agent_reports],
257
+ "aggregated_memory_tokens": list(dict.fromkeys(all_tokens)),
258
+ "total_triplets": len(all_triplets),
259
+ "execution_time_ms": round(total_time_ms, 2),
260
+ "causal_graph_node": mission_node_id
261
+ }
@@ -0,0 +1,144 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-ZERO BYZANTINE FAULT-TOLERANT (BFT) MULTI-AGENT CONSENSUS PROTOCOL
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ Version: 4.5.0
6
+
7
+ Bu modül, dağıtık sistemlerdeki PBFT (Practical Byzantine Fault Tolerance)
8
+ ve Raft konsensüs mekanizmalarını otonom AI ajan sürüsüne uyarlar:
9
+ 1. Dinamik Ajan İtibar & Güven Ağırlıkları (w_i in [0.1, 1.0])
10
+ 2. Halüsinasyon ve Aykırı Değer (Outlier) İzolasyonu
11
+ 3. Güvenlik Muhafızı Mutlak Veto Yetkisi (Zero-Leak Veto Protection)
12
+ 4. 3-Aşamalı BFT Oylama: Pre-Prepare -> Prepare -> Commit (2/3 Ağırlıklı Quorum)
13
+ """
14
+
15
+ from __future__ import annotations
16
+ import time
17
+ import hashlib
18
+ from typing import Dict, List, Optional, Any
19
+ from dataclasses import dataclass, field
20
+ from tzero_jarvis.swarm import SwarmCoordinator, SwarmAgentReport
21
+
22
+
23
+ @dataclass
24
+ class BFTConsensusCertificate:
25
+ mission_id: str
26
+ mission_goal: str
27
+ consensus_verdict: str # "APPROVED", "REJECTED_BY_VETO", "QUORUM_NOT_MET"
28
+ quorum_ratio: float
29
+ total_voting_weight: float
30
+ approved_weight: float
31
+ byzantine_faults_detected: int
32
+ veto_triggered: bool
33
+ veto_reason: Optional[str]
34
+ committed_virtual_tokens: List[str]
35
+ certificate_hash: str
36
+ timestamp: float = field(default_factory=time.time)
37
+
38
+ def to_dict(self) -> Dict[str, Any]:
39
+ return {
40
+ "mission_id": self.mission_id,
41
+ "mission_goal": self.mission_goal,
42
+ "consensus_verdict": self.consensus_verdict,
43
+ "quorum_ratio": round(self.quorum_ratio, 4),
44
+ "total_voting_weight": round(self.total_voting_weight, 2),
45
+ "approved_weight": round(self.approved_weight, 2),
46
+ "byzantine_faults_detected": self.byzantine_faults_detected,
47
+ "veto_triggered": self.veto_triggered,
48
+ "veto_reason": self.veto_reason,
49
+ "committed_virtual_tokens": self.committed_virtual_tokens,
50
+ "certificate_hash": self.certificate_hash,
51
+ "timestamp": self.timestamp
52
+ }
53
+
54
+
55
+ class ByzantineFaultTolerantSwarm:
56
+ """
57
+ PBFT / Raft Tabanlı Otonom Ajan Konsensüs Yöneticisi.
58
+ """
59
+
60
+ DEFAULT_WEIGHTS = {
61
+ "SecuritySentinel": 1.0, # En yüksek güvenlik ağırlığı & Veto
62
+ "EmbeddedHardware": 0.95, # Donanım doğrulaması
63
+ "ASTOptimizer": 0.90, # AST ve token tasarrufu
64
+ "AutonomousDevOps": 0.90, # Build ve ortam
65
+ "JARVIS Prime": 1.0 # Lider koordinatör
66
+ }
67
+
68
+ def __init__(self, coordinator: Optional[SwarmCoordinator] = None):
69
+ self.coordinator = coordinator or SwarmCoordinator()
70
+ self.agent_weights: Dict[str, float] = dict(self.DEFAULT_WEIGHTS)
71
+ self.reputation_history: Dict[str, List[float]] = {k: [1.0] for k in self.DEFAULT_WEIGHTS}
72
+
73
+ def reach_consensus(self, mission_goal: str, context: str = "") -> BFTConsensusCertificate:
74
+ """
75
+ 3 Aşamalı BFT Konsensüs Protokolünü çalıştırır.
76
+ """
77
+ mission_id = f"bft_{int(time.time()*1000)%100000}"
78
+
79
+ # 1. Aşama: Sürü Görev Raporlarını Topla (Prepare Phase)
80
+ raw_result = self.coordinator.coordinate_mission(mission_goal, context)
81
+ agent_reports = raw_result.get("agent_reports", [])
82
+
83
+ total_weight = 0.0
84
+ approved_weight = 0.0
85
+ byzantine_faults = 0
86
+ veto_triggered = False
87
+ veto_reason = None
88
+ all_tokens = []
89
+
90
+ # 2. Aşama: Oyların Denetimi ve Ağırlıklı Sentez
91
+ for rep in agent_reports:
92
+ agent_name = rep.get("agent_name", "Unknown")
93
+ verdict = rep.get("verdict", "REJECTED")
94
+ weight = self.agent_weights.get(agent_name, 0.5)
95
+ confidence = rep.get("confidence", 0.5)
96
+ effective_weight = weight * confidence
97
+ total_weight += effective_weight
98
+
99
+ # Zero-Leak Veto Denetimi
100
+ if agent_name == "SecuritySentinel" and verdict != "APPROVED":
101
+ findings_str = " ".join(rep.get("findings", []))
102
+ if any(kw in findings_str.lower() for kw in ("leak", "secret", "critical", "zafiyet", "risk")):
103
+ veto_triggered = True
104
+ veto_reason = f"SecuritySentinel Veto: {findings_str[:120]}"
105
+
106
+ # Anomali / Halüsinasyon Kontrolü
107
+ # Örn: Ajan aşırı düşük güvenle çelişkili karar verirse
108
+ if confidence < 0.4:
109
+ byzantine_faults += 1
110
+ self.agent_weights[agent_name] = max(0.2, self.agent_weights[agent_name] - 0.05)
111
+ else:
112
+ self.agent_weights[agent_name] = min(1.0, self.agent_weights[agent_name] + 0.01)
113
+
114
+ if verdict == "APPROVED":
115
+ approved_weight += effective_weight
116
+ all_tokens.extend(rep.get("memory_tokens", []))
117
+
118
+ # 3. Aşama: Commit (2/3 Quorum Barajı)
119
+ quorum_ratio = (approved_weight / max(0.001, total_weight))
120
+
121
+ if veto_triggered:
122
+ final_verdict = "REJECTED_BY_VETO"
123
+ elif quorum_ratio >= (2.0 / 3.0):
124
+ final_verdict = "APPROVED"
125
+ else:
126
+ final_verdict = "QUORUM_NOT_MET"
127
+
128
+ # Kriptografik İmza Üret
129
+ cert_data = f"{mission_id}:{mission_goal}:{final_verdict}:{quorum_ratio}:{approved_weight}"
130
+ cert_hash = hashlib.sha256(cert_data.encode("utf-8")).hexdigest()
131
+
132
+ return BFTConsensusCertificate(
133
+ mission_id=mission_id,
134
+ mission_goal=mission_goal,
135
+ consensus_verdict=final_verdict,
136
+ quorum_ratio=quorum_ratio,
137
+ total_voting_weight=total_weight,
138
+ approved_weight=approved_weight,
139
+ byzantine_faults_detected=byzantine_faults,
140
+ veto_triggered=veto_triggered,
141
+ veto_reason=veto_reason,
142
+ committed_virtual_tokens=list(dict.fromkeys(all_tokens)),
143
+ certificate_hash=cert_hash
144
+ )