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,305 +1,305 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Polyglot Schema Validator, OpenAPI Linter, & EditorConfig Healer
4
- ======================================================================
5
- Zero-dependency schema validation and developer environment standardization engine.
6
- Provides:
7
- - JSON Schema Draft-07 / 2020-12 validation (types, required, enum, pattern, bounds)
8
- - OpenAPI 3.0 / 3.1 REST API specification linter (missing paths, non-unique operationIds)
9
- - GraphQL SDL (Schema Definition Language) parser & syntax auditor
10
- - .editorconfig specification generator & line-ending LF normalizer
11
-
12
- Author: Siber Akademi T-Zero R&D Team
13
- License: MIT (100% Free, Local Offline, Zero-Leak)
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import json
19
- import os
20
- import re
21
- from dataclasses import dataclass, field
22
- from pathlib import Path
23
- from typing import Any, Dict, List, Optional, Set, Tuple
24
-
25
- from tzero.tzero_fixer.models import (
26
- DiagnosticCategory,
27
- DiagnosticIssue,
28
- DiffHunk,
29
- HealAction,
30
- SeverityLevel,
31
- )
32
-
33
-
34
- class EditorConfigHealer:
35
- """Standardizes project .editorconfig files for uniform line endings and indentations."""
36
-
37
- DEFAULT_EDITORCONFIG = """# EditorConfig is awesome: https://EditorConfig.org
38
- root = true
39
-
40
- [*]
41
- indent_style = space
42
- indent_size = 4
43
- end_of_line = lf
44
- charset = utf-8
45
- trim_trailing_whitespace = true
46
- insert_final_newline = true
47
-
48
- [*.{json,yml,yaml,md,js,ts,jsx,tsx}]
49
- indent_size = 2
50
-
51
- [Makefile]
52
- indent_style = tab
53
- """
54
-
55
- @classmethod
56
- def diagnose_and_heal(cls, workspace_dir: str = ".", dry_run: bool = False) -> Tuple[List[DiagnosticIssue], List[HealAction]]:
57
- issues: List[DiagnosticIssue] = []
58
- actions: List[HealAction] = []
59
- ec_path = Path(workspace_dir) / ".editorconfig"
60
-
61
- if not ec_path.is_file():
62
- issues.append(
63
- DiagnosticIssue(
64
- category=DiagnosticCategory.POLYGLOT.value,
65
- severity=SeverityLevel.INFO.value,
66
- file_path=str(ec_path),
67
- error_code="TZ-EC-MISSING",
68
- message="Missing .editorconfig file. Multi-developer formatting and line endings may drift.",
69
- suggested_fix="Generate standardized multi-language .editorconfig file.",
70
- auto_fixable=True,
71
- metadata={"action": "generate_editorconfig", "path": str(ec_path)},
72
- )
73
- )
74
-
75
- if not dry_run:
76
- try:
77
- with open(ec_path, "w", encoding="utf-8", newline="\n") as f:
78
- f.write(cls.DEFAULT_EDITORCONFIG)
79
- actions.append(
80
- HealAction(
81
- category=DiagnosticCategory.POLYGLOT.value,
82
- action_type="generate_editorconfig",
83
- file_path=str(ec_path),
84
- description="Generated standardized .editorconfig across project",
85
- success=True,
86
- )
87
- )
88
- except Exception as e:
89
- actions.append(
90
- HealAction(
91
- category=DiagnosticCategory.POLYGLOT.value,
92
- action_type="generate_editorconfig",
93
- file_path=str(ec_path),
94
- description=f"Failed to create .editorconfig: {e}",
95
- success=False,
96
- )
97
- )
98
-
99
- return issues, actions
100
-
101
-
102
- class OpenApiSpecLinter:
103
- """Validates OpenAPI 3.0 / 3.1 REST API specification definitions."""
104
-
105
- @classmethod
106
- def lint_openapi_dict(cls, spec: Dict[str, Any], file_path: str) -> List[DiagnosticIssue]:
107
- issues: List[DiagnosticIssue] = []
108
-
109
- # 1. Check openapi version tag
110
- if "openapi" not in spec and "swagger" not in spec:
111
- issues.append(
112
- DiagnosticIssue(
113
- category=DiagnosticCategory.POLYGLOT.value,
114
- severity=SeverityLevel.CRITICAL.value,
115
- file_path=file_path,
116
- error_code="TZ-API-001",
117
- message="Missing 'openapi' or 'swagger' root version field.",
118
- suggested_fix="Specify 'openapi: 3.1.0'.",
119
- auto_fixable=False,
120
- )
121
- )
122
-
123
- # 2. Check info object
124
- info = spec.get("info")
125
- if not isinstance(info, dict):
126
- issues.append(
127
- DiagnosticIssue(
128
- category=DiagnosticCategory.POLYGLOT.value,
129
- severity=SeverityLevel.WARNING.value,
130
- file_path=file_path,
131
- error_code="TZ-API-002",
132
- message="Missing required 'info' object in OpenAPI specification.",
133
- suggested_fix="Provide title, version, and description in 'info' block.",
134
- auto_fixable=False,
135
- )
136
- )
137
- else:
138
- if "title" not in info:
139
- issues.append(
140
- DiagnosticIssue(
141
- category=DiagnosticCategory.POLYGLOT.value,
142
- severity=SeverityLevel.WARNING.value,
143
- file_path=file_path,
144
- error_code="TZ-API-003",
145
- message="Missing 'info.title' in OpenAPI specification.",
146
- suggested_fix="Define API title in info metadata.",
147
- auto_fixable=False,
148
- )
149
- )
150
-
151
- # 3. Check paths
152
- paths = spec.get("paths")
153
- if not isinstance(paths, dict) or not paths:
154
- issues.append(
155
- DiagnosticIssue(
156
- category=DiagnosticCategory.POLYGLOT.value,
157
- severity=SeverityLevel.INFO.value,
158
- file_path=file_path,
159
- error_code="TZ-API-004",
160
- message="OpenAPI specification contains no endpoint 'paths'.",
161
- suggested_fix="Define API route operations under 'paths:'.",
162
- auto_fixable=False,
163
- )
164
- )
165
- else:
166
- op_ids: Set[str] = set()
167
- for path_k, path_item in paths.items():
168
- if isinstance(path_item, dict):
169
- for method in ["get", "post", "put", "delete", "patch"]:
170
- op = path_item.get(method)
171
- if isinstance(op, dict):
172
- op_id = op.get("operationId")
173
- if op_id:
174
- if op_id in op_ids:
175
- issues.append(
176
- DiagnosticIssue(
177
- category=DiagnosticCategory.POLYGLOT.value,
178
- severity=SeverityLevel.WARNING.value,
179
- file_path=file_path,
180
- error_code="TZ-API-005",
181
- message=f"Duplicate operationId '{op_id}' in {method.upper()} {path_k}.",
182
- suggested_fix="Ensure all operationId values are globally unique for code generators.",
183
- auto_fixable=False,
184
- )
185
- )
186
- op_ids.add(op_id)
187
- # Check response definitions
188
- responses = op.get("responses")
189
- if not responses:
190
- issues.append(
191
- DiagnosticIssue(
192
- category=DiagnosticCategory.POLYGLOT.value,
193
- severity=SeverityLevel.WARNING.value,
194
- file_path=file_path,
195
- error_code="TZ-API-006",
196
- message=f"Missing 'responses' table in {method.upper()} {path_k}.",
197
- suggested_fix="Define HTTP status codes (e.g. '200', '400') under responses.",
198
- auto_fixable=False,
199
- )
200
- )
201
-
202
- return issues
203
-
204
-
205
- class PureJsonSchemaValidator:
206
- """
207
- Zero-dependency, offline JSON Schema Draft-07 / 2020-12 validator.
208
- Validates types, required fields, numeric bounds, enums, and regular expressions.
209
- """
210
-
211
- TYPE_MAP = {
212
- "string": str,
213
- "integer": int,
214
- "number": (int, float),
215
- "boolean": bool,
216
- "array": list,
217
- "object": dict,
218
- "null": type(None),
219
- }
220
-
221
- @classmethod
222
- def validate_instance(
223
- cls,
224
- instance: Any,
225
- schema: Dict[str, Any],
226
- path: str = "$",
227
- ) -> List[str]:
228
- """Validates a JSON-like object against schema specifications without external libs."""
229
- errors: List[str] = []
230
-
231
- # 1. Type validation
232
- expected_type = schema.get("type")
233
- if expected_type:
234
- if isinstance(expected_type, str):
235
- expected_types = [expected_type]
236
- else:
237
- expected_types = expected_type
238
-
239
- matched = False
240
- for t_name in expected_types:
241
- py_type = cls.TYPE_MAP.get(t_name)
242
- # bool is subclass of int in Python, handle carefully
243
- if t_name == "integer" and isinstance(instance, bool):
244
- continue
245
- if t_name == "number" and isinstance(instance, bool):
246
- continue
247
- if py_type and isinstance(instance, py_type):
248
- matched = True
249
- break
250
-
251
- if not matched:
252
- errors.append(f"{path}: expected type '{expected_type}', got '{type(instance).__name__}'")
253
- return errors
254
-
255
- # 2. Required properties (for objects)
256
- if isinstance(instance, dict):
257
- required = schema.get("required", [])
258
- for req_field in required:
259
- if req_field not in instance:
260
- errors.append(f"{path}: missing required property '{req_field}'")
261
-
262
- # Property definitions
263
- properties = schema.get("properties", {})
264
- for prop_name, prop_schema in properties.items():
265
- if prop_name in instance:
266
- errors.extend(
267
- cls.validate_instance(instance[prop_name], prop_schema, path=f"{path}.{prop_name}")
268
- )
269
-
270
- # 3. Array items validation
271
- if isinstance(instance, list):
272
- items_schema = schema.get("items")
273
- if isinstance(items_schema, dict):
274
- for idx, elem in enumerate(instance):
275
- errors.extend(cls.validate_instance(elem, items_schema, path=f"{path}[{idx}]"))
276
-
277
- min_items = schema.get("minItems")
278
- if min_items is not None and len(instance) < min_items:
279
- errors.append(f"{path}: array length {len(instance)} is less than minItems {min_items}")
280
-
281
- # 4. Enum validation
282
- enum_values = schema.get("enum")
283
- if enum_values is not None and instance not in enum_values:
284
- errors.append(f"{path}: value '{instance}' not in allowed enum {enum_values}")
285
-
286
- # 5. String length & pattern
287
- if isinstance(instance, str):
288
- min_len = schema.get("minLength")
289
- if min_len is not None and len(instance) < min_len:
290
- errors.append(f"{path}: string length {len(instance)} is shorter than minLength {min_len}")
291
-
292
- pattern = schema.get("pattern")
293
- if pattern and not re.search(pattern, instance):
294
- errors.append(f"{path}: string does not match regex pattern '{pattern}'")
295
-
296
- # 6. Numeric minimum & maximum
297
- if isinstance(instance, (int, float)) and not isinstance(instance, bool):
298
- min_val = schema.get("minimum")
299
- if min_val is not None and instance < min_val:
300
- errors.append(f"{path}: number {instance} is less than minimum {min_val}")
301
- max_val = schema.get("maximum")
302
- if max_val is not None and instance > max_val:
303
- errors.append(f"{path}: number {instance} exceeds maximum {max_val}")
304
-
305
- return errors
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Polyglot Schema Validator, OpenAPI Linter, & EditorConfig Healer
4
+ ======================================================================
5
+ Zero-dependency schema validation and developer environment standardization engine.
6
+ Provides:
7
+ - JSON Schema Draft-07 / 2020-12 validation (types, required, enum, pattern, bounds)
8
+ - OpenAPI 3.0 / 3.1 REST API specification linter (missing paths, non-unique operationIds)
9
+ - GraphQL SDL (Schema Definition Language) parser & syntax auditor
10
+ - .editorconfig specification generator & line-ending LF normalizer
11
+
12
+ Author: Siber Akademi T-Zero R&D Team
13
+ License: MIT (100% Free, Local Offline, Zero-Leak)
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+ from typing import Any, Dict, List, Optional, Set, Tuple
24
+
25
+ from tzero.tzero_fixer.models import (
26
+ DiagnosticCategory,
27
+ DiagnosticIssue,
28
+ DiffHunk,
29
+ HealAction,
30
+ SeverityLevel,
31
+ )
32
+
33
+
34
+ class EditorConfigHealer:
35
+ """Standardizes project .editorconfig files for uniform line endings and indentations."""
36
+
37
+ DEFAULT_EDITORCONFIG = """# EditorConfig is awesome: https://EditorConfig.org
38
+ root = true
39
+
40
+ [*]
41
+ indent_style = space
42
+ indent_size = 4
43
+ end_of_line = lf
44
+ charset = utf-8
45
+ trim_trailing_whitespace = true
46
+ insert_final_newline = true
47
+
48
+ [*.{json,yml,yaml,md,js,ts,jsx,tsx}]
49
+ indent_size = 2
50
+
51
+ [Makefile]
52
+ indent_style = tab
53
+ """
54
+
55
+ @classmethod
56
+ def diagnose_and_heal(cls, workspace_dir: str = ".", dry_run: bool = False) -> Tuple[List[DiagnosticIssue], List[HealAction]]:
57
+ issues: List[DiagnosticIssue] = []
58
+ actions: List[HealAction] = []
59
+ ec_path = Path(workspace_dir) / ".editorconfig"
60
+
61
+ if not ec_path.is_file():
62
+ issues.append(
63
+ DiagnosticIssue(
64
+ category=DiagnosticCategory.POLYGLOT.value,
65
+ severity=SeverityLevel.INFO.value,
66
+ file_path=str(ec_path),
67
+ error_code="TZ-EC-MISSING",
68
+ message="Missing .editorconfig file. Multi-developer formatting and line endings may drift.",
69
+ suggested_fix="Generate standardized multi-language .editorconfig file.",
70
+ auto_fixable=True,
71
+ metadata={"action": "generate_editorconfig", "path": str(ec_path)},
72
+ )
73
+ )
74
+
75
+ if not dry_run:
76
+ try:
77
+ with open(ec_path, "w", encoding="utf-8", newline="\n") as f:
78
+ f.write(cls.DEFAULT_EDITORCONFIG)
79
+ actions.append(
80
+ HealAction(
81
+ category=DiagnosticCategory.POLYGLOT.value,
82
+ action_type="generate_editorconfig",
83
+ file_path=str(ec_path),
84
+ description="Generated standardized .editorconfig across project",
85
+ success=True,
86
+ )
87
+ )
88
+ except Exception as e:
89
+ actions.append(
90
+ HealAction(
91
+ category=DiagnosticCategory.POLYGLOT.value,
92
+ action_type="generate_editorconfig",
93
+ file_path=str(ec_path),
94
+ description=f"Failed to create .editorconfig: {e}",
95
+ success=False,
96
+ )
97
+ )
98
+
99
+ return issues, actions
100
+
101
+
102
+ class OpenApiSpecLinter:
103
+ """Validates OpenAPI 3.0 / 3.1 REST API specification definitions."""
104
+
105
+ @classmethod
106
+ def lint_openapi_dict(cls, spec: Dict[str, Any], file_path: str) -> List[DiagnosticIssue]:
107
+ issues: List[DiagnosticIssue] = []
108
+
109
+ # 1. Check openapi version tag
110
+ if "openapi" not in spec and "swagger" not in spec:
111
+ issues.append(
112
+ DiagnosticIssue(
113
+ category=DiagnosticCategory.POLYGLOT.value,
114
+ severity=SeverityLevel.CRITICAL.value,
115
+ file_path=file_path,
116
+ error_code="TZ-API-001",
117
+ message="Missing 'openapi' or 'swagger' root version field.",
118
+ suggested_fix="Specify 'openapi: 3.1.0'.",
119
+ auto_fixable=False,
120
+ )
121
+ )
122
+
123
+ # 2. Check info object
124
+ info = spec.get("info")
125
+ if not isinstance(info, dict):
126
+ issues.append(
127
+ DiagnosticIssue(
128
+ category=DiagnosticCategory.POLYGLOT.value,
129
+ severity=SeverityLevel.WARNING.value,
130
+ file_path=file_path,
131
+ error_code="TZ-API-002",
132
+ message="Missing required 'info' object in OpenAPI specification.",
133
+ suggested_fix="Provide title, version, and description in 'info' block.",
134
+ auto_fixable=False,
135
+ )
136
+ )
137
+ else:
138
+ if "title" not in info:
139
+ issues.append(
140
+ DiagnosticIssue(
141
+ category=DiagnosticCategory.POLYGLOT.value,
142
+ severity=SeverityLevel.WARNING.value,
143
+ file_path=file_path,
144
+ error_code="TZ-API-003",
145
+ message="Missing 'info.title' in OpenAPI specification.",
146
+ suggested_fix="Define API title in info metadata.",
147
+ auto_fixable=False,
148
+ )
149
+ )
150
+
151
+ # 3. Check paths
152
+ paths = spec.get("paths")
153
+ if not isinstance(paths, dict) or not paths:
154
+ issues.append(
155
+ DiagnosticIssue(
156
+ category=DiagnosticCategory.POLYGLOT.value,
157
+ severity=SeverityLevel.INFO.value,
158
+ file_path=file_path,
159
+ error_code="TZ-API-004",
160
+ message="OpenAPI specification contains no endpoint 'paths'.",
161
+ suggested_fix="Define API route operations under 'paths:'.",
162
+ auto_fixable=False,
163
+ )
164
+ )
165
+ else:
166
+ op_ids: Set[str] = set()
167
+ for path_k, path_item in paths.items():
168
+ if isinstance(path_item, dict):
169
+ for method in ["get", "post", "put", "delete", "patch"]:
170
+ op = path_item.get(method)
171
+ if isinstance(op, dict):
172
+ op_id = op.get("operationId")
173
+ if op_id:
174
+ if op_id in op_ids:
175
+ issues.append(
176
+ DiagnosticIssue(
177
+ category=DiagnosticCategory.POLYGLOT.value,
178
+ severity=SeverityLevel.WARNING.value,
179
+ file_path=file_path,
180
+ error_code="TZ-API-005",
181
+ message=f"Duplicate operationId '{op_id}' in {method.upper()} {path_k}.",
182
+ suggested_fix="Ensure all operationId values are globally unique for code generators.",
183
+ auto_fixable=False,
184
+ )
185
+ )
186
+ op_ids.add(op_id)
187
+ # Check response definitions
188
+ responses = op.get("responses")
189
+ if not responses:
190
+ issues.append(
191
+ DiagnosticIssue(
192
+ category=DiagnosticCategory.POLYGLOT.value,
193
+ severity=SeverityLevel.WARNING.value,
194
+ file_path=file_path,
195
+ error_code="TZ-API-006",
196
+ message=f"Missing 'responses' table in {method.upper()} {path_k}.",
197
+ suggested_fix="Define HTTP status codes (e.g. '200', '400') under responses.",
198
+ auto_fixable=False,
199
+ )
200
+ )
201
+
202
+ return issues
203
+
204
+
205
+ class PureJsonSchemaValidator:
206
+ """
207
+ Zero-dependency, offline JSON Schema Draft-07 / 2020-12 validator.
208
+ Validates types, required fields, numeric bounds, enums, and regular expressions.
209
+ """
210
+
211
+ TYPE_MAP = {
212
+ "string": str,
213
+ "integer": int,
214
+ "number": (int, float),
215
+ "boolean": bool,
216
+ "array": list,
217
+ "object": dict,
218
+ "null": type(None),
219
+ }
220
+
221
+ @classmethod
222
+ def validate_instance(
223
+ cls,
224
+ instance: Any,
225
+ schema: Dict[str, Any],
226
+ path: str = "$",
227
+ ) -> List[str]:
228
+ """Validates a JSON-like object against schema specifications without external libs."""
229
+ errors: List[str] = []
230
+
231
+ # 1. Type validation
232
+ expected_type = schema.get("type")
233
+ if expected_type:
234
+ if isinstance(expected_type, str):
235
+ expected_types = [expected_type]
236
+ else:
237
+ expected_types = expected_type
238
+
239
+ matched = False
240
+ for t_name in expected_types:
241
+ py_type = cls.TYPE_MAP.get(t_name)
242
+ # bool is subclass of int in Python, handle carefully
243
+ if t_name == "integer" and isinstance(instance, bool):
244
+ continue
245
+ if t_name == "number" and isinstance(instance, bool):
246
+ continue
247
+ if py_type and isinstance(instance, py_type):
248
+ matched = True
249
+ break
250
+
251
+ if not matched:
252
+ errors.append(f"{path}: expected type '{expected_type}', got '{type(instance).__name__}'")
253
+ return errors
254
+
255
+ # 2. Required properties (for objects)
256
+ if isinstance(instance, dict):
257
+ required = schema.get("required", [])
258
+ for req_field in required:
259
+ if req_field not in instance:
260
+ errors.append(f"{path}: missing required property '{req_field}'")
261
+
262
+ # Property definitions
263
+ properties = schema.get("properties", {})
264
+ for prop_name, prop_schema in properties.items():
265
+ if prop_name in instance:
266
+ errors.extend(
267
+ cls.validate_instance(instance[prop_name], prop_schema, path=f"{path}.{prop_name}")
268
+ )
269
+
270
+ # 3. Array items validation
271
+ if isinstance(instance, list):
272
+ items_schema = schema.get("items")
273
+ if isinstance(items_schema, dict):
274
+ for idx, elem in enumerate(instance):
275
+ errors.extend(cls.validate_instance(elem, items_schema, path=f"{path}[{idx}]"))
276
+
277
+ min_items = schema.get("minItems")
278
+ if min_items is not None and len(instance) < min_items:
279
+ errors.append(f"{path}: array length {len(instance)} is less than minItems {min_items}")
280
+
281
+ # 4. Enum validation
282
+ enum_values = schema.get("enum")
283
+ if enum_values is not None and instance not in enum_values:
284
+ errors.append(f"{path}: value '{instance}' not in allowed enum {enum_values}")
285
+
286
+ # 5. String length & pattern
287
+ if isinstance(instance, str):
288
+ min_len = schema.get("minLength")
289
+ if min_len is not None and len(instance) < min_len:
290
+ errors.append(f"{path}: string length {len(instance)} is shorter than minLength {min_len}")
291
+
292
+ pattern = schema.get("pattern")
293
+ if pattern and not re.search(pattern, instance):
294
+ errors.append(f"{path}: string does not match regex pattern '{pattern}'")
295
+
296
+ # 6. Numeric minimum & maximum
297
+ if isinstance(instance, (int, float)) and not isinstance(instance, bool):
298
+ min_val = schema.get("minimum")
299
+ if min_val is not None and instance < min_val:
300
+ errors.append(f"{path}: number {instance} is less than minimum {min_val}")
301
+ max_val = schema.get("maximum")
302
+ if max_val is not None and instance > max_val:
303
+ errors.append(f"{path}: number {instance} exceeds maximum {max_val}")
304
+
305
+ return errors