tzero-mcp 11.0.0 → 11.12.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 (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -1,313 +1,313 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Siber Akademi — T-Zero AST Type Stub & Interface (.pyi) Generator.
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- License: MIT
6
-
7
- Extracts ultra-compact, type-safe Python interface stubs (.pyi) directly from
8
- AST syntax trees. Replaces function/method implementations with `...`, preserves
9
- all type hints, decorators, class hierarchies, and infers missing types from
10
- default parameter values. Delivers 90-95% token reduction for agent context ingestion.
11
- """
12
-
13
- import sys
14
- if sys.platform == "win32":
15
- try:
16
- sys.stdout.reconfigure(encoding="utf-8")
17
- sys.stderr.reconfigure(encoding="utf-8")
18
- except Exception:
19
- pass
20
-
21
- import os
22
- import ast
23
- import re
24
- from typing import Dict, List, Optional, Tuple, Any, Set
25
-
26
- from tzero.tzero_features import should_skip_dir, should_skip_file
27
-
28
-
29
- def _infer_type_from_ast_node(node: Optional[ast.AST]) -> Optional[str]:
30
- """Infers a type string from a literal AST constant or default value."""
31
- if node is None:
32
- return None
33
- if isinstance(node, ast.Constant):
34
- val = node.value
35
- if isinstance(val, bool):
36
- return "bool"
37
- elif isinstance(val, int):
38
- return "int"
39
- elif isinstance(val, float):
40
- return "float"
41
- elif isinstance(val, str):
42
- return "str"
43
- elif isinstance(val, bytes):
44
- return "bytes"
45
- elif val is None:
46
- return "Optional[Any]"
47
- elif isinstance(node, ast.List):
48
- return "List[Any]"
49
- elif isinstance(node, ast.Dict):
50
- return "Dict[str, Any]"
51
- elif isinstance(node, ast.Set):
52
- return "Set[Any]"
53
- elif isinstance(node, ast.Tuple):
54
- return "Tuple[Any, ...]"
55
- return None
56
-
57
-
58
- class TypeStubGenerator:
59
- """Enterprise-grade AST type stub (.pyi) extractor and interface generator."""
60
-
61
- @classmethod
62
- def generate_stub_from_code(cls, code: str, file_path: str = "") -> str:
63
- """Parses Python source code and returns a clean, PEP-484 compliant .pyi stub."""
64
- try:
65
- tree = ast.parse(code)
66
- except SyntaxError:
67
- # If code has syntax errors, fallback to basic regex signature extractor
68
- return cls._fallback_regex_stub(code)
69
-
70
- lines: List[str] = []
71
- lines.append("# Auto-generated T-Zero AST Type Stub")
72
- lines.append("from __future__ import annotations")
73
- lines.append("from typing import Any, Optional, List, Dict, Tuple, Set, Union\n")
74
-
75
- # Top-level docstring
76
- doc = ast.get_docstring(tree, clean=True)
77
- if doc:
78
- first_line = doc.strip().split("\n")[0]
79
- lines.append(f'"""{first_line}"""\n')
80
-
81
- # Collect top-level imports and type aliases
82
- for node in tree.body:
83
- if isinstance(node, (ast.Import, ast.ImportFrom)):
84
- # Keep typing and core library imports
85
- imp_code = ast.unparse(node)
86
- if any(k in imp_code for k in ("typing", "abc", "dataclass", "collections", "datetime", "enum")):
87
- lines.append(imp_code)
88
- elif isinstance(node, ast.Assign):
89
- # Check for TypeVar or uppercase module-level constants
90
- for target in node.targets:
91
- if isinstance(target, ast.Name):
92
- name = target.id
93
- val_str = ast.unparse(node.value)
94
- if "TypeVar" in val_str or "NewType" in val_str:
95
- lines.append(f"{name} = {val_str}")
96
- elif name.isupper() and len(name) > 1:
97
- inferred = _infer_type_from_ast_node(node.value) or "Any"
98
- lines.append(f"{name}: {inferred}")
99
-
100
- if len(lines) > 4:
101
- lines.append("")
102
-
103
- # Process classes and top-level functions
104
- for node in tree.body:
105
- if isinstance(node, ast.ClassDef):
106
- cls._format_class(node, lines, indent="")
107
- elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
108
- cls._format_function(node, lines, indent="")
109
-
110
- raw_stub = "\n".join(lines).strip() + "\n"
111
- # Deduplicate multiple consecutive blank lines
112
- cleaned = re.sub(r"\n{3,}", "\n\n", raw_stub)
113
- return cleaned
114
-
115
- @classmethod
116
- def _format_class(cls, node: ast.ClassDef, lines: List[str], indent: str = ""):
117
- """Formats a class declaration and its methods into stub representation."""
118
- decorators = [f"{indent}@{ast.unparse(d)}" for d in node.decorator_list]
119
- lines.extend(decorators)
120
-
121
- # Base classes
122
- bases_str = ", ".join(ast.unparse(b) for b in node.bases)
123
- header = f"{indent}class {node.name}" + (f"({bases_str}):" if bases_str else ":")
124
- lines.append(header)
125
-
126
- inner_indent = indent + " "
127
- has_content = False
128
-
129
- # Class docstring
130
- doc = ast.get_docstring(node, clean=True)
131
- if doc:
132
- first_line = doc.strip().split("\n")[0]
133
- lines.append(f'{inner_indent}"""{first_line}"""')
134
- has_content = True
135
-
136
- for item in node.body:
137
- if isinstance(item, ast.AnnAssign):
138
- target_str = ast.unparse(item.target)
139
- type_str = ast.unparse(item.annotation)
140
- lines.append(f"{inner_indent}{target_str}: {type_str}")
141
- has_content = True
142
- elif isinstance(item, ast.Assign):
143
- for target in item.targets:
144
- if isinstance(target, ast.Name) and not target.id.startswith("_"):
145
- inferred = _infer_type_from_ast_node(item.value) or "Any"
146
- lines.append(f"{inner_indent}{target.id}: {inferred}")
147
- has_content = True
148
- elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
149
- cls._format_function(item, lines, indent=inner_indent)
150
- has_content = True
151
- elif isinstance(item, ast.ClassDef):
152
- cls._format_class(item, lines, indent=inner_indent)
153
- has_content = True
154
-
155
- if not has_content:
156
- lines.append(f"{inner_indent}...")
157
- lines.append("")
158
-
159
- @classmethod
160
- def _format_function(cls, node: Any, lines: List[str], indent: str = ""):
161
- """Formats a function or method into a PEP-484 stub signature with ellipsis."""
162
- # Decorators (skip internal helpers, preserve properties and typing decorators)
163
- for d in node.decorator_list:
164
- dec_str = ast.unparse(d)
165
- lines.append(f"{indent}@{dec_str}")
166
-
167
- prefix = "async def " if isinstance(node, ast.AsyncFunctionDef) else "def "
168
- args_str = cls._format_arguments(node.args)
169
-
170
- # Return type
171
- ret_type = " -> " + ast.unparse(node.returns) if node.returns else ""
172
-
173
- # Function docstring
174
- doc = ast.get_docstring(node, clean=True)
175
- if doc and not indent: # Only for top-level functions to conserve tokens
176
- first_line = doc.strip().split("\n")[0]
177
- sig = f"{indent}{prefix}{node.name}({args_str}){ret_type}:"
178
- lines.append(sig)
179
- lines.append(f'{indent} """{first_line}"""')
180
- lines.append(f"{indent} ...")
181
- else:
182
- sig = f"{indent}{prefix}{node.name}({args_str}){ret_type}: ..."
183
- lines.append(sig)
184
-
185
- @classmethod
186
- def _format_arguments(cls, args: ast.arguments) -> str:
187
- """Formats ast.arguments with type annotations and inferred defaults."""
188
- parts: List[str] = []
189
-
190
- # Positional args and defaults
191
- defaults_offset = len(args.args) - len(args.defaults)
192
- for i, a in enumerate(args.args):
193
- arg_str = a.arg
194
- if a.annotation:
195
- arg_str += f": {ast.unparse(a.annotation)}"
196
- elif i >= defaults_offset:
197
- def_node = args.defaults[i - defaults_offset]
198
- inferred = _infer_type_from_ast_node(def_node)
199
- if inferred:
200
- arg_str += f": {inferred}"
201
-
202
- # Default value representation
203
- if i >= defaults_offset:
204
- def_node = args.defaults[i - defaults_offset]
205
- arg_str += f" = {ast.unparse(def_node)}"
206
- parts.append(arg_str)
207
-
208
- # *vararg
209
- if args.vararg:
210
- v_str = f"*{args.vararg.arg}"
211
- if args.vararg.annotation:
212
- v_str += f": {ast.unparse(args.vararg.annotation)}"
213
- parts.append(v_str)
214
-
215
- # Keyword-only args
216
- for i, a in enumerate(args.kwonlyargs):
217
- arg_str = a.arg
218
- if a.annotation:
219
- arg_str += f": {ast.unparse(a.annotation)}"
220
- if i < len(args.kw_defaults) and args.kw_defaults[i] is not None:
221
- arg_str += f" = {ast.unparse(args.kw_defaults[i])}"
222
- parts.append(arg_str)
223
-
224
- # **kwarg
225
- if args.kwarg:
226
- k_str = f"**{args.kwarg.arg}"
227
- if args.kwarg.annotation:
228
- k_str += f": {ast.unparse(args.kwarg.annotation)}"
229
- parts.append(k_str)
230
-
231
- return ", ".join(parts)
232
-
233
- @classmethod
234
- def _fallback_regex_stub(cls, code: str) -> str:
235
- """Regex-based fallback for unparseable syntax."""
236
- out = ["# -*- coding: utf-8 -*-", "# T-Zero Fallback Interface Stub", ""]
237
- for line in code.splitlines():
238
- m = re.match(r"^(\s*(?:async\s+)?def\s+[A-Za-z0-9_]+\s*\([^)]*\)(?:\s*->\s*[^:]+)?)\s*:", line)
239
- if m:
240
- out.append(f"{m.group(1)}: ...")
241
- elif re.match(r"^(\s*class\s+[A-Za-z0-9_]+(?:\([^)]*\))?)\s*:", line):
242
- out.append(f"{line.rstrip()} ...")
243
- return "\n".join(out)
244
-
245
- @classmethod
246
- def generate_stub_file(cls, src_path: str, dst_path: Optional[str] = None) -> Tuple[str, int, int, float]:
247
- """Generates a .pyi stub for a single file on disk and returns metrics."""
248
- with open(src_path, "r", encoding="utf-8", errors="replace") as f:
249
- code = f.read()
250
-
251
- stub = cls.generate_stub_from_code(code, file_path=src_path)
252
- raw_tokens = max(1, len(code) // 4)
253
- stub_tokens = max(1, len(stub) // 4)
254
- savings_pct = max(0.0, (1.0 - (stub_tokens / raw_tokens)) * 100.0)
255
-
256
- target_file = dst_path if dst_path else (os.path.splitext(src_path)[0] + ".pyi")
257
- with open(target_file, "w", encoding="utf-8") as f:
258
- f.write(stub)
259
-
260
- return stub, raw_tokens, stub_tokens, savings_pct
261
-
262
- @classmethod
263
- def generate_workspace_stubs(
264
- cls,
265
- workspace_dir: str = ".",
266
- output_dir: Optional[str] = None
267
- ) -> Dict[str, Any]:
268
- """Recursively generates .pyi type stubs across a project workspace."""
269
- abs_ws = os.path.abspath(workspace_dir)
270
- target_out = os.path.abspath(output_dir) if output_dir else None
271
- if target_out:
272
- os.makedirs(target_out, exist_ok=True)
273
-
274
- results = []
275
- total_raw = 0
276
- total_stub = 0
277
-
278
- for root, dirs, files in os.walk(abs_ws):
279
- dirs[:] = [d for d in dirs if not should_skip_dir(os.path.join(root, d), abs_ws)]
280
- for file in files:
281
- if file.endswith(".py") and not file.endswith("_hud.html"):
282
- full_p = os.path.join(root, file)
283
- if should_skip_file(full_p, abs_ws):
284
- continue
285
- rel_p = os.path.relpath(full_p, abs_ws)
286
-
287
- dst = None
288
- if target_out:
289
- dst = os.path.join(target_out, os.path.splitext(rel_p)[0] + ".pyi")
290
- os.makedirs(os.path.dirname(dst), exist_ok=True)
291
-
292
- try:
293
- _, raw_t, stub_t, sav = cls.generate_stub_file(full_p, dst_path=dst)
294
- total_raw += raw_t
295
- total_stub += stub_t
296
- results.append({
297
- "file": rel_p,
298
- "raw_tokens": raw_t,
299
- "stub_tokens": stub_t,
300
- "savings_pct": sav
301
- })
302
- except Exception as err:
303
- sys.stderr.write(f"[WARN] Failed to stub {rel_p}: {err}\n")
304
-
305
- overall_sav = max(0.0, (1.0 - (total_stub / max(1, total_raw))) * 100.0)
306
- return {
307
- "total_files": len(results),
308
- "raw_tokens": total_raw,
309
- "stub_tokens": total_stub,
310
- "overall_savings_pct": round(overall_sav, 1),
311
- "output_dir": target_out or "in-place",
312
- "files": results
313
- }
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Siber Akademi — T-Zero AST Type Stub & Interface (.pyi) Generator.
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ License: MIT
6
+
7
+ Extracts ultra-compact, type-safe Python interface stubs (.pyi) directly from
8
+ AST syntax trees. Replaces function/method implementations with `...`, preserves
9
+ all type hints, decorators, class hierarchies, and infers missing types from
10
+ default parameter values. Delivers 90-95% token reduction for agent context ingestion.
11
+ """
12
+
13
+ import sys
14
+ if sys.platform == "win32":
15
+ try:
16
+ sys.stdout.reconfigure(encoding="utf-8")
17
+ sys.stderr.reconfigure(encoding="utf-8")
18
+ except Exception:
19
+ pass
20
+
21
+ import os
22
+ import ast
23
+ import re
24
+ from typing import Dict, List, Optional, Tuple, Any, Set
25
+
26
+ from tzero.tzero_features import should_skip_dir, should_skip_file
27
+
28
+
29
+ def _infer_type_from_ast_node(node: Optional[ast.AST]) -> Optional[str]:
30
+ """Infers a type string from a literal AST constant or default value."""
31
+ if node is None:
32
+ return None
33
+ if isinstance(node, ast.Constant):
34
+ val = node.value
35
+ if isinstance(val, bool):
36
+ return "bool"
37
+ elif isinstance(val, int):
38
+ return "int"
39
+ elif isinstance(val, float):
40
+ return "float"
41
+ elif isinstance(val, str):
42
+ return "str"
43
+ elif isinstance(val, bytes):
44
+ return "bytes"
45
+ elif val is None:
46
+ return "Optional[Any]"
47
+ elif isinstance(node, ast.List):
48
+ return "List[Any]"
49
+ elif isinstance(node, ast.Dict):
50
+ return "Dict[str, Any]"
51
+ elif isinstance(node, ast.Set):
52
+ return "Set[Any]"
53
+ elif isinstance(node, ast.Tuple):
54
+ return "Tuple[Any, ...]"
55
+ return None
56
+
57
+
58
+ class TypeStubGenerator:
59
+ """Enterprise-grade AST type stub (.pyi) extractor and interface generator."""
60
+
61
+ @classmethod
62
+ def generate_stub_from_code(cls, code: str, file_path: str = "") -> str:
63
+ """Parses Python source code and returns a clean, PEP-484 compliant .pyi stub."""
64
+ try:
65
+ tree = ast.parse(code)
66
+ except SyntaxError:
67
+ # If code has syntax errors, fallback to basic regex signature extractor
68
+ return cls._fallback_regex_stub(code)
69
+
70
+ lines: List[str] = []
71
+ lines.append("# Auto-generated T-Zero AST Type Stub")
72
+ lines.append("from __future__ import annotations")
73
+ lines.append("from typing import Any, Optional, List, Dict, Tuple, Set, Union\n")
74
+
75
+ # Top-level docstring
76
+ doc = ast.get_docstring(tree, clean=True)
77
+ if doc:
78
+ first_line = doc.strip().split("\n")[0]
79
+ lines.append(f'"""{first_line}"""\n')
80
+
81
+ # Collect top-level imports and type aliases
82
+ for node in tree.body:
83
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
84
+ # Keep typing and core library imports
85
+ imp_code = ast.unparse(node)
86
+ if any(k in imp_code for k in ("typing", "abc", "dataclass", "collections", "datetime", "enum")):
87
+ lines.append(imp_code)
88
+ elif isinstance(node, ast.Assign):
89
+ # Check for TypeVar or uppercase module-level constants
90
+ for target in node.targets:
91
+ if isinstance(target, ast.Name):
92
+ name = target.id
93
+ val_str = ast.unparse(node.value)
94
+ if "TypeVar" in val_str or "NewType" in val_str:
95
+ lines.append(f"{name} = {val_str}")
96
+ elif name.isupper() and len(name) > 1:
97
+ inferred = _infer_type_from_ast_node(node.value) or "Any"
98
+ lines.append(f"{name}: {inferred}")
99
+
100
+ if len(lines) > 4:
101
+ lines.append("")
102
+
103
+ # Process classes and top-level functions
104
+ for node in tree.body:
105
+ if isinstance(node, ast.ClassDef):
106
+ cls._format_class(node, lines, indent="")
107
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
108
+ cls._format_function(node, lines, indent="")
109
+
110
+ raw_stub = "\n".join(lines).strip() + "\n"
111
+ # Deduplicate multiple consecutive blank lines
112
+ cleaned = re.sub(r"\n{3,}", "\n\n", raw_stub)
113
+ return cleaned
114
+
115
+ @classmethod
116
+ def _format_class(cls, node: ast.ClassDef, lines: List[str], indent: str = ""):
117
+ """Formats a class declaration and its methods into stub representation."""
118
+ decorators = [f"{indent}@{ast.unparse(d)}" for d in node.decorator_list]
119
+ lines.extend(decorators)
120
+
121
+ # Base classes
122
+ bases_str = ", ".join(ast.unparse(b) for b in node.bases)
123
+ header = f"{indent}class {node.name}" + (f"({bases_str}):" if bases_str else ":")
124
+ lines.append(header)
125
+
126
+ inner_indent = indent + " "
127
+ has_content = False
128
+
129
+ # Class docstring
130
+ doc = ast.get_docstring(node, clean=True)
131
+ if doc:
132
+ first_line = doc.strip().split("\n")[0]
133
+ lines.append(f'{inner_indent}"""{first_line}"""')
134
+ has_content = True
135
+
136
+ for item in node.body:
137
+ if isinstance(item, ast.AnnAssign):
138
+ target_str = ast.unparse(item.target)
139
+ type_str = ast.unparse(item.annotation)
140
+ lines.append(f"{inner_indent}{target_str}: {type_str}")
141
+ has_content = True
142
+ elif isinstance(item, ast.Assign):
143
+ for target in item.targets:
144
+ if isinstance(target, ast.Name) and not target.id.startswith("_"):
145
+ inferred = _infer_type_from_ast_node(item.value) or "Any"
146
+ lines.append(f"{inner_indent}{target.id}: {inferred}")
147
+ has_content = True
148
+ elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
149
+ cls._format_function(item, lines, indent=inner_indent)
150
+ has_content = True
151
+ elif isinstance(item, ast.ClassDef):
152
+ cls._format_class(item, lines, indent=inner_indent)
153
+ has_content = True
154
+
155
+ if not has_content:
156
+ lines.append(f"{inner_indent}...")
157
+ lines.append("")
158
+
159
+ @classmethod
160
+ def _format_function(cls, node: Any, lines: List[str], indent: str = ""):
161
+ """Formats a function or method into a PEP-484 stub signature with ellipsis."""
162
+ # Decorators (skip internal helpers, preserve properties and typing decorators)
163
+ for d in node.decorator_list:
164
+ dec_str = ast.unparse(d)
165
+ lines.append(f"{indent}@{dec_str}")
166
+
167
+ prefix = "async def " if isinstance(node, ast.AsyncFunctionDef) else "def "
168
+ args_str = cls._format_arguments(node.args)
169
+
170
+ # Return type
171
+ ret_type = " -> " + ast.unparse(node.returns) if node.returns else ""
172
+
173
+ # Function docstring
174
+ doc = ast.get_docstring(node, clean=True)
175
+ if doc and not indent: # Only for top-level functions to conserve tokens
176
+ first_line = doc.strip().split("\n")[0]
177
+ sig = f"{indent}{prefix}{node.name}({args_str}){ret_type}:"
178
+ lines.append(sig)
179
+ lines.append(f'{indent} """{first_line}"""')
180
+ lines.append(f"{indent} ...")
181
+ else:
182
+ sig = f"{indent}{prefix}{node.name}({args_str}){ret_type}: ..."
183
+ lines.append(sig)
184
+
185
+ @classmethod
186
+ def _format_arguments(cls, args: ast.arguments) -> str:
187
+ """Formats ast.arguments with type annotations and inferred defaults."""
188
+ parts: List[str] = []
189
+
190
+ # Positional args and defaults
191
+ defaults_offset = len(args.args) - len(args.defaults)
192
+ for i, a in enumerate(args.args):
193
+ arg_str = a.arg
194
+ if a.annotation:
195
+ arg_str += f": {ast.unparse(a.annotation)}"
196
+ elif i >= defaults_offset:
197
+ def_node = args.defaults[i - defaults_offset]
198
+ inferred = _infer_type_from_ast_node(def_node)
199
+ if inferred:
200
+ arg_str += f": {inferred}"
201
+
202
+ # Default value representation
203
+ if i >= defaults_offset:
204
+ def_node = args.defaults[i - defaults_offset]
205
+ arg_str += f" = {ast.unparse(def_node)}"
206
+ parts.append(arg_str)
207
+
208
+ # *vararg
209
+ if args.vararg:
210
+ v_str = f"*{args.vararg.arg}"
211
+ if args.vararg.annotation:
212
+ v_str += f": {ast.unparse(args.vararg.annotation)}"
213
+ parts.append(v_str)
214
+
215
+ # Keyword-only args
216
+ for i, a in enumerate(args.kwonlyargs):
217
+ arg_str = a.arg
218
+ if a.annotation:
219
+ arg_str += f": {ast.unparse(a.annotation)}"
220
+ if i < len(args.kw_defaults) and args.kw_defaults[i] is not None:
221
+ arg_str += f" = {ast.unparse(args.kw_defaults[i])}"
222
+ parts.append(arg_str)
223
+
224
+ # **kwarg
225
+ if args.kwarg:
226
+ k_str = f"**{args.kwarg.arg}"
227
+ if args.kwarg.annotation:
228
+ k_str += f": {ast.unparse(args.kwarg.annotation)}"
229
+ parts.append(k_str)
230
+
231
+ return ", ".join(parts)
232
+
233
+ @classmethod
234
+ def _fallback_regex_stub(cls, code: str) -> str:
235
+ """Regex-based fallback for unparseable syntax."""
236
+ out = ["# -*- coding: utf-8 -*-", "# T-Zero Fallback Interface Stub", ""]
237
+ for line in code.splitlines():
238
+ m = re.match(r"^(\s*(?:async\s+)?def\s+[A-Za-z0-9_]+\s*\([^)]*\)(?:\s*->\s*[^:]+)?)\s*:", line)
239
+ if m:
240
+ out.append(f"{m.group(1)}: ...")
241
+ elif re.match(r"^(\s*class\s+[A-Za-z0-9_]+(?:\([^)]*\))?)\s*:", line):
242
+ out.append(f"{line.rstrip()} ...")
243
+ return "\n".join(out)
244
+
245
+ @classmethod
246
+ def generate_stub_file(cls, src_path: str, dst_path: Optional[str] = None) -> Tuple[str, int, int, float]:
247
+ """Generates a .pyi stub for a single file on disk and returns metrics."""
248
+ with open(src_path, "r", encoding="utf-8", errors="replace") as f:
249
+ code = f.read()
250
+
251
+ stub = cls.generate_stub_from_code(code, file_path=src_path)
252
+ raw_tokens = max(1, len(code) // 4)
253
+ stub_tokens = max(1, len(stub) // 4)
254
+ savings_pct = max(0.0, (1.0 - (stub_tokens / raw_tokens)) * 100.0)
255
+
256
+ target_file = dst_path if dst_path else (os.path.splitext(src_path)[0] + ".pyi")
257
+ with open(target_file, "w", encoding="utf-8") as f:
258
+ f.write(stub)
259
+
260
+ return stub, raw_tokens, stub_tokens, savings_pct
261
+
262
+ @classmethod
263
+ def generate_workspace_stubs(
264
+ cls,
265
+ workspace_dir: str = ".",
266
+ output_dir: Optional[str] = None
267
+ ) -> Dict[str, Any]:
268
+ """Recursively generates .pyi type stubs across a project workspace."""
269
+ abs_ws = os.path.abspath(workspace_dir)
270
+ target_out = os.path.abspath(output_dir) if output_dir else None
271
+ if target_out:
272
+ os.makedirs(target_out, exist_ok=True)
273
+
274
+ results = []
275
+ total_raw = 0
276
+ total_stub = 0
277
+
278
+ for root, dirs, files in os.walk(abs_ws):
279
+ dirs[:] = [d for d in dirs if not should_skip_dir(os.path.join(root, d), abs_ws)]
280
+ for file in files:
281
+ if file.endswith(".py") and not file.endswith("_hud.html"):
282
+ full_p = os.path.join(root, file)
283
+ if should_skip_file(full_p, abs_ws):
284
+ continue
285
+ rel_p = os.path.relpath(full_p, abs_ws)
286
+
287
+ dst = None
288
+ if target_out:
289
+ dst = os.path.join(target_out, os.path.splitext(rel_p)[0] + ".pyi")
290
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
291
+
292
+ try:
293
+ _, raw_t, stub_t, sav = cls.generate_stub_file(full_p, dst_path=dst)
294
+ total_raw += raw_t
295
+ total_stub += stub_t
296
+ results.append({
297
+ "file": rel_p,
298
+ "raw_tokens": raw_t,
299
+ "stub_tokens": stub_t,
300
+ "savings_pct": sav
301
+ })
302
+ except Exception as err:
303
+ sys.stderr.write(f"[WARN] Failed to stub {rel_p}: {err}\n")
304
+
305
+ overall_sav = max(0.0, (1.0 - (total_stub / max(1, total_raw))) * 100.0)
306
+ return {
307
+ "total_files": len(results),
308
+ "raw_tokens": total_raw,
309
+ "stub_tokens": total_stub,
310
+ "overall_savings_pct": round(overall_sav, 1),
311
+ "output_dir": target_out or "in-place",
312
+ "files": results
313
+ }