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
@@ -1,244 +1,313 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Siber Akademi — T-Zero Terminal User Interface (TUI) & Live Cockpit.
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- License: MIT
6
-
7
- Pure standard-library ANSI terminal dashboard and interactive executive cockpit.
8
- Provides live workspace token metrics, AST compression meters, zero-leak security
9
- auditing, and instantaneous action triggers without any external GUI dependencies.
10
- """
11
-
12
- import sys
13
- if sys.platform == "win32":
14
- try:
15
- sys.stdout.reconfigure(encoding="utf-8")
16
- sys.stderr.reconfigure(encoding="utf-8")
17
- except Exception:
18
- pass
19
-
20
- import os
21
- import time
22
- from typing import Dict, List, Optional, Any, Tuple
23
-
24
- from tzero_features import should_skip_dir, should_skip_file
25
- from tzero_polyglot import PolyglotTokenReducer
26
-
27
-
28
- class TZeroTerminalCockpit:
29
- """Zero-dependency, high-density terminal dashboard and interactive cockpit."""
30
-
31
- # ANSI Palette
32
- CYAN = "\033[36m"
33
- BRIGHT_CYAN = "\033[96m"
34
- GREEN = "\033[32m"
35
- BRIGHT_GREEN = "\033[92m"
36
- YELLOW = "\033[33m"
37
- MAGENTA = "\033[35m"
38
- BLUE = "\033[34m"
39
- RED = "\033[31m"
40
- BOLD = "\033[1m"
41
- DIM = "\033[2m"
42
- RESET = "\033[0m"
43
-
44
- @classmethod
45
- def gather_workspace_metrics(cls, workspace_dir: str = ".") -> Dict[str, Any]:
46
- """Scans workspace and compiles metrics for the terminal cockpit."""
47
- abs_ws = os.path.abspath(workspace_dir)
48
- files_by_lang: Dict[str, int] = {}
49
- raw_tokens_total = 0
50
- pruned_tokens_total = 0
51
- file_count = 0
52
-
53
- reducer = PolyglotTokenReducer()
54
-
55
- for root, dirs, files in os.walk(abs_ws):
56
- dirs[:] = [d for d in dirs if not should_skip_dir(os.path.join(root, d), abs_ws)]
57
- for f in files:
58
- full_p = os.path.join(root, f)
59
- if should_skip_file(full_p, abs_ws):
60
- continue
61
- file_count += 1
62
- ext = os.path.splitext(f)[1].lower()
63
- lang = reducer.detect_language(full_p) or "Other"
64
- files_by_lang[lang] = files_by_lang.get(lang, 0) + 1
65
-
66
- # Sample quick token calculation on code files
67
- if file_count <= 250 and ext in (
68
- ".py", ".ts", ".js", ".rs", ".go", ".cpp", ".c", ".h",
69
- ".swift", ".kt", ".dart", ".rb", ".sol", ".scala", ".php"
70
- ):
71
- try:
72
- with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
73
- raw_code = fp.read()
74
- raw_t = max(1, len(raw_code) // 4)
75
- pruned_code, _ = reducer.reduce_code(raw_code, lang=lang, mode="ultra")
76
- pruned_t = max(1, len(pruned_code) // 4)
77
- raw_tokens_total += raw_t
78
- pruned_tokens_total += pruned_t
79
- except Exception:
80
- pass
81
-
82
- # Estimate savings if sample available, or default to standard 94.8%
83
- if raw_tokens_total > 0:
84
- savings_pct = max(0.0, (1.0 - (pruned_tokens_total / raw_tokens_total)) * 100.0)
85
- else:
86
- savings_pct = 94.8
87
- raw_tokens_total = file_count * 450
88
- pruned_tokens_total = int(raw_tokens_total * 0.052)
89
-
90
- # Monthly ROI savings calculation (assuming 50 queries/day at Claude 3.7 $3/1M input)
91
- daily_saved_tokens = (raw_tokens_total - pruned_tokens_total) * 50
92
- monthly_cost_saved = (daily_saved_tokens * 30 / 1_000_000) * 3.0
93
-
94
- return {
95
- "workspace_name": os.path.basename(abs_ws) or "Workspace",
96
- "workspace_dir": abs_ws,
97
- "total_files": file_count,
98
- "raw_tokens": raw_tokens_total,
99
- "pruned_tokens": pruned_tokens_total,
100
- "savings_pct": round(savings_pct, 1),
101
- "monthly_roi_saved": round(monthly_cost_saved, 2),
102
- "languages": files_by_lang,
103
- "zero_leak_status": "100% SECURE (VERIFIED)",
104
- }
105
-
106
- @classmethod
107
- def render_gauge(cls, percentage: float, width: int = 24) -> str:
108
- """Renders an ANSI progress bar gauge."""
109
- filled = int(width * (percentage / 100.0))
110
- empty = width - filled
111
- bar = f"{cls.BRIGHT_CYAN}{'█' * filled}{cls.DIM}{'░' * empty}{cls.RESET}"
112
- return f"[{bar}] {cls.BOLD}{percentage:.1f}%{cls.RESET}"
113
-
114
- @classmethod
115
- def render_cockpit(cls, metrics: Dict[str, Any]) -> str:
116
- """Constructs high-density ASCII / ANSI terminal cockpit screen."""
117
- c = cls
118
- lines = []
119
-
120
- box_top = f"{c.CYAN}╔══════════════════════════════════════════════════════════════════════════════╗{c.RESET}"
121
- box_mid = f"{c.CYAN}╠══════════════════════════════════════════════════════════════════════════════╣{c.RESET}"
122
- box_bottom = f"{c.CYAN}╚══════════════════════════════════════════════════════════════════════════════╝{c.RESET}"
123
-
124
- lines.append(box_top)
125
- lines.append(f"{c.CYAN}║{c.RESET} {c.BOLD}{c.BRIGHT_CYAN}⚡ SİBER AKADEMİ — T-ZERO CONTEXT ARCHITECT & LIVE COCKPIT v10.0.0{c.RESET} {c.CYAN}║{c.RESET}")
126
- lines.append(f"{c.CYAN}║{c.RESET} {c.DIM}Zero-Leak AST Intelligence | 100% Offline | $0 Cloud Cost Guarantee{c.RESET} {c.CYAN}║{c.RESET}")
127
- lines.append(box_mid)
128
-
129
- # Workspace summary line
130
- ws_name = metrics.get("workspace_name", "Workspace")[:20]
131
- files_cnt = metrics.get("total_files", 0)
132
- lines.append(f"{c.CYAN}║{c.RESET} 📁 {c.BOLD}Workspace:{c.RESET} {ws_name:<20} │ 📦 {c.BOLD}Files Tracked:{c.RESET} {files_cnt:<6} {c.CYAN}║{c.RESET}")
133
-
134
- # Metrics lines
135
- raw_t = metrics.get("raw_tokens", 0)
136
- pruned_t = metrics.get("pruned_tokens", 0)
137
- sav_pct = metrics.get("savings_pct", 94.8)
138
- roi = metrics.get("monthly_roi_saved", 0.0)
139
-
140
- gauge = cls.render_gauge(sav_pct, width=20)
141
- lines.append(f"{c.CYAN}║{c.RESET} 🗜️ {c.BOLD}AST Reduction:{c.RESET} {gauge:<38} {c.CYAN}║{c.RESET}")
142
- lines.append(f"{c.CYAN}║{c.RESET} 📊 {c.BOLD}Raw Tokens:{c.RESET} ~{raw_t:,} │ {c.BOLD}Pruned Tokens:{c.RESET} ~{pruned_t:,} {c.CYAN}║{c.RESET}")
143
- lines.append(f"{c.CYAN}║{c.RESET} 💰 {c.BOLD}Est. Monthly Team ROI Saved:{c.RESET} {c.BRIGHT_GREEN}${roi:,.2f}{c.RESET} / month (Claude 3.7 / GPT-4o) {c.CYAN}║{c.RESET}")
144
- lines.append(f"{c.CYAN}║{c.RESET} 🔒 {c.BOLD}Security Guard:{c.RESET} {c.BRIGHT_GREEN}100% ZERO-LEAK PASSED{c.RESET} (0 Exposed Credentials) {c.CYAN}║{c.RESET}")
145
- lines.append(box_mid)
146
-
147
- # Top languages line
148
- langs = metrics.get("languages", {})
149
- top_langs = sorted(langs.items(), key=lambda x: x[1], reverse=True)[:5]
150
- lang_str = " | ".join(f"{k}: {v}" for k, v in top_langs)
151
- lines.append(f"{c.CYAN}║{c.RESET} 🌐 {c.BOLD}Polyglot Stack:{c.RESET} {lang_str[:54]:<54} {c.CYAN}║{c.RESET}")
152
- lines.append(box_mid)
153
-
154
- # Interactive Command Menu
155
- lines.append(f"{c.CYAN}║{c.RESET} {c.BOLD}🚀 QUICK COMMAND DISPATCH:{c.RESET} {c.CYAN}║{c.RESET}")
156
- lines.append(f"{c.CYAN}║{c.RESET} [1] 🗜️ Pack Context Window (`tzero --pack 16000`) {c.CYAN}║{c.RESET}")
157
- lines.append(f"{c.CYAN}║{c.RESET} [2] 📑 Generate PEP-484 Type Stubs (`tzero --stubs`) {c.CYAN}║{c.RESET}")
158
- lines.append(f"{c.CYAN}║{c.RESET} [3] ✍️ Synthesize Conventional Commit (`tzero --commit-msg`) {c.CYAN}║{c.RESET}")
159
- lines.append(f"{c.CYAN}║{c.RESET} [4] 📜 Generate Release CHANGELOG (`tzero --changelog`) {c.CYAN}║{c.RESET}")
160
- lines.append(f"{c.CYAN}║{c.RESET} [5] 🛠️ Apply AST-Tolerant Patch (`tzero --patch <diff>`) {c.CYAN}║{c.RESET}")
161
- lines.append(f"{c.CYAN}║{c.RESET} [6] 🌐 Launch Web Comparison Dashboard (`tzero --web`) {c.CYAN}║{c.RESET}")
162
- lines.append(f"{c.CYAN}║{c.RESET} [7] 🛡️ Install Git Zero-Leak Guard & CI (`tzero --guard-install`) {c.CYAN}║{c.RESET}")
163
- lines.append(f"{c.CYAN}║{c.RESET} [0] 🚪 Exit TUI {c.CYAN}║{c.RESET}")
164
- lines.append(box_bottom)
165
-
166
- return "\n".join(lines)
167
-
168
- @classmethod
169
- def run_interactive(cls, workspace_dir: str = "."):
170
- """Runs the interactive loop in the user terminal."""
171
- while True:
172
- metrics = cls.gather_workspace_metrics(workspace_dir)
173
- screen = cls.render_cockpit(metrics)
174
- print("\033[H\033[J", end="") # Clear screen ANSI
175
- print(screen)
176
-
177
- try:
178
- choice = input(f"\n{cls.BOLD}Select an action [0-7] (or press Enter to refresh): {cls.RESET}").strip()
179
- except (KeyboardInterrupt, EOFError):
180
- print(f"\n{cls.CYAN}Goodbye! T-Zero Context Engine active.{cls.RESET}")
181
- break
182
-
183
- if choice == "0":
184
- print(f"\n{cls.CYAN}Exiting T-Zero Cockpit.{cls.RESET}")
185
- break
186
- elif choice == "1":
187
- from tzero_packer import pack_workspace
188
- print(f"\n{cls.YELLOW}[Running Context Packer (16,000 tokens)]...{cls.RESET}")
189
- res = pack_workspace(workspace_dir=workspace_dir, budget_tokens=16000)
190
- print(f"{cls.GREEN}[SUCCESS] Packed {res.total_tokens:,} tokens ({res.token_savings_pct:.1f}% reduction).{cls.RESET}")
191
- input("Press Enter to return to cockpit...")
192
- elif choice == "2":
193
- from tzero_stubs import TypeStubGenerator
194
- print(f"\n{cls.YELLOW}[Generating PEP-484 Type Stubs]...{cls.RESET}")
195
- res = TypeStubGenerator.generate_workspace_stubs(workspace_dir=workspace_dir)
196
- print(f"{cls.GREEN}[SUCCESS] Generated {res['total_files']} stubs ({res['overall_savings_pct']}% reduction).{cls.RESET}")
197
- input("Press Enter to return to cockpit...")
198
- elif choice == "3":
199
- from tzero_commit import LocalSemanticCommitSynthesizer
200
- print(f"\n{cls.YELLOW}[Synthesizing Offline Commit Message]...{cls.RESET}")
201
- msg = LocalSemanticCommitSynthesizer.generate_commit_message(repo_dir=workspace_dir, staged=True)
202
- print(f"\n{cls.BRIGHT_CYAN}{msg}{cls.RESET}\n")
203
- input("Press Enter to return to cockpit...")
204
- elif choice == "4":
205
- from tzero_commit import LocalSemanticCommitSynthesizer
206
- print(f"\n{cls.YELLOW}[Synthesizing Release CHANGELOG]...{cls.RESET}")
207
- entry = LocalSemanticCommitSynthesizer.generate_changelog_entry(version="v10.0.0", repo_dir=workspace_dir)
208
- print(f"\n{cls.BRIGHT_CYAN}{entry}{cls.RESET}\n")
209
- input("Press Enter to return to cockpit...")
210
- elif choice == "5":
211
- patch_path = input("Enter path to unified diff file: ").strip()
212
- if patch_path and os.path.exists(patch_path):
213
- from tzero_patch import ASTFuzzyPatcher
214
- res = ASTFuzzyPatcher.apply_patch_file(patch_path, workspace_dir=workspace_dir)
215
- print(f"{cls.GREEN}[RESULT] Applied {res.get('applied_hunks', 0)}/{res.get('total_hunks', 0)} hunks.{cls.RESET}")
216
- else:
217
- print(f"{cls.RED}File not found.{cls.RESET}")
218
- input("Press Enter to return to cockpit...")
219
- elif choice == "6":
220
- print(f"\n{cls.GREEN}[Launching Web Dashboard on http://localhost:8421]...{cls.RESET}")
221
- import webbrowser
222
- webbrowser.open("http://localhost:8421")
223
- time.sleep(1)
224
- elif choice == "7":
225
- from tzero_guard import GitSecurityGuard
226
- from tzero_ci import CIPipelineGenerator
227
- res = GitSecurityGuard.install_hook(workspace_dir)
228
- CIPipelineGenerator.install_github_workflow(workspace_dir)
229
- print(f"{cls.GREEN}[SUCCESS] Pre-commit hook & GitHub Actions CI installed!{cls.RESET}")
230
- input("Press Enter to return to cockpit...")
231
-
232
-
233
- def main():
234
- """CLI entrypoint for standalone cockpit execution."""
235
- target_dir = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("-") else "."
236
- if "--snapshot" in sys.argv:
237
- metrics = TZeroTerminalCockpit.gather_workspace_metrics(target_dir)
238
- print(TZeroTerminalCockpit.render_cockpit(metrics))
239
- else:
240
- TZeroTerminalCockpit.run_interactive(target_dir)
241
-
242
-
243
- if __name__ == "__main__":
244
- main()
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Siber Akademi — T-Zero Terminal User Interface (TUI) & Live Cockpit.
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ License: MIT
6
+
7
+ Pure standard-library ANSI terminal dashboard and interactive executive cockpit.
8
+ Provides live workspace token metrics, AST compression meters, zero-leak security
9
+ auditing, and instantaneous action triggers without any external GUI dependencies.
10
+ """
11
+
12
+ import sys
13
+ if sys.platform == "win32":
14
+ try:
15
+ sys.stdout.reconfigure(encoding="utf-8")
16
+ sys.stderr.reconfigure(encoding="utf-8")
17
+ except Exception:
18
+ pass
19
+
20
+ import os
21
+ import time
22
+ from typing import Dict, List, Optional, Any, Tuple
23
+
24
+ from tzero.tzero_features import should_skip_dir, should_skip_file
25
+ from tzero.tzero_polyglot import PolyglotTokenReducer
26
+
27
+
28
+ class TZeroTerminalCockpit:
29
+ """Zero-dependency, high-density terminal dashboard and interactive cockpit."""
30
+
31
+ # ANSI Palette
32
+ CYAN = "\033[36m"
33
+ BRIGHT_CYAN = "\033[96m"
34
+ GREEN = "\033[32m"
35
+ BRIGHT_GREEN = "\033[92m"
36
+ YELLOW = "\033[33m"
37
+ MAGENTA = "\033[35m"
38
+ BLUE = "\033[34m"
39
+ RED = "\033[31m"
40
+ BOLD = "\033[1m"
41
+ DIM = "\033[2m"
42
+ RESET = "\033[0m"
43
+
44
+ @classmethod
45
+ def gather_workspace_metrics(cls, workspace_dir: str = ".") -> Dict[str, Any]:
46
+ """Scans workspace and compiles metrics for the terminal cockpit."""
47
+ abs_ws = os.path.abspath(workspace_dir)
48
+ files_by_lang: Dict[str, int] = {}
49
+ raw_tokens_total = 0
50
+ pruned_tokens_total = 0
51
+ file_count = 0
52
+ code_files_sampled = 0
53
+
54
+ reducer = PolyglotTokenReducer()
55
+
56
+ for root, dirs, files in os.walk(abs_ws):
57
+ dirs[:] = [d for d in dirs if not should_skip_dir(os.path.join(root, d), abs_ws)]
58
+ for f in files:
59
+ full_p = os.path.join(root, f)
60
+ if should_skip_file(full_p, abs_ws):
61
+ continue
62
+ file_count += 1
63
+ ext = os.path.splitext(f)[1].lower()
64
+ lang = reducer.detect_language(full_p) or "Other"
65
+ files_by_lang[lang] = files_by_lang.get(lang, 0) + 1
66
+
67
+ # Sample quick token calculation on code files (independent of non-code assets)
68
+ if code_files_sampled < 250 and ext in (
69
+ ".py", ".ts", ".js", ".rs", ".go", ".cpp", ".c", ".h",
70
+ ".swift", ".kt", ".dart", ".rb", ".sol", ".scala", ".php"
71
+ ):
72
+ try:
73
+ with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
74
+ raw_code = fp.read()
75
+ raw_t = max(1, len(raw_code) // 4)
76
+ pruned_code = reducer.reduce_code(raw_code, filename=full_p, mode="ultra")
77
+ pruned_t = max(1, len(pruned_code) // 4)
78
+ raw_tokens_total += raw_t
79
+ pruned_tokens_total += pruned_t
80
+ code_files_sampled += 1
81
+ except OSError:
82
+ pass
83
+
84
+ # Estimate savings if sample available, or zero for empty workspace
85
+ if raw_tokens_total > 0:
86
+ savings_pct = max(0.0, (1.0 - (pruned_tokens_total / raw_tokens_total)) * 100.0)
87
+ else:
88
+ savings_pct = 0.0
89
+
90
+ # Real Zero-Leak security status check
91
+ zero_leak_status = "UNVERIFIED"
92
+ try:
93
+ from tzero.tzero_security import ZeroLeakEngine
94
+ sec_res = ZeroLeakEngine.scan_workspace(abs_ws)
95
+ v_count = int(sec_res.get("violation_count", 0))
96
+ zero_leak_status = "100% SECURE (VERIFIED)" if v_count == 0 else f"WARNING: {v_count} SECRET(S)"
97
+ except Exception:
98
+ pass
99
+
100
+ # Monthly ROI savings calculation (assuming 50 queries/day at Claude 3.7 $3/1M input)
101
+ daily_saved_tokens = (raw_tokens_total - pruned_tokens_total) * 50
102
+ monthly_cost_saved = (daily_saved_tokens * 30 / 1_000_000) * 3.0
103
+
104
+ return {
105
+ "workspace_name": os.path.basename(abs_ws) or "Workspace",
106
+ "workspace_dir": abs_ws,
107
+ "total_files": file_count,
108
+ "raw_tokens": raw_tokens_total,
109
+ "pruned_tokens": pruned_tokens_total,
110
+ "savings_pct": round(savings_pct, 1),
111
+ "monthly_roi_saved": round(monthly_cost_saved, 2),
112
+ "languages": files_by_lang,
113
+ "zero_leak_status": zero_leak_status,
114
+ }
115
+
116
+ @classmethod
117
+ def render_gauge(cls, percentage: float, width: int = 24) -> str:
118
+ """Renders an ANSI progress bar gauge."""
119
+ filled = int(width * (percentage / 100.0))
120
+ empty = width - filled
121
+ bar = f"{cls.BRIGHT_CYAN}{'█' * filled}{cls.DIM}{'░' * empty}{cls.RESET}"
122
+ return f"[{bar}] {cls.BOLD}{percentage:.1f}%{cls.RESET}"
123
+
124
+ @classmethod
125
+ def render_cockpit(cls, metrics: Dict[str, Any]) -> str:
126
+ """Constructs high-density ASCII / ANSI terminal cockpit screen."""
127
+ c = cls
128
+ lines = []
129
+
130
+ box_top = f"{c.CYAN}╔══════════════════════════════════════════════════════════════════════════════╗{c.RESET}"
131
+ box_mid = f"{c.CYAN}╠══════════════════════════════════════════════════════════════════════════════╣{c.RESET}"
132
+ box_bottom = f"{c.CYAN}╚══════════════════════════════════════════════════════════════════════════════╝{c.RESET}"
133
+
134
+ lines.append(box_top)
135
+ lines.append(f"{c.CYAN}║{c.RESET} {c.BOLD}{c.BRIGHT_CYAN}⚡ SİBER AKADEMİ — T-ZERO CONTEXT ARCHITECT & LIVE COCKPIT v11.11.0{c.RESET} {c.CYAN}║{c.RESET}")
136
+ lines.append(f"{c.CYAN}║{c.RESET} {c.DIM}Zero-Leak AST Intelligence | 100% Offline | $0 Cloud Cost Guarantee{c.RESET} {c.CYAN}║{c.RESET}")
137
+ lines.append(box_mid)
138
+
139
+ # Workspace summary line
140
+ ws_name = metrics.get("workspace_name", "Workspace")[:20]
141
+ files_cnt = metrics.get("total_files", 0)
142
+ lines.append(f"{c.CYAN}║{c.RESET} 📁 {c.BOLD}Workspace:{c.RESET} {ws_name:<20} │ 📦 {c.BOLD}Files Tracked:{c.RESET} {files_cnt:<6} {c.CYAN}║{c.RESET}")
143
+
144
+ # Metrics lines
145
+ raw_t = metrics.get("raw_tokens", 0)
146
+ pruned_t = metrics.get("pruned_tokens", 0)
147
+ sav_pct = metrics.get("savings_pct", 94.8)
148
+ roi = metrics.get("monthly_roi_saved", 0.0)
149
+
150
+ gauge = cls.render_gauge(sav_pct, width=20)
151
+ lines.append(f"{c.CYAN}║{c.RESET} 🗜️ {c.BOLD}AST Reduction:{c.RESET} {gauge:<38} {c.CYAN}║{c.RESET}")
152
+ lines.append(f"{c.CYAN}║{c.RESET} 📊 {c.BOLD}Raw Tokens:{c.RESET} ~{raw_t:,} │ {c.BOLD}Pruned Tokens:{c.RESET} ~{pruned_t:,} {c.CYAN}║{c.RESET}")
153
+ lines.append(f"{c.CYAN}║{c.RESET} 💰 {c.BOLD}Est. Monthly Team ROI Saved:{c.RESET} {c.BRIGHT_GREEN}${roi:,.2f}{c.RESET} / month (Claude 3.7 / GPT-4o) {c.CYAN}║{c.RESET}")
154
+ sec_stat = str(metrics.get("zero_leak_status", "100% SECURE (VERIFIED)"))
155
+ sec_color = c.BRIGHT_GREEN if ("SECURE" in sec_stat or "PASSED" in sec_stat) else c.RED
156
+ sec_note = "(0 Exposed Credentials)" if sec_color == c.BRIGHT_GREEN else "(Action Required)"
157
+ sec_field = f"{sec_color}{sec_stat}{c.RESET} {sec_note}"
158
+ lines.append(f"{c.CYAN}║{c.RESET} 🔒 {c.BOLD}Security Guard:{c.RESET} {sec_field:<57} {c.CYAN}║{c.RESET}")
159
+ lines.append(box_mid)
160
+
161
+ # Top languages line
162
+ langs = metrics.get("languages", {})
163
+ top_langs = sorted(langs.items(), key=lambda x: x[1], reverse=True)[:5]
164
+ lang_str = " | ".join(f"{k}: {v}" for k, v in top_langs)
165
+ lines.append(f"{c.CYAN}║{c.RESET} 🌐 {c.BOLD}Polyglot Stack:{c.RESET} {lang_str[:54]:<54} {c.CYAN}║{c.RESET}")
166
+ lines.append(box_mid)
167
+
168
+ # Interactive Command Menu
169
+ lines.append(f"{c.CYAN}║{c.RESET} {c.BOLD}🚀 QUICK COMMAND DISPATCH:{c.RESET} {c.CYAN}║{c.RESET}")
170
+ lines.append(f"{c.CYAN}║{c.RESET} [1] 🗜️ Pack Context Window (`tzero --pack 16000`) {c.CYAN}║{c.RESET}")
171
+ lines.append(f"{c.CYAN}║{c.RESET} [2] 📑 Generate PEP-484 Type Stubs (`tzero --stubs`) {c.CYAN}║{c.RESET}")
172
+ lines.append(f"{c.CYAN}║{c.RESET} [3] ✍️ Synthesize Conventional Commit (`tzero --commit-msg`) {c.CYAN}║{c.RESET}")
173
+ lines.append(f"{c.CYAN}║{c.RESET} [4] 📜 Generate Release CHANGELOG (`tzero --changelog`) {c.CYAN}║{c.RESET}")
174
+ lines.append(f"{c.CYAN}║{c.RESET} [5] 🛠️ Apply AST-Tolerant Patch (`tzero --patch <diff>`) {c.CYAN}║{c.RESET}")
175
+ lines.append(f"{c.CYAN}║{c.RESET} [6] 🌐 Launch Web Comparison Dashboard (`tzero --web`) {c.CYAN}║{c.RESET}")
176
+ lines.append(f"{c.CYAN}║{c.RESET} [7] 🛡️ Install Git Zero-Leak Guard & CI (`tzero --guard-install`) {c.CYAN}║{c.RESET}")
177
+ lines.append(f"{c.CYAN}║{c.RESET} [8] 🏛️ Verify Architecture & 0 Cycles (`tzero --check-arch`) {c.CYAN}║{c.RESET}")
178
+ lines.append(f"{c.CYAN}║{c.RESET} [9] 🧬 Run AST Mutation Test Suite (`tzero --mutate <file>`) {c.CYAN}║{c.RESET}")
179
+ lines.append(f"{c.CYAN}║{c.RESET} [10] 🏥 Code Health & Technical Debt Index (`tzero --debt`) {c.CYAN}║{c.RESET}")
180
+ lines.append(f"{c.CYAN}║{c.RESET} [11] 📜 Context Budget Optimizer & Certificate (`tzero --budget`) {c.CYAN}║{c.RESET}")
181
+ lines.append(f"{c.CYAN}║{c.RESET} [0] 🚪 Exit TUI {c.CYAN}║{c.RESET}")
182
+ lines.append(box_bottom)
183
+
184
+ return "\n".join(lines)
185
+
186
+ @classmethod
187
+ def run_interactive(cls, workspace_dir: str = "."):
188
+ """Runs the interactive loop in the user terminal."""
189
+ while True:
190
+ metrics = cls.gather_workspace_metrics(workspace_dir)
191
+ screen = cls.render_cockpit(metrics)
192
+ print("\033[H\033[J", end="") # Clear screen ANSI
193
+ print(screen)
194
+
195
+ try:
196
+ choice = input(f"\n{cls.BOLD}Select an action [0-11] (or press Enter to refresh): {cls.RESET}").strip()
197
+ except (KeyboardInterrupt, EOFError):
198
+ print(f"\n{cls.CYAN}Goodbye! T-Zero Context Engine active.{cls.RESET}")
199
+ break
200
+
201
+ if choice == "0":
202
+ print(f"\n{cls.CYAN}Exiting T-Zero Cockpit.{cls.RESET}")
203
+ break
204
+ elif choice == "1":
205
+ from tzero.tzero_packer import pack_workspace
206
+ print(f"\n{cls.YELLOW}[Running Context Packer (16,000 tokens)]...{cls.RESET}")
207
+ res = pack_workspace(workspace_dir=workspace_dir, budget_tokens=16000)
208
+ print(f"{cls.GREEN}[SUCCESS] Packed {res.total_tokens:,} tokens ({res.token_savings_pct:.1f}% reduction).{cls.RESET}")
209
+ input("Press Enter to return to cockpit...")
210
+ elif choice == "2":
211
+ from tzero.tzero_stubs import TypeStubGenerator
212
+ print(f"\n{cls.YELLOW}[Generating PEP-484 Type Stubs]...{cls.RESET}")
213
+ res = TypeStubGenerator.generate_workspace_stubs(workspace_dir=workspace_dir)
214
+ print(f"{cls.GREEN}[SUCCESS] Generated {res['total_files']} stubs ({res['overall_savings_pct']}% reduction).{cls.RESET}")
215
+ input("Press Enter to return to cockpit...")
216
+ elif choice == "3":
217
+ from tzero.tzero_commit import LocalSemanticCommitSynthesizer
218
+ print(f"\n{cls.YELLOW}[Synthesizing Offline Commit Message]...{cls.RESET}")
219
+ msg = LocalSemanticCommitSynthesizer.generate_commit_message(repo_dir=workspace_dir, staged=True)
220
+ print(f"\n{cls.BRIGHT_CYAN}{msg}{cls.RESET}\n")
221
+ input("Press Enter to return to cockpit...")
222
+ elif choice == "4":
223
+ from tzero.tzero_commit import LocalSemanticCommitSynthesizer
224
+ print(f"\n{cls.YELLOW}[Synthesizing Release CHANGELOG]...{cls.RESET}")
225
+ entry = LocalSemanticCommitSynthesizer.generate_changelog_entry(version="v11.11.0", repo_dir=workspace_dir)
226
+ print(f"\n{cls.BRIGHT_CYAN}{entry}{cls.RESET}\n")
227
+ input("Press Enter to return to cockpit...")
228
+ elif choice == "5":
229
+ patch_path = input("Enter path to unified diff file: ").strip()
230
+ if patch_path and os.path.exists(patch_path):
231
+ from tzero.tzero_patch import ASTFuzzyPatcher
232
+ res = ASTFuzzyPatcher.apply_patch_file(patch_path, workspace_dir=workspace_dir)
233
+ print(f"{cls.GREEN}[RESULT] Applied {res.get('applied_hunks', 0)}/{res.get('total_hunks', 0)} hunks.{cls.RESET}")
234
+ else:
235
+ print(f"{cls.RED}File not found.{cls.RESET}")
236
+ input("Press Enter to return to cockpit...")
237
+ elif choice == "6":
238
+ print(f"\n{cls.GREEN}[Launching Web Dashboard on http://localhost:8421]...{cls.RESET}")
239
+ import socket
240
+ import threading
241
+ import webbrowser
242
+ is_up = False
243
+ try:
244
+ with socket.create_connection(("127.0.0.1", 8421), timeout=0.3):
245
+ is_up = True
246
+ except OSError:
247
+ is_up = False
248
+ if not is_up:
249
+ try:
250
+ from tzero.tzero_dashboard import start_dashboard_server
251
+ srv = start_dashboard_server(port=8421, open_browser=False)
252
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
253
+ except Exception:
254
+ pass
255
+ webbrowser.open("http://localhost:8421")
256
+ time.sleep(1)
257
+ elif choice == "7":
258
+ from tzero.tzero_guard import GitSecurityGuard
259
+ from tzero.tzero_ci import CIPipelineGenerator
260
+ res = GitSecurityGuard.install_hook(workspace_dir)
261
+ CIPipelineGenerator.install_github_workflow(workspace_dir)
262
+ print(f"{cls.GREEN}[SUCCESS] Pre-commit hook & GitHub Actions CI installed!{cls.RESET}")
263
+ input("Press Enter to return to cockpit...")
264
+ elif choice == "8":
265
+ from tzero.tzero_arch_test import ArchitectureTestSuiteGenerator
266
+ print(f"\n{cls.YELLOW}[Verifying Layer Boundaries, Cycles & Zero-Leak Security]...{cls.RESET}")
267
+ gen = ArchitectureTestSuiteGenerator(workspace_dir)
268
+ rep = gen.run_live_audit()
269
+ if rep["success"]:
270
+ print(f"\n{cls.GREEN}✅ [ARCH-AUDIT PASS] All {rep['scanned_files']} files conform to rules! Zero violations.{cls.RESET}\n")
271
+ else:
272
+ print(f"\n{cls.RED}❌ [ARCH-AUDIT FAILED] Violations detected:{cls.RESET}")
273
+ for v in rep["layer_violations"]:
274
+ print(f" • {v['file']} (layer: {v['layer']}) imports forbidden '{v['imported']}'")
275
+ input("Press Enter to return to cockpit...")
276
+ elif choice == "9":
277
+ target_f = input("Enter path to file for mutation test (default: tzero_arch_test.py): ").strip() or "tzero_arch_test.py"
278
+ if os.path.exists(target_f):
279
+ from tzero.tzero_mutation import ASTMutationEngine
280
+ print(f"\n{cls.YELLOW}[Running AST Mutation Analysis on {target_f}]...{cls.RESET}")
281
+ m_rep = ASTMutationEngine.run_mutation_analysis(target_file=target_f, max_mutants=5)
282
+ print(f"{cls.GREEN}[RESULT] Mutation Score: {m_rep.mutation_score}% ({m_rep.killed}/{m_rep.total_mutants} killed).{cls.RESET}")
283
+ else:
284
+ print(f"{cls.RED}Target file not found.{cls.RESET}")
285
+ input("Press Enter to return to cockpit...")
286
+ elif choice == "10":
287
+ from tzero.tzero_debt import CodeHealthAnalyzer
288
+ print(f"\n{cls.YELLOW}[Analyzing Code Health & Technical Debt Index for {workspace_dir}]...{cls.RESET}")
289
+ rep = CodeHealthAnalyzer.analyze_workspace(workspace_dir)
290
+ print(f"\n{cls.BRIGHT_CYAN}{CodeHealthAnalyzer.format_markdown_report(rep)}{cls.RESET}\n")
291
+ input("Press Enter to return to cockpit...")
292
+ elif choice == "11":
293
+ from tzero.tzero_budget import ASTTokenBudgetOptimizer
294
+ print(f"\n{cls.YELLOW}[Sizing Context Payload & Issuing Compression Certificate for {workspace_dir}]...{cls.RESET}")
295
+ cert = ASTTokenBudgetOptimizer.optimize_budget(workspace_dir)
296
+ saved_p = ASTTokenBudgetOptimizer.save_certificate(cert)
297
+ print(f"\n{cls.BRIGHT_CYAN}{ASTTokenBudgetOptimizer.format_markdown_certificate(cert)}{cls.RESET}\n")
298
+ print(f"{cls.GREEN}[SUCCESS] Certificate saved to: {saved_p}{cls.RESET}")
299
+ input("Press Enter to return to cockpit...")
300
+
301
+
302
+ def main():
303
+ """CLI entrypoint for standalone cockpit execution."""
304
+ target_dir = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("-") else "."
305
+ if "--snapshot" in sys.argv:
306
+ metrics = TZeroTerminalCockpit.gather_workspace_metrics(target_dir)
307
+ print(TZeroTerminalCockpit.render_cockpit(metrics))
308
+ else:
309
+ TZeroTerminalCockpit.run_interactive(target_dir)
310
+
311
+
312
+ if __name__ == "__main__":
313
+ main()