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,463 +1,463 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Automated Architecture Test Suite Generator & Validator.
3
-
4
- Generates self-contained, zero-dependency `unittest` test suites from `tzero.rules.json`
5
- enforcing layer boundaries, circular import prohibition, and zero-leak security
6
- in standard CI/CD pipelines without external frameworks.
7
-
8
- Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
9
- Part of T-Zero Context Architect v10.8.0 Master Edition.
10
- """
11
-
12
- import ast
13
- import fnmatch
14
- import json
15
- import os
16
- import re
17
- import sys
18
- from typing import Dict, List, Any, Optional, Set, Tuple
19
-
20
- if sys.stdout and hasattr(sys.stdout, "reconfigure"):
21
- try:
22
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
23
- except Exception:
24
- pass
25
-
26
-
27
- def _should_skip_dir(dir_name: str) -> bool:
28
- """Returns True if the directory should be skipped during AST analysis."""
29
- skip_names = {
30
- ".git", ".svn", ".hg", "__pycache__", ".pytest_cache",
31
- "node_modules", "dist", "build", "venv", ".venv", "env",
32
- ".gemini", ".idea", ".vscode", "site-packages", ".egg-info",
33
- "installers", "benchmark-site"
34
- }
35
- return dir_name in skip_names or dir_name.endswith(".egg-info")
36
-
37
-
38
- def _extract_ast_imports(filepath: str, rel_p: str, top_level_only: bool = False) -> Set[Tuple[str, int]]:
39
- """Extracts imported module names and their line numbers from a python file."""
40
- imports = set()
41
- try:
42
- with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
43
- tree = ast.parse(f.read(), filename=filepath)
44
-
45
- if top_level_only:
46
- nodes_to_visit = []
47
- for item in tree.body:
48
- nodes_to_visit.append(item)
49
- if isinstance(item, (ast.If, ast.Try)):
50
- nodes_to_visit.extend(ast.walk(item))
51
- else:
52
- nodes_to_visit = list(ast.walk(tree))
53
-
54
- for node in nodes_to_visit:
55
- line_no = getattr(node, "lineno", 1)
56
- if isinstance(node, ast.Import):
57
- for n in node.names:
58
- imports.add((n.name, line_no))
59
- elif isinstance(node, ast.ImportFrom):
60
- if node.level and node.level > 0:
61
- base_parts = os.path.dirname(rel_p).replace("\\", "/").split("/") if os.path.dirname(rel_p) else []
62
- if node.level <= len(base_parts):
63
- prefix = ".".join(base_parts[:len(base_parts) - node.level + 1])
64
- mod = f"{prefix}.{node.module}" if node.module else prefix
65
- else:
66
- mod = node.module or ""
67
- if mod:
68
- imports.add((mod, line_no))
69
- elif node.module:
70
- imports.add((node.module, line_no))
71
- except Exception:
72
- pass
73
- return imports
74
-
75
-
76
- class ArchitectureTestSuiteGenerator:
77
- """Generates and executes zero-dependency architectural guard test suites."""
78
-
79
- def __init__(self, project_dir: str = ".", rules_path: Optional[str] = None):
80
- self.project_dir = os.path.abspath(project_dir)
81
- self.rules_path = rules_path or os.path.join(self.project_dir, "tzero.rules.json")
82
- self.rules = self._load_rules()
83
-
84
- def _load_rules(self) -> Dict[str, Any]:
85
- """Loads rules from tzero.rules.json or returns sensible enterprise defaults."""
86
- if os.path.isfile(self.rules_path):
87
- try:
88
- with open(self.rules_path, "r", encoding="utf-8") as f:
89
- return json.load(f)
90
- except Exception:
91
- pass
92
- return {
93
- "version": "5.0.0",
94
- "project_name": os.path.basename(self.project_dir) or "Project",
95
- "layers": {
96
- "presentation": ["cli/**", "gui/**", "web/**"],
97
- "business": ["services/**", "core/**"],
98
- "persistence": ["models/**", "db/**", "utils/**"]
99
- },
100
- "forbidden_imports": [
101
- {
102
- "from_layer": "persistence",
103
- "cannot_import": ["presentation", "business"],
104
- "reason": "Persistence layer must not depend on higher layers."
105
- },
106
- {
107
- "from_layer": "business",
108
- "cannot_import": ["presentation"],
109
- "reason": "Business services must remain presentation-agnostic."
110
- }
111
- ],
112
- "security": {
113
- "zero_leak_enforced": True,
114
- "disallow_hardcoded_keys": True
115
- }
116
- }
117
-
118
- def generate_test_code(self) -> str:
119
- """Generates the full Python source code for the standalone architecture test suite."""
120
- project_name = self.rules.get("project_name", "T-Zero Project")
121
- layers_json = json.dumps(self.rules.get("layers", {}), indent=8)
122
- forbidden_json = json.dumps(self.rules.get("forbidden_imports", []), indent=8)
123
- security_config = self.rules.get("security", {})
124
- zero_leak = bool(security_config.get("zero_leak_enforced", True))
125
-
126
- code = f'''# -*- coding: utf-8 -*-
127
- """Auto-generated T-Zero Architectural Integrity Guard Test Suite.
128
- Project: {project_name}
129
- Generated by: T-Zero ArchitectureTestSuiteGenerator
130
- Zero-Dependency: Runs in standard Python unittest / pytest environments.
131
- """
132
-
133
- import ast
134
- import fnmatch
135
- import os
136
- import re
137
- import sys
138
- import unittest
139
- from typing import Dict, List, Set, Tuple, Any
140
-
141
- WORKSPACE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
142
- SKIP_DIRS = {{
143
- ".git", ".svn", "__pycache__", "node_modules", "dist", "build",
144
- "venv", ".venv", "env", ".gemini", ".idea", ".vscode", "installers", "benchmark-site"
145
- }}
146
-
147
- LAYERS: Dict[str, List[str]] = {layers_json}
148
-
149
- FORBIDDEN_IMPORTS: List[Dict[str, Any]] = {forbidden_json}
150
-
151
- ZERO_LEAK_ENFORCED = {zero_leak}
152
-
153
- SECRET_PATTERNS = [
154
- re.compile(r"sk-[a-zA-Z0-9]{{20,}}"),
155
- re.compile(r"ghp_[a-zA-Z0-9]{{30,}}"),
156
- re.compile(r"AIza[0-9A-Za-z-_]{{35}}"),
157
- re.compile(r"AKIA[0-9A-Z]{{16}}"),
158
- re.compile(r"-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY-----")
159
- ]
160
-
161
-
162
- def _matches_layer(file_rel: str, patterns: List[str]) -> bool:
163
- for p in patterns:
164
- p_clean = p.replace("\\\\", "/").rstrip("/*")
165
- if p.endswith("/*") or p.endswith("/**"):
166
- if file_rel.startswith(p_clean + "/") or file_rel == p_clean:
167
- return True
168
- elif file_rel == p_clean or os.path.basename(file_rel) == p_clean:
169
- return True
170
- return False
171
-
172
-
173
- def _extract_ast_imports(filepath: str, rel_p: str, top_level_only: bool = False) -> Set[Tuple[str, int]]:
174
- imports = set()
175
- try:
176
- with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
177
- tree = ast.parse(f.read(), filename=filepath)
178
-
179
- if top_level_only:
180
- nodes_to_visit = []
181
- for item in tree.body:
182
- nodes_to_visit.append(item)
183
- if isinstance(item, (ast.If, ast.Try)):
184
- nodes_to_visit.extend(ast.walk(item))
185
- else:
186
- nodes_to_visit = list(ast.walk(tree))
187
-
188
- for node in nodes_to_visit:
189
- line_no = getattr(node, "lineno", 1)
190
- if isinstance(node, ast.Import):
191
- for n in node.names:
192
- imports.add((n.name, line_no))
193
- elif isinstance(node, ast.ImportFrom):
194
- if node.level and node.level > 0:
195
- base_parts = os.path.dirname(rel_p).replace("\\\\", "/").split("/") if os.path.dirname(rel_p) else []
196
- if node.level <= len(base_parts):
197
- prefix = ".".join(base_parts[:len(base_parts) - node.level + 1])
198
- mod = f"{{prefix}}.{{node.module}}" if node.module else prefix
199
- else:
200
- mod = node.module or ""
201
- if mod:
202
- imports.add((mod, line_no))
203
- elif node.module:
204
- imports.add((node.module, line_no))
205
- except Exception:
206
- pass
207
- return imports
208
-
209
-
210
- class TestArchitectureGuard(unittest.TestCase):
211
- """Verifies that codebase conforms 100% to declared architectural boundaries."""
212
-
213
- @classmethod
214
- def setUpClass(cls):
215
- cls.python_files: Dict[str, str] = {{}} # rel_path -> full_path
216
- cls.import_graph: Dict[str, Set[Tuple[str, int]]] = {{}} # rel_path -> set of (module, line)
217
- cls.top_import_graph: Dict[str, Set[str]] = {{}} # mod_name -> set of top-level imported root mods
218
-
219
- for root, dirs, files in os.walk(WORKSPACE_ROOT):
220
- dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info")]
221
- for f in files:
222
- if f.endswith(".py"):
223
- full_p = os.path.join(root, f)
224
- rel_p = os.path.relpath(full_p, WORKSPACE_ROOT).replace("\\\\", "/")
225
- cls.python_files[rel_p] = full_p
226
- cls.import_graph[rel_p] = _extract_ast_imports(full_p, rel_p, top_level_only=False)
227
-
228
- mod = os.path.splitext(f)[0]
229
- top_imps = _extract_ast_imports(full_p, rel_p, top_level_only=True)
230
- cls.top_import_graph[mod] = {{imp.split(".")[0] for imp, _ in top_imps}}
231
-
232
- def test_layer_boundaries_and_forbidden_imports(self):
233
- """Ensures that lower layers never import from upper or restricted layers."""
234
- violations = []
235
- for rule in FORBIDDEN_IMPORTS:
236
- from_layer = rule.get("from_layer")
237
- cannot_import = rule.get("cannot_import", [])
238
- reason = rule.get("reason", "Layer boundary violation")
239
- layer_patterns = LAYERS.get(from_layer, [])
240
-
241
- for rel_p, full_p in self.python_files.items():
242
- if not _matches_layer(rel_p, layer_patterns):
243
- continue
244
-
245
- for full_imp, line_no in self.import_graph.get(rel_p, set()):
246
- imp_segments = full_imp.split(".")
247
- for forbidden_target in cannot_import:
248
- clean_forbidden = forbidden_target.replace("/", ".").rstrip("/*")
249
- is_violation = (
250
- full_imp == clean_forbidden
251
- or full_imp.startswith(clean_forbidden + ".")
252
- or full_imp.endswith("." + clean_forbidden)
253
- or clean_forbidden in imp_segments
254
- or fnmatch.fnmatch(full_imp, forbidden_target)
255
- or fnmatch.fnmatch(full_imp, f"{{clean_forbidden}}.*")
256
- )
257
- if is_violation:
258
- violations.append(
259
- f"File '{{rel_p}}:{{line_no}}' (layer: '{{from_layer}}') imports forbidden '{{full_imp}}'. "
260
- f"Rule reason: {{reason}}"
261
- )
262
-
263
- self.assertEqual(
264
- violations, [],
265
- f"Detected {{len(violations)}} architectural layer violations:\\n" + "\\n".join(violations)
266
- )
267
-
268
- def test_zero_circular_imports(self):
269
- """Ensures there are no circular dependency cycles among top-level modules."""
270
- cycles = []
271
- visited = set()
272
- rec_stack = set()
273
-
274
- def dfs(node: str, path: List[str]):
275
- visited.add(node)
276
- rec_stack.add(node)
277
- for neighbor in self.top_import_graph.get(node, set()):
278
- if neighbor not in self.top_import_graph or neighbor == node:
279
- continue
280
- if neighbor not in visited:
281
- dfs(neighbor, path + [neighbor])
282
- elif neighbor in rec_stack:
283
- if neighbor in path:
284
- cycle = path[path.index(neighbor):] + [neighbor]
285
- cycles.append(" -> ".join(cycle))
286
- rec_stack.remove(node)
287
-
288
- for m in list(self.top_import_graph.keys()):
289
- if m not in visited:
290
- dfs(m, [m])
291
-
292
- self.assertEqual(
293
- cycles, [],
294
- f"Detected {{len(cycles)}} circular import cycles:\\n" + "\\n".join(cycles)
295
- )
296
-
297
- def test_zero_leak_security_policy(self):
298
- """Ensures that no source files contain hardcoded secrets, private keys, or API tokens."""
299
- if not ZERO_LEAK_ENFORCED:
300
- self.skipTest("Zero-Leak policy is disabled in configuration.")
301
-
302
- secret_leaks = []
303
- for rel_p, full_p in self.python_files.items():
304
- if "test" in rel_p.lower():
305
- continue # Skip test fixtures
306
- try:
307
- with open(full_p, "r", encoding="utf-8", errors="ignore") as f:
308
- content = f.read()
309
- for pat in SECRET_PATTERNS:
310
- match = pat.search(content)
311
- if match:
312
- secret_leaks.append(f"Secret matched in '{{rel_p}}': {{match.group(0)[:8]}}...")
313
- except Exception:
314
- pass
315
-
316
- self.assertEqual(
317
- secret_leaks, [],
318
- f"Detected {{len(secret_leaks)}} secret leaks in source code:\\n" + "\\n".join(secret_leaks)
319
- )
320
-
321
-
322
- if __name__ == "__main__":
323
- unittest.main()
324
- '''
325
- return code
326
-
327
- def write_test_file(self, target_path: Optional[str] = None) -> str:
328
- """Writes the generated architecture test file to disk."""
329
- if not target_path:
330
- tests_dir = os.path.join(self.project_dir, "tests")
331
- os.makedirs(tests_dir, exist_ok=True)
332
- target_path = os.path.join(tests_dir, "test_architecture_guard.py")
333
-
334
- code = self.generate_test_code()
335
- with open(target_path, "w", encoding="utf-8") as f:
336
- f.write(code)
337
-
338
- return target_path
339
-
340
- def run_live_audit(self) -> Dict[str, Any]:
341
- """Runs in-memory live validation of layer rules, circular imports, and zero-leak security."""
342
- layers = self.rules.get("layers", {})
343
- forbidden = self.rules.get("forbidden_imports", [])
344
- security = self.rules.get("security", {})
345
-
346
- python_files: Dict[str, str] = {}
347
- import_graph: Dict[str, Set[Tuple[str, int]]] = {}
348
- top_import_graph: Dict[str, Set[str]] = {}
349
-
350
- for root, dirs, files in os.walk(self.project_dir):
351
- dirs[:] = [d for d in dirs if not _should_skip_dir(d)]
352
- for f in files:
353
- if f.endswith(".py"):
354
- full_p = os.path.join(root, f)
355
- rel_p = os.path.relpath(full_p, self.project_dir).replace("\\", "/")
356
- python_files[rel_p] = full_p
357
- import_graph[rel_p] = _extract_ast_imports(full_p, rel_p, top_level_only=False)
358
-
359
- mod = os.path.splitext(f)[0]
360
- top_imps = _extract_ast_imports(full_p, rel_p, top_level_only=True)
361
- top_import_graph[mod] = {imp.split(".")[0] for imp, _ in top_imps}
362
-
363
- # 1. Layer boundary violations
364
- layer_violations = []
365
- for rule in forbidden:
366
- from_layer = rule.get("from_layer")
367
- cannot_import = rule.get("cannot_import", [])
368
- reason = rule.get("reason", "Forbidden cross-layer coupling")
369
- layer_patterns = layers.get(from_layer, [])
370
-
371
- for rel_p, full_p in python_files.items():
372
- matches = False
373
- for p in layer_patterns:
374
- p_clean = p.replace("\\", "/").rstrip("/*")
375
- if p.endswith("/*") or p.endswith("/**"):
376
- if rel_p.startswith(p_clean + "/") or rel_p == p_clean:
377
- matches = True
378
- break
379
- elif rel_p == p_clean or os.path.basename(rel_p) == p_clean:
380
- matches = True
381
- break
382
-
383
- if not matches:
384
- continue
385
-
386
- for full_imp, line_no in import_graph.get(rel_p, set()):
387
- imp_segments = full_imp.split(".")
388
- for forbidden_target in cannot_import:
389
- clean_forbidden = forbidden_target.replace("/", ".").rstrip("/*")
390
- is_violation = (
391
- full_imp == clean_forbidden
392
- or full_imp.startswith(clean_forbidden + ".")
393
- or full_imp.endswith("." + clean_forbidden)
394
- or clean_forbidden in imp_segments
395
- or fnmatch.fnmatch(full_imp, forbidden_target)
396
- or fnmatch.fnmatch(full_imp, f"{clean_forbidden}.*")
397
- )
398
- if is_violation:
399
- layer_violations.append({
400
- "file": rel_p,
401
- "line": line_no,
402
- "layer": from_layer,
403
- "from_layer": from_layer,
404
- "forbidden_target": forbidden_target,
405
- "imported": full_imp,
406
- "reason": reason
407
- })
408
-
409
- # 2. Circular dependency check
410
- cycles: List[str] = []
411
- visited: Set[str] = set()
412
- rec_stack: Set[str] = set()
413
-
414
- def dfs(node: str, path: List[str]):
415
- visited.add(node)
416
- rec_stack.add(node)
417
- for neighbor in top_import_graph.get(node, set()):
418
- if neighbor not in top_import_graph or neighbor == node:
419
- continue
420
- if neighbor not in visited:
421
- dfs(neighbor, path + [neighbor])
422
- elif neighbor in rec_stack:
423
- if neighbor in path:
424
- cycle = path[path.index(neighbor):] + [neighbor]
425
- cycles.append(" -> ".join(cycle))
426
- rec_stack.remove(node)
427
-
428
- for m in list(top_import_graph.keys()):
429
- if m not in visited:
430
- dfs(m, [m])
431
-
432
- # 3. Zero leak check
433
- secret_leaks = []
434
- patterns = [
435
- re.compile(r"sk-[a-zA-Z0-9]{20,}"),
436
- re.compile(r"ghp_[a-zA-Z0-9]{30,}"),
437
- re.compile(r"AIza[0-9A-Za-z-_]{35}"),
438
- re.compile(r"AKIA[0-9A-Z]{16}")
439
- ]
440
- if security.get("zero_leak_enforced", True):
441
- for rel_p, full_p in python_files.items():
442
- if "test" in rel_p.lower():
443
- continue
444
- try:
445
- with open(full_p, "r", encoding="utf-8", errors="ignore") as fp:
446
- content = fp.read()
447
- for p in patterns:
448
- m = p.search(content)
449
- if m:
450
- secret_leaks.append({"file": rel_p, "pattern": m.group(0)[:8] + "..."})
451
- except Exception:
452
- pass
453
-
454
- passed = len(layer_violations) == 0 and len(cycles) == 0 and len(secret_leaks) == 0
455
-
456
- return {
457
- "success": passed,
458
- "scanned_files": len(python_files),
459
- "layers_count": len(layers),
460
- "layer_violations": layer_violations,
461
- "circular_cycles": cycles,
462
- "secret_leaks": secret_leaks
463
- }
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Automated Architecture Test Suite Generator & Validator.
3
+
4
+ Generates self-contained, zero-dependency `unittest` test suites from `tzero.rules.json`
5
+ enforcing layer boundaries, circular import prohibition, and zero-leak security
6
+ in standard CI/CD pipelines without external frameworks.
7
+
8
+ Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
9
+ Part of T-Zero Context Architect v10.8.0 Master Edition.
10
+ """
11
+
12
+ import ast
13
+ import fnmatch
14
+ import json
15
+ import os
16
+ import re
17
+ import sys
18
+ from typing import Dict, List, Any, Optional, Set, Tuple
19
+
20
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
21
+ try:
22
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
23
+ except Exception:
24
+ pass
25
+
26
+
27
+ def _should_skip_dir(dir_name: str) -> bool:
28
+ """Returns True if the directory should be skipped during AST analysis."""
29
+ skip_names = {
30
+ ".git", ".svn", ".hg", "__pycache__", ".pytest_cache",
31
+ "node_modules", "dist", "build", "venv", ".venv", "env",
32
+ ".gemini", ".idea", ".vscode", "site-packages", ".egg-info",
33
+ "installers", "benchmark-site"
34
+ }
35
+ return dir_name in skip_names or dir_name.endswith(".egg-info")
36
+
37
+
38
+ def _extract_ast_imports(filepath: str, rel_p: str, top_level_only: bool = False) -> Set[Tuple[str, int]]:
39
+ """Extracts imported module names and their line numbers from a python file."""
40
+ imports = set()
41
+ try:
42
+ with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
43
+ tree = ast.parse(f.read(), filename=filepath)
44
+
45
+ if top_level_only:
46
+ nodes_to_visit = []
47
+ for item in tree.body:
48
+ nodes_to_visit.append(item)
49
+ if isinstance(item, (ast.If, ast.Try)):
50
+ nodes_to_visit.extend(ast.walk(item))
51
+ else:
52
+ nodes_to_visit = list(ast.walk(tree))
53
+
54
+ for node in nodes_to_visit:
55
+ line_no = getattr(node, "lineno", 1)
56
+ if isinstance(node, ast.Import):
57
+ for n in node.names:
58
+ imports.add((n.name, line_no))
59
+ elif isinstance(node, ast.ImportFrom):
60
+ if node.level and node.level > 0:
61
+ base_parts = os.path.dirname(rel_p).replace("\\", "/").split("/") if os.path.dirname(rel_p) else []
62
+ if node.level <= len(base_parts):
63
+ prefix = ".".join(base_parts[:len(base_parts) - node.level + 1])
64
+ mod = f"{prefix}.{node.module}" if node.module else prefix
65
+ else:
66
+ mod = node.module or ""
67
+ if mod:
68
+ imports.add((mod, line_no))
69
+ elif node.module:
70
+ imports.add((node.module, line_no))
71
+ except Exception:
72
+ pass
73
+ return imports
74
+
75
+
76
+ class ArchitectureTestSuiteGenerator:
77
+ """Generates and executes zero-dependency architectural guard test suites."""
78
+
79
+ def __init__(self, project_dir: str = ".", rules_path: Optional[str] = None):
80
+ self.project_dir = os.path.abspath(project_dir)
81
+ self.rules_path = rules_path or os.path.join(self.project_dir, "tzero.rules.json")
82
+ self.rules = self._load_rules()
83
+
84
+ def _load_rules(self) -> Dict[str, Any]:
85
+ """Loads rules from tzero.rules.json or returns sensible enterprise defaults."""
86
+ if os.path.isfile(self.rules_path):
87
+ try:
88
+ with open(self.rules_path, "r", encoding="utf-8") as f:
89
+ return json.load(f)
90
+ except Exception:
91
+ pass
92
+ return {
93
+ "version": "5.0.0",
94
+ "project_name": os.path.basename(self.project_dir) or "Project",
95
+ "layers": {
96
+ "presentation": ["cli/**", "gui/**", "web/**"],
97
+ "business": ["services/**", "core/**"],
98
+ "persistence": ["models/**", "db/**", "utils/**"]
99
+ },
100
+ "forbidden_imports": [
101
+ {
102
+ "from_layer": "persistence",
103
+ "cannot_import": ["presentation", "business"],
104
+ "reason": "Persistence layer must not depend on higher layers."
105
+ },
106
+ {
107
+ "from_layer": "business",
108
+ "cannot_import": ["presentation"],
109
+ "reason": "Business services must remain presentation-agnostic."
110
+ }
111
+ ],
112
+ "security": {
113
+ "zero_leak_enforced": True,
114
+ "disallow_hardcoded_keys": True
115
+ }
116
+ }
117
+
118
+ def generate_test_code(self) -> str:
119
+ """Generates the full Python source code for the standalone architecture test suite."""
120
+ project_name = self.rules.get("project_name", "T-Zero Project")
121
+ layers_json = json.dumps(self.rules.get("layers", {}), indent=8)
122
+ forbidden_json = json.dumps(self.rules.get("forbidden_imports", []), indent=8)
123
+ security_config = self.rules.get("security", {})
124
+ zero_leak = bool(security_config.get("zero_leak_enforced", True))
125
+
126
+ code = f'''# -*- coding: utf-8 -*-
127
+ """Auto-generated T-Zero Architectural Integrity Guard Test Suite.
128
+ Project: {project_name}
129
+ Generated by: T-Zero ArchitectureTestSuiteGenerator
130
+ Zero-Dependency: Runs in standard Python unittest / pytest environments.
131
+ """
132
+
133
+ import ast
134
+ import fnmatch
135
+ import os
136
+ import re
137
+ import sys
138
+ import unittest
139
+ from typing import Dict, List, Set, Tuple, Any
140
+
141
+ WORKSPACE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
142
+ SKIP_DIRS = {{
143
+ ".git", ".svn", "__pycache__", "node_modules", "dist", "build",
144
+ "venv", ".venv", "env", ".gemini", ".idea", ".vscode", "installers", "benchmark-site"
145
+ }}
146
+
147
+ LAYERS: Dict[str, List[str]] = {layers_json}
148
+
149
+ FORBIDDEN_IMPORTS: List[Dict[str, Any]] = {forbidden_json}
150
+
151
+ ZERO_LEAK_ENFORCED = {zero_leak}
152
+
153
+ SECRET_PATTERNS = [
154
+ re.compile(r"sk-[a-zA-Z0-9]{{20,}}"),
155
+ re.compile(r"ghp_[a-zA-Z0-9]{{30,}}"),
156
+ re.compile(r"AIza[0-9A-Za-z-_]{{35}}"),
157
+ re.compile(r"AKIA[0-9A-Z]{{16}}"),
158
+ re.compile(r"-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY-----")
159
+ ]
160
+
161
+
162
+ def _matches_layer(file_rel: str, patterns: List[str]) -> bool:
163
+ for p in patterns:
164
+ p_clean = p.replace("\\\\", "/").rstrip("/*")
165
+ if p.endswith("/*") or p.endswith("/**"):
166
+ if file_rel.startswith(p_clean + "/") or file_rel == p_clean:
167
+ return True
168
+ elif file_rel == p_clean or os.path.basename(file_rel) == p_clean:
169
+ return True
170
+ return False
171
+
172
+
173
+ def _extract_ast_imports(filepath: str, rel_p: str, top_level_only: bool = False) -> Set[Tuple[str, int]]:
174
+ imports = set()
175
+ try:
176
+ with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
177
+ tree = ast.parse(f.read(), filename=filepath)
178
+
179
+ if top_level_only:
180
+ nodes_to_visit = []
181
+ for item in tree.body:
182
+ nodes_to_visit.append(item)
183
+ if isinstance(item, (ast.If, ast.Try)):
184
+ nodes_to_visit.extend(ast.walk(item))
185
+ else:
186
+ nodes_to_visit = list(ast.walk(tree))
187
+
188
+ for node in nodes_to_visit:
189
+ line_no = getattr(node, "lineno", 1)
190
+ if isinstance(node, ast.Import):
191
+ for n in node.names:
192
+ imports.add((n.name, line_no))
193
+ elif isinstance(node, ast.ImportFrom):
194
+ if node.level and node.level > 0:
195
+ base_parts = os.path.dirname(rel_p).replace("\\\\", "/").split("/") if os.path.dirname(rel_p) else []
196
+ if node.level <= len(base_parts):
197
+ prefix = ".".join(base_parts[:len(base_parts) - node.level + 1])
198
+ mod = f"{{prefix}}.{{node.module}}" if node.module else prefix
199
+ else:
200
+ mod = node.module or ""
201
+ if mod:
202
+ imports.add((mod, line_no))
203
+ elif node.module:
204
+ imports.add((node.module, line_no))
205
+ except Exception:
206
+ pass
207
+ return imports
208
+
209
+
210
+ class TestArchitectureGuard(unittest.TestCase):
211
+ """Verifies that codebase conforms 100% to declared architectural boundaries."""
212
+
213
+ @classmethod
214
+ def setUpClass(cls):
215
+ cls.python_files: Dict[str, str] = {{}} # rel_path -> full_path
216
+ cls.import_graph: Dict[str, Set[Tuple[str, int]]] = {{}} # rel_path -> set of (module, line)
217
+ cls.top_import_graph: Dict[str, Set[str]] = {{}} # mod_name -> set of top-level imported root mods
218
+
219
+ for root, dirs, files in os.walk(WORKSPACE_ROOT):
220
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info")]
221
+ for f in files:
222
+ if f.endswith(".py"):
223
+ full_p = os.path.join(root, f)
224
+ rel_p = os.path.relpath(full_p, WORKSPACE_ROOT).replace("\\\\", "/")
225
+ cls.python_files[rel_p] = full_p
226
+ cls.import_graph[rel_p] = _extract_ast_imports(full_p, rel_p, top_level_only=False)
227
+
228
+ mod = os.path.splitext(f)[0]
229
+ top_imps = _extract_ast_imports(full_p, rel_p, top_level_only=True)
230
+ cls.top_import_graph[mod] = {{imp.split(".")[0] for imp, _ in top_imps}}
231
+
232
+ def test_layer_boundaries_and_forbidden_imports(self):
233
+ """Ensures that lower layers never import from upper or restricted layers."""
234
+ violations = []
235
+ for rule in FORBIDDEN_IMPORTS:
236
+ from_layer = rule.get("from_layer")
237
+ cannot_import = rule.get("cannot_import", [])
238
+ reason = rule.get("reason", "Layer boundary violation")
239
+ layer_patterns = LAYERS.get(from_layer, [])
240
+
241
+ for rel_p, full_p in self.python_files.items():
242
+ if not _matches_layer(rel_p, layer_patterns):
243
+ continue
244
+
245
+ for full_imp, line_no in self.import_graph.get(rel_p, set()):
246
+ imp_segments = full_imp.split(".")
247
+ for forbidden_target in cannot_import:
248
+ clean_forbidden = forbidden_target.replace("/", ".").rstrip("/*")
249
+ is_violation = (
250
+ full_imp == clean_forbidden
251
+ or full_imp.startswith(clean_forbidden + ".")
252
+ or full_imp.endswith("." + clean_forbidden)
253
+ or clean_forbidden in imp_segments
254
+ or fnmatch.fnmatch(full_imp, forbidden_target)
255
+ or fnmatch.fnmatch(full_imp, f"{{clean_forbidden}}.*")
256
+ )
257
+ if is_violation:
258
+ violations.append(
259
+ f"File '{{rel_p}}:{{line_no}}' (layer: '{{from_layer}}') imports forbidden '{{full_imp}}'. "
260
+ f"Rule reason: {{reason}}"
261
+ )
262
+
263
+ self.assertEqual(
264
+ violations, [],
265
+ f"Detected {{len(violations)}} architectural layer violations:\\n" + "\\n".join(violations)
266
+ )
267
+
268
+ def test_zero_circular_imports(self):
269
+ """Ensures there are no circular dependency cycles among top-level modules."""
270
+ cycles = []
271
+ visited = set()
272
+ rec_stack = set()
273
+
274
+ def dfs(node: str, path: List[str]):
275
+ visited.add(node)
276
+ rec_stack.add(node)
277
+ for neighbor in self.top_import_graph.get(node, set()):
278
+ if neighbor not in self.top_import_graph or neighbor == node:
279
+ continue
280
+ if neighbor not in visited:
281
+ dfs(neighbor, path + [neighbor])
282
+ elif neighbor in rec_stack:
283
+ if neighbor in path:
284
+ cycle = path[path.index(neighbor):] + [neighbor]
285
+ cycles.append(" -> ".join(cycle))
286
+ rec_stack.remove(node)
287
+
288
+ for m in list(self.top_import_graph.keys()):
289
+ if m not in visited:
290
+ dfs(m, [m])
291
+
292
+ self.assertEqual(
293
+ cycles, [],
294
+ f"Detected {{len(cycles)}} circular import cycles:\\n" + "\\n".join(cycles)
295
+ )
296
+
297
+ def test_zero_leak_security_policy(self):
298
+ """Ensures that no source files contain hardcoded secrets, private keys, or API tokens."""
299
+ if not ZERO_LEAK_ENFORCED:
300
+ self.skipTest("Zero-Leak policy is disabled in configuration.")
301
+
302
+ secret_leaks = []
303
+ for rel_p, full_p in self.python_files.items():
304
+ if "test" in rel_p.lower():
305
+ continue # Skip test fixtures
306
+ try:
307
+ with open(full_p, "r", encoding="utf-8", errors="ignore") as f:
308
+ content = f.read()
309
+ for pat in SECRET_PATTERNS:
310
+ match = pat.search(content)
311
+ if match:
312
+ secret_leaks.append(f"Secret matched in '{{rel_p}}': {{match.group(0)[:8]}}...")
313
+ except Exception:
314
+ pass
315
+
316
+ self.assertEqual(
317
+ secret_leaks, [],
318
+ f"Detected {{len(secret_leaks)}} secret leaks in source code:\\n" + "\\n".join(secret_leaks)
319
+ )
320
+
321
+
322
+ if __name__ == "__main__":
323
+ unittest.main()
324
+ '''
325
+ return code
326
+
327
+ def write_test_file(self, target_path: Optional[str] = None) -> str:
328
+ """Writes the generated architecture test file to disk."""
329
+ if not target_path:
330
+ tests_dir = os.path.join(self.project_dir, "tests")
331
+ os.makedirs(tests_dir, exist_ok=True)
332
+ target_path = os.path.join(tests_dir, "test_architecture_guard.py")
333
+
334
+ code = self.generate_test_code()
335
+ with open(target_path, "w", encoding="utf-8") as f:
336
+ f.write(code)
337
+
338
+ return target_path
339
+
340
+ def run_live_audit(self) -> Dict[str, Any]:
341
+ """Runs in-memory live validation of layer rules, circular imports, and zero-leak security."""
342
+ layers = self.rules.get("layers", {})
343
+ forbidden = self.rules.get("forbidden_imports", [])
344
+ security = self.rules.get("security", {})
345
+
346
+ python_files: Dict[str, str] = {}
347
+ import_graph: Dict[str, Set[Tuple[str, int]]] = {}
348
+ top_import_graph: Dict[str, Set[str]] = {}
349
+
350
+ for root, dirs, files in os.walk(self.project_dir):
351
+ dirs[:] = [d for d in dirs if not _should_skip_dir(d)]
352
+ for f in files:
353
+ if f.endswith(".py"):
354
+ full_p = os.path.join(root, f)
355
+ rel_p = os.path.relpath(full_p, self.project_dir).replace("\\", "/")
356
+ python_files[rel_p] = full_p
357
+ import_graph[rel_p] = _extract_ast_imports(full_p, rel_p, top_level_only=False)
358
+
359
+ mod = os.path.splitext(f)[0]
360
+ top_imps = _extract_ast_imports(full_p, rel_p, top_level_only=True)
361
+ top_import_graph[mod] = {imp.split(".")[0] for imp, _ in top_imps}
362
+
363
+ # 1. Layer boundary violations
364
+ layer_violations = []
365
+ for rule in forbidden:
366
+ from_layer = rule.get("from_layer")
367
+ cannot_import = rule.get("cannot_import", [])
368
+ reason = rule.get("reason", "Forbidden cross-layer coupling")
369
+ layer_patterns = layers.get(from_layer, [])
370
+
371
+ for rel_p, full_p in python_files.items():
372
+ matches = False
373
+ for p in layer_patterns:
374
+ p_clean = p.replace("\\", "/").rstrip("/*")
375
+ if p.endswith("/*") or p.endswith("/**"):
376
+ if rel_p.startswith(p_clean + "/") or rel_p == p_clean:
377
+ matches = True
378
+ break
379
+ elif rel_p == p_clean or os.path.basename(rel_p) == p_clean:
380
+ matches = True
381
+ break
382
+
383
+ if not matches:
384
+ continue
385
+
386
+ for full_imp, line_no in import_graph.get(rel_p, set()):
387
+ imp_segments = full_imp.split(".")
388
+ for forbidden_target in cannot_import:
389
+ clean_forbidden = forbidden_target.replace("/", ".").rstrip("/*")
390
+ is_violation = (
391
+ full_imp == clean_forbidden
392
+ or full_imp.startswith(clean_forbidden + ".")
393
+ or full_imp.endswith("." + clean_forbidden)
394
+ or clean_forbidden in imp_segments
395
+ or fnmatch.fnmatch(full_imp, forbidden_target)
396
+ or fnmatch.fnmatch(full_imp, f"{clean_forbidden}.*")
397
+ )
398
+ if is_violation:
399
+ layer_violations.append({
400
+ "file": rel_p,
401
+ "line": line_no,
402
+ "layer": from_layer,
403
+ "from_layer": from_layer,
404
+ "forbidden_target": forbidden_target,
405
+ "imported": full_imp,
406
+ "reason": reason
407
+ })
408
+
409
+ # 2. Circular dependency check
410
+ cycles: List[str] = []
411
+ visited: Set[str] = set()
412
+ rec_stack: Set[str] = set()
413
+
414
+ def dfs(node: str, path: List[str]):
415
+ visited.add(node)
416
+ rec_stack.add(node)
417
+ for neighbor in top_import_graph.get(node, set()):
418
+ if neighbor not in top_import_graph or neighbor == node:
419
+ continue
420
+ if neighbor not in visited:
421
+ dfs(neighbor, path + [neighbor])
422
+ elif neighbor in rec_stack:
423
+ if neighbor in path:
424
+ cycle = path[path.index(neighbor):] + [neighbor]
425
+ cycles.append(" -> ".join(cycle))
426
+ rec_stack.remove(node)
427
+
428
+ for m in list(top_import_graph.keys()):
429
+ if m not in visited:
430
+ dfs(m, [m])
431
+
432
+ # 3. Zero leak check
433
+ secret_leaks = []
434
+ patterns = [
435
+ re.compile(r"sk-[a-zA-Z0-9]{20,}"),
436
+ re.compile(r"ghp_[a-zA-Z0-9]{30,}"),
437
+ re.compile(r"AIza[0-9A-Za-z-_]{35}"),
438
+ re.compile(r"AKIA[0-9A-Z]{16}")
439
+ ]
440
+ if security.get("zero_leak_enforced", True):
441
+ for rel_p, full_p in python_files.items():
442
+ if "test" in rel_p.lower():
443
+ continue
444
+ try:
445
+ with open(full_p, "r", encoding="utf-8", errors="ignore") as fp:
446
+ content = fp.read()
447
+ for p in patterns:
448
+ m = p.search(content)
449
+ if m:
450
+ secret_leaks.append({"file": rel_p, "pattern": m.group(0)[:8] + "..."})
451
+ except Exception:
452
+ pass
453
+
454
+ passed = len(layer_violations) == 0 and len(cycles) == 0 and len(secret_leaks) == 0
455
+
456
+ return {
457
+ "success": passed,
458
+ "scanned_files": len(python_files),
459
+ "layers_count": len(layers),
460
+ "layer_violations": layer_violations,
461
+ "circular_cycles": cycles,
462
+ "secret_leaks": secret_leaks
463
+ }