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,319 +1,319 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Autonomous Golden Baseline & AST Regression Engine.
3
-
4
- Captures a cryptographically signed baseline snapshot of all public AST signatures
5
- across the workspace and verifies against accidental regressions in CI/CD pipelines.
6
-
7
- Capabilities:
8
- - Zero-drift public API golden snapshot generation (.tzero/goldens.json).
9
- - Deterministic signature diffing (removed symbols, altered parameters, return type drift).
10
- - Pre-merge regression guard: fails CI if public contract breaks without explicit baseline update.
11
- - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
12
-
13
- Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
- Part of T-Zero Context Architect v11.0.0 Master Edition.
15
- """
16
-
17
- import ast
18
- import hashlib
19
- import json
20
- import os
21
- import sys
22
- import time
23
- from dataclasses import dataclass, asdict
24
- from typing import Dict, List, Optional, Tuple, Any
25
-
26
- if sys.stdout and hasattr(sys.stdout, "reconfigure"):
27
- try:
28
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
29
- except Exception:
30
- pass
31
-
32
-
33
- @dataclass
34
- class SymbolSignature:
35
- file_path: str
36
- symbol_name: str
37
- kind: str # "function", "class", "method"
38
- signature: str
39
- return_type: Optional[str] = None
40
- docstring_hash: str = ""
41
-
42
-
43
- @dataclass
44
- class GoldenBaseline:
45
- workspace_root: str
46
- version: str
47
- created_at: float
48
- symbols: Dict[str, Dict[str, Any]]
49
- total_symbols: int
50
- sha256_checksum: str
51
-
52
-
53
- class ASTGoldenRegressionEngine:
54
- """Extracts and verifies golden AST signature baselines for zero-drift CI pipelines."""
55
-
56
- @classmethod
57
- def extract_file_signatures(cls, file_path: str, code: str) -> List[SymbolSignature]:
58
- """Extracts all public function, class, and method signatures from Python code."""
59
- try:
60
- tree = ast.parse(code)
61
- except Exception:
62
- return []
63
-
64
- signatures: List[SymbolSignature] = []
65
- rel_p = file_path.replace("\\", "/")
66
-
67
- for node in tree.body:
68
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
69
- if node.name.startswith("_") and not node.name.startswith("__"):
70
- continue
71
- sig = cls._extract_function_signature(node)
72
- ret = ast.unparse(node.returns) if getattr(node, "returns", None) else None
73
- doc = ast.get_docstring(node) or ""
74
- doc_h = hashlib.sha256(doc.encode("utf-8")).hexdigest()[:12]
75
- signatures.append(SymbolSignature(
76
- file_path=rel_p,
77
- symbol_name=node.name,
78
- kind="function",
79
- signature=sig,
80
- return_type=ret,
81
- docstring_hash=doc_h
82
- ))
83
-
84
- elif isinstance(node, ast.ClassDef):
85
- if node.name.startswith("_"):
86
- continue
87
- bases = ", ".join(ast.unparse(b) for b in node.bases)
88
- cls_sig = f"class {node.name}({bases})" if bases else f"class {node.name}"
89
- doc = ast.get_docstring(node) or ""
90
- doc_h = hashlib.sha256(doc.encode("utf-8")).hexdigest()[:12]
91
- signatures.append(SymbolSignature(
92
- file_path=rel_p,
93
- symbol_name=node.name,
94
- kind="class",
95
- signature=cls_sig,
96
- return_type=None,
97
- docstring_hash=doc_h
98
- ))
99
-
100
- for item in node.body:
101
- if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
102
- if item.name.startswith("_") and not item.name.startswith("__"):
103
- continue
104
- m_sig = cls._extract_function_signature(item)
105
- m_ret = ast.unparse(item.returns) if getattr(item, "returns", None) else None
106
- m_doc = ast.get_docstring(item) or ""
107
- m_doc_h = hashlib.sha256(m_doc.encode("utf-8")).hexdigest()[:12]
108
- signatures.append(SymbolSignature(
109
- file_path=rel_p,
110
- symbol_name=f"{node.name}.{item.name}",
111
- kind="method",
112
- signature=m_sig,
113
- return_type=m_ret,
114
- docstring_hash=m_doc_h
115
- ))
116
-
117
- return signatures
118
-
119
- @classmethod
120
- def _extract_function_signature(cls, node: Any) -> str:
121
- params = []
122
- args = node.args
123
-
124
- num_defaults = len(args.defaults)
125
- num_pos = len(args.args)
126
- defaults_start = num_pos - num_defaults
127
-
128
- for i, a in enumerate(args.args):
129
- p_str = a.arg
130
- if getattr(a, "annotation", None):
131
- p_str += f": {ast.unparse(a.annotation)}"
132
- if i >= defaults_start:
133
- def_node = args.defaults[i - defaults_start]
134
- p_str += f" = {ast.unparse(def_node)}"
135
- params.append(p_str)
136
-
137
- if args.vararg:
138
- v_str = f"*{args.vararg.arg}"
139
- if getattr(args.vararg, "annotation", None):
140
- v_str += f": {ast.unparse(args.vararg.annotation)}"
141
- params.append(v_str)
142
-
143
- for i, a in enumerate(args.kwonlyargs):
144
- kw_str = a.arg
145
- if getattr(a, "annotation", None):
146
- kw_str += f": {ast.unparse(a.annotation)}"
147
- if i < len(args.kw_defaults) and args.kw_defaults[i] is not None:
148
- kw_str += f" = {ast.unparse(args.kw_defaults[i])}"
149
- params.append(kw_str)
150
-
151
- if args.kwarg:
152
- kwarg_str = f"**{args.kwarg.arg}"
153
- if getattr(args.kwarg, "annotation", None):
154
- kwarg_str += f": {ast.unparse(args.kwarg.annotation)}"
155
- params.append(kwarg_str)
156
-
157
- prefix = "async def " if isinstance(node, ast.AsyncFunctionDef) else "def "
158
- return f"{prefix}{node.name}({', '.join(params)})"
159
-
160
- @classmethod
161
- def generate_baseline(cls, workspace_root: str = ".", max_files: int = 300) -> GoldenBaseline:
162
- """Scans workspace and generates the golden contract baseline."""
163
- abs_root = os.path.abspath(workspace_root)
164
- all_sigs: Dict[str, Dict[str, Any]] = {}
165
- hasher = hashlib.sha256()
166
-
167
- ignore_dirs = {".git", ".venv", "venv", "__pycache__", "node_modules", "dist", "build", ".pytest_cache"}
168
-
169
- file_count = 0
170
- for root, dirs, files in os.walk(abs_root):
171
- dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
172
- for f in files:
173
- if f.endswith(".py"):
174
- full_p = os.path.join(root, f)
175
- rel_p = os.path.relpath(full_p, abs_root).replace("\\", "/")
176
- try:
177
- with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
178
- code = fp.read()
179
- sigs = cls.extract_file_signatures(rel_p, code)
180
- for s in sigs:
181
- key = f"{s.file_path}:{s.symbol_name}"
182
- d = asdict(s)
183
- all_sigs[key] = d
184
- hasher.update(f"{key}:{s.signature}:{s.return_type}".encode("utf-8"))
185
- file_count += 1
186
- if file_count >= max_files:
187
- break
188
- except Exception:
189
- pass
190
- if file_count >= max_files:
191
- break
192
-
193
- return GoldenBaseline(
194
- workspace_root=abs_root,
195
- version="11.0.0",
196
- created_at=time.time(),
197
- symbols=all_sigs,
198
- total_symbols=len(all_sigs),
199
- sha256_checksum=hasher.hexdigest()
200
- )
201
-
202
- @classmethod
203
- def save_baseline(cls, baseline: GoldenBaseline, file_path: Optional[str] = None) -> str:
204
- out_p = file_path or os.path.join(baseline.workspace_root, ".tzero", "goldens.json")
205
- os.makedirs(os.path.dirname(out_p), exist_ok=True)
206
- with open(out_p, "w", encoding="utf-8") as f:
207
- json.dump(asdict(baseline), f, indent=2)
208
- return out_p
209
-
210
- @classmethod
211
- def verify_against_golden(cls, workspace_root: str = ".", golden_path: Optional[str] = None) -> Dict[str, Any]:
212
- """Compares current working tree AST signatures against the golden baseline."""
213
- abs_root = os.path.abspath(workspace_root)
214
- g_path = golden_path or os.path.join(abs_root, ".tzero", "goldens.json")
215
-
216
- if not os.path.isfile(g_path):
217
- return {
218
- "success": False,
219
- "error": f"Golden baseline file not found at: {g_path}. Run 'tzero golden' first to establish baseline."
220
- }
221
-
222
- try:
223
- with open(g_path, "r", encoding="utf-8") as f:
224
- baseline_data = json.load(f)
225
- baseline_symbols = baseline_data.get("symbols", {})
226
- except Exception as e:
227
- return {"success": False, "error": f"Corrupt golden file: {e}"}
228
-
229
- current_baseline = cls.generate_baseline(abs_root)
230
- curr_symbols = current_baseline.symbols
231
-
232
- removed_symbols = []
233
- modified_signatures = []
234
- added_symbols = []
235
-
236
- for key, base_s in baseline_symbols.items():
237
- if key not in curr_symbols:
238
- removed_symbols.append({
239
- "symbol": key,
240
- "kind": base_s.get("kind"),
241
- "last_known_signature": base_s.get("signature")
242
- })
243
- else:
244
- curr_s = curr_symbols[key]
245
- if base_s.get("signature") != curr_s.get("signature") or base_s.get("return_type") != curr_s.get("return_type"):
246
- modified_signatures.append({
247
- "symbol": key,
248
- "old_signature": base_s.get("signature"),
249
- "new_signature": curr_s.get("signature"),
250
- "old_return": base_s.get("return_type"),
251
- "new_return": curr_s.get("return_type")
252
- })
253
-
254
- for key, curr_s in curr_symbols.items():
255
- if key not in baseline_symbols:
256
- added_symbols.append({
257
- "symbol": key,
258
- "kind": curr_s.get("kind"),
259
- "signature": curr_s.get("signature")
260
- })
261
-
262
- clean = len(removed_symbols) == 0 and len(modified_signatures) == 0
263
-
264
- return {
265
- "success": clean,
266
- "total_baseline_symbols": len(baseline_symbols),
267
- "total_current_symbols": len(curr_symbols),
268
- "removed_symbols": removed_symbols,
269
- "modified_signatures": modified_signatures,
270
- "added_symbols": added_symbols,
271
- "clean": clean
272
- }
273
-
274
- @classmethod
275
- def format_markdown_report(cls, report: Dict[str, Any]) -> str:
276
- """Formats the golden regression comparison into a clear Markdown document."""
277
- if not report.get("success", False) and "error" in report:
278
- return f"❌ **T-Zero Golden Verification Error:** {report['error']}"
279
-
280
- clean = report.get("clean", False)
281
- status_badge = "🟢 ZERO REGRESSIONS (PASS)" if clean else "🔴 CONTRACT DRIFT DETECTED (REGRESSION)"
282
-
283
- lines = [
284
- "# 🏆 T-Zero Golden Baseline & AST Regression Report",
285
- f"**Status:** {status_badge}",
286
- f"- **Baseline Symbols:** `{report.get('total_baseline_symbols', 0)}`",
287
- f"- **Current Symbols:** `{report.get('total_current_symbols', 0)}`",
288
- ""
289
- ]
290
-
291
- if report.get("removed_symbols"):
292
- lines.append("## ❌ Removed Public Symbols (Breaking Regressions)")
293
- for r in report["removed_symbols"]:
294
- lines.append(f"- **`{r['symbol']}`** (`{r['kind']}`): Last signature was `{r['last_known_signature']}`")
295
- lines.append("")
296
-
297
- if report.get("modified_signatures"):
298
- lines.append("## ⚠️ Modified Public Signatures")
299
- for m in report["modified_signatures"]:
300
- lines.append(f"- **`{m['symbol']}`**:")
301
- lines.append(f" - 🔴 Previous: `{m['old_signature']}` -> `{m['old_return']}`")
302
- lines.append(f" - 🟢 Current: `{m['new_signature']}` -> `{m['new_return']}`")
303
- lines.append("")
304
-
305
- if report.get("added_symbols"):
306
- lines.append(f"## ✨ New Public Symbols (`{len(report['added_symbols'])}` added)")
307
- for a in report["added_symbols"][:10]:
308
- lines.append(f"- ➕ `{a['symbol']}`: `{a['signature']}`")
309
- if len(report["added_symbols"]) > 10:
310
- lines.append(f"- ... and {len(report['added_symbols']) - 10} more additions.")
311
- lines.append("")
312
-
313
- if clean:
314
- lines.append("✅ **All public AST signatures strictly adhere to the established Golden Baseline.**")
315
- else:
316
- lines.append("💡 **To update the golden baseline deliberately:** run `tzero golden --update`.")
317
-
318
- return "\n".join(lines).strip()
319
-
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Autonomous Golden Baseline & AST Regression Engine.
3
+
4
+ Captures a cryptographically signed baseline snapshot of all public AST signatures
5
+ across the workspace and verifies against accidental regressions in CI/CD pipelines.
6
+
7
+ Capabilities:
8
+ - Zero-drift public API golden snapshot generation (.tzero/goldens.json).
9
+ - Deterministic signature diffing (removed symbols, altered parameters, return type drift).
10
+ - Pre-merge regression guard: fails CI if public contract breaks without explicit baseline update.
11
+ - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
12
+
13
+ Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
+ Part of T-Zero Context Architect v11.11.0 Master Edition.
15
+ """
16
+
17
+ import ast
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import sys
22
+ import time
23
+ from dataclasses import dataclass, asdict
24
+ from typing import Dict, List, Optional, Tuple, Any
25
+
26
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
27
+ try:
28
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
29
+ except Exception:
30
+ pass
31
+
32
+
33
+ @dataclass
34
+ class SymbolSignature:
35
+ file_path: str
36
+ symbol_name: str
37
+ kind: str # "function", "class", "method"
38
+ signature: str
39
+ return_type: Optional[str] = None
40
+ docstring_hash: str = ""
41
+
42
+
43
+ @dataclass
44
+ class GoldenBaseline:
45
+ workspace_root: str
46
+ version: str
47
+ created_at: float
48
+ symbols: Dict[str, Dict[str, Any]]
49
+ total_symbols: int
50
+ sha256_checksum: str
51
+
52
+
53
+ class ASTGoldenRegressionEngine:
54
+ """Extracts and verifies golden AST signature baselines for zero-drift CI pipelines."""
55
+
56
+ @classmethod
57
+ def extract_file_signatures(cls, file_path: str, code: str) -> List[SymbolSignature]:
58
+ """Extracts all public function, class, and method signatures from Python code."""
59
+ try:
60
+ tree = ast.parse(code)
61
+ except Exception:
62
+ return []
63
+
64
+ signatures: List[SymbolSignature] = []
65
+ rel_p = file_path.replace("\\", "/")
66
+
67
+ for node in tree.body:
68
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
69
+ if node.name.startswith("_") and not node.name.startswith("__"):
70
+ continue
71
+ sig = cls._extract_function_signature(node)
72
+ ret = ast.unparse(node.returns) if getattr(node, "returns", None) else None
73
+ doc = ast.get_docstring(node) or ""
74
+ doc_h = hashlib.sha256(doc.encode("utf-8")).hexdigest()[:12]
75
+ signatures.append(SymbolSignature(
76
+ file_path=rel_p,
77
+ symbol_name=node.name,
78
+ kind="function",
79
+ signature=sig,
80
+ return_type=ret,
81
+ docstring_hash=doc_h
82
+ ))
83
+
84
+ elif isinstance(node, ast.ClassDef):
85
+ if node.name.startswith("_"):
86
+ continue
87
+ bases = ", ".join(ast.unparse(b) for b in node.bases)
88
+ cls_sig = f"class {node.name}({bases})" if bases else f"class {node.name}"
89
+ doc = ast.get_docstring(node) or ""
90
+ doc_h = hashlib.sha256(doc.encode("utf-8")).hexdigest()[:12]
91
+ signatures.append(SymbolSignature(
92
+ file_path=rel_p,
93
+ symbol_name=node.name,
94
+ kind="class",
95
+ signature=cls_sig,
96
+ return_type=None,
97
+ docstring_hash=doc_h
98
+ ))
99
+
100
+ for item in node.body:
101
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
102
+ if item.name.startswith("_") and not item.name.startswith("__"):
103
+ continue
104
+ m_sig = cls._extract_function_signature(item)
105
+ m_ret = ast.unparse(item.returns) if getattr(item, "returns", None) else None
106
+ m_doc = ast.get_docstring(item) or ""
107
+ m_doc_h = hashlib.sha256(m_doc.encode("utf-8")).hexdigest()[:12]
108
+ signatures.append(SymbolSignature(
109
+ file_path=rel_p,
110
+ symbol_name=f"{node.name}.{item.name}",
111
+ kind="method",
112
+ signature=m_sig,
113
+ return_type=m_ret,
114
+ docstring_hash=m_doc_h
115
+ ))
116
+
117
+ return signatures
118
+
119
+ @classmethod
120
+ def _extract_function_signature(cls, node: Any) -> str:
121
+ params = []
122
+ args = node.args
123
+
124
+ num_defaults = len(args.defaults)
125
+ num_pos = len(args.args)
126
+ defaults_start = num_pos - num_defaults
127
+
128
+ for i, a in enumerate(args.args):
129
+ p_str = a.arg
130
+ if getattr(a, "annotation", None):
131
+ p_str += f": {ast.unparse(a.annotation)}"
132
+ if i >= defaults_start:
133
+ def_node = args.defaults[i - defaults_start]
134
+ p_str += f" = {ast.unparse(def_node)}"
135
+ params.append(p_str)
136
+
137
+ if args.vararg:
138
+ v_str = f"*{args.vararg.arg}"
139
+ if getattr(args.vararg, "annotation", None):
140
+ v_str += f": {ast.unparse(args.vararg.annotation)}"
141
+ params.append(v_str)
142
+
143
+ for i, a in enumerate(args.kwonlyargs):
144
+ kw_str = a.arg
145
+ if getattr(a, "annotation", None):
146
+ kw_str += f": {ast.unparse(a.annotation)}"
147
+ if i < len(args.kw_defaults) and args.kw_defaults[i] is not None:
148
+ kw_str += f" = {ast.unparse(args.kw_defaults[i])}"
149
+ params.append(kw_str)
150
+
151
+ if args.kwarg:
152
+ kwarg_str = f"**{args.kwarg.arg}"
153
+ if getattr(args.kwarg, "annotation", None):
154
+ kwarg_str += f": {ast.unparse(args.kwarg.annotation)}"
155
+ params.append(kwarg_str)
156
+
157
+ prefix = "async def " if isinstance(node, ast.AsyncFunctionDef) else "def "
158
+ return f"{prefix}{node.name}({', '.join(params)})"
159
+
160
+ @classmethod
161
+ def generate_baseline(cls, workspace_root: str = ".", max_files: int = 300) -> GoldenBaseline:
162
+ """Scans workspace and generates the golden contract baseline."""
163
+ abs_root = os.path.abspath(workspace_root)
164
+ all_sigs: Dict[str, Dict[str, Any]] = {}
165
+ hasher = hashlib.sha256()
166
+
167
+ ignore_dirs = {".git", ".venv", "venv", "__pycache__", "node_modules", "dist", "build", ".pytest_cache"}
168
+
169
+ file_count = 0
170
+ for root, dirs, files in os.walk(abs_root):
171
+ dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
172
+ for f in files:
173
+ if f.endswith(".py"):
174
+ full_p = os.path.join(root, f)
175
+ rel_p = os.path.relpath(full_p, abs_root).replace("\\", "/")
176
+ try:
177
+ with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
178
+ code = fp.read()
179
+ sigs = cls.extract_file_signatures(rel_p, code)
180
+ for s in sigs:
181
+ key = f"{s.file_path}:{s.symbol_name}"
182
+ d = asdict(s)
183
+ all_sigs[key] = d
184
+ hasher.update(f"{key}:{s.signature}:{s.return_type}".encode("utf-8"))
185
+ file_count += 1
186
+ if file_count >= max_files:
187
+ break
188
+ except Exception:
189
+ pass
190
+ if file_count >= max_files:
191
+ break
192
+
193
+ return GoldenBaseline(
194
+ workspace_root=abs_root,
195
+ version="11.11.0",
196
+ created_at=time.time(),
197
+ symbols=all_sigs,
198
+ total_symbols=len(all_sigs),
199
+ sha256_checksum=hasher.hexdigest()
200
+ )
201
+
202
+ @classmethod
203
+ def save_baseline(cls, baseline: GoldenBaseline, file_path: Optional[str] = None) -> str:
204
+ out_p = file_path or os.path.join(baseline.workspace_root, ".tzero", "goldens.json")
205
+ os.makedirs(os.path.dirname(out_p), exist_ok=True)
206
+ with open(out_p, "w", encoding="utf-8") as f:
207
+ json.dump(asdict(baseline), f, indent=2)
208
+ return out_p
209
+
210
+ @classmethod
211
+ def verify_against_golden(cls, workspace_root: str = ".", golden_path: Optional[str] = None) -> Dict[str, Any]:
212
+ """Compares current working tree AST signatures against the golden baseline."""
213
+ abs_root = os.path.abspath(workspace_root)
214
+ g_path = golden_path or os.path.join(abs_root, ".tzero", "goldens.json")
215
+
216
+ if not os.path.isfile(g_path):
217
+ return {
218
+ "success": False,
219
+ "error": f"Golden baseline file not found at: {g_path}. Run 'tzero golden' first to establish baseline."
220
+ }
221
+
222
+ try:
223
+ with open(g_path, "r", encoding="utf-8") as f:
224
+ baseline_data = json.load(f)
225
+ baseline_symbols = baseline_data.get("symbols", {})
226
+ except Exception as e:
227
+ return {"success": False, "error": f"Corrupt golden file: {e}"}
228
+
229
+ current_baseline = cls.generate_baseline(abs_root)
230
+ curr_symbols = current_baseline.symbols
231
+
232
+ removed_symbols = []
233
+ modified_signatures = []
234
+ added_symbols = []
235
+
236
+ for key, base_s in baseline_symbols.items():
237
+ if key not in curr_symbols:
238
+ removed_symbols.append({
239
+ "symbol": key,
240
+ "kind": base_s.get("kind"),
241
+ "last_known_signature": base_s.get("signature")
242
+ })
243
+ else:
244
+ curr_s = curr_symbols[key]
245
+ if base_s.get("signature") != curr_s.get("signature") or base_s.get("return_type") != curr_s.get("return_type"):
246
+ modified_signatures.append({
247
+ "symbol": key,
248
+ "old_signature": base_s.get("signature"),
249
+ "new_signature": curr_s.get("signature"),
250
+ "old_return": base_s.get("return_type"),
251
+ "new_return": curr_s.get("return_type")
252
+ })
253
+
254
+ for key, curr_s in curr_symbols.items():
255
+ if key not in baseline_symbols:
256
+ added_symbols.append({
257
+ "symbol": key,
258
+ "kind": curr_s.get("kind"),
259
+ "signature": curr_s.get("signature")
260
+ })
261
+
262
+ clean = len(removed_symbols) == 0 and len(modified_signatures) == 0
263
+
264
+ return {
265
+ "success": clean,
266
+ "total_baseline_symbols": len(baseline_symbols),
267
+ "total_current_symbols": len(curr_symbols),
268
+ "removed_symbols": removed_symbols,
269
+ "modified_signatures": modified_signatures,
270
+ "added_symbols": added_symbols,
271
+ "clean": clean
272
+ }
273
+
274
+ @classmethod
275
+ def format_markdown_report(cls, report: Dict[str, Any]) -> str:
276
+ """Formats the golden regression comparison into a clear Markdown document."""
277
+ if not report.get("success", False) and "error" in report:
278
+ return f"❌ **T-Zero Golden Verification Error:** {report['error']}"
279
+
280
+ clean = report.get("clean", False)
281
+ status_badge = "🟢 ZERO REGRESSIONS (PASS)" if clean else "🔴 CONTRACT DRIFT DETECTED (REGRESSION)"
282
+
283
+ lines = [
284
+ "# 🏆 T-Zero Golden Baseline & AST Regression Report",
285
+ f"**Status:** {status_badge}",
286
+ f"- **Baseline Symbols:** `{report.get('total_baseline_symbols', 0)}`",
287
+ f"- **Current Symbols:** `{report.get('total_current_symbols', 0)}`",
288
+ ""
289
+ ]
290
+
291
+ if report.get("removed_symbols"):
292
+ lines.append("## ❌ Removed Public Symbols (Breaking Regressions)")
293
+ for r in report["removed_symbols"]:
294
+ lines.append(f"- **`{r['symbol']}`** (`{r['kind']}`): Last signature was `{r['last_known_signature']}`")
295
+ lines.append("")
296
+
297
+ if report.get("modified_signatures"):
298
+ lines.append("## ⚠️ Modified Public Signatures")
299
+ for m in report["modified_signatures"]:
300
+ lines.append(f"- **`{m['symbol']}`**:")
301
+ lines.append(f" - 🔴 Previous: `{m['old_signature']}` -> `{m['old_return']}`")
302
+ lines.append(f" - 🟢 Current: `{m['new_signature']}` -> `{m['new_return']}`")
303
+ lines.append("")
304
+
305
+ if report.get("added_symbols"):
306
+ lines.append(f"## ✨ New Public Symbols (`{len(report['added_symbols'])}` added)")
307
+ for a in report["added_symbols"][:10]:
308
+ lines.append(f"- ➕ `{a['symbol']}`: `{a['signature']}`")
309
+ if len(report["added_symbols"]) > 10:
310
+ lines.append(f"- ... and {len(report['added_symbols']) - 10} more additions.")
311
+ lines.append("")
312
+
313
+ if clean:
314
+ lines.append("✅ **All public AST signatures strictly adhere to the established Golden Baseline.**")
315
+ else:
316
+ lines.append("💡 **To update the golden baseline deliberately:** run `tzero golden --update`.")
317
+
318
+ return "\n".join(lines).strip()
319
+