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,1093 +1,1093 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Autonomous AST Public API Contract & Semantic Versioning Guardian.
3
-
4
- Analyzes AST signature changes between code revisions, determining if modifications
5
- are backward-compatible or introduce breaking changes to public callers.
6
-
7
- Capabilities:
8
- - Detects removed public functions, methods, and classes.
9
- - Flags added required parameters without defaults (caller breaking change).
10
- - Detects parameter deletions, reorderings, and return type modifications.
11
- - Recommends exact Semantic Versioning (SemVer) bump: MAJOR, MINOR, or PATCH.
12
- - Computes Git revision contract diffs (HEAD vs uncommitted, or base_ref vs HEAD).
13
- - 100% Offline, $0 cost, zero external dependencies (pure Python standard library).
14
-
15
- Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v11.0.0 Master Edition.
17
- """
18
-
19
- import ast
20
- import json
21
- import os
22
- import re
23
- import subprocess
24
- import sys
25
- from dataclasses import dataclass, field
26
- from enum import Enum
27
- from typing import Dict, List, Optional, Set, Tuple, Any
28
-
29
- if sys.stdout and hasattr(sys.stdout, "reconfigure"):
30
- try:
31
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
32
- except Exception:
33
- pass
34
-
35
-
36
- class SemVerBump(str, Enum):
37
- PATCH = "PATCH" # Internal logic / docs changed, 100% contract compatible
38
- MINOR = "MINOR" # New public functions/classes/optional parameters added
39
- MAJOR = "MAJOR" # Incompatible public API contract change (breaking change)
40
-
41
-
42
- @dataclass
43
- class ParameterContract:
44
- name: str
45
- has_default: bool
46
- type_annotation: Optional[str] = None
47
- is_kwonly: bool = False
48
- is_vararg: bool = False
49
- is_kwarg: bool = False
50
-
51
-
52
- @dataclass
53
- class FunctionContract:
54
- name: str
55
- parameters: List[ParameterContract]
56
- return_annotation: Optional[str] = None
57
- is_async: bool = False
58
- docstring: Optional[str] = None
59
-
60
- @property
61
- def required_param_count(self) -> int:
62
- return sum(1 for p in self.parameters if not p.has_default and not p.is_vararg and not p.is_kwarg)
63
-
64
- @property
65
- def param_names(self) -> List[str]:
66
- return [p.name for p in self.parameters]
67
-
68
-
69
- @dataclass
70
- class ClassContract:
71
- name: str
72
- bases: List[str]
73
- methods: Dict[str, FunctionContract] = field(default_factory=dict)
74
- docstring: Optional[str] = None
75
-
76
-
77
- @dataclass
78
- class ContractViolation:
79
- severity: str # BREAKING, ADDITION, MODIFICATION
80
- category: str # REMOVED_SYMBOL, SIGNATURE_BREAK, PARAMETER_REMOVED, etc.
81
- symbol: str
82
- details: str
83
-
84
-
85
- @dataclass
86
- class ContractDiffReport:
87
- file_path: str
88
- semver_bump: SemVerBump
89
- breaking_changes: List[ContractViolation] = field(default_factory=list)
90
- non_breaking_additions: List[ContractViolation] = field(default_factory=list)
91
- modifications: List[ContractViolation] = field(default_factory=list)
92
-
93
- @property
94
- def is_breaking(self) -> bool:
95
- return len(self.breaking_changes) > 0
96
-
97
-
98
- class ASTContractExtractor:
99
- """Extracts public API signatures and contracts from an AST tree."""
100
-
101
- POLYGLOT_EXTENSIONS = {".ts", ".tsx", ".js", ".jsx", ".rs", ".go", ".java", ".cs"}
102
-
103
- @classmethod
104
- def extract_from_code(cls, code: str) -> Tuple[Dict[str, FunctionContract], Dict[str, ClassContract]]:
105
- try:
106
- tree = ast.parse(code)
107
- except Exception:
108
- return {}, {}
109
-
110
- functions: Dict[str, FunctionContract] = {}
111
- classes: Dict[str, ClassContract] = {}
112
-
113
- for node in tree.body:
114
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
115
- # Ignore private functions starting with single underscore (except __init__)
116
- if node.name.startswith("_") and not node.name.startswith("__"):
117
- continue
118
- fc = cls._extract_function(node)
119
- functions[node.name] = fc
120
-
121
- elif isinstance(node, ast.ClassDef):
122
- if node.name.startswith("_"):
123
- continue
124
- cc = cls._extract_class(node)
125
- classes[node.name] = cc
126
-
127
- return functions, classes
128
-
129
- @classmethod
130
- def _extract_function(cls, node: Any) -> FunctionContract:
131
- params: List[ParameterContract] = []
132
- args = node.args
133
-
134
- # Calculate defaults offset
135
- num_defaults = len(args.defaults)
136
- num_pos = len(args.args)
137
- defaults_start = num_pos - num_defaults
138
-
139
- for i, a in enumerate(args.args):
140
- has_def = i >= defaults_start
141
- ann = ast.unparse(a.annotation) if getattr(a, "annotation", None) else None
142
- params.append(ParameterContract(name=a.arg, has_default=has_def, type_annotation=ann))
143
-
144
- if args.vararg:
145
- ann = ast.unparse(args.vararg.annotation) if getattr(args.vararg, "annotation", None) else None
146
- params.append(ParameterContract(name=f"*{args.vararg.arg}", has_default=True, type_annotation=ann, is_vararg=True))
147
-
148
- for i, a in enumerate(args.kwonlyargs):
149
- kw_def = False
150
- if i < len(args.kw_defaults) and args.kw_defaults[i] is not None:
151
- kw_def = True
152
- ann = ast.unparse(a.annotation) if getattr(a, "annotation", None) else None
153
- params.append(ParameterContract(name=a.arg, has_default=kw_def, type_annotation=ann, is_kwonly=True))
154
-
155
- if args.kwarg:
156
- ann = ast.unparse(args.kwarg.annotation) if getattr(args.kwarg, "annotation", None) else None
157
- params.append(ParameterContract(name=f"**{args.kwarg.arg}", has_default=True, type_annotation=ann, is_kwarg=True))
158
-
159
- ret_ann = ast.unparse(node.returns) if getattr(node, "returns", None) else None
160
- doc = ast.get_docstring(node)
161
-
162
- return FunctionContract(
163
- name=node.name,
164
- parameters=params,
165
- return_annotation=ret_ann,
166
- is_async=isinstance(node, ast.AsyncFunctionDef),
167
- docstring=doc
168
- )
169
-
170
- @classmethod
171
- def _extract_class(cls, node: ast.ClassDef) -> ClassContract:
172
- bases = [ast.unparse(b) for b in node.bases]
173
- methods: Dict[str, FunctionContract] = {}
174
- for item in node.body:
175
- if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
176
- if item.name.startswith("_") and not item.name.startswith("__"):
177
- continue
178
- methods[item.name] = cls._extract_function(item)
179
-
180
- return ClassContract(
181
- name=node.name,
182
- bases=bases,
183
- methods=methods,
184
- docstring=ast.get_docstring(node)
185
- )
186
-
187
- @classmethod
188
- def _strip_comments(cls, code: str) -> str:
189
- """Removes single-line (//) and multi-line (/* */) comments preserving strings."""
190
- out = []
191
- i = 0
192
- n = len(code)
193
- in_quote: Optional[str] = None
194
- while i < n:
195
- ch = code[i]
196
- nxt = code[i + 1] if i + 1 < n else ""
197
- if in_quote:
198
- out.append(ch)
199
- if ch == "\\" and i + 1 < n:
200
- i += 1
201
- out.append(code[i])
202
- elif ch == in_quote:
203
- in_quote = None
204
- i += 1
205
- continue
206
- if ch in ('"', "'", '`'):
207
- in_quote = ch
208
- out.append(ch)
209
- i += 1
210
- continue
211
- if ch == "/" and nxt == "/":
212
- i += 2
213
- while i < n and code[i] != "\n":
214
- i += 1
215
- if i < n and code[i] == "\n":
216
- out.append("\n")
217
- i += 1
218
- continue
219
- if ch == "/" and nxt == "*":
220
- i += 2
221
- while i + 1 < n and not (code[i] == "*" and code[i + 1] == "/"):
222
- if code[i] == "\n":
223
- out.append("\n")
224
- i += 1
225
- i += 2
226
- continue
227
- out.append(ch)
228
- i += 1
229
- return "".join(out)
230
-
231
- @staticmethod
232
- def _split_param_list(raw_params: str) -> List[str]:
233
- """Splits parameter string by commas outside of () [] {} <> quotes."""
234
- parts = []
235
- current = []
236
- depth = 0
237
- in_quote: Optional[str] = None
238
- i = 0
239
- n = len(raw_params)
240
- while i < n:
241
- ch = raw_params[i]
242
- if in_quote:
243
- current.append(ch)
244
- if ch == "\\" and i + 1 < n:
245
- i += 1
246
- current.append(raw_params[i])
247
- elif ch == in_quote:
248
- in_quote = None
249
- i += 1
250
- continue
251
- if ch in ('"', "'", '`'):
252
- in_quote = ch
253
- current.append(ch)
254
- i += 1
255
- continue
256
- if ch in ("(", "[", "{", "<"):
257
- depth += 1
258
- current.append(ch)
259
- elif ch in (")", "]", "}", ">"):
260
- if depth > 0:
261
- depth -= 1
262
- current.append(ch)
263
- elif ch == "," and depth == 0:
264
- part = "".join(current).strip()
265
- if part:
266
- parts.append(part)
267
- current = []
268
- else:
269
- current.append(ch)
270
- i += 1
271
- if current:
272
- part = "".join(current).strip()
273
- if part:
274
- parts.append(part)
275
- return parts
276
-
277
- @staticmethod
278
- def _find_matching_paren(text: str, start_idx: int) -> int:
279
- """Given start_idx of '(', returns index of matching ')'."""
280
- depth = 0
281
- in_quote = None
282
- i = start_idx
283
- n = len(text)
284
- while i < n:
285
- ch = text[i]
286
- if in_quote:
287
- if ch == "\\" and i + 1 < n:
288
- i += 2
289
- continue
290
- if ch == in_quote:
291
- in_quote = None
292
- i += 1
293
- continue
294
- if ch in ('"', "'", '`'):
295
- in_quote = ch
296
- i += 1
297
- continue
298
- if ch == "(":
299
- depth += 1
300
- elif ch == ")":
301
- depth -= 1
302
- if depth == 0:
303
- return i
304
- i += 1
305
- return -1
306
-
307
- @staticmethod
308
- def _find_matching_brace(text: str, start_idx: int) -> int:
309
- """Given start_idx of '{', returns index of matching '}'."""
310
- depth = 0
311
- in_quote = None
312
- i = start_idx
313
- n = len(text)
314
- while i < n:
315
- ch = text[i]
316
- if in_quote:
317
- if ch == "\\" and i + 1 < n:
318
- i += 2
319
- continue
320
- if ch == in_quote:
321
- in_quote = None
322
- i += 1
323
- continue
324
- if ch in ('"', "'", '`'):
325
- in_quote = ch
326
- i += 1
327
- continue
328
- if ch == "{":
329
- depth += 1
330
- elif ch == "}":
331
- depth -= 1
332
- if depth == 0:
333
- return i
334
- i += 1
335
- return -1
336
-
337
- @classmethod
338
- def _parse_ts_param(cls, p: str) -> ParameterContract:
339
- p = p.strip()
340
- is_vararg = False
341
- if p.startswith("..."):
342
- is_vararg = True
343
- p = p[3:].strip()
344
-
345
- has_default = is_vararg
346
- if "=" in p:
347
- left, _ = p.split("=", 1)
348
- has_default = True
349
- left = left.strip()
350
- else:
351
- left = p
352
-
353
- if "?:" in left:
354
- name_p, type_p = left.split("?:", 1)
355
- name = name_p.strip()
356
- type_ann = type_p.strip()
357
- has_default = True
358
- elif ":" in left:
359
- name_p, type_p = left.split(":", 1)
360
- name = name_p.strip()
361
- type_ann = type_p.strip()
362
- if name.endswith("?"):
363
- name = name[:-1].strip()
364
- has_default = True
365
- else:
366
- name = left.strip()
367
- if name.endswith("?"):
368
- name = name[:-1].strip()
369
- has_default = True
370
- type_ann = None
371
-
372
- if name.startswith("..."):
373
- name = name[3:].strip()
374
- is_vararg = True
375
- has_default = True
376
-
377
- return ParameterContract(
378
- name=name,
379
- has_default=has_default,
380
- type_annotation=type_ann,
381
- is_vararg=is_vararg
382
- )
383
-
384
- @classmethod
385
- def _parse_go_params(cls, raw: str) -> List[ParameterContract]:
386
- if not raw.strip():
387
- return []
388
- parts = cls._split_param_list(raw)
389
- resolved: List[Tuple[str, str]] = []
390
- current_type = ""
391
- for p in reversed(parts):
392
- tokens = p.strip().split()
393
- if len(tokens) >= 2:
394
- current_type = " ".join(tokens[1:])
395
- resolved.append((tokens[0], current_type))
396
- elif len(tokens) == 1:
397
- resolved.append((tokens[0], current_type))
398
- resolved.reverse()
399
-
400
- params: List[ParameterContract] = []
401
- for name, typ in resolved:
402
- is_var = typ.startswith("...")
403
- params.append(ParameterContract(
404
- name=name,
405
- has_default=is_var,
406
- type_annotation=typ if typ else None,
407
- is_vararg=is_var
408
- ))
409
- return params
410
-
411
- @classmethod
412
- def _parse_rust_param(cls, p: str) -> Optional[ParameterContract]:
413
- p = p.strip()
414
- if not p or p in ("self", "&self", "&mut self"):
415
- return None
416
- if ":" in p:
417
- name, typ = p.split(":", 1)
418
- return ParameterContract(
419
- name=name.strip(),
420
- has_default=False,
421
- type_annotation=typ.strip()
422
- )
423
- return ParameterContract(name=p, has_default=False)
424
-
425
- @classmethod
426
- def _parse_java_param(cls, p: str) -> ParameterContract:
427
- p = p.strip()
428
- has_default = False
429
- if "=" in p:
430
- left, _ = p.split("=", 1)
431
- has_default = True
432
- left = left.strip()
433
- else:
434
- left = p
435
-
436
- tokens = left.split()
437
- if not tokens:
438
- return ParameterContract(name="", has_default=has_default)
439
-
440
- name = tokens[-1]
441
- type_ann = " ".join(tokens[:-1]) if len(tokens) > 1 else None
442
- is_vararg = False
443
- if name.startswith("..."):
444
- name = name[3:]
445
- is_vararg = True
446
- has_default = True
447
- elif type_ann and ("..." in type_ann or "params " in left):
448
- is_vararg = True
449
- has_default = True
450
-
451
- return ParameterContract(
452
- name=name,
453
- has_default=has_default,
454
- type_annotation=type_ann,
455
- is_vararg=is_vararg
456
- )
457
-
458
- @classmethod
459
- def _extract_ts_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
460
- class_pattern = re.compile(
461
- r'(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)(?:\s+extends\s+([^{]+))?\s*\{'
462
- )
463
- top_level_code = list(clean_code)
464
-
465
- for m in class_pattern.finditer(clean_code):
466
- cls_name = m.group(1)
467
- bases = [b.strip() for b in m.group(2).split(",")] if m.group(2) else []
468
- brace_idx = m.end() - 1
469
- end_brace = cls._find_matching_brace(clean_code, brace_idx)
470
- if end_brace == -1:
471
- end_brace = len(clean_code) - 1
472
-
473
- for k in range(m.start(), end_brace + 1):
474
- if top_level_code[k] != "\n":
475
- top_level_code[k] = " "
476
-
477
- class_body = clean_code[brace_idx + 1:end_brace]
478
- methods: Dict[str, FunctionContract] = {}
479
-
480
- method_depth = 0
481
- idx = 0
482
- n = len(class_body)
483
- while idx < n:
484
- ch = class_body[idx]
485
- if ch == "{":
486
- method_depth += 1
487
- idx += 1
488
- continue
489
- elif ch == "}":
490
- if method_depth > 0:
491
- method_depth -= 1
492
- idx += 1
493
- continue
494
-
495
- if method_depth == 0:
496
- m_hdr = re.match(
497
- r'^(?:(?:public|static|async|get|set|override|readonly)\s+)*([A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\(',
498
- class_body[idx:]
499
- )
500
- if m_hdr:
501
- full_match = m_hdr.group(0)
502
- fn_name = m_hdr.group(1)
503
- matched_str = class_body[idx:idx + len(full_match)]
504
-
505
- if (
506
- fn_name in {"if", "for", "while", "switch", "catch", "return"}
507
- or "private " in matched_str
508
- or "protected " in matched_str
509
- or fn_name.startswith("_")
510
- or fn_name.startswith("#")
511
- ):
512
- idx += len(full_match)
513
- continue
514
-
515
- paren_start = idx + len(full_match) - 1
516
- paren_end = cls._find_matching_paren(class_body, paren_start)
517
- if paren_end != -1:
518
- raw_params = class_body[paren_start + 1:paren_end]
519
- rest = class_body[paren_end + 1:]
520
- ret_match = re.match(r'^\s*:\s*([^{;]+)', rest)
521
- ret_ann = ret_match.group(1).strip() if ret_match else None
522
- is_async = "async " in matched_str
523
-
524
- params = [cls._parse_ts_param(p) for p in cls._split_param_list(raw_params)]
525
- methods[fn_name] = FunctionContract(
526
- name=fn_name,
527
- parameters=params,
528
- return_annotation=ret_ann,
529
- is_async=is_async
530
- )
531
- idx = paren_end + 1
532
- continue
533
-
534
- idx += 1
535
-
536
- classes[cls_name] = ClassContract(name=cls_name, bases=bases, methods=methods)
537
-
538
- top_str = "".join(top_level_code)
539
- fn_pattern = re.compile(
540
- r'(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\('
541
- )
542
- for m in fn_pattern.finditer(top_str):
543
- fn_name = m.group(1)
544
- prefix = top_str[m.start():m.end()]
545
- is_exported = "export" in prefix
546
- if fn_name.startswith("_") and not is_exported:
547
- continue
548
-
549
- paren_start = m.end() - 1
550
- paren_end = cls._find_matching_paren(top_str, paren_start)
551
- if paren_end != -1:
552
- raw_params = top_str[paren_start + 1:paren_end]
553
- rest = top_str[paren_end + 1:]
554
- ret_match = re.match(r'^\s*:\s*([^{;]+)', rest)
555
- ret_ann = ret_match.group(1).strip() if ret_match else None
556
- is_async = "async" in prefix
557
- params = [cls._parse_ts_param(p) for p in cls._split_param_list(raw_params)]
558
- functions[fn_name] = FunctionContract(
559
- name=fn_name,
560
- parameters=params,
561
- return_annotation=ret_ann,
562
- is_async=is_async
563
- )
564
-
565
- @classmethod
566
- def _extract_go_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
567
- for m in re.finditer(r'\btype\s+([A-Za-z0-9_]+)\s+(?:struct|interface)\b', clean_code):
568
- name = m.group(1)
569
- if name and name[0].isupper():
570
- classes.setdefault(name, ClassContract(name=name, bases=[]))
571
-
572
- func_pattern = re.compile(r'\bfunc\s+')
573
- for m in func_pattern.finditer(clean_code):
574
- start = m.end()
575
- rem = clean_code[start:].lstrip()
576
- recv_type: Optional[str] = None
577
- if rem.startswith("("):
578
- paren_start = clean_code.find("(", start)
579
- paren_end = cls._find_matching_paren(clean_code, paren_start)
580
- if paren_end == -1:
581
- continue
582
- recv_content = clean_code[paren_start + 1:paren_end].strip()
583
- tokens = recv_content.split()
584
- if tokens:
585
- recv_type = tokens[-1].lstrip("*")
586
- start = paren_end + 1
587
-
588
- fn_match = re.match(r'^\s*([A-Za-z0-9_]+)\s*\(', clean_code[start:])
589
- if not fn_match:
590
- continue
591
-
592
- fn_name = fn_match.group(1)
593
- if not fn_name or not fn_name[0].isupper():
594
- continue
595
-
596
- paren_start = clean_code.find("(", start)
597
- paren_end = cls._find_matching_paren(clean_code, paren_start)
598
- if paren_end == -1:
599
- continue
600
-
601
- raw_params = clean_code[paren_start + 1:paren_end]
602
- params = cls._parse_go_params(raw_params)
603
-
604
- after_paren = clean_code[paren_end + 1:]
605
- brace_pos = after_paren.find("{")
606
- ret_ann = None
607
- if brace_pos != -1:
608
- raw_ret = after_paren[:brace_pos].strip()
609
- if raw_ret:
610
- ret_ann = raw_ret
611
-
612
- fc = FunctionContract(
613
- name=fn_name,
614
- parameters=params,
615
- return_annotation=ret_ann
616
- )
617
-
618
- if recv_type:
619
- if recv_type not in classes:
620
- classes[recv_type] = ClassContract(name=recv_type, bases=[])
621
- classes[recv_type].methods[fn_name] = fc
622
- else:
623
- functions[fn_name] = fc
624
-
625
- @classmethod
626
- def _extract_rust_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
627
- for m in re.finditer(r'\bpub\s+(?:struct|enum)\s+([A-Za-z0-9_]+)\b', clean_code):
628
- name = m.group(1)
629
- classes.setdefault(name, ClassContract(name=name, bases=[]))
630
-
631
- top_level_code = list(clean_code)
632
-
633
- impl_pattern = re.compile(r'\bimpl(?:\s+<[^>]+>)?\s+([A-Za-z0-9_]+)\b[^{]*\{')
634
- for m in impl_pattern.finditer(clean_code):
635
- impl_name = m.group(1)
636
- brace_idx = m.end() - 1
637
- end_brace = cls._find_matching_brace(clean_code, brace_idx)
638
- if end_brace == -1:
639
- end_brace = len(clean_code) - 1
640
-
641
- for k in range(m.start(), end_brace + 1):
642
- if top_level_code[k] != "\n":
643
- top_level_code[k] = " "
644
-
645
- if impl_name not in classes:
646
- classes[impl_name] = ClassContract(name=impl_name, bases=[])
647
-
648
- impl_body = clean_code[brace_idx + 1:end_brace]
649
- for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]+>)?\s*\(', impl_body):
650
- fn_name = fn_m.group(1)
651
- p_start = fn_m.end() - 1
652
- p_end = cls._find_matching_paren(impl_body, p_start)
653
- if p_end != -1:
654
- raw_params = impl_body[p_start + 1:p_end]
655
- params = [p for p in (cls._parse_rust_param(x) for x in cls._split_param_list(raw_params)) if p is not None]
656
- after_p = impl_body[p_end + 1:]
657
- ret_m = re.match(r'^\s*->\s*([^{;]+)', after_p)
658
- ret_ann = ret_m.group(1).strip() if ret_m else None
659
- classes[impl_name].methods[fn_name] = FunctionContract(
660
- name=fn_name,
661
- parameters=params,
662
- return_annotation=ret_ann
663
- )
664
-
665
- top_str = "".join(top_level_code)
666
- for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]+>)?\s*\(', top_str):
667
- fn_name = fn_m.group(1)
668
- p_start = fn_m.end() - 1
669
- p_end = cls._find_matching_paren(top_str, p_start)
670
- if p_end != -1:
671
- raw_params = top_str[p_start + 1:p_end]
672
- params = [p for p in (cls._parse_rust_param(x) for x in cls._split_param_list(raw_params)) if p is not None]
673
- after_p = top_str[p_end + 1:]
674
- ret_m = re.match(r'^\s*->\s*([^{;]+)', after_p)
675
- ret_ann = ret_m.group(1).strip() if ret_m else None
676
- functions[fn_name] = FunctionContract(
677
- name=fn_name,
678
- parameters=params,
679
- return_annotation=ret_ann
680
- )
681
-
682
- @classmethod
683
- def _extract_java_cs_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
684
- class_pattern = re.compile(
685
- r'\bpublic\s+(?:abstract\s+|static\s+|sealed\s+)?(?:class|interface)\s+([A-Za-z0-9_]+)(?:\s+extends\s+([^{]+))?\s*\{'
686
- )
687
- for m in class_pattern.finditer(clean_code):
688
- cls_name = m.group(1)
689
- bases = [b.strip() for b in m.group(2).split(",")] if m.group(2) else []
690
- brace_idx = m.end() - 1
691
- end_brace = cls._find_matching_brace(clean_code, brace_idx)
692
- if end_brace == -1:
693
- end_brace = len(clean_code) - 1
694
-
695
- class_body = clean_code[brace_idx + 1:end_brace]
696
- methods: Dict[str, FunctionContract] = {}
697
-
698
- method_depth = 0
699
- idx = 0
700
- n = len(class_body)
701
- while idx < n:
702
- ch = class_body[idx]
703
- if ch == "{":
704
- method_depth += 1
705
- idx += 1
706
- continue
707
- elif ch == "}":
708
- if method_depth > 0:
709
- method_depth -= 1
710
- idx += 1
711
- continue
712
-
713
- if method_depth == 0:
714
- m_hdr = re.match(
715
- r'^\s*public\s+(?:static\s+|async\s+|final\s+|virtual\s+|override\s+)?([A-Za-z0-9_<>[\]]+)\s+([A-Za-z0-9_]+)\s*\(',
716
- class_body[idx:]
717
- )
718
- if m_hdr:
719
- ret_ann = m_hdr.group(1)
720
- fn_name = m_hdr.group(2)
721
- p_start = class_body.find("(", idx)
722
- p_end = cls._find_matching_paren(class_body, p_start)
723
- if p_end != -1:
724
- raw_params = class_body[p_start + 1:p_end]
725
- params = [cls._parse_java_param(p) for p in cls._split_param_list(raw_params)]
726
- methods[fn_name] = FunctionContract(
727
- name=fn_name,
728
- parameters=params,
729
- return_annotation=ret_ann
730
- )
731
- idx = p_end + 1
732
- continue
733
- idx += 1
734
-
735
- classes[cls_name] = ClassContract(name=cls_name, bases=bases, methods=methods)
736
-
737
- @classmethod
738
- def extract_polyglot_contracts(cls, code: str, file_path: str = "module.ts") -> Tuple[Dict[str, FunctionContract], Dict[str, ClassContract]]:
739
- ext = os.path.splitext(file_path.lower())[1]
740
- clean_code = cls._strip_comments(code)
741
- functions: Dict[str, FunctionContract] = {}
742
- classes: Dict[str, ClassContract] = {}
743
-
744
- if ext in {".ts", ".tsx", ".js", ".jsx"}:
745
- cls._extract_ts_contracts(clean_code, functions, classes)
746
- elif ext == ".go":
747
- cls._extract_go_contracts(clean_code, functions, classes)
748
- elif ext == ".rs":
749
- cls._extract_rust_contracts(clean_code, functions, classes)
750
- elif ext in {".java", ".cs"}:
751
- cls._extract_java_cs_contracts(clean_code, functions, classes)
752
-
753
- return functions, classes
754
-
755
-
756
- class ASTContractComparator:
757
- """Compares two versions of public AST contracts and evaluates breaking changes."""
758
-
759
- @classmethod
760
- def compare_code(cls, old_code: str, new_code: str, file_path: str = "code.py") -> ContractDiffReport:
761
- ext = os.path.splitext(file_path.lower())[1]
762
- if ext in ASTContractExtractor.POLYGLOT_EXTENSIONS:
763
- old_funcs, old_classes = ASTContractExtractor.extract_polyglot_contracts(old_code, file_path=file_path)
764
- new_funcs, new_classes = ASTContractExtractor.extract_polyglot_contracts(new_code, file_path=file_path)
765
- else:
766
- old_funcs, old_classes = ASTContractExtractor.extract_from_code(old_code)
767
- new_funcs, new_classes = ASTContractExtractor.extract_from_code(new_code)
768
-
769
- breaking: List[ContractViolation] = []
770
- additions: List[ContractViolation] = []
771
- modifications: List[ContractViolation] = []
772
-
773
- # 1. Check top-level functions
774
- for fn_name, old_fn in old_funcs.items():
775
- if fn_name not in new_funcs:
776
- breaking.append(ContractViolation(
777
- severity="BREAKING",
778
- category="REMOVED_FUNCTION",
779
- symbol=fn_name,
780
- details=f"Public function '{fn_name}()' was removed."
781
- ))
782
- else:
783
- new_fn = new_funcs[fn_name]
784
- cls._compare_function_signatures(old_fn, new_fn, fn_name, breaking, additions, modifications)
785
-
786
- for fn_name, new_fn in new_funcs.items():
787
- if fn_name not in old_funcs:
788
- additions.append(ContractViolation(
789
- severity="ADDITION",
790
- category="ADDED_FUNCTION",
791
- symbol=fn_name,
792
- details=f"New public function '{fn_name}()' added."
793
- ))
794
-
795
- # 2. Check classes and methods
796
- for cls_name, old_cls in old_classes.items():
797
- if cls_name not in new_classes:
798
- breaking.append(ContractViolation(
799
- severity="BREAKING",
800
- category="REMOVED_CLASS",
801
- symbol=cls_name,
802
- details=f"Public class '{cls_name}' was removed."
803
- ))
804
- else:
805
- new_cls = new_classes[cls_name]
806
- # Compare class methods
807
- for m_name, old_m in old_cls.methods.items():
808
- if m_name not in new_cls.methods:
809
- breaking.append(ContractViolation(
810
- severity="BREAKING",
811
- category="REMOVED_METHOD",
812
- symbol=f"{cls_name}.{m_name}",
813
- details=f"Public method '{cls_name}.{m_name}()' was removed."
814
- ))
815
- else:
816
- new_m = new_cls.methods[m_name]
817
- cls._compare_function_signatures(old_m, new_m, f"{cls_name}.{m_name}", breaking, additions, modifications)
818
-
819
- for m_name, new_m in new_cls.methods.items():
820
- if m_name not in old_cls.methods:
821
- additions.append(ContractViolation(
822
- severity="ADDITION",
823
- category="ADDED_METHOD",
824
- symbol=f"{cls_name}.{m_name}",
825
- details=f"New public method '{cls_name}.{m_name}()' added."
826
- ))
827
-
828
- for cls_name, new_cls in new_classes.items():
829
- if cls_name not in old_classes:
830
- additions.append(ContractViolation(
831
- severity="ADDITION",
832
- category="ADDED_CLASS",
833
- symbol=cls_name,
834
- details=f"New public class '{cls_name}' added."
835
- ))
836
-
837
- # Determine SemVer bump
838
- if breaking:
839
- bump = SemVerBump.MAJOR
840
- elif additions:
841
- bump = SemVerBump.MINOR
842
- else:
843
- bump = SemVerBump.PATCH
844
-
845
- return ContractDiffReport(
846
- file_path=file_path,
847
- semver_bump=bump,
848
- breaking_changes=breaking,
849
- non_breaking_additions=additions,
850
- modifications=modifications
851
- )
852
-
853
- @classmethod
854
- def _compare_function_signatures(
855
- cls,
856
- old_fn: FunctionContract,
857
- new_fn: FunctionContract,
858
- symbol_name: str,
859
- breaking: List[ContractViolation],
860
- additions: List[ContractViolation],
861
- modifications: List[ContractViolation]
862
- ):
863
- old_pnames = old_fn.param_names
864
- new_pnames = new_fn.param_names
865
-
866
- # Check removed parameters
867
- for p in old_fn.parameters:
868
- if p.name not in new_pnames:
869
- breaking.append(ContractViolation(
870
- severity="BREAKING",
871
- category="REMOVED_PARAMETER",
872
- symbol=symbol_name,
873
- details=f"Parameter '{p.name}' was removed from '{symbol_name}'."
874
- ))
875
-
876
- # Check added required parameters (breaking!)
877
- for p in new_fn.parameters:
878
- if p.name not in old_pnames:
879
- if not p.has_default and not p.is_vararg and not p.is_kwarg:
880
- breaking.append(ContractViolation(
881
- severity="BREAKING",
882
- category="REQUIRED_PARAMETER_ADDED",
883
- symbol=symbol_name,
884
- details=f"New required parameter '{p.name}' added to '{symbol_name}' without default value."
885
- ))
886
- else:
887
- additions.append(ContractViolation(
888
- severity="ADDITION",
889
- category="OPTIONAL_PARAMETER_ADDED",
890
- symbol=symbol_name,
891
- details=f"Optional parameter '{p.name}' added to '{symbol_name}'."
892
- ))
893
-
894
- # Check return type annotation change
895
- if old_fn.return_annotation and new_fn.return_annotation and old_fn.return_annotation != new_fn.return_annotation:
896
- modifications.append(ContractViolation(
897
- severity="MODIFICATION",
898
- category="RETURN_TYPE_CHANGED",
899
- symbol=symbol_name,
900
- details=f"Return type changed from '{old_fn.return_annotation}' to '{new_fn.return_annotation}'."
901
- ))
902
-
903
- @classmethod
904
- def compare_git_revision(cls, repo_dir: str = ".", base_ref: str = "HEAD~1") -> List[ContractDiffReport]:
905
- """Compares public API contracts between base_ref and working tree / HEAD."""
906
- abs_repo = os.path.abspath(repo_dir)
907
-
908
- # Get list of changed python and polyglot files
909
- valid_exts = {".py"} | ASTContractExtractor.POLYGLOT_EXTENSIONS
910
- try:
911
- diff_proc = subprocess.run(
912
- ["git", "diff", "--name-only", base_ref],
913
- cwd=abs_repo,
914
- capture_output=True,
915
- text=True,
916
- encoding="utf-8",
917
- errors="replace"
918
- )
919
- files = [
920
- f.strip() for f in diff_proc.stdout.splitlines()
921
- if f.strip() and os.path.splitext(f.strip().lower())[1] in valid_exts
922
- ]
923
- except Exception:
924
- return []
925
-
926
- reports: List[ContractDiffReport] = []
927
- for rel_file in files:
928
- full_p = os.path.join(abs_repo, rel_file)
929
- if not os.path.isfile(full_p):
930
- continue
931
-
932
- with open(full_p, "r", encoding="utf-8", errors="replace") as f:
933
- new_code = f.read()
934
-
935
- # Fetch base_ref content via git show
936
- try:
937
- show_proc = subprocess.run(
938
- ["git", "show", f"{base_ref}:{rel_file}"],
939
- cwd=abs_repo,
940
- capture_output=True,
941
- text=True,
942
- encoding="utf-8",
943
- errors="replace"
944
- )
945
- if show_proc.returncode == 0:
946
- old_code = show_proc.stdout
947
- else:
948
- old_code = ""
949
- except Exception:
950
- old_code = ""
951
-
952
- rep = cls.compare_code(old_code, new_code, file_path=rel_file)
953
- reports.append(rep)
954
-
955
- return reports
956
-
957
- @classmethod
958
- def format_sarif_report(cls, reports: List[ContractDiffReport]) -> Dict[str, Any]:
959
- """Formats contract diff reports into an industry-standard SARIF 2.1.0 JSON object."""
960
- rules_map: Dict[str, Dict[str, Any]] = {}
961
- results: List[Dict[str, Any]] = []
962
-
963
- for r in reports:
964
- # Breaking changes -> error
965
- for v in r.breaking_changes:
966
- if v.category not in rules_map:
967
- rules_map[v.category] = {
968
- "id": v.category,
969
- "name": v.category,
970
- "shortDescription": {"text": f"Contract violation rule {v.category}"}
971
- }
972
- results.append({
973
- "ruleId": v.category,
974
- "level": "error",
975
- "message": {"text": v.details},
976
- "locations": [{
977
- "physicalLocation": {
978
- "artifactLocation": {
979
- "uri": r.file_path.replace("\\", "/")
980
- }
981
- }
982
- }]
983
- })
984
-
985
- # Modifications -> warning for RETURN_TYPE_CHANGED, else note
986
- for v in r.modifications:
987
- lvl = "warning" if v.category == "RETURN_TYPE_CHANGED" else "note"
988
- if v.category not in rules_map:
989
- rules_map[v.category] = {
990
- "id": v.category,
991
- "name": v.category,
992
- "shortDescription": {"text": f"Contract modification rule {v.category}"}
993
- }
994
- results.append({
995
- "ruleId": v.category,
996
- "level": lvl,
997
- "message": {"text": v.details},
998
- "locations": [{
999
- "physicalLocation": {
1000
- "artifactLocation": {
1001
- "uri": r.file_path.replace("\\", "/")
1002
- }
1003
- }
1004
- }]
1005
- })
1006
-
1007
- # Additions -> note
1008
- for v in r.non_breaking_additions:
1009
- if v.category not in rules_map:
1010
- rules_map[v.category] = {
1011
- "id": v.category,
1012
- "name": v.category,
1013
- "shortDescription": {"text": f"Contract addition rule {v.category}"}
1014
- }
1015
- results.append({
1016
- "ruleId": v.category,
1017
- "level": "note",
1018
- "message": {"text": v.details},
1019
- "locations": [{
1020
- "physicalLocation": {
1021
- "artifactLocation": {
1022
- "uri": r.file_path.replace("\\", "/")
1023
- }
1024
- }
1025
- }]
1026
- })
1027
-
1028
- rules_list = [rules_map[k] for k in sorted(rules_map.keys())]
1029
-
1030
- return {
1031
- "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1032
- "version": "2.1.0",
1033
- "runs": [
1034
- {
1035
- "tool": {
1036
- "driver": {
1037
- "name": "T-Zero Contract Guardian",
1038
- "version": "11.0.0",
1039
- "rules": rules_list
1040
- }
1041
- },
1042
- "results": results
1043
- }
1044
- ]
1045
- }
1046
-
1047
- @classmethod
1048
- def format_markdown_report(cls, reports: List[ContractDiffReport]) -> str:
1049
- """Formats the contract diffs into a GitHub PR Shield Markdown document."""
1050
- if not reports:
1051
- return "✅ **Public API Contracts:** No modified Python files found in git revision diff."
1052
-
1053
- has_breaking = any(r.is_breaking for r in reports)
1054
- highest_bump = SemVerBump.PATCH
1055
- if has_breaking:
1056
- highest_bump = SemVerBump.MAJOR
1057
- elif any(r.semver_bump == SemVerBump.MINOR for r in reports):
1058
- highest_bump = SemVerBump.MINOR
1059
-
1060
- badge = "🔴 **MAJOR (BREAKING)**" if highest_bump == SemVerBump.MAJOR else (
1061
- "đŸŸĸ **MINOR (FEATURE)**" if highest_bump == SemVerBump.MINOR else "đŸ”ĩ **PATCH (REFACTOR)**"
1062
- )
1063
-
1064
- lines = [
1065
- "## đŸ›Ąī¸ T-Zero Public API Contract & SemVer Guardian",
1066
- f"**Recommended SemVer Bump:** {badge}",
1067
- f"**Files Evaluated:** `{len(reports)}`",
1068
- ""
1069
- ]
1070
-
1071
- for r in reports:
1072
- status_icon = "🔴 BREAKING" if r.is_breaking else ("đŸŸĸ COMPATIBLE" if r.semver_bump == SemVerBump.MINOR else "đŸ”ĩ REFACTOR")
1073
- lines.append(f"### `{r.file_path}` — {status_icon} (`{r.semver_bump.value}`)")
1074
-
1075
- if r.breaking_changes:
1076
- lines.append("**âš ī¸ Breaking Changes:**")
1077
- for b in r.breaking_changes:
1078
- lines.append(f"- ❌ `{b.category}`: `{b.symbol}` — {b.details}")
1079
-
1080
- if r.non_breaking_additions:
1081
- lines.append("**✨ Additions:**")
1082
- for a in r.non_breaking_additions:
1083
- lines.append(f"- ➕ `{a.category}`: `{a.symbol}` — {a.details}")
1084
-
1085
- if r.modifications:
1086
- lines.append("**📝 Modifications:**")
1087
- for m in r.modifications:
1088
- lines.append(f"- â„šī¸ `{m.category}`: `{m.symbol}` — {m.details}")
1089
-
1090
- lines.append("")
1091
-
1092
- return "\n".join(lines).strip()
1093
-
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Autonomous AST Public API Contract & Semantic Versioning Guardian.
3
+
4
+ Analyzes AST signature changes between code revisions, determining if modifications
5
+ are backward-compatible or introduce breaking changes to public callers.
6
+
7
+ Capabilities:
8
+ - Detects removed public functions, methods, and classes.
9
+ - Flags added required parameters without defaults (caller breaking change).
10
+ - Detects parameter deletions, reorderings, and return type modifications.
11
+ - Recommends exact Semantic Versioning (SemVer) bump: MAJOR, MINOR, or PATCH.
12
+ - Computes Git revision contract diffs (HEAD vs uncommitted, or base_ref vs HEAD).
13
+ - 100% Offline, $0 cost, zero external dependencies (pure Python standard library).
14
+
15
+ Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
+ Part of T-Zero Context Architect v11.11.0 Master Edition.
17
+ """
18
+
19
+ import ast
20
+ import json
21
+ import os
22
+ import re
23
+ import subprocess
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from enum import Enum
27
+ from typing import Dict, List, Optional, Set, Tuple, Any
28
+
29
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
30
+ try:
31
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
32
+ except Exception:
33
+ pass
34
+
35
+
36
+ class SemVerBump(str, Enum):
37
+ PATCH = "PATCH" # Internal logic / docs changed, 100% contract compatible
38
+ MINOR = "MINOR" # New public functions/classes/optional parameters added
39
+ MAJOR = "MAJOR" # Incompatible public API contract change (breaking change)
40
+
41
+
42
+ @dataclass
43
+ class ParameterContract:
44
+ name: str
45
+ has_default: bool
46
+ type_annotation: Optional[str] = None
47
+ is_kwonly: bool = False
48
+ is_vararg: bool = False
49
+ is_kwarg: bool = False
50
+
51
+
52
+ @dataclass
53
+ class FunctionContract:
54
+ name: str
55
+ parameters: List[ParameterContract]
56
+ return_annotation: Optional[str] = None
57
+ is_async: bool = False
58
+ docstring: Optional[str] = None
59
+
60
+ @property
61
+ def required_param_count(self) -> int:
62
+ return sum(1 for p in self.parameters if not p.has_default and not p.is_vararg and not p.is_kwarg)
63
+
64
+ @property
65
+ def param_names(self) -> List[str]:
66
+ return [p.name for p in self.parameters]
67
+
68
+
69
+ @dataclass
70
+ class ClassContract:
71
+ name: str
72
+ bases: List[str]
73
+ methods: Dict[str, FunctionContract] = field(default_factory=dict)
74
+ docstring: Optional[str] = None
75
+
76
+
77
+ @dataclass
78
+ class ContractViolation:
79
+ severity: str # BREAKING, ADDITION, MODIFICATION
80
+ category: str # REMOVED_SYMBOL, SIGNATURE_BREAK, PARAMETER_REMOVED, etc.
81
+ symbol: str
82
+ details: str
83
+
84
+
85
+ @dataclass
86
+ class ContractDiffReport:
87
+ file_path: str
88
+ semver_bump: SemVerBump
89
+ breaking_changes: List[ContractViolation] = field(default_factory=list)
90
+ non_breaking_additions: List[ContractViolation] = field(default_factory=list)
91
+ modifications: List[ContractViolation] = field(default_factory=list)
92
+
93
+ @property
94
+ def is_breaking(self) -> bool:
95
+ return len(self.breaking_changes) > 0
96
+
97
+
98
+ class ASTContractExtractor:
99
+ """Extracts public API signatures and contracts from an AST tree."""
100
+
101
+ POLYGLOT_EXTENSIONS = {".ts", ".tsx", ".js", ".jsx", ".rs", ".go", ".java", ".cs"}
102
+
103
+ @classmethod
104
+ def extract_from_code(cls, code: str) -> Tuple[Dict[str, FunctionContract], Dict[str, ClassContract]]:
105
+ try:
106
+ tree = ast.parse(code)
107
+ except Exception:
108
+ return {}, {}
109
+
110
+ functions: Dict[str, FunctionContract] = {}
111
+ classes: Dict[str, ClassContract] = {}
112
+
113
+ for node in tree.body:
114
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
115
+ # Ignore private functions starting with single underscore (except __init__)
116
+ if node.name.startswith("_") and not node.name.startswith("__"):
117
+ continue
118
+ fc = cls._extract_function(node)
119
+ functions[node.name] = fc
120
+
121
+ elif isinstance(node, ast.ClassDef):
122
+ if node.name.startswith("_"):
123
+ continue
124
+ cc = cls._extract_class(node)
125
+ classes[node.name] = cc
126
+
127
+ return functions, classes
128
+
129
+ @classmethod
130
+ def _extract_function(cls, node: Any) -> FunctionContract:
131
+ params: List[ParameterContract] = []
132
+ args = node.args
133
+
134
+ # Calculate defaults offset
135
+ num_defaults = len(args.defaults)
136
+ num_pos = len(args.args)
137
+ defaults_start = num_pos - num_defaults
138
+
139
+ for i, a in enumerate(args.args):
140
+ has_def = i >= defaults_start
141
+ ann = ast.unparse(a.annotation) if getattr(a, "annotation", None) else None
142
+ params.append(ParameterContract(name=a.arg, has_default=has_def, type_annotation=ann))
143
+
144
+ if args.vararg:
145
+ ann = ast.unparse(args.vararg.annotation) if getattr(args.vararg, "annotation", None) else None
146
+ params.append(ParameterContract(name=f"*{args.vararg.arg}", has_default=True, type_annotation=ann, is_vararg=True))
147
+
148
+ for i, a in enumerate(args.kwonlyargs):
149
+ kw_def = False
150
+ if i < len(args.kw_defaults) and args.kw_defaults[i] is not None:
151
+ kw_def = True
152
+ ann = ast.unparse(a.annotation) if getattr(a, "annotation", None) else None
153
+ params.append(ParameterContract(name=a.arg, has_default=kw_def, type_annotation=ann, is_kwonly=True))
154
+
155
+ if args.kwarg:
156
+ ann = ast.unparse(args.kwarg.annotation) if getattr(args.kwarg, "annotation", None) else None
157
+ params.append(ParameterContract(name=f"**{args.kwarg.arg}", has_default=True, type_annotation=ann, is_kwarg=True))
158
+
159
+ ret_ann = ast.unparse(node.returns) if getattr(node, "returns", None) else None
160
+ doc = ast.get_docstring(node)
161
+
162
+ return FunctionContract(
163
+ name=node.name,
164
+ parameters=params,
165
+ return_annotation=ret_ann,
166
+ is_async=isinstance(node, ast.AsyncFunctionDef),
167
+ docstring=doc
168
+ )
169
+
170
+ @classmethod
171
+ def _extract_class(cls, node: ast.ClassDef) -> ClassContract:
172
+ bases = [ast.unparse(b) for b in node.bases]
173
+ methods: Dict[str, FunctionContract] = {}
174
+ for item in node.body:
175
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
176
+ if item.name.startswith("_") and not item.name.startswith("__"):
177
+ continue
178
+ methods[item.name] = cls._extract_function(item)
179
+
180
+ return ClassContract(
181
+ name=node.name,
182
+ bases=bases,
183
+ methods=methods,
184
+ docstring=ast.get_docstring(node)
185
+ )
186
+
187
+ @classmethod
188
+ def _strip_comments(cls, code: str) -> str:
189
+ """Removes single-line (//) and multi-line (/* */) comments preserving strings."""
190
+ out = []
191
+ i = 0
192
+ n = len(code)
193
+ in_quote: Optional[str] = None
194
+ while i < n:
195
+ ch = code[i]
196
+ nxt = code[i + 1] if i + 1 < n else ""
197
+ if in_quote:
198
+ out.append(ch)
199
+ if ch == "\\" and i + 1 < n:
200
+ i += 1
201
+ out.append(code[i])
202
+ elif ch == in_quote:
203
+ in_quote = None
204
+ i += 1
205
+ continue
206
+ if ch in ('"', "'", '`'):
207
+ in_quote = ch
208
+ out.append(ch)
209
+ i += 1
210
+ continue
211
+ if ch == "/" and nxt == "/":
212
+ i += 2
213
+ while i < n and code[i] != "\n":
214
+ i += 1
215
+ if i < n and code[i] == "\n":
216
+ out.append("\n")
217
+ i += 1
218
+ continue
219
+ if ch == "/" and nxt == "*":
220
+ i += 2
221
+ while i + 1 < n and not (code[i] == "*" and code[i + 1] == "/"):
222
+ if code[i] == "\n":
223
+ out.append("\n")
224
+ i += 1
225
+ i += 2
226
+ continue
227
+ out.append(ch)
228
+ i += 1
229
+ return "".join(out)
230
+
231
+ @staticmethod
232
+ def _split_param_list(raw_params: str) -> List[str]:
233
+ """Splits parameter string by commas outside of () [] {} <> quotes."""
234
+ parts = []
235
+ current = []
236
+ depth = 0
237
+ in_quote: Optional[str] = None
238
+ i = 0
239
+ n = len(raw_params)
240
+ while i < n:
241
+ ch = raw_params[i]
242
+ if in_quote:
243
+ current.append(ch)
244
+ if ch == "\\" and i + 1 < n:
245
+ i += 1
246
+ current.append(raw_params[i])
247
+ elif ch == in_quote:
248
+ in_quote = None
249
+ i += 1
250
+ continue
251
+ if ch in ('"', "'", '`'):
252
+ in_quote = ch
253
+ current.append(ch)
254
+ i += 1
255
+ continue
256
+ if ch in ("(", "[", "{", "<"):
257
+ depth += 1
258
+ current.append(ch)
259
+ elif ch in (")", "]", "}", ">"):
260
+ if depth > 0:
261
+ depth -= 1
262
+ current.append(ch)
263
+ elif ch == "," and depth == 0:
264
+ part = "".join(current).strip()
265
+ if part:
266
+ parts.append(part)
267
+ current = []
268
+ else:
269
+ current.append(ch)
270
+ i += 1
271
+ if current:
272
+ part = "".join(current).strip()
273
+ if part:
274
+ parts.append(part)
275
+ return parts
276
+
277
+ @staticmethod
278
+ def _find_matching_paren(text: str, start_idx: int) -> int:
279
+ """Given start_idx of '(', returns index of matching ')'."""
280
+ depth = 0
281
+ in_quote = None
282
+ i = start_idx
283
+ n = len(text)
284
+ while i < n:
285
+ ch = text[i]
286
+ if in_quote:
287
+ if ch == "\\" and i + 1 < n:
288
+ i += 2
289
+ continue
290
+ if ch == in_quote:
291
+ in_quote = None
292
+ i += 1
293
+ continue
294
+ if ch in ('"', "'", '`'):
295
+ in_quote = ch
296
+ i += 1
297
+ continue
298
+ if ch == "(":
299
+ depth += 1
300
+ elif ch == ")":
301
+ depth -= 1
302
+ if depth == 0:
303
+ return i
304
+ i += 1
305
+ return -1
306
+
307
+ @staticmethod
308
+ def _find_matching_brace(text: str, start_idx: int) -> int:
309
+ """Given start_idx of '{', returns index of matching '}'."""
310
+ depth = 0
311
+ in_quote = None
312
+ i = start_idx
313
+ n = len(text)
314
+ while i < n:
315
+ ch = text[i]
316
+ if in_quote:
317
+ if ch == "\\" and i + 1 < n:
318
+ i += 2
319
+ continue
320
+ if ch == in_quote:
321
+ in_quote = None
322
+ i += 1
323
+ continue
324
+ if ch in ('"', "'", '`'):
325
+ in_quote = ch
326
+ i += 1
327
+ continue
328
+ if ch == "{":
329
+ depth += 1
330
+ elif ch == "}":
331
+ depth -= 1
332
+ if depth == 0:
333
+ return i
334
+ i += 1
335
+ return -1
336
+
337
+ @classmethod
338
+ def _parse_ts_param(cls, p: str) -> ParameterContract:
339
+ p = p.strip()
340
+ is_vararg = False
341
+ if p.startswith("..."):
342
+ is_vararg = True
343
+ p = p[3:].strip()
344
+
345
+ has_default = is_vararg
346
+ if "=" in p:
347
+ left, _ = p.split("=", 1)
348
+ has_default = True
349
+ left = left.strip()
350
+ else:
351
+ left = p
352
+
353
+ if "?:" in left:
354
+ name_p, type_p = left.split("?:", 1)
355
+ name = name_p.strip()
356
+ type_ann = type_p.strip()
357
+ has_default = True
358
+ elif ":" in left:
359
+ name_p, type_p = left.split(":", 1)
360
+ name = name_p.strip()
361
+ type_ann = type_p.strip()
362
+ if name.endswith("?"):
363
+ name = name[:-1].strip()
364
+ has_default = True
365
+ else:
366
+ name = left.strip()
367
+ if name.endswith("?"):
368
+ name = name[:-1].strip()
369
+ has_default = True
370
+ type_ann = None
371
+
372
+ if name.startswith("..."):
373
+ name = name[3:].strip()
374
+ is_vararg = True
375
+ has_default = True
376
+
377
+ return ParameterContract(
378
+ name=name,
379
+ has_default=has_default,
380
+ type_annotation=type_ann,
381
+ is_vararg=is_vararg
382
+ )
383
+
384
+ @classmethod
385
+ def _parse_go_params(cls, raw: str) -> List[ParameterContract]:
386
+ if not raw.strip():
387
+ return []
388
+ parts = cls._split_param_list(raw)
389
+ resolved: List[Tuple[str, str]] = []
390
+ current_type = ""
391
+ for p in reversed(parts):
392
+ tokens = p.strip().split()
393
+ if len(tokens) >= 2:
394
+ current_type = " ".join(tokens[1:])
395
+ resolved.append((tokens[0], current_type))
396
+ elif len(tokens) == 1:
397
+ resolved.append((tokens[0], current_type))
398
+ resolved.reverse()
399
+
400
+ params: List[ParameterContract] = []
401
+ for name, typ in resolved:
402
+ is_var = typ.startswith("...")
403
+ params.append(ParameterContract(
404
+ name=name,
405
+ has_default=is_var,
406
+ type_annotation=typ if typ else None,
407
+ is_vararg=is_var
408
+ ))
409
+ return params
410
+
411
+ @classmethod
412
+ def _parse_rust_param(cls, p: str) -> Optional[ParameterContract]:
413
+ p = p.strip()
414
+ if not p or p in ("self", "&self", "&mut self"):
415
+ return None
416
+ if ":" in p:
417
+ name, typ = p.split(":", 1)
418
+ return ParameterContract(
419
+ name=name.strip(),
420
+ has_default=False,
421
+ type_annotation=typ.strip()
422
+ )
423
+ return ParameterContract(name=p, has_default=False)
424
+
425
+ @classmethod
426
+ def _parse_java_param(cls, p: str) -> ParameterContract:
427
+ p = p.strip()
428
+ has_default = False
429
+ if "=" in p:
430
+ left, _ = p.split("=", 1)
431
+ has_default = True
432
+ left = left.strip()
433
+ else:
434
+ left = p
435
+
436
+ tokens = left.split()
437
+ if not tokens:
438
+ return ParameterContract(name="", has_default=has_default)
439
+
440
+ name = tokens[-1]
441
+ type_ann = " ".join(tokens[:-1]) if len(tokens) > 1 else None
442
+ is_vararg = False
443
+ if name.startswith("..."):
444
+ name = name[3:]
445
+ is_vararg = True
446
+ has_default = True
447
+ elif type_ann and ("..." in type_ann or "params " in left):
448
+ is_vararg = True
449
+ has_default = True
450
+
451
+ return ParameterContract(
452
+ name=name,
453
+ has_default=has_default,
454
+ type_annotation=type_ann,
455
+ is_vararg=is_vararg
456
+ )
457
+
458
+ @classmethod
459
+ def _extract_ts_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
460
+ class_pattern = re.compile(
461
+ r'(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)(?:\s+extends\s+([^{]+))?\s*\{'
462
+ )
463
+ top_level_code = list(clean_code)
464
+
465
+ for m in class_pattern.finditer(clean_code):
466
+ cls_name = m.group(1)
467
+ bases = [b.strip() for b in m.group(2).split(",")] if m.group(2) else []
468
+ brace_idx = m.end() - 1
469
+ end_brace = cls._find_matching_brace(clean_code, brace_idx)
470
+ if end_brace == -1:
471
+ end_brace = len(clean_code) - 1
472
+
473
+ for k in range(m.start(), end_brace + 1):
474
+ if top_level_code[k] != "\n":
475
+ top_level_code[k] = " "
476
+
477
+ class_body = clean_code[brace_idx + 1:end_brace]
478
+ methods: Dict[str, FunctionContract] = {}
479
+
480
+ method_depth = 0
481
+ idx = 0
482
+ n = len(class_body)
483
+ while idx < n:
484
+ ch = class_body[idx]
485
+ if ch == "{":
486
+ method_depth += 1
487
+ idx += 1
488
+ continue
489
+ elif ch == "}":
490
+ if method_depth > 0:
491
+ method_depth -= 1
492
+ idx += 1
493
+ continue
494
+
495
+ if method_depth == 0:
496
+ m_hdr = re.match(
497
+ r'^(?:(?:public|static|async|get|set|override|readonly)\s+)*([A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\(',
498
+ class_body[idx:]
499
+ )
500
+ if m_hdr:
501
+ full_match = m_hdr.group(0)
502
+ fn_name = m_hdr.group(1)
503
+ matched_str = class_body[idx:idx + len(full_match)]
504
+
505
+ if (
506
+ fn_name in {"if", "for", "while", "switch", "catch", "return"}
507
+ or "private " in matched_str
508
+ or "protected " in matched_str
509
+ or fn_name.startswith("_")
510
+ or fn_name.startswith("#")
511
+ ):
512
+ idx += len(full_match)
513
+ continue
514
+
515
+ paren_start = idx + len(full_match) - 1
516
+ paren_end = cls._find_matching_paren(class_body, paren_start)
517
+ if paren_end != -1:
518
+ raw_params = class_body[paren_start + 1:paren_end]
519
+ rest = class_body[paren_end + 1:]
520
+ ret_match = re.match(r'^\s*:\s*([^{;]+)', rest)
521
+ ret_ann = ret_match.group(1).strip() if ret_match else None
522
+ is_async = "async " in matched_str
523
+
524
+ params = [cls._parse_ts_param(p) for p in cls._split_param_list(raw_params)]
525
+ methods[fn_name] = FunctionContract(
526
+ name=fn_name,
527
+ parameters=params,
528
+ return_annotation=ret_ann,
529
+ is_async=is_async
530
+ )
531
+ idx = paren_end + 1
532
+ continue
533
+
534
+ idx += 1
535
+
536
+ classes[cls_name] = ClassContract(name=cls_name, bases=bases, methods=methods)
537
+
538
+ top_str = "".join(top_level_code)
539
+ fn_pattern = re.compile(
540
+ r'(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\('
541
+ )
542
+ for m in fn_pattern.finditer(top_str):
543
+ fn_name = m.group(1)
544
+ prefix = top_str[m.start():m.end()]
545
+ is_exported = "export" in prefix
546
+ if fn_name.startswith("_") and not is_exported:
547
+ continue
548
+
549
+ paren_start = m.end() - 1
550
+ paren_end = cls._find_matching_paren(top_str, paren_start)
551
+ if paren_end != -1:
552
+ raw_params = top_str[paren_start + 1:paren_end]
553
+ rest = top_str[paren_end + 1:]
554
+ ret_match = re.match(r'^\s*:\s*([^{;]+)', rest)
555
+ ret_ann = ret_match.group(1).strip() if ret_match else None
556
+ is_async = "async" in prefix
557
+ params = [cls._parse_ts_param(p) for p in cls._split_param_list(raw_params)]
558
+ functions[fn_name] = FunctionContract(
559
+ name=fn_name,
560
+ parameters=params,
561
+ return_annotation=ret_ann,
562
+ is_async=is_async
563
+ )
564
+
565
+ @classmethod
566
+ def _extract_go_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
567
+ for m in re.finditer(r'\btype\s+([A-Za-z0-9_]+)\s+(?:struct|interface)\b', clean_code):
568
+ name = m.group(1)
569
+ if name and name[0].isupper():
570
+ classes.setdefault(name, ClassContract(name=name, bases=[]))
571
+
572
+ func_pattern = re.compile(r'\bfunc\s+')
573
+ for m in func_pattern.finditer(clean_code):
574
+ start = m.end()
575
+ rem = clean_code[start:].lstrip()
576
+ recv_type: Optional[str] = None
577
+ if rem.startswith("("):
578
+ paren_start = clean_code.find("(", start)
579
+ paren_end = cls._find_matching_paren(clean_code, paren_start)
580
+ if paren_end == -1:
581
+ continue
582
+ recv_content = clean_code[paren_start + 1:paren_end].strip()
583
+ tokens = recv_content.split()
584
+ if tokens:
585
+ recv_type = tokens[-1].lstrip("*")
586
+ start = paren_end + 1
587
+
588
+ fn_match = re.match(r'^\s*([A-Za-z0-9_]+)\s*\(', clean_code[start:])
589
+ if not fn_match:
590
+ continue
591
+
592
+ fn_name = fn_match.group(1)
593
+ if not fn_name or not fn_name[0].isupper():
594
+ continue
595
+
596
+ paren_start = clean_code.find("(", start)
597
+ paren_end = cls._find_matching_paren(clean_code, paren_start)
598
+ if paren_end == -1:
599
+ continue
600
+
601
+ raw_params = clean_code[paren_start + 1:paren_end]
602
+ params = cls._parse_go_params(raw_params)
603
+
604
+ after_paren = clean_code[paren_end + 1:]
605
+ brace_pos = after_paren.find("{")
606
+ ret_ann = None
607
+ if brace_pos != -1:
608
+ raw_ret = after_paren[:brace_pos].strip()
609
+ if raw_ret:
610
+ ret_ann = raw_ret
611
+
612
+ fc = FunctionContract(
613
+ name=fn_name,
614
+ parameters=params,
615
+ return_annotation=ret_ann
616
+ )
617
+
618
+ if recv_type:
619
+ if recv_type not in classes:
620
+ classes[recv_type] = ClassContract(name=recv_type, bases=[])
621
+ classes[recv_type].methods[fn_name] = fc
622
+ else:
623
+ functions[fn_name] = fc
624
+
625
+ @classmethod
626
+ def _extract_rust_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
627
+ for m in re.finditer(r'\bpub\s+(?:struct|enum)\s+([A-Za-z0-9_]+)\b', clean_code):
628
+ name = m.group(1)
629
+ classes.setdefault(name, ClassContract(name=name, bases=[]))
630
+
631
+ top_level_code = list(clean_code)
632
+
633
+ impl_pattern = re.compile(r'\bimpl(?:\s+<[^>]+>)?\s+([A-Za-z0-9_]+)\b[^{]*\{')
634
+ for m in impl_pattern.finditer(clean_code):
635
+ impl_name = m.group(1)
636
+ brace_idx = m.end() - 1
637
+ end_brace = cls._find_matching_brace(clean_code, brace_idx)
638
+ if end_brace == -1:
639
+ end_brace = len(clean_code) - 1
640
+
641
+ for k in range(m.start(), end_brace + 1):
642
+ if top_level_code[k] != "\n":
643
+ top_level_code[k] = " "
644
+
645
+ if impl_name not in classes:
646
+ classes[impl_name] = ClassContract(name=impl_name, bases=[])
647
+
648
+ impl_body = clean_code[brace_idx + 1:end_brace]
649
+ for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]+>)?\s*\(', impl_body):
650
+ fn_name = fn_m.group(1)
651
+ p_start = fn_m.end() - 1
652
+ p_end = cls._find_matching_paren(impl_body, p_start)
653
+ if p_end != -1:
654
+ raw_params = impl_body[p_start + 1:p_end]
655
+ params = [p for p in (cls._parse_rust_param(x) for x in cls._split_param_list(raw_params)) if p is not None]
656
+ after_p = impl_body[p_end + 1:]
657
+ ret_m = re.match(r'^\s*->\s*([^{;]+)', after_p)
658
+ ret_ann = ret_m.group(1).strip() if ret_m else None
659
+ classes[impl_name].methods[fn_name] = FunctionContract(
660
+ name=fn_name,
661
+ parameters=params,
662
+ return_annotation=ret_ann
663
+ )
664
+
665
+ top_str = "".join(top_level_code)
666
+ for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]+>)?\s*\(', top_str):
667
+ fn_name = fn_m.group(1)
668
+ p_start = fn_m.end() - 1
669
+ p_end = cls._find_matching_paren(top_str, p_start)
670
+ if p_end != -1:
671
+ raw_params = top_str[p_start + 1:p_end]
672
+ params = [p for p in (cls._parse_rust_param(x) for x in cls._split_param_list(raw_params)) if p is not None]
673
+ after_p = top_str[p_end + 1:]
674
+ ret_m = re.match(r'^\s*->\s*([^{;]+)', after_p)
675
+ ret_ann = ret_m.group(1).strip() if ret_m else None
676
+ functions[fn_name] = FunctionContract(
677
+ name=fn_name,
678
+ parameters=params,
679
+ return_annotation=ret_ann
680
+ )
681
+
682
+ @classmethod
683
+ def _extract_java_cs_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
684
+ class_pattern = re.compile(
685
+ r'\bpublic\s+(?:abstract\s+|static\s+|sealed\s+)?(?:class|interface)\s+([A-Za-z0-9_]+)(?:\s+extends\s+([^{]+))?\s*\{'
686
+ )
687
+ for m in class_pattern.finditer(clean_code):
688
+ cls_name = m.group(1)
689
+ bases = [b.strip() for b in m.group(2).split(",")] if m.group(2) else []
690
+ brace_idx = m.end() - 1
691
+ end_brace = cls._find_matching_brace(clean_code, brace_idx)
692
+ if end_brace == -1:
693
+ end_brace = len(clean_code) - 1
694
+
695
+ class_body = clean_code[brace_idx + 1:end_brace]
696
+ methods: Dict[str, FunctionContract] = {}
697
+
698
+ method_depth = 0
699
+ idx = 0
700
+ n = len(class_body)
701
+ while idx < n:
702
+ ch = class_body[idx]
703
+ if ch == "{":
704
+ method_depth += 1
705
+ idx += 1
706
+ continue
707
+ elif ch == "}":
708
+ if method_depth > 0:
709
+ method_depth -= 1
710
+ idx += 1
711
+ continue
712
+
713
+ if method_depth == 0:
714
+ m_hdr = re.match(
715
+ r'^\s*public\s+(?:static\s+|async\s+|final\s+|virtual\s+|override\s+)?([A-Za-z0-9_<>[\]]+)\s+([A-Za-z0-9_]+)\s*\(',
716
+ class_body[idx:]
717
+ )
718
+ if m_hdr:
719
+ ret_ann = m_hdr.group(1)
720
+ fn_name = m_hdr.group(2)
721
+ p_start = class_body.find("(", idx)
722
+ p_end = cls._find_matching_paren(class_body, p_start)
723
+ if p_end != -1:
724
+ raw_params = class_body[p_start + 1:p_end]
725
+ params = [cls._parse_java_param(p) for p in cls._split_param_list(raw_params)]
726
+ methods[fn_name] = FunctionContract(
727
+ name=fn_name,
728
+ parameters=params,
729
+ return_annotation=ret_ann
730
+ )
731
+ idx = p_end + 1
732
+ continue
733
+ idx += 1
734
+
735
+ classes[cls_name] = ClassContract(name=cls_name, bases=bases, methods=methods)
736
+
737
+ @classmethod
738
+ def extract_polyglot_contracts(cls, code: str, file_path: str = "module.ts") -> Tuple[Dict[str, FunctionContract], Dict[str, ClassContract]]:
739
+ ext = os.path.splitext(file_path.lower())[1]
740
+ clean_code = cls._strip_comments(code)
741
+ functions: Dict[str, FunctionContract] = {}
742
+ classes: Dict[str, ClassContract] = {}
743
+
744
+ if ext in {".ts", ".tsx", ".js", ".jsx"}:
745
+ cls._extract_ts_contracts(clean_code, functions, classes)
746
+ elif ext == ".go":
747
+ cls._extract_go_contracts(clean_code, functions, classes)
748
+ elif ext == ".rs":
749
+ cls._extract_rust_contracts(clean_code, functions, classes)
750
+ elif ext in {".java", ".cs"}:
751
+ cls._extract_java_cs_contracts(clean_code, functions, classes)
752
+
753
+ return functions, classes
754
+
755
+
756
+ class ASTContractComparator:
757
+ """Compares two versions of public AST contracts and evaluates breaking changes."""
758
+
759
+ @classmethod
760
+ def compare_code(cls, old_code: str, new_code: str, file_path: str = "code.py") -> ContractDiffReport:
761
+ ext = os.path.splitext(file_path.lower())[1]
762
+ if ext in ASTContractExtractor.POLYGLOT_EXTENSIONS:
763
+ old_funcs, old_classes = ASTContractExtractor.extract_polyglot_contracts(old_code, file_path=file_path)
764
+ new_funcs, new_classes = ASTContractExtractor.extract_polyglot_contracts(new_code, file_path=file_path)
765
+ else:
766
+ old_funcs, old_classes = ASTContractExtractor.extract_from_code(old_code)
767
+ new_funcs, new_classes = ASTContractExtractor.extract_from_code(new_code)
768
+
769
+ breaking: List[ContractViolation] = []
770
+ additions: List[ContractViolation] = []
771
+ modifications: List[ContractViolation] = []
772
+
773
+ # 1. Check top-level functions
774
+ for fn_name, old_fn in old_funcs.items():
775
+ if fn_name not in new_funcs:
776
+ breaking.append(ContractViolation(
777
+ severity="BREAKING",
778
+ category="REMOVED_FUNCTION",
779
+ symbol=fn_name,
780
+ details=f"Public function '{fn_name}()' was removed."
781
+ ))
782
+ else:
783
+ new_fn = new_funcs[fn_name]
784
+ cls._compare_function_signatures(old_fn, new_fn, fn_name, breaking, additions, modifications)
785
+
786
+ for fn_name, new_fn in new_funcs.items():
787
+ if fn_name not in old_funcs:
788
+ additions.append(ContractViolation(
789
+ severity="ADDITION",
790
+ category="ADDED_FUNCTION",
791
+ symbol=fn_name,
792
+ details=f"New public function '{fn_name}()' added."
793
+ ))
794
+
795
+ # 2. Check classes and methods
796
+ for cls_name, old_cls in old_classes.items():
797
+ if cls_name not in new_classes:
798
+ breaking.append(ContractViolation(
799
+ severity="BREAKING",
800
+ category="REMOVED_CLASS",
801
+ symbol=cls_name,
802
+ details=f"Public class '{cls_name}' was removed."
803
+ ))
804
+ else:
805
+ new_cls = new_classes[cls_name]
806
+ # Compare class methods
807
+ for m_name, old_m in old_cls.methods.items():
808
+ if m_name not in new_cls.methods:
809
+ breaking.append(ContractViolation(
810
+ severity="BREAKING",
811
+ category="REMOVED_METHOD",
812
+ symbol=f"{cls_name}.{m_name}",
813
+ details=f"Public method '{cls_name}.{m_name}()' was removed."
814
+ ))
815
+ else:
816
+ new_m = new_cls.methods[m_name]
817
+ cls._compare_function_signatures(old_m, new_m, f"{cls_name}.{m_name}", breaking, additions, modifications)
818
+
819
+ for m_name, new_m in new_cls.methods.items():
820
+ if m_name not in old_cls.methods:
821
+ additions.append(ContractViolation(
822
+ severity="ADDITION",
823
+ category="ADDED_METHOD",
824
+ symbol=f"{cls_name}.{m_name}",
825
+ details=f"New public method '{cls_name}.{m_name}()' added."
826
+ ))
827
+
828
+ for cls_name, new_cls in new_classes.items():
829
+ if cls_name not in old_classes:
830
+ additions.append(ContractViolation(
831
+ severity="ADDITION",
832
+ category="ADDED_CLASS",
833
+ symbol=cls_name,
834
+ details=f"New public class '{cls_name}' added."
835
+ ))
836
+
837
+ # Determine SemVer bump
838
+ if breaking:
839
+ bump = SemVerBump.MAJOR
840
+ elif additions:
841
+ bump = SemVerBump.MINOR
842
+ else:
843
+ bump = SemVerBump.PATCH
844
+
845
+ return ContractDiffReport(
846
+ file_path=file_path,
847
+ semver_bump=bump,
848
+ breaking_changes=breaking,
849
+ non_breaking_additions=additions,
850
+ modifications=modifications
851
+ )
852
+
853
+ @classmethod
854
+ def _compare_function_signatures(
855
+ cls,
856
+ old_fn: FunctionContract,
857
+ new_fn: FunctionContract,
858
+ symbol_name: str,
859
+ breaking: List[ContractViolation],
860
+ additions: List[ContractViolation],
861
+ modifications: List[ContractViolation]
862
+ ):
863
+ old_pnames = old_fn.param_names
864
+ new_pnames = new_fn.param_names
865
+
866
+ # Check removed parameters
867
+ for p in old_fn.parameters:
868
+ if p.name not in new_pnames:
869
+ breaking.append(ContractViolation(
870
+ severity="BREAKING",
871
+ category="REMOVED_PARAMETER",
872
+ symbol=symbol_name,
873
+ details=f"Parameter '{p.name}' was removed from '{symbol_name}'."
874
+ ))
875
+
876
+ # Check added required parameters (breaking!)
877
+ for p in new_fn.parameters:
878
+ if p.name not in old_pnames:
879
+ if not p.has_default and not p.is_vararg and not p.is_kwarg:
880
+ breaking.append(ContractViolation(
881
+ severity="BREAKING",
882
+ category="REQUIRED_PARAMETER_ADDED",
883
+ symbol=symbol_name,
884
+ details=f"New required parameter '{p.name}' added to '{symbol_name}' without default value."
885
+ ))
886
+ else:
887
+ additions.append(ContractViolation(
888
+ severity="ADDITION",
889
+ category="OPTIONAL_PARAMETER_ADDED",
890
+ symbol=symbol_name,
891
+ details=f"Optional parameter '{p.name}' added to '{symbol_name}'."
892
+ ))
893
+
894
+ # Check return type annotation change
895
+ if old_fn.return_annotation and new_fn.return_annotation and old_fn.return_annotation != new_fn.return_annotation:
896
+ modifications.append(ContractViolation(
897
+ severity="MODIFICATION",
898
+ category="RETURN_TYPE_CHANGED",
899
+ symbol=symbol_name,
900
+ details=f"Return type changed from '{old_fn.return_annotation}' to '{new_fn.return_annotation}'."
901
+ ))
902
+
903
+ @classmethod
904
+ def compare_git_revision(cls, repo_dir: str = ".", base_ref: str = "HEAD~1") -> List[ContractDiffReport]:
905
+ """Compares public API contracts between base_ref and working tree / HEAD."""
906
+ abs_repo = os.path.abspath(repo_dir)
907
+
908
+ # Get list of changed python and polyglot files
909
+ valid_exts = {".py"} | ASTContractExtractor.POLYGLOT_EXTENSIONS
910
+ try:
911
+ diff_proc = subprocess.run(
912
+ ["git", "diff", "--name-only", base_ref],
913
+ cwd=abs_repo,
914
+ capture_output=True,
915
+ text=True,
916
+ encoding="utf-8",
917
+ errors="replace"
918
+ )
919
+ files = [
920
+ f.strip() for f in diff_proc.stdout.splitlines()
921
+ if f.strip() and os.path.splitext(f.strip().lower())[1] in valid_exts
922
+ ]
923
+ except Exception:
924
+ return []
925
+
926
+ reports: List[ContractDiffReport] = []
927
+ for rel_file in files:
928
+ full_p = os.path.join(abs_repo, rel_file)
929
+ if not os.path.isfile(full_p):
930
+ continue
931
+
932
+ with open(full_p, "r", encoding="utf-8", errors="replace") as f:
933
+ new_code = f.read()
934
+
935
+ # Fetch base_ref content via git show
936
+ try:
937
+ show_proc = subprocess.run(
938
+ ["git", "show", f"{base_ref}:{rel_file}"],
939
+ cwd=abs_repo,
940
+ capture_output=True,
941
+ text=True,
942
+ encoding="utf-8",
943
+ errors="replace"
944
+ )
945
+ if show_proc.returncode == 0:
946
+ old_code = show_proc.stdout
947
+ else:
948
+ old_code = ""
949
+ except Exception:
950
+ old_code = ""
951
+
952
+ rep = cls.compare_code(old_code, new_code, file_path=rel_file)
953
+ reports.append(rep)
954
+
955
+ return reports
956
+
957
+ @classmethod
958
+ def format_sarif_report(cls, reports: List[ContractDiffReport]) -> Dict[str, Any]:
959
+ """Formats contract diff reports into an industry-standard SARIF 2.1.0 JSON object."""
960
+ rules_map: Dict[str, Dict[str, Any]] = {}
961
+ results: List[Dict[str, Any]] = []
962
+
963
+ for r in reports:
964
+ # Breaking changes -> error
965
+ for v in r.breaking_changes:
966
+ if v.category not in rules_map:
967
+ rules_map[v.category] = {
968
+ "id": v.category,
969
+ "name": v.category,
970
+ "shortDescription": {"text": f"Contract violation rule {v.category}"}
971
+ }
972
+ results.append({
973
+ "ruleId": v.category,
974
+ "level": "error",
975
+ "message": {"text": v.details},
976
+ "locations": [{
977
+ "physicalLocation": {
978
+ "artifactLocation": {
979
+ "uri": r.file_path.replace("\\", "/")
980
+ }
981
+ }
982
+ }]
983
+ })
984
+
985
+ # Modifications -> warning for RETURN_TYPE_CHANGED, else note
986
+ for v in r.modifications:
987
+ lvl = "warning" if v.category == "RETURN_TYPE_CHANGED" else "note"
988
+ if v.category not in rules_map:
989
+ rules_map[v.category] = {
990
+ "id": v.category,
991
+ "name": v.category,
992
+ "shortDescription": {"text": f"Contract modification rule {v.category}"}
993
+ }
994
+ results.append({
995
+ "ruleId": v.category,
996
+ "level": lvl,
997
+ "message": {"text": v.details},
998
+ "locations": [{
999
+ "physicalLocation": {
1000
+ "artifactLocation": {
1001
+ "uri": r.file_path.replace("\\", "/")
1002
+ }
1003
+ }
1004
+ }]
1005
+ })
1006
+
1007
+ # Additions -> note
1008
+ for v in r.non_breaking_additions:
1009
+ if v.category not in rules_map:
1010
+ rules_map[v.category] = {
1011
+ "id": v.category,
1012
+ "name": v.category,
1013
+ "shortDescription": {"text": f"Contract addition rule {v.category}"}
1014
+ }
1015
+ results.append({
1016
+ "ruleId": v.category,
1017
+ "level": "note",
1018
+ "message": {"text": v.details},
1019
+ "locations": [{
1020
+ "physicalLocation": {
1021
+ "artifactLocation": {
1022
+ "uri": r.file_path.replace("\\", "/")
1023
+ }
1024
+ }
1025
+ }]
1026
+ })
1027
+
1028
+ rules_list = [rules_map[k] for k in sorted(rules_map.keys())]
1029
+
1030
+ return {
1031
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1032
+ "version": "2.1.0",
1033
+ "runs": [
1034
+ {
1035
+ "tool": {
1036
+ "driver": {
1037
+ "name": "T-Zero Contract Guardian",
1038
+ "version": "11.11.0",
1039
+ "rules": rules_list
1040
+ }
1041
+ },
1042
+ "results": results
1043
+ }
1044
+ ]
1045
+ }
1046
+
1047
+ @classmethod
1048
+ def format_markdown_report(cls, reports: List[ContractDiffReport]) -> str:
1049
+ """Formats the contract diffs into a GitHub PR Shield Markdown document."""
1050
+ if not reports:
1051
+ return "✅ **Public API Contracts:** No modified Python files found in git revision diff."
1052
+
1053
+ has_breaking = any(r.is_breaking for r in reports)
1054
+ highest_bump = SemVerBump.PATCH
1055
+ if has_breaking:
1056
+ highest_bump = SemVerBump.MAJOR
1057
+ elif any(r.semver_bump == SemVerBump.MINOR for r in reports):
1058
+ highest_bump = SemVerBump.MINOR
1059
+
1060
+ badge = "🔴 **MAJOR (BREAKING)**" if highest_bump == SemVerBump.MAJOR else (
1061
+ "đŸŸĸ **MINOR (FEATURE)**" if highest_bump == SemVerBump.MINOR else "đŸ”ĩ **PATCH (REFACTOR)**"
1062
+ )
1063
+
1064
+ lines = [
1065
+ "## đŸ›Ąī¸ T-Zero Public API Contract & SemVer Guardian",
1066
+ f"**Recommended SemVer Bump:** {badge}",
1067
+ f"**Files Evaluated:** `{len(reports)}`",
1068
+ ""
1069
+ ]
1070
+
1071
+ for r in reports:
1072
+ status_icon = "🔴 BREAKING" if r.is_breaking else ("đŸŸĸ COMPATIBLE" if r.semver_bump == SemVerBump.MINOR else "đŸ”ĩ REFACTOR")
1073
+ lines.append(f"### `{r.file_path}` — {status_icon} (`{r.semver_bump.value}`)")
1074
+
1075
+ if r.breaking_changes:
1076
+ lines.append("**âš ī¸ Breaking Changes:**")
1077
+ for b in r.breaking_changes:
1078
+ lines.append(f"- ❌ `{b.category}`: `{b.symbol}` — {b.details}")
1079
+
1080
+ if r.non_breaking_additions:
1081
+ lines.append("**✨ Additions:**")
1082
+ for a in r.non_breaking_additions:
1083
+ lines.append(f"- ➕ `{a.category}`: `{a.symbol}` — {a.details}")
1084
+
1085
+ if r.modifications:
1086
+ lines.append("**📝 Modifications:**")
1087
+ for m in r.modifications:
1088
+ lines.append(f"- â„šī¸ `{m.category}`: `{m.symbol}` — {m.details}")
1089
+
1090
+ lines.append("")
1091
+
1092
+ return "\n".join(lines).strip()
1093
+