tzero-mcp 11.0.0 → 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 (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -1,313 +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.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.0.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.0.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()
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()