tzero-mcp 10.7.4 → 11.0.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 (127) hide show
  1. package/CHANGELOG.md +56 -29
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -66
  5. package/bin/tzero.js +61 -65
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -88
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -43
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -1,274 +1,274 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Siber Akademi — T-Zero Infrastructure & Database Schema AST Compressor.
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- License: MIT
6
-
7
- Extracts high-value architectural contracts from SQL DDL, Kubernetes YAML,
8
- Dockerfiles, and Terraform HCL, achieving 75% to 95% token reduction on
9
- infrastructure and database artifacts without semantic loss.
10
- """
11
-
12
- import sys
13
- if sys.platform == "win32":
14
- try:
15
- sys.stdout.reconfigure(encoding="utf-8")
16
- sys.stderr.reconfigure(encoding="utf-8")
17
- except Exception:
18
- pass
19
-
20
- import re
21
- from typing import Tuple, List, Dict, Any
22
-
23
-
24
- class SchemaInfraReducer:
25
- """AST & Structural heuristic compressor for SQL, Kubernetes, Dockerfile, and Terraform."""
26
-
27
- # --------------------------------------------------------------------------
28
- # 1. SQL DDL SCHEMA COMPRESSOR
29
- # --------------------------------------------------------------------------
30
- @staticmethod
31
- def reduce_sql(content: str, mode: str = "ultra") -> Tuple[str, float]:
32
- """Compresses SQL DDL/DML into pure schema contracts.
33
-
34
- Strips huge INSERT INTO statements, runtime log statements, and comments.
35
- Retains: CREATE TABLE, CREATE VIEW, CREATE TYPE, ALTER TABLE ADD CONSTRAINT, CREATE INDEX.
36
- """
37
- orig_len = len(content)
38
- if orig_len < 100:
39
- return content, 0.0
40
-
41
- # Strip single line and multi-line comments
42
- no_comments = re.sub(r"--.*?$", "", content, flags=re.MULTILINE)
43
- no_comments = re.sub(r"/\*.*?\*/", "", no_comments, flags=re.DOTALL)
44
-
45
- # Match CREATE TABLE blocks
46
- table_pattern = re.compile(r"CREATE\s+(?:TEMP\s+|TEMPORARY\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s(]+)\s*\((.*?)\);", re.IGNORECASE | re.DOTALL)
47
- # Match CREATE VIEW / TYPE
48
- view_pattern = re.compile(r"CREATE\s+(?:OR\s+REPLACE\s+)?VIEW\s+([^\s(]+)\s+AS\s+(.*?);", re.IGNORECASE | re.DOTALL)
49
- type_pattern = re.compile(r"CREATE\s+TYPE\s+([^\s(]+)\s+AS\s+(?:ENUM\s*)?\((.*?)\);", re.IGNORECASE | re.DOTALL)
50
- index_pattern = re.compile(r"CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s]+)\s+ON\s+([^\s(]+)\s*\((.*?)\);", re.IGNORECASE)
51
- fk_pattern = re.compile(r"ALTER\s+TABLE\s+(?:ONLY\s+)?([^\s]+)\s+ADD\s+CONSTRAINT\s+([^\s]+)\s+FOREIGN\s+KEY\s*\((.*?)\)\s*REFERENCES\s+([^\s(]+)\s*\((.*?)\);", re.IGNORECASE)
52
-
53
- output_blocks = []
54
-
55
- # 1. Custom Types / Enums
56
- types_found = list(type_pattern.finditer(no_comments))
57
- if types_found:
58
- output_blocks.append("-- [T-Zero AST Schema Types]")
59
- for m in types_found:
60
- name = m.group(1).strip()
61
- vals = re.sub(r"\s+", " ", m.group(2)).strip()
62
- output_blocks.append(f"CREATE TYPE {name} AS ({vals});")
63
- output_blocks.append("")
64
-
65
- # 2. Tables & Columns
66
- tables_found = list(table_pattern.finditer(no_comments))
67
- if tables_found:
68
- output_blocks.append("-- [T-Zero AST Schema Tables]")
69
- for m in tables_found:
70
- tname = m.group(1).strip()
71
- raw_cols = m.group(2)
72
-
73
- # Parse individual column/constraint definitions
74
- col_defs = []
75
- # Split by commas not inside parentheses
76
- lines = [c.strip() for c in re.split(r",\s*(?![^()]*\))", raw_cols) if c.strip()]
77
- for col in lines:
78
- col_clean = re.sub(r"\s+", " ", col)
79
- if mode == "ultra":
80
- # Ultra mode: keep Column Name + Type + Primary/Unique/Not Null/References
81
- col_clean = re.sub(r"(?i)\s+DEFAULT\s+[^,]+", "", col_clean)
82
- col_clean = re.sub(r"(?i)\s*(?:CONSTRAINT\s+[^\s]+\s+)?CHECK\s*\(.*?\)", "", col_clean)
83
- if col_clean.strip():
84
- col_defs.append(f" {col_clean.strip()}")
85
-
86
- output_blocks.append(f"CREATE TABLE {tname} (\n" + ",\n".join(col_defs) + "\n);")
87
- output_blocks.append("")
88
-
89
- # 3. Foreign Keys / Relationships
90
- fks_found = list(fk_pattern.finditer(no_comments))
91
- if fks_found:
92
- output_blocks.append("-- [T-Zero AST Foreign Keys & Boundaries]")
93
- for m in fks_found:
94
- tbl = m.group(1).strip()
95
- cname = m.group(2).strip()
96
- src_cols = m.group(3).strip()
97
- ref_tbl = m.group(4).strip()
98
- ref_cols = m.group(5).strip()
99
- output_blocks.append(f"ALTER TABLE {tbl} ADD CONSTRAINT {cname} FOREIGN KEY ({src_cols}) REFERENCES {ref_tbl}({ref_cols});")
100
- output_blocks.append("")
101
-
102
- # 4. Indexes
103
- idx_found = list(index_pattern.finditer(no_comments))
104
- if idx_found and mode != "ultra":
105
- output_blocks.append("-- [T-Zero AST Indexes]")
106
- for m in idx_found:
107
- iname = m.group(1).strip()
108
- on_tbl = m.group(2).strip()
109
- icols = m.group(3).strip()
110
- output_blocks.append(f"CREATE INDEX {iname} ON {on_tbl} ({icols});")
111
- output_blocks.append("")
112
-
113
- res = "\n".join(output_blocks).strip()
114
- if not res:
115
- # Fallback if raw queries without explicit CREATE TABLE
116
- lines = [l.strip() for l in no_comments.splitlines() if l.strip() and not l.strip().upper().startswith(("INSERT INTO", "COPY "))]
117
- res = "\n".join(lines[:120])
118
-
119
- savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
120
- return res, savings
121
-
122
- # --------------------------------------------------------------------------
123
- # 2. KUBERNETES MANIFEST & YAML COMPRESSOR
124
- # --------------------------------------------------------------------------
125
- @staticmethod
126
- def reduce_k8s_yaml(content: str, mode: str = "ultra") -> Tuple[str, float]:
127
- """Compresses Kubernetes YAML manifests down to architectural interfaces."""
128
- orig_len = len(content)
129
- if orig_len < 80:
130
- return content, 0.0
131
-
132
- docs = re.split(r"^---\s*$", content, flags=re.MULTILINE)
133
- reduced_docs = []
134
-
135
- for doc in docs:
136
- doc_str = doc.strip()
137
- if not doc_str:
138
- continue
139
-
140
- lines = doc_str.splitlines()
141
- retained_lines = []
142
- skip_section = False
143
- skip_indent = 0
144
-
145
- for line in lines:
146
- raw_indent = len(line) - len(line.lstrip())
147
- stripped = line.strip()
148
-
149
- # Skip kubectl / runtime status bloat
150
- if re.match(r"^(status|managedFields|annotations):", stripped):
151
- skip_section = True
152
- skip_indent = raw_indent
153
- continue
154
-
155
- if skip_section:
156
- if raw_indent > skip_indent:
157
- continue
158
- else:
159
- skip_section = False
160
-
161
- # Keep structural keys
162
- if any(stripped.startswith(k) for k in [
163
- "apiVersion:", "kind:", "name:", "namespace:", "replicas:",
164
- "containers:", "- name:", "image:", "containerPort:", "port:",
165
- "targetPort:", "protocol:", "serviceAccountName:", "type:",
166
- "claimName:", "mountPath:", "host:", "path:", "service:"
167
- ]):
168
- retained_lines.append(line)
169
- elif mode == "balanced" and raw_indent <= 4 and ":" in stripped:
170
- retained_lines.append(line)
171
-
172
- if retained_lines:
173
- reduced_docs.append("\n".join(retained_lines))
174
-
175
- res = "\n---\n".join(reduced_docs)
176
- if not res.strip():
177
- res = content[:300]
178
-
179
- savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
180
- return res, savings
181
-
182
- # --------------------------------------------------------------------------
183
- # 3. DOCKERFILE COMPRESSOR
184
- # --------------------------------------------------------------------------
185
- @staticmethod
186
- def reduce_dockerfile(content: str, mode: str = "ultra") -> Tuple[str, float]:
187
- """Condenses Dockerfiles into clean build stage architectures."""
188
- orig_len = len(content)
189
- lines = content.splitlines()
190
- pruned = []
191
-
192
- in_multiline_run = False
193
- for line in lines:
194
- s = line.strip()
195
- if not s or s.startswith("#"):
196
- continue
197
-
198
- if in_multiline_run:
199
- if s.endswith("\\"):
200
- continue
201
- else:
202
- in_multiline_run = False
203
- continue
204
-
205
- if s.startswith(("FROM ", "EXPOSE ", "ENTRYPOINT ", "CMD ", "ENV ", "WORKDIR ", "ARG ", "HEALTHCHECK ")):
206
- pruned.append(s)
207
- elif s.startswith("COPY "):
208
- pruned.append(re.sub(r"\s+", " ", s))
209
- elif s.startswith("RUN "):
210
- if s.endswith("\\"):
211
- in_multiline_run = True
212
- pruned.append(f"RUN [build dependencies & binary install]")
213
- else:
214
- pruned.append(s[:70] + ("..." if len(s) > 70 else ""))
215
-
216
- res = "\n".join(pruned)
217
- savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
218
- return res, savings
219
-
220
- # --------------------------------------------------------------------------
221
- # 4. TERRAFORM / HCL COMPRESSOR
222
- # --------------------------------------------------------------------------
223
- @staticmethod
224
- def reduce_terraform(content: str, mode: str = "ultra") -> Tuple[str, float]:
225
- """Condenses Terraform HCL into infrastructure topology contracts."""
226
- orig_len = len(content)
227
- block_pattern = re.compile(
228
- r'((?:resource|data|module|variable|output|provider|terraform)(?:\s+["\w_-]+){0,2})\s*\{(.*?)\n[ \t]*\}',
229
- re.DOTALL
230
- )
231
-
232
- matches = list(block_pattern.finditer(content))
233
- if not matches:
234
- return content, 0.0
235
-
236
- pruned_blocks = []
237
- for m in matches:
238
- header = m.group(1).strip()
239
- body = m.group(2)
240
-
241
- key_lines = []
242
- for line in body.splitlines():
243
- s = line.strip()
244
- if not s or s.startswith("#") or s.startswith("//"):
245
- continue
246
- if "=" in s or "{" in s:
247
- k = s.split("=")[0].strip()
248
- if any(req in k for req in ["type", "default", "description", "source", "version", "name", "id", "ami", "instance_type"]):
249
- key_lines.append(f" {s}")
250
-
251
- if key_lines:
252
- pruned_blocks.append(f"{header} {{\n" + "\n".join(key_lines) + "\n}")
253
- else:
254
- pruned_blocks.append(f"{header} {{ ... }}")
255
-
256
- res = "\n\n".join(pruned_blocks)
257
- savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
258
- return res, savings
259
-
260
- # --------------------------------------------------------------------------
261
- # UNIVERSAL DISPATCHER
262
- # --------------------------------------------------------------------------
263
- @classmethod
264
- def reduce(cls, filename_or_ext: str, content: str, mode: str = "ultra") -> Tuple[str, float]:
265
- f = filename_or_ext.lower()
266
- if f.endswith(".sql"):
267
- return cls.reduce_sql(content, mode)
268
- elif f.endswith((".yaml", ".yml")):
269
- return cls.reduce_k8s_yaml(content, mode)
270
- elif "dockerfile" in f:
271
- return cls.reduce_dockerfile(content, mode)
272
- elif f.endswith((".tf", ".hcl")):
273
- return cls.reduce_terraform(content, mode)
274
- return content, 0.0
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Siber Akademi — T-Zero Infrastructure & Database Schema AST Compressor.
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ License: MIT
6
+
7
+ Extracts high-value architectural contracts from SQL DDL, Kubernetes YAML,
8
+ Dockerfiles, and Terraform HCL, achieving 75% to 95% token reduction on
9
+ infrastructure and database artifacts without semantic loss.
10
+ """
11
+
12
+ import sys
13
+ if sys.platform == "win32":
14
+ try:
15
+ sys.stdout.reconfigure(encoding="utf-8")
16
+ sys.stderr.reconfigure(encoding="utf-8")
17
+ except Exception:
18
+ pass
19
+
20
+ import re
21
+ from typing import Tuple, List, Dict, Any
22
+
23
+
24
+ class SchemaInfraReducer:
25
+ """AST & Structural heuristic compressor for SQL, Kubernetes, Dockerfile, and Terraform."""
26
+
27
+ # --------------------------------------------------------------------------
28
+ # 1. SQL DDL SCHEMA COMPRESSOR
29
+ # --------------------------------------------------------------------------
30
+ @staticmethod
31
+ def reduce_sql(content: str, mode: str = "ultra") -> Tuple[str, float]:
32
+ """Compresses SQL DDL/DML into pure schema contracts.
33
+
34
+ Strips huge INSERT INTO statements, runtime log statements, and comments.
35
+ Retains: CREATE TABLE, CREATE VIEW, CREATE TYPE, ALTER TABLE ADD CONSTRAINT, CREATE INDEX.
36
+ """
37
+ orig_len = len(content)
38
+ if orig_len < 100:
39
+ return content, 0.0
40
+
41
+ # Strip single line and multi-line comments
42
+ no_comments = re.sub(r"--.*?$", "", content, flags=re.MULTILINE)
43
+ no_comments = re.sub(r"/\*.*?\*/", "", no_comments, flags=re.DOTALL)
44
+
45
+ # Match CREATE TABLE blocks
46
+ table_pattern = re.compile(r"CREATE\s+(?:TEMP\s+|TEMPORARY\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s(]+)\s*\((.*?)\);", re.IGNORECASE | re.DOTALL)
47
+ # Match CREATE VIEW / TYPE
48
+ view_pattern = re.compile(r"CREATE\s+(?:OR\s+REPLACE\s+)?VIEW\s+([^\s(]+)\s+AS\s+(.*?);", re.IGNORECASE | re.DOTALL)
49
+ type_pattern = re.compile(r"CREATE\s+TYPE\s+([^\s(]+)\s+AS\s+(?:ENUM\s*)?\((.*?)\);", re.IGNORECASE | re.DOTALL)
50
+ index_pattern = re.compile(r"CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s]+)\s+ON\s+([^\s(]+)\s*\((.*?)\);", re.IGNORECASE)
51
+ fk_pattern = re.compile(r"ALTER\s+TABLE\s+(?:ONLY\s+)?([^\s]+)\s+ADD\s+CONSTRAINT\s+([^\s]+)\s+FOREIGN\s+KEY\s*\((.*?)\)\s*REFERENCES\s+([^\s(]+)\s*\((.*?)\);", re.IGNORECASE)
52
+
53
+ output_blocks = []
54
+
55
+ # 1. Custom Types / Enums
56
+ types_found = list(type_pattern.finditer(no_comments))
57
+ if types_found:
58
+ output_blocks.append("-- [T-Zero AST Schema Types]")
59
+ for m in types_found:
60
+ name = m.group(1).strip()
61
+ vals = re.sub(r"\s+", " ", m.group(2)).strip()
62
+ output_blocks.append(f"CREATE TYPE {name} AS ({vals});")
63
+ output_blocks.append("")
64
+
65
+ # 2. Tables & Columns
66
+ tables_found = list(table_pattern.finditer(no_comments))
67
+ if tables_found:
68
+ output_blocks.append("-- [T-Zero AST Schema Tables]")
69
+ for m in tables_found:
70
+ tname = m.group(1).strip()
71
+ raw_cols = m.group(2)
72
+
73
+ # Parse individual column/constraint definitions
74
+ col_defs = []
75
+ # Split by commas not inside parentheses
76
+ lines = [c.strip() for c in re.split(r",\s*(?![^()]*\))", raw_cols) if c.strip()]
77
+ for col in lines:
78
+ col_clean = re.sub(r"\s+", " ", col)
79
+ if mode == "ultra":
80
+ # Ultra mode: keep Column Name + Type + Primary/Unique/Not Null/References
81
+ col_clean = re.sub(r"(?i)\s+DEFAULT\s+[^,]+", "", col_clean)
82
+ col_clean = re.sub(r"(?i)\s*(?:CONSTRAINT\s+[^\s]+\s+)?CHECK\s*\(.*?\)", "", col_clean)
83
+ if col_clean.strip():
84
+ col_defs.append(f" {col_clean.strip()}")
85
+
86
+ output_blocks.append(f"CREATE TABLE {tname} (\n" + ",\n".join(col_defs) + "\n);")
87
+ output_blocks.append("")
88
+
89
+ # 3. Foreign Keys / Relationships
90
+ fks_found = list(fk_pattern.finditer(no_comments))
91
+ if fks_found:
92
+ output_blocks.append("-- [T-Zero AST Foreign Keys & Boundaries]")
93
+ for m in fks_found:
94
+ tbl = m.group(1).strip()
95
+ cname = m.group(2).strip()
96
+ src_cols = m.group(3).strip()
97
+ ref_tbl = m.group(4).strip()
98
+ ref_cols = m.group(5).strip()
99
+ output_blocks.append(f"ALTER TABLE {tbl} ADD CONSTRAINT {cname} FOREIGN KEY ({src_cols}) REFERENCES {ref_tbl}({ref_cols});")
100
+ output_blocks.append("")
101
+
102
+ # 4. Indexes
103
+ idx_found = list(index_pattern.finditer(no_comments))
104
+ if idx_found and mode != "ultra":
105
+ output_blocks.append("-- [T-Zero AST Indexes]")
106
+ for m in idx_found:
107
+ iname = m.group(1).strip()
108
+ on_tbl = m.group(2).strip()
109
+ icols = m.group(3).strip()
110
+ output_blocks.append(f"CREATE INDEX {iname} ON {on_tbl} ({icols});")
111
+ output_blocks.append("")
112
+
113
+ res = "\n".join(output_blocks).strip()
114
+ if not res:
115
+ # Fallback if raw queries without explicit CREATE TABLE
116
+ lines = [l.strip() for l in no_comments.splitlines() if l.strip() and not l.strip().upper().startswith(("INSERT INTO", "COPY "))]
117
+ res = "\n".join(lines[:120])
118
+
119
+ savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
120
+ return res, savings
121
+
122
+ # --------------------------------------------------------------------------
123
+ # 2. KUBERNETES MANIFEST & YAML COMPRESSOR
124
+ # --------------------------------------------------------------------------
125
+ @staticmethod
126
+ def reduce_k8s_yaml(content: str, mode: str = "ultra") -> Tuple[str, float]:
127
+ """Compresses Kubernetes YAML manifests down to architectural interfaces."""
128
+ orig_len = len(content)
129
+ if orig_len < 80:
130
+ return content, 0.0
131
+
132
+ docs = re.split(r"^---\s*$", content, flags=re.MULTILINE)
133
+ reduced_docs = []
134
+
135
+ for doc in docs:
136
+ doc_str = doc.strip()
137
+ if not doc_str:
138
+ continue
139
+
140
+ lines = doc_str.splitlines()
141
+ retained_lines = []
142
+ skip_section = False
143
+ skip_indent = 0
144
+
145
+ for line in lines:
146
+ raw_indent = len(line) - len(line.lstrip())
147
+ stripped = line.strip()
148
+
149
+ # Skip kubectl / runtime status bloat
150
+ if re.match(r"^(status|managedFields|annotations):", stripped):
151
+ skip_section = True
152
+ skip_indent = raw_indent
153
+ continue
154
+
155
+ if skip_section:
156
+ if raw_indent > skip_indent:
157
+ continue
158
+ else:
159
+ skip_section = False
160
+
161
+ # Keep structural keys
162
+ if any(stripped.startswith(k) for k in [
163
+ "apiVersion:", "kind:", "name:", "namespace:", "replicas:",
164
+ "containers:", "- name:", "image:", "containerPort:", "port:",
165
+ "targetPort:", "protocol:", "serviceAccountName:", "type:",
166
+ "claimName:", "mountPath:", "host:", "path:", "service:"
167
+ ]):
168
+ retained_lines.append(line)
169
+ elif mode == "balanced" and raw_indent <= 4 and ":" in stripped:
170
+ retained_lines.append(line)
171
+
172
+ if retained_lines:
173
+ reduced_docs.append("\n".join(retained_lines))
174
+
175
+ res = "\n---\n".join(reduced_docs)
176
+ if not res.strip():
177
+ res = content[:300]
178
+
179
+ savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
180
+ return res, savings
181
+
182
+ # --------------------------------------------------------------------------
183
+ # 3. DOCKERFILE COMPRESSOR
184
+ # --------------------------------------------------------------------------
185
+ @staticmethod
186
+ def reduce_dockerfile(content: str, mode: str = "ultra") -> Tuple[str, float]:
187
+ """Condenses Dockerfiles into clean build stage architectures."""
188
+ orig_len = len(content)
189
+ lines = content.splitlines()
190
+ pruned = []
191
+
192
+ in_multiline_run = False
193
+ for line in lines:
194
+ s = line.strip()
195
+ if not s or s.startswith("#"):
196
+ continue
197
+
198
+ if in_multiline_run:
199
+ if s.endswith("\\"):
200
+ continue
201
+ else:
202
+ in_multiline_run = False
203
+ continue
204
+
205
+ if s.startswith(("FROM ", "EXPOSE ", "ENTRYPOINT ", "CMD ", "ENV ", "WORKDIR ", "ARG ", "HEALTHCHECK ")):
206
+ pruned.append(s)
207
+ elif s.startswith("COPY "):
208
+ pruned.append(re.sub(r"\s+", " ", s))
209
+ elif s.startswith("RUN "):
210
+ if s.endswith("\\"):
211
+ in_multiline_run = True
212
+ pruned.append(f"RUN [build dependencies & binary install]")
213
+ else:
214
+ pruned.append(s[:70] + ("..." if len(s) > 70 else ""))
215
+
216
+ res = "\n".join(pruned)
217
+ savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
218
+ return res, savings
219
+
220
+ # --------------------------------------------------------------------------
221
+ # 4. TERRAFORM / HCL COMPRESSOR
222
+ # --------------------------------------------------------------------------
223
+ @staticmethod
224
+ def reduce_terraform(content: str, mode: str = "ultra") -> Tuple[str, float]:
225
+ """Condenses Terraform HCL into infrastructure topology contracts."""
226
+ orig_len = len(content)
227
+ block_pattern = re.compile(
228
+ r'((?:resource|data|module|variable|output|provider|terraform)(?:\s+["\w_-]+){0,2})\s*\{(.*?)\n[ \t]*\}',
229
+ re.DOTALL
230
+ )
231
+
232
+ matches = list(block_pattern.finditer(content))
233
+ if not matches:
234
+ return content, 0.0
235
+
236
+ pruned_blocks = []
237
+ for m in matches:
238
+ header = m.group(1).strip()
239
+ body = m.group(2)
240
+
241
+ key_lines = []
242
+ for line in body.splitlines():
243
+ s = line.strip()
244
+ if not s or s.startswith("#") or s.startswith("//"):
245
+ continue
246
+ if "=" in s or "{" in s:
247
+ k = s.split("=")[0].strip()
248
+ if any(req in k for req in ["type", "default", "description", "source", "version", "name", "id", "ami", "instance_type"]):
249
+ key_lines.append(f" {s}")
250
+
251
+ if key_lines:
252
+ pruned_blocks.append(f"{header} {{\n" + "\n".join(key_lines) + "\n}")
253
+ else:
254
+ pruned_blocks.append(f"{header} {{ ... }}")
255
+
256
+ res = "\n\n".join(pruned_blocks)
257
+ savings = max(0.0, ((orig_len - len(res)) / max(orig_len, 1)) * 100.0)
258
+ return res, savings
259
+
260
+ # --------------------------------------------------------------------------
261
+ # UNIVERSAL DISPATCHER
262
+ # --------------------------------------------------------------------------
263
+ @classmethod
264
+ def reduce(cls, filename_or_ext: str, content: str, mode: str = "ultra") -> Tuple[str, float]:
265
+ f = filename_or_ext.lower()
266
+ if f.endswith(".sql"):
267
+ return cls.reduce_sql(content, mode)
268
+ elif f.endswith((".yaml", ".yml")):
269
+ return cls.reduce_k8s_yaml(content, mode)
270
+ elif "dockerfile" in f:
271
+ return cls.reduce_dockerfile(content, mode)
272
+ elif f.endswith((".tf", ".hcl")):
273
+ return cls.reduce_terraform(content, mode)
274
+ return content, 0.0