tzero-mcp 10.7.4 → 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 (131) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/bin/tzero-mcp.js +7 -11
  5. package/bin/tzero.js +7 -11
  6. package/index.js +3 -3
  7. package/package.json +3 -2
  8. package/src/addmcp.py +1203 -1194
  9. package/src/app.py +1810 -0
  10. package/src/main.py +60 -60
  11. package/src/pc_fixer_mcp.py +25 -0
  12. package/src/tzero/__init__.py +54 -0
  13. package/src/tzero/__main__.py +6 -0
  14. package/src/tzero/siber_akademi.ico +0 -0
  15. package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +77 -77
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +2 -2
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +184 -0
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/tzero/tzero_card.py +431 -0
  22. package/src/{tzero_ci.py → tzero/tzero_ci.py} +7 -7
  23. package/src/{tzero_commit.py → tzero/tzero_commit.py} +1 -1
  24. package/src/tzero/tzero_contracts.py +1093 -0
  25. package/src/{tzero_cost.py → tzero/tzero_cost.py} +4 -1
  26. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +1960 -1448
  27. package/src/tzero/tzero_debt.py +461 -0
  28. package/src/{tzero_deps.py → tzero/tzero_deps.py} +462 -287
  29. package/src/{tzero_drift.py → tzero/tzero_drift.py} +1 -1
  30. package/src/{tzero_explain.py → tzero/tzero_explain.py} +306 -240
  31. package/src/{tzero_features.py → tzero/tzero_features.py} +3024 -3022
  32. package/src/tzero/tzero_federation.py +299 -0
  33. package/src/tzero/tzero_fix.py +557 -0
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +334 -334
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +1 -1
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +8 -8
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +1 -1
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +1 -1
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +1 -1
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +1 -1
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +1 -1
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +280 -280
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +325 -325
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +489 -447
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +385 -385
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +375 -375
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +323 -323
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +2 -1
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +1 -1
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +1 -1
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +364 -364
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +619 -619
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +1 -1
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +2 -2
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +493 -493
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +1 -1
  58. package/src/tzero/tzero_golden.py +319 -0
  59. package/src/tzero/tzero_graph_hud.html +338 -0
  60. package/src/tzero/tzero_graph_rag.py +263 -0
  61. package/src/tzero/tzero_growth.py +415 -0
  62. package/src/{tzero_guard.py → tzero/tzero_guard.py} +11 -3
  63. package/src/tzero/tzero_hooks.py +565 -0
  64. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +11 -1
  65. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +1 -1
  66. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  67. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +1 -1
  68. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +2 -2
  69. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +1 -1
  70. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +1 -1
  71. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +2 -2
  72. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +1 -1
  73. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +3 -3
  74. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +1 -1
  75. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +6 -6
  76. package/src/tzero/tzero_lsp.py +634 -0
  77. package/src/tzero/tzero_mcp.py +5314 -0
  78. package/src/tzero/tzero_mutation.py +358 -0
  79. package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +1425 -1425
  80. package/src/tzero/tzero_packer.py +577 -0
  81. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +42 -0
  82. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +1 -1
  83. package/src/tzero/tzero_polyglot.py +799 -0
  84. package/src/tzero/tzero_proxy.py +127 -0
  85. package/src/tzero/tzero_rust_bridge.py +198 -0
  86. package/src/tzero/tzero_scip.py +368 -0
  87. package/src/{tzero_security.py → tzero/tzero_security.py} +573 -570
  88. package/src/tzero/tzero_semantic_merge.py +189 -0
  89. package/src/tzero/tzero_snapshot.py +471 -0
  90. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +1 -1
  91. package/src/tzero/tzero_subagent_engine.py +459 -0
  92. package/src/{tzero_sync.py → tzero/tzero_sync.py} +2 -2
  93. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +174 -31
  94. package/src/{tzero_tui.py → tzero/tzero_tui.py} +313 -244
  95. package/src/tzero/tzero_turbo.py +264 -0
  96. package/src/{tzero_v3.py → tzero/tzero_v3.py} +9997 -9435
  97. package/src/tzero.py +6 -58
  98. package/src/tzero_mcp.py +25 -4858
  99. package/test/package.test.js +14 -2
  100. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  101. package/src/tzero_fix.py +0 -228
  102. package/src/tzero_gateway.py +0 -885
  103. package/src/tzero_packer.py +0 -370
  104. package/src/tzero_polyglot.py +0 -422
  105. package/src/tzero_snapshot.py +0 -258
  106. /package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +0 -0
  107. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +0 -0
  108. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +0 -0
  109. /package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +0 -0
  110. /package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +0 -0
  111. /package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +0 -0
  112. /package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +0 -0
  113. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +0 -0
  114. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +0 -0
  115. /package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +0 -0
  116. /package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +0 -0
  117. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +0 -0
  118. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +0 -0
  119. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +0 -0
  120. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +0 -0
  121. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +0 -0
  122. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +0 -0
  123. /package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +0 -0
  124. /package/src/{tzero_infra.py → tzero/tzero_infra.py} +0 -0
  125. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +0 -0
  126. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +0 -0
  127. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +0 -0
  128. /package/src/{tzero_patch.py → tzero/tzero_patch.py} +0 -0
  129. /package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +0 -0
  130. /package/src/{tzero_replay.py → tzero/tzero_replay.py} +0 -0
  131. /package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +0 -0
@@ -17,7 +17,7 @@ import json
17
17
  from dataclasses import dataclass, field
18
18
  from typing import Dict, List, Any, Optional
19
19
 
20
- from tzero_security import ZeroLeakEngine
20
+ from tzero.tzero_security import ZeroLeakEngine
21
21
 
22
22
 
23
23
  @dataclass
@@ -1,240 +1,306 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Explain: Ultra-Dense AST Architectural Passport Generator.
3
-
4
- Generates high-density, prompt-ready architectural passports for codebases and files,
5
- delivering maximum semantic grounding to LLMs (Claude, GPT, Gemini, DeepSeek) with
6
- up to 95% token savings compared to raw file ingestion.
7
-
8
- Author: Toprak Ahmet Aydogmus (Siber Akademi)
9
- Version: 10.5.0
10
- """
11
-
12
- import ast
13
- import os
14
- import sys
15
-
16
- if sys.platform == "win32":
17
- try:
18
- if hasattr(sys.stdout, "reconfigure"):
19
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
20
- if hasattr(sys.stderr, "reconfigure"):
21
- sys.stderr.reconfigure(encoding="utf-8", errors="replace")
22
- except Exception:
23
- pass
24
- from dataclasses import asdict, dataclass, field
25
- from pathlib import Path
26
- from typing import Any, Dict, List, Optional, Set, Tuple
27
-
28
-
29
- @dataclass
30
- class SymbolPassport:
31
- name: str
32
- kind: str # 'class', 'function', 'async_function'
33
- lineno: int
34
- docstring: Optional[str]
35
- signatures: List[str] = field(default_factory=list)
36
- complexity: int = 1
37
-
38
-
39
- @dataclass
40
- class ModulePassport:
41
- file_path: str
42
- module_name: str
43
- docstring: Optional[str]
44
- raw_lines: int
45
- raw_tokens: int
46
- passport_tokens: int
47
- token_savings_pct: float
48
- role: str # 'presentation', 'business_service', 'data_model', 'utility'
49
- symbols: List[SymbolPassport] = field(default_factory=list)
50
- dependencies_internal: List[str] = field(default_factory=list)
51
- dependencies_external: List[str] = field(default_factory=list)
52
- markdown_passport: str = ""
53
-
54
-
55
- class ArchitecturalPassportGenerator:
56
- """Extracts ultra-dense AST architecture passports for LLM prompts."""
57
-
58
- @staticmethod
59
- def _estimate_tokens(text: str) -> int:
60
- return max(1, int(len(text) / 3.8))
61
-
62
- @classmethod
63
- def _compute_complexity(cls, node: ast.AST) -> int:
64
- """Calculate cyclomatic complexity of an AST node."""
65
- complexity = 1
66
- for child in ast.walk(node):
67
- if isinstance(child, (ast.If, ast.While, ast.For, ast.ExceptHandler,
68
- ast.With, ast.Assert, ast.comprehension)):
69
- complexity += 1
70
- elif isinstance(child, ast.BoolOp):
71
- complexity += len(child.values) - 1
72
- return complexity
73
-
74
- @classmethod
75
- def _classify_role(cls, path_str: str, symbols: List[SymbolPassport]) -> str:
76
- name = Path(path_str).stem.lower()
77
- parent_parts = [p.lower() for p in Path(path_str).parent.parts]
78
- if any(k in name for k in ("cli", "gui", "tui", "view", "api", "mcp", "endpoint", "controller")) or any(k in parent_parts for k in ("cli", "gui", "ui", "views", "api", "mcp", "routes", "controllers")):
79
- return "presentation"
80
- elif any(k in name for k in ("model", "schema", "dto", "entity")) or any(k in parent_parts for k in ("models", "schemas", "dtos", "entities")):
81
- return "data_model"
82
- elif any(k in name for k in ("util", "helper", "common", "tools")) or any(k in parent_parts for k in ("utils", "helpers", "common")):
83
- return "utility"
84
- elif any(s.name.endswith(("Service", "Engine", "Manager", "Analyzer", "Architect", "Orchestrator")) for s in symbols):
85
- return "business_service"
86
- return "business_service"
87
-
88
- @classmethod
89
- def explain_file(cls, file_path: str) -> ModulePassport:
90
- """Generate high-density AST passport for a single Python file."""
91
- p = Path(file_path).resolve()
92
- if not p.is_file():
93
- raise FileNotFoundError(f"File not found: {file_path}")
94
-
95
- try:
96
- with open(p, "r", encoding="utf-8", errors="replace") as f:
97
- content = f.read()
98
- except Exception as e:
99
- raise IOError(f"Cannot read file {file_path}: {e}")
100
-
101
- raw_lines = len(content.splitlines())
102
- raw_tokens = cls._estimate_tokens(content)
103
-
104
- try:
105
- tree = ast.parse(content, filename=str(p))
106
- module_doc = ast.get_docstring(tree)
107
- except SyntaxError:
108
- module_doc = None
109
- tree = None
110
-
111
- symbols: List[SymbolPassport] = []
112
- internal_deps: Set[str] = set()
113
- external_deps: Set[str] = set()
114
-
115
- if tree:
116
- for node in tree.body:
117
- if isinstance(node, ast.Import):
118
- for alias in node.names:
119
- base = alias.name.split(".")[0]
120
- if base in sys.builtin_module_names or base in ("os", "sys", "json", "re", "math", "typing", "pathlib", "ast", "time", "shutil"):
121
- external_deps.add(base)
122
- else:
123
- internal_deps.add(base)
124
- elif isinstance(node, ast.ImportFrom):
125
- if node.module:
126
- base = node.module.split(".")[0]
127
- if node.level > 0 or base not in sys.builtin_module_names:
128
- internal_deps.add(node.module)
129
- else:
130
- external_deps.add(base)
131
-
132
- elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
133
- fn_doc = ast.get_docstring(node)
134
- # build signature
135
- args_list = []
136
- for a in node.args.args:
137
- ann = f": {ast.unparse(a.annotation)}" if a.annotation else ""
138
- args_list.append(f"{a.arg}{ann}")
139
- ret = f" -> {ast.unparse(node.returns)}" if node.returns else ""
140
- sig = f"def {node.name}({', '.join(args_list)}){ret}"
141
- symbols.append(SymbolPassport(
142
- name=node.name,
143
- kind="async_function" if isinstance(node, ast.AsyncFunctionDef) else "function",
144
- lineno=node.lineno,
145
- docstring=fn_doc.split("\n")[0] if fn_doc else None,
146
- signatures=[sig],
147
- complexity=cls._compute_complexity(node)
148
- ))
149
-
150
- elif isinstance(node, ast.ClassDef):
151
- cls_doc = ast.get_docstring(node)
152
- bases = [ast.unparse(b) for b in node.bases]
153
- base_str = f"({', '.join(bases)})" if bases else ""
154
- methods_sig = []
155
- for item in node.body:
156
- if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
157
- m_args = []
158
- for a in item.args.args:
159
- m_ann = f": {ast.unparse(a.annotation)}" if a.annotation else ""
160
- m_args.append(f"{a.arg}{m_ann}")
161
- m_ret = f" -> {ast.unparse(item.returns)}" if item.returns else ""
162
- methods_sig.append(f" def {item.name}({', '.join(m_args)}){m_ret}")
163
-
164
- symbols.append(SymbolPassport(
165
- name=node.name,
166
- kind="class",
167
- lineno=node.lineno,
168
- docstring=cls_doc.split("\n")[0] if cls_doc else None,
169
- signatures=[f"class {node.name}{base_str}:"] + methods_sig[:10],
170
- complexity=cls._compute_complexity(node)
171
- ))
172
-
173
- role = cls._classify_role(str(p), symbols)
174
-
175
- # Build Markdown Passport
176
- md_lines = [
177
- f"### 🏛️ AST Architectural Passport: `{p.name}`",
178
- f"- **Role:** `{role.upper()}` | **Lines:** {raw_lines} | **Symbols:** {len(symbols)}",
179
- ]
180
- if module_doc:
181
- md_lines.append(f"- **Purpose:** {module_doc.strip().splitlines()[0]}")
182
- if internal_deps:
183
- md_lines.append(f"- **Internal Dependencies:** `{', '.join(sorted(internal_deps)[:6])}`")
184
- if external_deps:
185
- md_lines.append(f"- **External Dependencies:** `{', '.join(sorted(external_deps)[:6])}`")
186
-
187
- md_lines.append("\n```python")
188
- for sym in symbols:
189
- doc_str = f" # {sym.docstring}" if sym.docstring else ""
190
- if sym.kind == "class":
191
- md_lines.append(f"{sym.signatures[0]}{doc_str}")
192
- for ms in sym.signatures[1:]:
193
- md_lines.append(ms)
194
- else:
195
- md_lines.append(f"{sym.signatures[0]}: ...{doc_str}")
196
- md_lines.append("```\n")
197
-
198
- markdown_passport = "\n".join(md_lines)
199
- passport_tokens = cls._estimate_tokens(markdown_passport)
200
- savings_pct = round(max(0.0, (1.0 - passport_tokens / max(1, raw_tokens)) * 100), 1)
201
-
202
- return ModulePassport(
203
- file_path=str(p),
204
- module_name=p.stem,
205
- docstring=module_doc,
206
- raw_lines=raw_lines,
207
- raw_tokens=raw_tokens,
208
- passport_tokens=passport_tokens,
209
- token_savings_pct=savings_pct,
210
- role=role,
211
- symbols=symbols,
212
- dependencies_internal=sorted(internal_deps),
213
- dependencies_external=sorted(external_deps),
214
- markdown_passport=markdown_passport
215
- )
216
-
217
- @classmethod
218
- def render_cli(cls, passport: ModulePassport):
219
- """Render passport output to stdout."""
220
- print("=" * 80)
221
- print("\033[1;36m🏛️ T-ZERO AST ARCHITECTURAL PASSPORT\033[0m")
222
- print("=" * 80)
223
- print(f"File: \033[33m{passport.file_path}\033[0m")
224
- print(f"Module: \033[32m{passport.module_name}\033[0m")
225
- print(f"Layer Role: \033[1;35m{passport.role.upper()}\033[0m")
226
- print(f"Token Economy: Raw: \033[31m{passport.raw_tokens:,} tokens\033[0m -> "
227
- f"Passport: \033[32m{passport.passport_tokens:,} tokens\033[0m "
228
- f"(\033[1;32m-{passport.token_savings_pct}%\033[0m reduction)")
229
- print("-" * 80)
230
- print(passport.markdown_passport)
231
- print("=" * 80)
232
-
233
-
234
- if __name__ == "__main__":
235
- if len(sys.argv) < 2:
236
- print("Usage: python tzero_explain.py <path_to_file.py>")
237
- sys.exit(1)
238
- target = sys.argv[1]
239
- res = ArchitecturalPassportGenerator.explain_file(target)
240
- ArchitecturalPassportGenerator.render_cli(res)
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Explain: Ultra-Dense AST Architectural Passport Generator.
3
+
4
+ Generates high-density, prompt-ready architectural passports for codebases and files,
5
+ delivering maximum semantic grounding to LLMs (Claude, GPT, Gemini, DeepSeek) with
6
+ up to 95% token savings compared to raw file ingestion.
7
+
8
+ Author: Toprak Ahmet Aydogmus (Siber Akademi)
9
+ Version: 10.5.0
10
+ """
11
+
12
+ import ast
13
+ import os
14
+ import re
15
+ import sys
16
+
17
+ if sys.platform == "win32":
18
+ try:
19
+ if hasattr(sys.stdout, "reconfigure"):
20
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
21
+ if hasattr(sys.stderr, "reconfigure"):
22
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
23
+ except Exception:
24
+ pass
25
+ from dataclasses import asdict, dataclass, field
26
+ from pathlib import Path
27
+ from typing import Any, Dict, List, Optional, Set, Tuple
28
+
29
+
30
+ @dataclass
31
+ class SymbolPassport:
32
+ name: str
33
+ kind: str # 'class', 'function', 'async_function'
34
+ lineno: int
35
+ docstring: Optional[str]
36
+ signatures: List[str] = field(default_factory=list)
37
+ complexity: int = 1
38
+
39
+
40
+ @dataclass
41
+ class ModulePassport:
42
+ file_path: str
43
+ module_name: str
44
+ docstring: Optional[str]
45
+ raw_lines: int
46
+ raw_tokens: int
47
+ passport_tokens: int
48
+ token_savings_pct: float
49
+ role: str # 'presentation', 'business_service', 'data_model', 'utility'
50
+ symbols: List[SymbolPassport] = field(default_factory=list)
51
+ dependencies_internal: List[str] = field(default_factory=list)
52
+ dependencies_external: List[str] = field(default_factory=list)
53
+ markdown_passport: str = ""
54
+
55
+
56
+ class ArchitecturalPassportGenerator:
57
+ """Extracts ultra-dense AST architecture passports for LLM prompts."""
58
+
59
+ @staticmethod
60
+ def _estimate_tokens(text: str) -> int:
61
+ return max(1, int(len(text) / 3.8))
62
+
63
+ @classmethod
64
+ def _compute_complexity(cls, node: ast.AST) -> int:
65
+ """Calculate cyclomatic complexity of an AST node."""
66
+ complexity = 1
67
+ for child in ast.walk(node):
68
+ if isinstance(child, (ast.If, ast.While, ast.For, ast.ExceptHandler,
69
+ ast.With, ast.Assert, ast.comprehension)):
70
+ complexity += 1
71
+ elif isinstance(child, ast.BoolOp):
72
+ complexity += len(child.values) - 1
73
+ return complexity
74
+
75
+ @classmethod
76
+ def _classify_role(cls, path_str: str, symbols: List[SymbolPassport]) -> str:
77
+ name = Path(path_str).stem.lower()
78
+ parent_parts = [p.lower() for p in Path(path_str).parent.parts]
79
+ if any(k in name for k in ("cli", "gui", "tui", "view", "api", "mcp", "endpoint", "controller")) or any(k in parent_parts for k in ("cli", "gui", "ui", "views", "api", "mcp", "routes", "controllers")):
80
+ return "presentation"
81
+ elif any(k in name for k in ("model", "schema", "dto", "entity")) or any(k in parent_parts for k in ("models", "schemas", "dtos", "entities")):
82
+ return "data_model"
83
+ elif any(k in name for k in ("util", "helper", "common", "tools")) or any(k in parent_parts for k in ("utils", "helpers", "common")):
84
+ return "utility"
85
+ elif any(s.name.endswith(("Service", "Engine", "Manager", "Analyzer", "Architect", "Orchestrator")) for s in symbols):
86
+ return "business_service"
87
+ return "business_service"
88
+
89
+ @classmethod
90
+ def explain_file(cls, file_path: str) -> ModulePassport:
91
+ """Generate high-density AST passport for a single Python file."""
92
+ p = Path(file_path).resolve()
93
+ if not p.is_file():
94
+ raise FileNotFoundError(f"File not found: {file_path}")
95
+
96
+ try:
97
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
98
+ content = f.read()
99
+ except Exception as e:
100
+ raise IOError(f"Cannot read file {file_path}: {e}")
101
+
102
+ raw_lines = len(content.splitlines())
103
+ raw_tokens = cls._estimate_tokens(content)
104
+
105
+ tree = None
106
+ module_doc = None
107
+ is_python = p.suffix.lower() in (".py", ".pyi", "")
108
+ if is_python:
109
+ try:
110
+ tree = ast.parse(content, filename=str(p))
111
+ module_doc = ast.get_docstring(tree)
112
+ except SyntaxError:
113
+ module_doc = None
114
+ tree = None
115
+
116
+ symbols: List[SymbolPassport] = []
117
+ internal_deps: Set[str] = set()
118
+ external_deps: Set[str] = set()
119
+ code_lang = "python"
120
+ if tree is None and not is_python:
121
+ from tzero.tzero_polyglot import PolyglotTokenReducer
122
+ reducer = PolyglotTokenReducer()
123
+ code_lang = reducer.detect_language(str(p)) or p.suffix.lstrip(".") or "text"
124
+ reduced_sig = reducer.reduce_code(content, filename=str(p), mode="ultra")
125
+ sym_re = re.compile(
126
+ r'^\s*(?:export\s+(?:default\s+|async\s+)?)?'
127
+ r'(?:public\s+|private\s+|protected\s+|static\s+|abstract\s+|async\s+|pub(?:\([^)]*\))?\s+)*'
128
+ r'(?P<kind>class|interface|struct|enum|trait|impl|fn|func|function|def|type|contract)\s+'
129
+ r'(?P<name>[A-Za-z_][A-Za-z0-9_]*)'
130
+ )
131
+ import_re = re.compile(
132
+ r'^\s*(?:import\b[^"\']*["\']([^"\']+)["\']|import\s+([A-Za-z0-9_.]+)|use\s+([A-Za-z0-9_:]+))'
133
+ )
134
+ lines_list = content.splitlines()
135
+ reduced_lines = set(l.strip() for l in reduced_sig.splitlines() if l.strip())
136
+ for idx, line in enumerate(lines_list, start=1):
137
+ stripped = line.strip()
138
+ if not stripped:
139
+ continue
140
+ im = import_re.match(stripped)
141
+ if im:
142
+ mod = im.group(1) or im.group(2) or im.group(3)
143
+ if mod:
144
+ if mod.startswith((".", "/")):
145
+ internal_deps.add(mod)
146
+ else:
147
+ external_deps.add(mod.split("/")[0].split(".")[0].split("::")[0])
148
+ continue
149
+ sm = sym_re.match(stripped)
150
+ if sm:
151
+ raw_kind = sm.group("kind")
152
+ kind_norm = (
153
+ "class" if raw_kind in ("class", "interface", "struct", "enum", "trait", "contract")
154
+ else "function"
155
+ )
156
+ symbols.append(SymbolPassport(
157
+ name=sm.group("name"),
158
+ kind=kind_norm,
159
+ lineno=idx,
160
+ docstring=None,
161
+ signatures=[stripped],
162
+ complexity=1,
163
+ ))
164
+ if not symbols and reduced_lines:
165
+ for idx, sig_line in enumerate(reduced_sig.splitlines(), start=1):
166
+ s_clean = sig_line.strip()
167
+ if s_clean and not s_clean.startswith(("//", "#", "/*", "*")):
168
+ symbols.append(SymbolPassport(
169
+ name=s_clean.split("(")[0].split("{")[0].strip().split()[-1],
170
+ kind="symbol",
171
+ lineno=idx,
172
+ docstring=None,
173
+ signatures=[s_clean],
174
+ complexity=1,
175
+ ))
176
+ if len(symbols) >= 25:
177
+ break
178
+
179
+ if tree:
180
+ for node in tree.body:
181
+ if isinstance(node, ast.Import):
182
+ for alias in node.names:
183
+ base = alias.name.split(".")[0]
184
+ if base in sys.builtin_module_names or base in ("os", "sys", "json", "re", "math", "typing", "pathlib", "ast", "time", "shutil"):
185
+ external_deps.add(base)
186
+ else:
187
+ internal_deps.add(base)
188
+ elif isinstance(node, ast.ImportFrom):
189
+ if node.module:
190
+ base = node.module.split(".")[0]
191
+ if node.level > 0 or base not in sys.builtin_module_names:
192
+ internal_deps.add(node.module)
193
+ else:
194
+ external_deps.add(base)
195
+
196
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
197
+ fn_doc = ast.get_docstring(node)
198
+ # build signature
199
+ args_list = []
200
+ for a in node.args.args:
201
+ ann = f": {ast.unparse(a.annotation)}" if a.annotation else ""
202
+ args_list.append(f"{a.arg}{ann}")
203
+ ret = f" -> {ast.unparse(node.returns)}" if node.returns else ""
204
+ sig = f"def {node.name}({', '.join(args_list)}){ret}"
205
+ symbols.append(SymbolPassport(
206
+ name=node.name,
207
+ kind="async_function" if isinstance(node, ast.AsyncFunctionDef) else "function",
208
+ lineno=node.lineno,
209
+ docstring=fn_doc.split("\n")[0] if fn_doc else None,
210
+ signatures=[sig],
211
+ complexity=cls._compute_complexity(node)
212
+ ))
213
+
214
+ elif isinstance(node, ast.ClassDef):
215
+ cls_doc = ast.get_docstring(node)
216
+ bases = [ast.unparse(b) for b in node.bases]
217
+ base_str = f"({', '.join(bases)})" if bases else ""
218
+ methods_sig = []
219
+ for item in node.body:
220
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
221
+ m_args = []
222
+ for a in item.args.args:
223
+ m_ann = f": {ast.unparse(a.annotation)}" if a.annotation else ""
224
+ m_args.append(f"{a.arg}{m_ann}")
225
+ m_ret = f" -> {ast.unparse(item.returns)}" if item.returns else ""
226
+ methods_sig.append(f" def {item.name}({', '.join(m_args)}){m_ret}")
227
+
228
+ symbols.append(SymbolPassport(
229
+ name=node.name,
230
+ kind="class",
231
+ lineno=node.lineno,
232
+ docstring=cls_doc.split("\n")[0] if cls_doc else None,
233
+ signatures=[f"class {node.name}{base_str}:"] + methods_sig[:10],
234
+ complexity=cls._compute_complexity(node)
235
+ ))
236
+
237
+ role = cls._classify_role(str(p), symbols)
238
+
239
+ # Build Markdown Passport
240
+ md_lines = [
241
+ f"### 🏛️ AST Architectural Passport: `{p.name}`",
242
+ f"- **Role:** `{role.upper()}` | **Lines:** {raw_lines} | **Symbols:** {len(symbols)}",
243
+ ]
244
+ if module_doc:
245
+ md_lines.append(f"- **Purpose:** {module_doc.strip().splitlines()[0]}")
246
+ if internal_deps:
247
+ md_lines.append(f"- **Internal Dependencies:** `{', '.join(sorted(internal_deps)[:6])}`")
248
+ if external_deps:
249
+ md_lines.append(f"- **External Dependencies:** `{', '.join(sorted(external_deps)[:6])}`")
250
+
251
+ md_lines.append(f"\n```{code_lang}")
252
+ for sym in symbols:
253
+ doc_str = f" # {sym.docstring}" if sym.docstring else ""
254
+ if sym.kind == "class":
255
+ md_lines.append(f"{sym.signatures[0]}{doc_str}")
256
+ for ms in sym.signatures[1:]:
257
+ md_lines.append(ms)
258
+ elif code_lang != "python":
259
+ md_lines.append(f"{sym.signatures[0]}{doc_str}")
260
+ else:
261
+ md_lines.append(f"{sym.signatures[0]}: ...{doc_str}")
262
+ md_lines.append("```\n")
263
+
264
+ markdown_passport = "\n".join(md_lines)
265
+ passport_tokens = cls._estimate_tokens(markdown_passport)
266
+ savings_pct = round(max(0.0, (1.0 - passport_tokens / max(1, raw_tokens)) * 100), 1)
267
+
268
+ return ModulePassport(
269
+ file_path=str(p),
270
+ module_name=p.stem,
271
+ docstring=module_doc,
272
+ raw_lines=raw_lines,
273
+ raw_tokens=raw_tokens,
274
+ passport_tokens=passport_tokens,
275
+ token_savings_pct=savings_pct,
276
+ role=role,
277
+ symbols=symbols,
278
+ dependencies_internal=sorted(internal_deps),
279
+ dependencies_external=sorted(external_deps),
280
+ markdown_passport=markdown_passport
281
+ )
282
+
283
+ @classmethod
284
+ def render_cli(cls, passport: ModulePassport):
285
+ """Render passport output to stdout."""
286
+ print("=" * 80)
287
+ print("\033[1;36m🏛️ T-ZERO AST ARCHITECTURAL PASSPORT\033[0m")
288
+ print("=" * 80)
289
+ print(f"File: \033[33m{passport.file_path}\033[0m")
290
+ print(f"Module: \033[32m{passport.module_name}\033[0m")
291
+ print(f"Layer Role: \033[1;35m{passport.role.upper()}\033[0m")
292
+ print(f"Token Economy: Raw: \033[31m{passport.raw_tokens:,} tokens\033[0m -> "
293
+ f"Passport: \033[32m{passport.passport_tokens:,} tokens\033[0m "
294
+ f"(\033[1;32m-{passport.token_savings_pct}%\033[0m reduction)")
295
+ print("-" * 80)
296
+ print(passport.markdown_passport)
297
+ print("=" * 80)
298
+
299
+
300
+ if __name__ == "__main__":
301
+ if len(sys.argv) < 2:
302
+ print("Usage: python tzero_explain.py <path_to_file.py>")
303
+ sys.exit(1)
304
+ target = sys.argv[1]
305
+ res = ArchitecturalPassportGenerator.explain_file(target)
306
+ ArchitecturalPassportGenerator.render_cli(res)