tzero-mcp 10.7.3 → 11.0.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 (127) hide show
  1. package/CHANGELOG.md +44 -577
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -65
  5. package/bin/tzero.js +61 -64
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -67
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -19
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -0,0 +1,461 @@
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Autonomous AST Code Health, Cognitive Complexity & Technical Debt Index.
3
+
4
+ Computes exact AST-based cognitive complexity, standard Maintainability Index (MI 0-100),
5
+ Halstead volume approximations, and financial technical debt refactoring estimates ($ / hours).
6
+
7
+ Capabilities:
8
+ - Cognitive Complexity analysis (Sonarqube-style nesting & branching weights).
9
+ - Cyclomatic Complexity & Maintainability Index (MI 0-100: Green / Yellow / Red).
10
+ - God Class & Long Method code smell detection.
11
+ - Debt Marker Tracker (TODO, FIXME, HACK, XXX, TEMP).
12
+ - Quantitative Refactoring Hours & Financial Debt ROI computation.
13
+ - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
14
+
15
+ Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
+ Part of T-Zero Context Architect v11.0.0 Master Edition.
17
+ """
18
+
19
+ import ast
20
+ import json
21
+ import math
22
+ import os
23
+ import re
24
+ import sys
25
+ from dataclasses import dataclass, field, asdict
26
+ from typing import Dict, List, Optional, Tuple, Any
27
+
28
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
29
+ try:
30
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
31
+ except Exception:
32
+ pass
33
+
34
+
35
+ @dataclass
36
+ class FunctionHealth:
37
+ name: str
38
+ line_number: int
39
+ lines_of_code: int
40
+ cyclomatic_complexity: int
41
+ cognitive_complexity: int
42
+ debt_hours: float
43
+ issues: List[str] = field(default_factory=list)
44
+
45
+
46
+ @dataclass
47
+ class ClassHealth:
48
+ name: str
49
+ line_number: int
50
+ method_count: int
51
+ lines_of_code: int
52
+ total_cognitive_complexity: int
53
+ is_god_class: bool
54
+ issues: List[str] = field(default_factory=list)
55
+
56
+
57
+ @dataclass
58
+ class FileHealthReport:
59
+ file_path: str
60
+ lines_of_code: int
61
+ maintainability_index: float # 0 to 100
62
+ rating: str # A (Good), B (Fair), C (Warning), D (Critical)
63
+ cyclomatic_complexity: int
64
+ cognitive_complexity: int
65
+ debt_hours: float
66
+ debt_cost_usd: float # at $75/hr benchmark
67
+ todo_count: int
68
+ functions: List[FunctionHealth] = field(default_factory=list)
69
+ classes: List[ClassHealth] = field(default_factory=list)
70
+ debt_markers: List[Dict[str, Any]] = field(default_factory=list)
71
+
72
+
73
+ @dataclass
74
+ class WorkspaceHealthReport:
75
+ workspace_root: str
76
+ total_files: int
77
+ total_lines_of_code: int
78
+ average_maintainability_index: float
79
+ overall_rating: str
80
+ total_debt_hours: float
81
+ total_debt_cost_usd: float
82
+ total_todo_markers: int
83
+ top_refactoring_hotspots: List[Dict[str, Any]] = field(default_factory=list)
84
+ file_reports: List[FileHealthReport] = field(default_factory=list)
85
+
86
+
87
+ class ASTCognitiveComplexityVisitor(ast.NodeVisitor):
88
+ """Calculates cognitive complexity based on nesting penalties and structural breaks."""
89
+
90
+ def __init__(self):
91
+ self.complexity = 0
92
+ self.nesting_level = 0
93
+
94
+ def visit_FunctionDef(self, node: ast.FunctionDef):
95
+ # Don't increment nesting level for top-level function itself
96
+ old_nesting = self.nesting_level
97
+ for item in node.body:
98
+ self.visit(item)
99
+ self.nesting_level = old_nesting
100
+
101
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):
102
+ old_nesting = self.nesting_level
103
+ for item in node.body:
104
+ self.visit(item)
105
+ self.nesting_level = old_nesting
106
+
107
+ def visit_If(self, node: ast.If):
108
+ # +1 for if, plus nesting increment
109
+ self.complexity += (1 + self.nesting_level)
110
+ self.nesting_level += 1
111
+ for item in node.body:
112
+ self.visit(item)
113
+ self.nesting_level -= 1
114
+
115
+ if node.orelse:
116
+ # If elif, handled by child If; else increment
117
+ if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
118
+ self.visit(node.orelse[0])
119
+ else:
120
+ self.complexity += 1
121
+ self.nesting_level += 1
122
+ for item in node.orelse:
123
+ self.visit(item)
124
+ self.nesting_level -= 1
125
+
126
+ def visit_For(self, node: ast.For):
127
+ self.complexity += (1 + self.nesting_level)
128
+ self.nesting_level += 1
129
+ for item in node.body:
130
+ self.visit(item)
131
+ self.nesting_level -= 1
132
+
133
+ def visit_AsyncFor(self, node: ast.AsyncFor):
134
+ self.complexity += (1 + self.nesting_level)
135
+ self.nesting_level += 1
136
+ for item in node.body:
137
+ self.visit(item)
138
+ self.nesting_level -= 1
139
+
140
+ def visit_While(self, node: ast.While):
141
+ self.complexity += (1 + self.nesting_level)
142
+ self.nesting_level += 1
143
+ for item in node.body:
144
+ self.visit(item)
145
+ self.nesting_level -= 1
146
+
147
+ def visit_ExceptHandler(self, node: ast.ExceptHandler):
148
+ self.complexity += (1 + self.nesting_level)
149
+ self.nesting_level += 1
150
+ for item in node.body:
151
+ self.visit(item)
152
+ self.nesting_level -= 1
153
+
154
+ def visit_BoolOp(self, node: ast.BoolOp):
155
+ # Multiple binary boolean conditions (e.g. a and b and c -> +2)
156
+ if len(node.values) > 1:
157
+ self.complexity += (len(node.values) - 1)
158
+ self.generic_visit(node)
159
+
160
+
161
+ class CodeHealthAnalyzer:
162
+ """Analyzes AST maintainability index, cognitive complexity, and technical debt."""
163
+
164
+ HOURLY_DEV_RATE = 75.0 # $75/hr engineering benchmark
165
+
166
+ @classmethod
167
+ def compute_cognitive_complexity(cls, node: ast.AST) -> int:
168
+ visitor = ASTCognitiveComplexityVisitor()
169
+ visitor.visit(node)
170
+ return visitor.complexity
171
+
172
+ @classmethod
173
+ def compute_cyclomatic_complexity(cls, node: ast.AST) -> int:
174
+ """Computes McCabe cyclomatic complexity: decision points + 1."""
175
+ decisions = 0
176
+ for sub in ast.walk(node):
177
+ if isinstance(sub, (ast.If, ast.For, ast.While, ast.AsyncFor, ast.ExceptHandler, ast.With, ast.Assert)):
178
+ decisions += 1
179
+ elif isinstance(sub, ast.BoolOp):
180
+ decisions += max(1, len(sub.values) - 1)
181
+ return decisions + 1
182
+
183
+ @classmethod
184
+ def compute_maintainability_index(cls, code: str, cyclomatic: int) -> float:
185
+ """Computes SEI/Microsoft Maintainability Index normalized to 0-100."""
186
+ lines = [ln.strip() for ln in code.splitlines() if ln.strip() and not ln.strip().startswith("#")]
187
+ loc = max(1, len(lines))
188
+ # Estimate Halstead volume based on tokens and character volume
189
+ halstead_vol = max(1.0, len(code) * math.log2(max(2, len(set(code.split())))))
190
+
191
+ # Standard formula: 171 - 5.2 * ln(V) - 0.23 * CC - 16.2 * ln(LOC)
192
+ raw_mi = 171.0 - (5.2 * math.log(halstead_vol)) - (0.23 * cyclomatic) - (16.2 * math.log(loc))
193
+ normalized = max(0.0, min(100.0, (raw_mi * 100.0) / 171.0))
194
+ return round(normalized, 1)
195
+
196
+ @classmethod
197
+ def extract_debt_markers(cls, code: str) -> List[Dict[str, Any]]:
198
+ """Finds TODO, FIXME, HACK, XXX, TEMP debt comments."""
199
+ markers = []
200
+ pattern = re.compile(r"#\s*(TODO|FIXME|HACK|XXX|TEMP)[:\s]*(.*)", re.IGNORECASE)
201
+ for idx, line in enumerate(code.splitlines(), start=1):
202
+ match = pattern.search(line)
203
+ if match:
204
+ markers.append({
205
+ "line": idx,
206
+ "tag": match.group(1).upper(),
207
+ "text": match.group(2).strip()
208
+ })
209
+ return markers
210
+
211
+ @classmethod
212
+ def analyze_file(cls, file_path: str, code: Optional[str] = None) -> FileHealthReport:
213
+ if code is None:
214
+ try:
215
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
216
+ code = f.read()
217
+ except Exception as e:
218
+ return FileHealthReport(
219
+ file_path=file_path,
220
+ lines_of_code=0,
221
+ maintainability_index=100.0,
222
+ rating="A",
223
+ cyclomatic_complexity=1,
224
+ cognitive_complexity=0,
225
+ debt_hours=0.0,
226
+ debt_cost_usd=0.0,
227
+ todo_count=0
228
+ )
229
+
230
+ try:
231
+ tree = ast.parse(code)
232
+ except Exception:
233
+ return FileHealthReport(
234
+ file_path=file_path,
235
+ lines_of_code=len(code.splitlines()),
236
+ maintainability_index=0.0,
237
+ rating="D",
238
+ cyclomatic_complexity=10,
239
+ cognitive_complexity=10,
240
+ debt_hours=2.0,
241
+ debt_cost_usd=150.0,
242
+ todo_count=0
243
+ )
244
+
245
+ total_cc = cls.compute_cyclomatic_complexity(tree)
246
+ total_cog = cls.compute_cognitive_complexity(tree)
247
+ mi = cls.compute_maintainability_index(code, total_cc)
248
+ debt_markers = cls.extract_debt_markers(code)
249
+
250
+ fn_reports: List[FunctionHealth] = []
251
+ cls_reports: List[ClassHealth] = []
252
+ total_debt_hours = len(debt_markers) * 0.5 # 30m per TODO/FIXME
253
+
254
+ for node in ast.walk(tree):
255
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
256
+ fn_loc = (node.end_lineno - node.lineno + 1) if getattr(node, "end_lineno", None) else 10
257
+ fn_cc = cls.compute_cyclomatic_complexity(node)
258
+ fn_cog = cls.compute_cognitive_complexity(node)
259
+ issues = []
260
+ debt_h = 0.0
261
+
262
+ if fn_cog > 15:
263
+ issues.append(f"High cognitive complexity ({fn_cog} > 15)")
264
+ debt_h += (fn_cog - 15) * 0.25
265
+
266
+ if fn_loc > 50:
267
+ issues.append(f"Long function ({fn_loc} lines > 50)")
268
+ debt_h += 1.0
269
+
270
+ if fn_cc > 10:
271
+ issues.append(f"High cyclomatic complexity ({fn_cc} > 10)")
272
+ debt_h += 0.5
273
+
274
+ total_debt_hours += debt_h
275
+ fn_reports.append(FunctionHealth(
276
+ name=node.name,
277
+ line_number=node.lineno,
278
+ lines_of_code=fn_loc,
279
+ cyclomatic_complexity=fn_cc,
280
+ cognitive_complexity=fn_cog,
281
+ debt_hours=round(debt_h, 2),
282
+ issues=issues
283
+ ))
284
+
285
+ elif isinstance(node, ast.ClassDef):
286
+ cls_loc = (node.end_lineno - node.lineno + 1) if getattr(node, "end_lineno", None) else 20
287
+ methods = [item for item in node.body if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))]
288
+ m_count = len(methods)
289
+ is_god = m_count > 12 or cls_loc > 300
290
+ cls_cog = cls.compute_cognitive_complexity(node)
291
+ issues = []
292
+ debt_h = 0.0
293
+
294
+ if is_god:
295
+ issues.append(f"God class detected ({m_count} methods, {cls_loc} lines)")
296
+ debt_h += 2.5
297
+
298
+ total_debt_hours += debt_h
299
+ cls_reports.append(ClassHealth(
300
+ name=node.name,
301
+ line_number=node.lineno,
302
+ method_count=m_count,
303
+ lines_of_code=cls_loc,
304
+ total_cognitive_complexity=cls_cog,
305
+ is_god_class=is_god,
306
+ issues=issues
307
+ ))
308
+
309
+ if mi >= 80:
310
+ rating = "A"
311
+ elif mi >= 65:
312
+ rating = "B"
313
+ elif mi >= 50:
314
+ rating = "C"
315
+ else:
316
+ rating = "D"
317
+
318
+ total_debt_hours = round(total_debt_hours, 2)
319
+ debt_cost = round(total_debt_hours * cls.HOURLY_DEV_RATE, 2)
320
+
321
+ return FileHealthReport(
322
+ file_path=file_path,
323
+ lines_of_code=len(code.splitlines()),
324
+ maintainability_index=mi,
325
+ rating=rating,
326
+ cyclomatic_complexity=total_cc,
327
+ cognitive_complexity=total_cog,
328
+ debt_hours=total_debt_hours,
329
+ debt_cost_usd=debt_cost,
330
+ todo_count=len(debt_markers),
331
+ functions=fn_reports,
332
+ classes=cls_reports,
333
+ debt_markers=debt_markers
334
+ )
335
+
336
+ @classmethod
337
+ def analyze_workspace(cls, workspace_root: str = ".", max_files: int = 250) -> WorkspaceHealthReport:
338
+ abs_root = os.path.abspath(workspace_root)
339
+ reports: List[FileHealthReport] = []
340
+
341
+ ignore_dirs = {".git", ".venv", "venv", "__pycache__", "node_modules", "dist", "build", ".pytest_cache"}
342
+
343
+ for root, dirs, files in os.walk(abs_root):
344
+ dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
345
+ for f in files:
346
+ if f.endswith(".py"):
347
+ rel_p = os.path.relpath(os.path.join(root, f), abs_root)
348
+ rep = cls.analyze_file(os.path.join(root, f))
349
+ rep.file_path = rel_p.replace("\\", "/")
350
+ reports.append(rep)
351
+ if len(reports) >= max_files:
352
+ break
353
+ if len(reports) >= max_files:
354
+ break
355
+
356
+ if not reports:
357
+ return WorkspaceHealthReport(
358
+ workspace_root=workspace_root,
359
+ total_files=0,
360
+ total_lines_of_code=0,
361
+ average_maintainability_index=100.0,
362
+ overall_rating="A",
363
+ total_debt_hours=0.0,
364
+ total_debt_cost_usd=0.0,
365
+ total_todo_markers=0
366
+ )
367
+
368
+ total_loc = sum(r.lines_of_code for r in reports)
369
+ avg_mi = round(sum(r.maintainability_index for r in reports) / len(reports), 1)
370
+ tot_hours = round(sum(r.debt_hours for r in reports), 1)
371
+ tot_cost = round(tot_hours * cls.HOURLY_DEV_RATE, 2)
372
+ tot_todos = sum(r.todo_count for r in reports)
373
+
374
+ if avg_mi >= 80:
375
+ overall_r = "A"
376
+ elif avg_mi >= 65:
377
+ overall_r = "B"
378
+ elif avg_mi >= 50:
379
+ overall_r = "C"
380
+ else:
381
+ overall_r = "D"
382
+
383
+ # Find top 5 hotspots across files
384
+ all_hotspots = []
385
+ for r in reports:
386
+ for fn in r.functions:
387
+ if fn.issues:
388
+ all_hotspots.append({
389
+ "file": r.file_path,
390
+ "symbol": f"{fn.name}()",
391
+ "line": fn.line_number,
392
+ "cognitive": fn.cognitive_complexity,
393
+ "debt_hours": fn.debt_hours,
394
+ "issues": ", ".join(fn.issues)
395
+ })
396
+ for cl in r.classes:
397
+ if cl.is_god_class:
398
+ all_hotspots.append({
399
+ "file": r.file_path,
400
+ "symbol": f"class {cl.name}",
401
+ "line": cl.line_number,
402
+ "cognitive": cl.total_cognitive_complexity,
403
+ "debt_hours": 2.5,
404
+ "issues": ", ".join(cl.issues)
405
+ })
406
+
407
+ all_hotspots.sort(key=lambda x: x["cognitive"], reverse=True)
408
+ top_hotspots = all_hotspots[:5]
409
+
410
+ return WorkspaceHealthReport(
411
+ workspace_root=workspace_root,
412
+ total_files=len(reports),
413
+ total_lines_of_code=total_loc,
414
+ average_maintainability_index=avg_mi,
415
+ overall_rating=overall_r,
416
+ total_debt_hours=tot_hours,
417
+ total_debt_cost_usd=tot_cost,
418
+ total_todo_markers=tot_todos,
419
+ top_refactoring_hotspots=top_hotspots,
420
+ file_reports=reports
421
+ )
422
+
423
+ @classmethod
424
+ def format_markdown_report(cls, report: WorkspaceHealthReport) -> str:
425
+ """Formats the technical debt index into an executive GitHub Markdown document."""
426
+ badge = "🟢 Grade A (High Maintainability)" if report.overall_rating == "A" else (
427
+ "🟡 Grade B (Moderate Maintainability)" if report.overall_rating == "B" else (
428
+ "🟠 Grade C (Technical Debt Warning)" if report.overall_rating == "C" else "🔴 Grade D (Critical Refactor Required)"
429
+ )
430
+ )
431
+
432
+ lines = [
433
+ "# 🏥 T-Zero Code Health & Technical Debt Index",
434
+ f"**Workspace:** `{os.path.abspath(report.workspace_root)}` | **Status:** {badge}",
435
+ "",
436
+ "## 📊 Executive Summary Metrics",
437
+ f"- **Files Analyzed:** `{report.total_files}` modules (`{report.total_lines_of_code}` total lines of code)",
438
+ f"- **Average Maintainability Index (MI):** `{report.average_maintainability_index} / 100` (Grade `{report.overall_rating}`)",
439
+ f"- **Estimated Technical Debt:** `~{report.total_debt_hours} hours` (`${report.total_debt_cost_usd:,.2f}` refactor budget @ ${cls.HOURLY_DEV_RATE:.0f}/hr)",
440
+ f"- **Lingering Debt Markers:** `{report.total_todo_markers}` (TODO / FIXME / HACK comments)",
441
+ ""
442
+ ]
443
+
444
+ if report.top_refactoring_hotspots:
445
+ lines.append("## 🎯 Top Priority Refactoring Hotspots")
446
+ lines.append("| File | Symbol | Line | Cognitive Complexity | Debt Est. | Issues |")
447
+ lines.append("| :--- | :--- | :---: | :---: | :---: | :--- |")
448
+ for h in report.top_refactoring_hotspots:
449
+ lines.append(f"| `{h['file']}` | `{h['symbol']}` | `{h['line']}` | `{h['cognitive']}` | `~{h['debt_hours']}h` | {h['issues']} |")
450
+ lines.append("")
451
+
452
+ lines.append("## 💡 T-Zero Autonomous Recommendations")
453
+ if report.average_maintainability_index >= 80:
454
+ lines.append("1. ✅ **Outstanding Architecture:** Codebase exhibits high modularity and low cognitive overhead.")
455
+ else:
456
+ lines.append("1. ⚠️ **Decompose God Classes & Functions:** Extract methods with cognitive complexity > 15 into dedicated helper modules.")
457
+ lines.append("2. 🛡️ **Maintain Zero-Leak Security:** Keep all secret keys in environment variables.")
458
+ lines.append("3. ⚡ **Run AST Mutation Tests:** Validate that your test suite actively detects logical mutations (`tzero mutate <file>`).")
459
+
460
+ return "\n".join(lines).strip()
461
+
@@ -217,7 +217,171 @@ def _line(level: str, text: str) -> str:
217
217
  return f" [{level:^4}] {text}"
218
218
 
219
219
 
220
- def run_doctor() -> int:
220
+ def _run_deep_subsystem_check() -> int:
221
+ """Exercise all 9 v11 offline subsystems and report pass/fail. Returns failure count."""
222
+ import tempfile
223
+ from pathlib import Path
224
+
225
+ print("\nDeep Offline Subsystem Self-Check:")
226
+ checks = []
227
+
228
+ with tempfile.TemporaryDirectory() as tmpdir:
229
+ # 1. BPE Tokenizer
230
+ try:
231
+ from tzero.tzero_polyglot import count_bpe_tokens
232
+ tok = count_bpe_tokens("def hello(): pass\n")
233
+ if not (isinstance(tok, int) and tok > 0):
234
+ raise ValueError("unexpected diagnostic result")
235
+ checks.append(("BPE Tokenizer", True, ""))
236
+ except Exception as exc:
237
+ checks.append(("BPE Tokenizer", False, str(exc)))
238
+
239
+ # 2. Polyglot AST Reducer
240
+ try:
241
+ from tzero.tzero_polyglot import PolyglotTokenReducer
242
+ r = PolyglotTokenReducer()
243
+ out = r.reduce_code("def foo(x: int) -> int:\n return x + 1\n", filename="foo.py")
244
+ if not ("def foo" in out):
245
+ raise ValueError("unexpected diagnostic result")
246
+ ts = r.reduce_code("export function greet(name: string): string { return name; }", filename="sample.ts")
247
+ if not ("greet" in ts):
248
+ raise ValueError("unexpected diagnostic result")
249
+ checks.append(("Polyglot AST Reducer", True, ""))
250
+ except Exception as exc:
251
+ checks.append(("Polyglot AST Reducer", False, str(exc)))
252
+
253
+ # 3. Zero-Leak Engine
254
+ try:
255
+ from tzero.tzero_security import ZeroLeakEngine
256
+ fake_key = "sk" + "-" + "a" * 32
257
+ result = ZeroLeakEngine.scan_text(fake_key)
258
+ if not (isinstance(result, list) and len(result) > 0):
259
+ raise ValueError("unexpected diagnostic result")
260
+ checks.append(("Zero-Leak Engine", True, ""))
261
+ except Exception as exc:
262
+ checks.append(("Zero-Leak Engine", False, str(exc)))
263
+
264
+ # 4. LSP Server
265
+ try:
266
+ from tzero.tzero_lsp import TZeroLSPServer
267
+ lsp = TZeroLSPServer(workspace_dir=tmpdir)
268
+ py_path = os.path.join(tmpdir, "sample.py")
269
+ code = f'SERVICE_KEY = "{fake_key}"\n' + "def greet(name: str) -> str:\n return name\n"
270
+ Path(py_path).write_text(code, encoding="utf-8")
271
+ uri = Path(py_path).as_uri()
272
+ opened = lsp.handle_message({
273
+ "jsonrpc": "2.0",
274
+ "method": "textDocument/didOpen",
275
+ "params": {"textDocument": {"uri": uri, "text": code}},
276
+ })
277
+ hover = lsp.compute_hover(uri, code, line=1, character=4)
278
+ if hover is None:
279
+ raise ValueError("unexpected diagnostic result")
280
+ diagnostics = opened[0]["params"]["diagnostics"]
281
+ if not (lsp.compute_code_actions(uri, code, diagnostics)):
282
+ raise ValueError("unexpected diagnostic result")
283
+ checks.append(("LSP Server", True, ""))
284
+ except Exception as exc:
285
+ checks.append(("LSP Server", False, str(exc)))
286
+
287
+ # 5. Lifecycle Hooks
288
+ try:
289
+ from tzero.tzero_hooks import evaluate_pre_tool_use, evaluate_post_tool_use
290
+ blocked = evaluate_pre_tool_use(
291
+ {"tool_name": "Read", "tool_input": {"file_path": ".env"}},
292
+ workspace_dir=tmpdir,
293
+ )
294
+ if not (blocked["decision"] == "block"):
295
+ raise ValueError("unexpected diagnostic result")
296
+ big = "def x(): pass\n" * 20
297
+ pruned = evaluate_post_tool_use(
298
+ {"tool_name": "Read", "tool_input": {"file_path": "f.py"}, "tool_response": big},
299
+ workspace_dir=tmpdir,
300
+ max_chars=50,
301
+ )
302
+ if not (pruned["decision"] == "prune"):
303
+ raise ValueError("unexpected diagnostic result")
304
+ checks.append(("Lifecycle Hooks", True, ""))
305
+ except Exception as exc:
306
+ checks.append(("Lifecycle Hooks", False, str(exc)))
307
+
308
+ # 6. Federation Sync
309
+ try:
310
+ from tzero.tzero_federation import FederationSyncEngine
311
+ peer_ws = os.path.join(tmpdir, "peer")
312
+ os.mkdir(peer_ws)
313
+ peer_py = os.path.join(peer_ws, "ledger.py")
314
+ with open(peer_py, "w", encoding="utf-8") as fh:
315
+ fh.write("class Ledger:\n pass\n")
316
+ manifest_file = os.path.join(peer_ws, "manifest.json")
317
+ exported = FederationSyncEngine.export_manifest(peer_ws, repo_name="deep-peer", out_file=manifest_file)
318
+ if not (FederationSyncEngine.verify_manifest(exported)):
319
+ raise ValueError("unexpected diagnostic result")
320
+ imp = FederationSyncEngine.import_manifest(tmpdir, manifest_file)
321
+ if not (imp["verified"]):
322
+ raise ValueError("unexpected diagnostic result")
323
+ checks.append(("Federation Sync", True, ""))
324
+ except Exception as exc:
325
+ checks.append(("Federation Sync", False, str(exc)))
326
+
327
+ # 7. SCIP Importer
328
+ try:
329
+ from tzero.tzero_scip import ScipIndexImporter
330
+ sample = {"documents": [{"relative_path": "a.py", "occurrences": [
331
+ {"range": [0, 0, 0, 5], "symbol": "MyClass", "symbol_roles": 1},
332
+ ]}]}
333
+ graph = ScipIndexImporter.from_scip_dict(sample)
334
+ if not (graph.format_name in ("scip", "scip-dict")):
335
+ raise ValueError("unexpected diagnostic result")
336
+ checks.append(("SCIP Importer", True, ""))
337
+ except Exception as exc:
338
+ checks.append(("SCIP Importer", False, str(exc)))
339
+
340
+ # 8. Contracts & SARIF
341
+ try:
342
+ from tzero.tzero_contracts import ASTContractComparator
343
+ old = "def foo(x: int) -> int:\n return x\n"
344
+ new = "def foo(x: int, y: int) -> int:\n return x + y\n"
345
+ diff_rep = ASTContractComparator.compare_code(old, new, file_path="f.py")
346
+ if not (diff_rep.is_breaking):
347
+ raise ValueError("unexpected diagnostic result")
348
+ sarif = ASTContractComparator.format_sarif_report([diff_rep])
349
+ if not (sarif.get("version") == "2.1.0"):
350
+ raise ValueError("unexpected diagnostic result")
351
+ checks.append(("Contracts & SARIF", True, ""))
352
+ except Exception as exc:
353
+ checks.append(("Contracts & SARIF", False, str(exc)))
354
+
355
+ # 9. Agent Kernel & Snapshot
356
+ try:
357
+ from tzero.tzero_rust_bridge import AgentKernelSandbox
358
+ from tzero.tzero_snapshot import SnapshotEngine
359
+ kernel = AgentKernelSandbox(workspace_dir=tmpdir)
360
+ if not (kernel.validate_execution_plan({"allow_network": False, "read_paths": [tmpdir]})["allowed"]):
361
+ raise ValueError("unexpected diagnostic result")
362
+ if kernel.validate_execution_plan({"allow_network": True, "read_paths": [tmpdir]})["allowed"]:
363
+ raise ValueError("unexpected diagnostic result")
364
+ snap_py = os.path.join(tmpdir, "snap_test.py")
365
+ with open(snap_py, "w", encoding="utf-8") as fh:
366
+ fh.write("def snap_fn(): pass\n")
367
+ snap = SnapshotEngine.create_snapshot(tmpdir)
368
+ if not (snap.file_count >= 1):
369
+ raise ValueError("unexpected diagnostic result")
370
+ checks.append(("Agent Kernel & Snapshot", True, ""))
371
+ except Exception as exc:
372
+ checks.append(("Agent Kernel & Snapshot", False, str(exc)))
373
+
374
+ failures = 0
375
+ for name, passed, msg in checks:
376
+ if passed:
377
+ print(_line("OK", name))
378
+ else:
379
+ failures += 1
380
+ print(_line("FAIL", f"{name}: {msg}"))
381
+ return failures
382
+
383
+
384
+ def run_doctor(deep: bool = False) -> int:
221
385
  """Checks the environment, fixing missing packages when allowed. Returns a process exit code."""
222
386
  print("T-Zero Doctor: environment check\n")
223
387
  failures = 0
@@ -229,7 +393,8 @@ def run_doctor() -> int:
229
393
  failures += 1
230
394
  print(_line("FAIL", f"Python {py}: version {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is required"))
231
395
 
232
- ensure_dependencies(include_mcp=True)
396
+ if not deep:
397
+ ensure_dependencies(include_mcp=True)
233
398
  for dep in REQUIRED + [MCP_DEPENDENCY]:
234
399
  status, version = check_dependency(dep)
235
400
  label = f"{dep.dist_name} {version or ''}".strip()
@@ -272,8 +437,18 @@ def run_doctor() -> int:
272
437
  except Exception as exc:
273
438
  print(_line("WARN", f"keyring could not be checked: {exc}"))
274
439
 
275
- ensure_scripts_in_path(quiet=True)
276
- print(_line("OK", "Python Scripts PATH verified (tzero, tzero-gui, tzero-mcp accessible)"))
440
+ if not deep:
441
+ ensure_scripts_in_path(quiet=True)
442
+ print(_line("OK", "Python Scripts PATH verified (tzero, tzero-gui, tzero-mcp accessible)"))
443
+
444
+ if deep:
445
+ from tzero.tzero_polyglot import _ALLOW_BPE_DOWNLOAD
446
+
447
+ token = _ALLOW_BPE_DOWNLOAD.set(False)
448
+ try:
449
+ failures += _run_deep_subsystem_check()
450
+ finally:
451
+ _ALLOW_BPE_DOWNLOAD.reset(token)
277
452
 
278
453
  print()
279
454
  if failures: