tzero-mcp 11.15.3 → 12.2.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 (72) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CONTRIBUTING.md +4 -4
  3. package/README.md +5 -5
  4. package/bin/postinstall.js +10 -2
  5. package/bin/tzero-mcp.js +1 -1
  6. package/bin/tzero.js +17 -0
  7. package/package.json +1 -1
  8. package/src/addmcp.py +34 -23
  9. package/src/app.py +1 -1
  10. package/src/main.py +6 -0
  11. package/src/tzero/__init__.py +10 -0
  12. package/src/tzero/anti_rea/__init__.py +70 -0
  13. package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
  14. package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
  15. package/src/tzero/anti_rea/anti_debugger.py +239 -0
  16. package/src/tzero/anti_rea/anti_vm.py +160 -0
  17. package/src/tzero/anti_rea/asar_shield.py +99 -0
  18. package/src/tzero/anti_rea/auditor.py +158 -0
  19. package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
  20. package/src/tzero/anti_rea/bytecode_trap.py +85 -0
  21. package/src/tzero/anti_rea/canary_beacon.py +187 -0
  22. package/src/tzero/anti_rea/cli.py +102 -0
  23. package/src/tzero/anti_rea/confusables.py +86 -0
  24. package/src/tzero/anti_rea/engine.py +204 -0
  25. package/src/tzero/anti_rea/extractor_shield.py +102 -0
  26. package/src/tzero/anti_rea/flattener.py +136 -0
  27. package/src/tzero/anti_rea/gui.py +267 -0
  28. package/src/tzero/anti_rea/honeypot.py +58 -0
  29. package/src/tzero/anti_rea/integrity_guard.py +66 -0
  30. package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
  31. package/src/tzero/anti_rea/mcp_poison.py +41 -0
  32. package/src/tzero/anti_rea/native_bridge.py +169 -0
  33. package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
  34. package/src/tzero/anti_rea/string_vault.py +94 -0
  35. package/src/tzero/anti_rea/sybil_network.py +53 -0
  36. package/src/tzero/anti_rea/timing_guard.py +46 -0
  37. package/src/tzero/anti_rea/token_bomb.py +65 -0
  38. package/src/tzero/anti_rea/traps.py +76 -0
  39. package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
  40. package/src/tzero/siber_akademi.ico +0 -0
  41. package/src/tzero/siber_akademi_icon.py +1 -1
  42. package/src/tzero/tzero_armor.py +165 -0
  43. package/src/tzero/tzero_bridge.py +28 -15
  44. package/src/tzero/tzero_budget.py +10 -3
  45. package/src/tzero/tzero_card.py +7 -5
  46. package/src/tzero/tzero_ci.py +1 -0
  47. package/src/tzero/tzero_contracts.py +30 -11
  48. package/src/tzero/tzero_dashboard.py +34 -14
  49. package/src/tzero/tzero_debt.py +14 -5
  50. package/src/tzero/tzero_federation.py +11 -6
  51. package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
  52. package/src/tzero/tzero_golden.py +11 -6
  53. package/src/tzero/tzero_graph_hud.html +1 -1
  54. package/src/tzero/tzero_growth.py +10 -10
  55. package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
  56. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
  57. package/src/tzero/tzero_lsp.py +1 -1
  58. package/src/tzero/tzero_mcp.py +89 -31
  59. package/src/tzero/tzero_mutation.py +44 -16
  60. package/src/tzero/tzero_neural_cortex.py +1 -1
  61. package/src/tzero/tzero_pc_fixer.py +21 -3
  62. package/src/tzero/tzero_promo.py +196 -36
  63. package/src/tzero/tzero_rust_bridge.py +1086 -42
  64. package/src/tzero/tzero_scip.py +15 -2
  65. package/src/tzero/tzero_semantic_merge.py +34 -10
  66. package/src/tzero/tzero_task_benchmark.py +2 -2
  67. package/src/tzero/tzero_telemetry.py +146 -0
  68. package/src/tzero/tzero_terminal.py +366 -0
  69. package/src/tzero/tzero_traffic.py +350 -0
  70. package/src/tzero/tzero_tui.py +342 -133
  71. package/src/tzero/tzero_v3.py +652 -29
  72. package/src/tzero/tzero_welcome.py +124 -37
@@ -18,7 +18,9 @@ if sys.platform == "win32":
18
18
  pass
19
19
 
20
20
  import os
21
+ import re
21
22
  import time
23
+ import unicodedata
22
24
  from typing import Dict, List, Optional, Any, Tuple
23
25
 
24
26
  from tzero.tzero_features import should_skip_dir, should_skip_file
@@ -121,25 +123,71 @@ class TZeroTerminalCockpit:
121
123
  bar = f"{cls.BRIGHT_CYAN}{'█' * filled}{cls.DIM}{'░' * empty}{cls.RESET}"
122
124
  return f"[{bar}] {cls.BOLD}{percentage:.1f}%{cls.RESET}"
123
125
 
126
+ MENU_OPTIONS: List[Tuple[str, str, str]] = [
127
+ ("1", "Pack Context Window", "🗜️ Pack Context Window (`tzero --pack 16000`)"),
128
+ ("2", "Generate PEP-484 Type Stubs", "📑 Generate PEP-484 Type Stubs (`tzero --stubs`)"),
129
+ ("3", "Synthesize Conventional Commit", "✍️ Synthesize Conventional Commit (`tzero --commit-msg`)"),
130
+ ("4", "Generate Release CHANGELOG", "📜 Generate Release CHANGELOG (`tzero --changelog`)"),
131
+ ("5", "Apply AST-Tolerant Patch", "🛠️ Apply AST-Tolerant Patch (`tzero --patch <diff>`)"),
132
+ ("6", "Launch Web Comparison Dashboard", "🌐 Launch Web Comparison Dashboard (`tzero --web`)"),
133
+ ("7", "Install Git Zero-Leak Guard & CI", "🛡️ Install Git Zero-Leak Guard & CI (`tzero --guard-install`)"),
134
+ ("8", "Verify Architecture & 0 Cycles", "🏛️ Verify Architecture & 0 Cycles (`tzero --check-arch`)"),
135
+ ("9", "Run AST Mutation Test Suite", "🧬 Run AST Mutation Test Suite (`tzero --mutate <file>`)"),
136
+ ("10", "Code Health & Technical Debt Index", "🏥 Code Health & Technical Debt Index (`tzero --debt`)"),
137
+ ("11", "Context Budget Optimizer & Certificate", "📜 Context Budget Optimizer & Certificate (`tzero --budget`)"),
138
+ ("12", "Anti-REA 26-Tier Armor & Audit", "🛡️ Anti-REA 26-Tier Armor & Audit (`tzero --audit-rea`)"),
139
+ ("13", "Offline Telemetry & ROI Tracker", "📊 Offline Telemetry & ROI Tracker (`tzero --telemetry`)"),
140
+ ("0", "Exit TUI", "🚪 Exit TUI"),
141
+ ]
142
+
143
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
144
+
145
+ @classmethod
146
+ def visual_width(cls, text: str) -> int:
147
+ """Computes monospace display cell width of text, handling ANSI and emojis."""
148
+ clean = cls._ANSI_RE.sub("", text)
149
+ width = 0
150
+ for ch in clean:
151
+ cat = unicodedata.category(ch)
152
+ if cat in ("Mn", "Me", "Cf") or ch == "\ufe0f":
153
+ continue
154
+ ea = unicodedata.east_asian_width(ch)
155
+ if ea in ("W", "F"):
156
+ width += 2
157
+ continue
158
+ code = ord(ch)
159
+ if (0x1F300 <= code <= 0x1FAFF) or (0x2300 <= code <= 0x23FF) or (0x2600 <= code <= 0x27BF):
160
+ width += 2
161
+ else:
162
+ width += 1
163
+ return width
164
+
124
165
  @classmethod
125
- def render_cockpit(cls, metrics: Dict[str, Any]) -> str:
126
- """Constructs high-density ASCII / ANSI terminal cockpit screen."""
166
+ def _box_line(cls, content: str, inner_width: int = 78) -> str:
167
+ """Wraps content with box borders with exact column padding."""
168
+ w = cls.visual_width(content)
169
+ pad = max(0, inner_width - w)
170
+ return f"{cls.CYAN}║{cls.RESET}{content}{' ' * pad}{cls.CYAN}║{cls.RESET}"
171
+
172
+ @classmethod
173
+ def render_cockpit(cls, metrics: Dict[str, Any], selected_index: Optional[int] = 0) -> str:
174
+ """Constructs high-density ASCII / ANSI terminal cockpit screen with exact border alignment."""
127
175
  c = cls
128
176
  lines = []
129
177
 
130
- box_top = f"{c.CYAN}╔══════════════════════════════════════════════════════════════════════════════╗{c.RESET}"
131
- box_mid = f"{c.CYAN}╠══════════════════════════════════════════════════════════════════════════════╣{c.RESET}"
132
- box_bottom = f"{c.CYAN}╚══════════════════════════════════════════════════════════════════════════════╝{c.RESET}"
178
+ box_top = f"{c.CYAN}╔{'═' * 78}╗{c.RESET}"
179
+ box_mid = f"{c.CYAN}╠{'═' * 78}╣{c.RESET}"
180
+ box_bottom = f"{c.CYAN}╚{'═' * 78}╝{c.RESET}"
133
181
 
134
182
  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.15.2{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}")
183
+ lines.append(cls._box_line(f" {c.BOLD}{c.BRIGHT_CYAN}⚡ SİBER AKADEMİ — T-ZERO CONTEXT ARCHITECT & LIVE COCKPIT v12.2.1{c.RESET}"))
184
+ lines.append(cls._box_line(f" {c.DIM}Zero-Leak AST Intelligence | 100% Offline | $0 Cloud Cost Guarantee{c.RESET}"))
137
185
  lines.append(box_mid)
138
186
 
139
187
  # Workspace summary line
140
188
  ws_name = metrics.get("workspace_name", "Workspace")[:20]
141
189
  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}")
190
+ lines.append(cls._box_line(f" 📁 {c.BOLD}Workspace:{c.RESET} {ws_name:<20} │ 📦 {c.BOLD}Files Tracked:{c.RESET} {files_cnt:<6}"))
143
191
 
144
192
  # Metrics lines
145
193
  raw_t = metrics.get("raw_tokens", 0)
@@ -148,155 +196,316 @@ class TZeroTerminalCockpit:
148
196
  roi = metrics.get("monthly_roi_saved", 0.0)
149
197
 
150
198
  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}")
199
+ lines.append(cls._box_line(f" 🗜️ {c.BOLD}AST Reduction:{c.RESET} {gauge}"))
200
+ lines.append(cls._box_line(f" 📊 {c.BOLD}Raw Tokens:{c.RESET} ~{raw_t:,} │ {c.BOLD}Pruned Tokens:{c.RESET} ~{pruned_t:,}"))
201
+ lines.append(cls._box_line(f" 💰 {c.BOLD}Est. Monthly Team ROI Saved:{c.RESET} {c.BRIGHT_GREEN}${roi:,.2f}{c.RESET} / month (Claude 3.7 / GPT-4o)"))
154
202
  sec_stat = str(metrics.get("zero_leak_status", "100% SECURE (VERIFIED)"))
155
203
  sec_color = c.BRIGHT_GREEN if ("SECURE" in sec_stat or "PASSED" in sec_stat) else c.RED
156
204
  sec_note = "(0 Exposed Credentials)" if sec_color == c.BRIGHT_GREEN else "(Action Required)"
157
205
  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}")
206
+ lines.append(cls._box_line(f" 🔒 {c.BOLD}Security Guard:{c.RESET} {sec_field}"))
159
207
  lines.append(box_mid)
160
208
 
161
209
  # Top languages line
162
210
  langs = metrics.get("languages", {})
163
211
  top_langs = sorted(langs.items(), key=lambda x: x[1], reverse=True)[:5]
164
212
  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}")
213
+ lines.append(cls._box_line(f" 🌐 {c.BOLD}Polyglot Stack:{c.RESET} {lang_str[:54]}"))
166
214
  lines.append(box_mid)
167
215
 
168
216
  # 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}")
217
+ lines.append(cls._box_line(f" {c.BOLD}🚀 QUICK COMMAND DISPATCH:{c.RESET}"))
218
+ for idx, (mkey, short_label, full_text) in enumerate(cls.MENU_OPTIONS):
219
+ is_active = (selected_index is not None and (selected_index % len(cls.MENU_OPTIONS)) == idx)
220
+ if is_active:
221
+ prefix = f" {c.BRIGHT_GREEN}▶{c.RESET} "
222
+ styled_text = f"{c.BOLD}[{mkey}] {full_text}{c.RESET}"
223
+ else:
224
+ prefix = " "
225
+ styled_text = f"[{mkey}] {full_text}"
226
+ lines.append(cls._box_line(f"{prefix}{styled_text}"))
182
227
  lines.append(box_bottom)
183
228
 
184
229
  return "\n".join(lines)
185
230
 
231
+ @classmethod
232
+ def _read_key(cls) -> str:
233
+ """Reads a single keystroke cross-platform supporting arrow keys."""
234
+ if sys.platform == "win32":
235
+ try:
236
+ import msvcrt
237
+ ch = msvcrt.getwch()
238
+ if ch in ('\x00', '\xe0'):
239
+ ch2 = msvcrt.getwch()
240
+ if ch2 == 'H':
241
+ return 'UP'
242
+ elif ch2 == 'P':
243
+ return 'DOWN'
244
+ elif ch2 == 'K':
245
+ return 'LEFT'
246
+ elif ch2 == 'M':
247
+ return 'RIGHT'
248
+ return 'OTHER'
249
+ if ch in ('\r', '\n'):
250
+ return 'ENTER'
251
+ if ch == '\t':
252
+ return 'TAB'
253
+ if ch == '\x1b':
254
+ return 'ESC'
255
+ if ch == '\x03':
256
+ return 'CTRL_C'
257
+ return ch
258
+ except Exception:
259
+ return ''
260
+ else:
261
+ try:
262
+ import termios
263
+ import tty
264
+ import select
265
+ fd = sys.stdin.fileno()
266
+ old_settings = termios.tcgetattr(fd)
267
+ try:
268
+ tty.setraw(fd)
269
+ rlist, _, _ = select.select([sys.stdin], [], [], 0.05)
270
+ if rlist:
271
+ ch = sys.stdin.read(1)
272
+ if ch == '\x1b':
273
+ rlist, _, _ = select.select([sys.stdin], [], [], 0.05)
274
+ if rlist:
275
+ seq = sys.stdin.read(2)
276
+ if seq == '[A':
277
+ return 'UP'
278
+ elif seq == '[B':
279
+ return 'DOWN'
280
+ elif seq == '[C':
281
+ return 'RIGHT'
282
+ elif seq == '[D':
283
+ return 'LEFT'
284
+ elif seq == '[Z':
285
+ return 'SHIFT_TAB'
286
+ return 'ESC'
287
+ if ch in ('\r', '\n'):
288
+ return 'ENTER'
289
+ if ch == '\t':
290
+ return 'TAB'
291
+ if ch == '\x03':
292
+ return 'CTRL_C'
293
+ return ch
294
+ finally:
295
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
296
+ except Exception:
297
+ return ''
298
+ return ''
299
+
300
+ @classmethod
301
+ def execute_action(cls, choice: str, workspace_dir: str = ".") -> bool:
302
+ """Dispatches action for a choice string. Returns False if exiting, True otherwise."""
303
+ choice = choice.strip()
304
+ if choice in ("0", "q", "Q", "quit", "exit"):
305
+ print(f"\n{cls.CYAN}Exiting T-Zero Cockpit.{cls.RESET}")
306
+ return False
307
+ elif choice == "1":
308
+ from tzero.tzero_packer import pack_workspace
309
+ print(f"\n{cls.YELLOW}[Running Context Packer (16,000 tokens)]...{cls.RESET}")
310
+ res = pack_workspace(workspace_dir=workspace_dir, budget_tokens=16000)
311
+ print(f"{cls.GREEN}[SUCCESS] Packed {res.total_tokens:,} tokens ({res.token_savings_pct:.1f}% reduction).{cls.RESET}")
312
+ input("Press Enter to return to cockpit...")
313
+ elif choice == "2":
314
+ from tzero.tzero_stubs import TypeStubGenerator
315
+ print(f"\n{cls.YELLOW}[Generating PEP-484 Type Stubs]...{cls.RESET}")
316
+ res = TypeStubGenerator.generate_workspace_stubs(workspace_dir=workspace_dir)
317
+ print(f"{cls.GREEN}[SUCCESS] Generated {res['total_files']} stubs ({res['overall_savings_pct']}% reduction).{cls.RESET}")
318
+ input("Press Enter to return to cockpit...")
319
+ elif choice == "3":
320
+ from tzero.tzero_commit import LocalSemanticCommitSynthesizer
321
+ print(f"\n{cls.YELLOW}[Synthesizing Offline Commit Message]...{cls.RESET}")
322
+ msg = LocalSemanticCommitSynthesizer.generate_commit_message(repo_dir=workspace_dir, staged=True)
323
+ print(f"\n{cls.BRIGHT_CYAN}{msg}{cls.RESET}\n")
324
+ input("Press Enter to return to cockpit...")
325
+ elif choice == "4":
326
+ from tzero.tzero_commit import LocalSemanticCommitSynthesizer
327
+ print(f"\n{cls.YELLOW}[Synthesizing Release CHANGELOG]...{cls.RESET}")
328
+ entry = LocalSemanticCommitSynthesizer.generate_changelog_entry(version="v12.2.1", repo_dir=workspace_dir)
329
+ print(f"\n{cls.BRIGHT_CYAN}{entry}{cls.RESET}\n")
330
+ input("Press Enter to return to cockpit...")
331
+ elif choice == "5":
332
+ patch_path = input("Enter path to unified diff file: ").strip()
333
+ if patch_path and os.path.exists(patch_path):
334
+ from tzero.tzero_patch import ASTFuzzyPatcher
335
+ res = ASTFuzzyPatcher.apply_patch_file(patch_path, workspace_dir=workspace_dir)
336
+ print(f"{cls.GREEN}[RESULT] Applied {res.get('applied_hunks', 0)}/{res.get('total_hunks', 0)} hunks.{cls.RESET}")
337
+ else:
338
+ print(f"{cls.RED}File not found.{cls.RESET}")
339
+ input("Press Enter to return to cockpit...")
340
+ elif choice == "6":
341
+ print(f"\n{cls.GREEN}[Launching Web Dashboard on http://localhost:8421]...{cls.RESET}")
342
+ import socket
343
+ import threading
344
+ import webbrowser
345
+ is_up = False
346
+ try:
347
+ with socket.create_connection(("127.0.0.1", 8421), timeout=0.3):
348
+ is_up = True
349
+ except OSError:
350
+ is_up = False
351
+ if not is_up:
352
+ try:
353
+ from tzero.tzero_dashboard import start_dashboard_server
354
+ srv = start_dashboard_server(port=8421, open_browser=False)
355
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
356
+ except Exception:
357
+ pass
358
+ webbrowser.open("http://localhost:8421")
359
+ time.sleep(1)
360
+ elif choice == "7":
361
+ from tzero.tzero_guard import GitSecurityGuard
362
+ from tzero.tzero_ci import CIPipelineGenerator
363
+ GitSecurityGuard.install_hook(workspace_dir)
364
+ CIPipelineGenerator.install_github_workflow(workspace_dir)
365
+ print(f"{cls.GREEN}[SUCCESS] Pre-commit hook & GitHub Actions CI installed!{cls.RESET}")
366
+ input("Press Enter to return to cockpit...")
367
+ elif choice == "8":
368
+ from tzero.tzero_arch_test import ArchitectureTestSuiteGenerator
369
+ print(f"\n{cls.YELLOW}[Verifying Layer Boundaries, Cycles & Zero-Leak Security]...{cls.RESET}")
370
+ gen = ArchitectureTestSuiteGenerator(workspace_dir)
371
+ rep = gen.run_live_audit()
372
+ if rep["success"]:
373
+ print(f"\n{cls.GREEN}✅ [ARCH-AUDIT PASS] All {rep['scanned_files']} files conform to rules! Zero violations.{cls.RESET}\n")
374
+ else:
375
+ print(f"\n{cls.RED}❌ [ARCH-AUDIT FAILED] Violations detected:{cls.RESET}")
376
+ for v in rep["layer_violations"]:
377
+ print(f" • {v['file']} (layer: {v['layer']}) imports forbidden '{v['imported']}'")
378
+ input("Press Enter to return to cockpit...")
379
+ elif choice == "9":
380
+ target_f = input("Enter path to file for mutation test (default: tzero_arch_test.py): ").strip() or "tzero_arch_test.py"
381
+ if os.path.exists(target_f):
382
+ from tzero.tzero_mutation import ASTMutationEngine
383
+ print(f"\n{cls.YELLOW}[Running AST Mutation Analysis on {target_f}]...{cls.RESET}")
384
+ m_rep = ASTMutationEngine.run_mutation_analysis(target_file=target_f, max_mutants=5)
385
+ print(f"{cls.GREEN}[RESULT] Mutation Score: {m_rep.mutation_score}% ({m_rep.killed}/{m_rep.total_mutants} killed).{cls.RESET}")
386
+ else:
387
+ print(f"{cls.RED}Target file not found.{cls.RESET}")
388
+ input("Press Enter to return to cockpit...")
389
+ elif choice == "10":
390
+ from tzero.tzero_debt import CodeHealthAnalyzer
391
+ print(f"\n{cls.YELLOW}[Analyzing Code Health & Technical Debt Index for {workspace_dir}]...{cls.RESET}")
392
+ rep = CodeHealthAnalyzer.analyze_workspace(workspace_dir)
393
+ print(f"\n{cls.BRIGHT_CYAN}{CodeHealthAnalyzer.format_markdown_report(rep)}{cls.RESET}\n")
394
+ input("Press Enter to return to cockpit...")
395
+ elif choice == "11":
396
+ from tzero.tzero_budget import ASTTokenBudgetOptimizer
397
+ print(f"\n{cls.YELLOW}[Sizing Context Payload & Issuing Compression Certificate for {workspace_dir}]...{cls.RESET}")
398
+ cert = ASTTokenBudgetOptimizer.optimize_budget(workspace_dir)
399
+ saved_p = ASTTokenBudgetOptimizer.save_certificate(cert)
400
+ print(f"\n{cls.BRIGHT_CYAN}{ASTTokenBudgetOptimizer.format_markdown_certificate(cert)}{cls.RESET}\n")
401
+ print(f"{cls.GREEN}[SUCCESS] Certificate saved to: {saved_p}{cls.RESET}")
402
+ input("Press Enter to return to cockpit...")
403
+ elif choice == "12":
404
+ from tzero.tzero_armor import audit_path_rea_resistance, protect_path_with_armor
405
+ print(f"\n{cls.YELLOW}[Auditing 26-Tier Anti-REA Resistance for {workspace_dir}]...{cls.RESET}")
406
+ audit = audit_path_rea_resistance(workspace_dir)
407
+ print(f"{cls.BRIGHT_CYAN}AI Resistance Score: {audit.get('score', 0)}/100 ({audit.get('rating', 'UNKNOWN')}){cls.RESET}")
408
+ apply_ans = input("Apply Anti-REA armor to target file/dir now? [y/N]: ").strip().lower()
409
+ if apply_ans == "y":
410
+ res = protect_path_with_armor(workspace_dir)
411
+ print(f"{cls.GREEN}[OK] Protected: {res}{cls.RESET}")
412
+ input("Press Enter to return to cockpit...")
413
+ elif choice == "13":
414
+ from tzero.tzero_telemetry import render_report
415
+ print(f"\n{cls.BRIGHT_CYAN}{render_report(workspace_dir)}{cls.RESET}\n")
416
+ input("Press Enter to return to cockpit...")
417
+ else:
418
+ print(f"{cls.RED}Invalid selection: {choice}{cls.RESET}")
419
+ time.sleep(0.5)
420
+ return True
421
+
186
422
  @classmethod
187
423
  def run_interactive(cls, workspace_dir: str = "."):
188
- """Runs the interactive loop in the user terminal."""
424
+ """Runs the interactive loop in the user terminal with smooth wrap-around navigation."""
425
+ if sys.platform == "win32":
426
+ try:
427
+ os.system("")
428
+ except Exception:
429
+ pass
430
+
431
+ selected_index = 0
432
+ menu_len = len(cls.MENU_OPTIONS)
433
+ num_buffer = ""
434
+ last_num_time = 0.0
435
+
189
436
  while True:
190
437
  metrics = cls.gather_workspace_metrics(workspace_dir)
191
- screen = cls.render_cockpit(metrics)
192
- print("\033[H\033[J", end="") # Clear screen ANSI
438
+ screen = cls.render_cockpit(metrics, selected_index=selected_index)
439
+ # Smooth screen clearing without scrolling overflow
440
+ print("\033[2J\033[H", end="", flush=True)
193
441
  print(screen)
194
442
 
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.15.2", 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
443
+ # Fallback for non-interactive / piped environments
444
+ if not sys.stdin.isatty():
243
445
  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...")
446
+ choice = input(f"\n{cls.BOLD}Select an action [0-11] (or press Enter to refresh): {cls.RESET}").strip()
447
+ except (KeyboardInterrupt, EOFError):
448
+ print(f"\n{cls.CYAN}Goodbye! T-Zero Context Engine active.{cls.RESET}")
449
+ break
450
+ if not choice:
451
+ continue
452
+ if not cls.execute_action(choice, workspace_dir):
453
+ break
454
+ continue
455
+
456
+ # Interactive keyboard loop with arrow navigation & smooth wrap-around
457
+ chosen = False
458
+ choice = ""
459
+ while not chosen:
460
+ print(f"\r{cls.BOLD} Navigate [↑/↓/←/→, w/s, k/j] │ Select [Enter] │ Quick Jump [0-11] │ Exit [q/esc]: {cls.RESET}", end="", flush=True)
461
+ key = cls._read_key()
462
+ if not key:
463
+ time.sleep(0.04)
464
+ continue
465
+
466
+ if key in ("CTRL_C", "q", "Q", "ESC"):
467
+ print(f"\n{cls.CYAN}Goodbye! T-Zero Context Engine active.{cls.RESET}")
468
+ return
469
+ elif key in ("UP", "LEFT", "k", "K", "w", "W", "SHIFT_TAB"):
470
+ # Smooth wrap-around: jump from top item to bottom item
471
+ selected_index = (selected_index - 1) % menu_len
472
+ break
473
+ elif key in ("DOWN", "RIGHT", "j", "J", "s", "S", "TAB"):
474
+ # Smooth wrap-around: jump from bottom item to top item
475
+ selected_index = (selected_index + 1) % menu_len
476
+ break
477
+ elif key == "ENTER":
478
+ choice = cls.MENU_OPTIONS[selected_index][0]
479
+ chosen = True
480
+ elif key in [str(i) for i in range(10)]:
481
+ now = time.time()
482
+ if now - last_num_time > 0.8:
483
+ num_buffer = key
484
+ else:
485
+ num_buffer += key
486
+ last_num_time = now
487
+
488
+ # Match against menu item keys
489
+ matched_idx = None
490
+ for idx, (mkey, _, _) in enumerate(cls.MENU_OPTIONS):
491
+ if mkey == num_buffer:
492
+ matched_idx = idx
493
+ break
494
+ if matched_idx is not None:
495
+ selected_index = matched_idx
496
+ break
497
+ elif len(num_buffer) > 1:
498
+ num_buffer = key
499
+ for idx, (mkey, _, _) in enumerate(cls.MENU_OPTIONS):
500
+ if mkey == num_buffer:
501
+ selected_index = idx
502
+ break
503
+ break
504
+
505
+ if chosen and choice:
506
+ print()
507
+ if not cls.execute_action(choice, workspace_dir):
508
+ break
300
509
 
301
510
 
302
511
  def main():