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
@@ -0,0 +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
+ }
@@ -18,8 +18,8 @@ import time
18
18
  from dataclasses import dataclass, field
19
19
  from typing import Dict, List, Any, Optional
20
20
 
21
- from tzero_packer import TokenBudgetPacker
22
- from tzero_cost import TokenCostCalculator, CostReport, ModelCostComparison
21
+ from tzero.tzero_packer import TokenBudgetPacker
22
+ from tzero.tzero_cost import TokenCostCalculator, CostReport, ModelCostComparison
23
23
 
24
24
 
25
25
  @dataclass