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,461 +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
-
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.11.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
+