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
@@ -0,0 +1,799 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Siber Akademi T-Zero — Universal Polyglot AST Engine.
3
+
4
+ Provides zero-dependency, deterministic structural parsing and signature extraction
5
+ for Python, TypeScript/JavaScript, Rust, Go, C/C++, Java/C#, and Solidity.
6
+ Prunes function/method bodies, loops, and implementation details down to signatures,
7
+ interfaces, structs, and declarations with up to 95% context token reduction.
8
+
9
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
10
+ License: MIT
11
+ """
12
+
13
+ import ast
14
+ import re
15
+ from contextvars import ContextVar
16
+ from typing import Any, Callable, Dict, List, Tuple, Optional
17
+
18
+
19
+ _BPE_ENCODING_CACHE: Dict[str, Any] = {}
20
+ _ALLOW_BPE_DOWNLOAD = ContextVar("allow_bpe_download", default=True)
21
+
22
+
23
+ def count_bpe_tokens(text: str, model_name: str = "gpt-4o", fallback_divisor: float = 4.0) -> int:
24
+ """Count tokens using cached local tiktoken BPE encodings with deterministic fallback."""
25
+ if not text:
26
+ return 0
27
+ try:
28
+ import tiktoken
29
+ lower_m = (model_name or "gpt-4o").lower()
30
+ if any(k in lower_m for k in ("gpt-4o", "o1", "o3", "o4", "gpt-5", "gemini", "deepseek")):
31
+ enc_name = "o200k_base"
32
+ elif any(k in lower_m for k in ("claude", "gpt-4", "gpt-3.5", "llama", "mistral", "qwen")):
33
+ enc_name = "cl100k_base"
34
+ else:
35
+ enc_name = "o200k_base"
36
+ enc = _BPE_ENCODING_CACHE.get(enc_name)
37
+ if enc is None:
38
+ if not _ALLOW_BPE_DOWNLOAD.get():
39
+ return max(1, int(len(text) / fallback_divisor))
40
+ enc = tiktoken.get_encoding(enc_name)
41
+ _BPE_ENCODING_CACHE[enc_name] = enc
42
+ return max(1, len(enc.encode(text, disallowed_special=())))
43
+ except Exception:
44
+ return max(1, int(len(text) / fallback_divisor))
45
+
46
+
47
+ class PolyglotTokenReducer:
48
+ """Universal multi-language structural signature extractor."""
49
+
50
+ SUPPORTED_LANGUAGES = {
51
+ "python": [".py", ".pyw"],
52
+ "javascript": [".js", ".jsx", ".mjs", ".cjs"],
53
+ "typescript": [".ts", ".tsx"],
54
+ "rust": [".rs"],
55
+ "go": [".go"],
56
+ "cpp": [".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"],
57
+ "java": [".java", ".cs"],
58
+ "solidity": [".sol"],
59
+ "ruby": [".rb", ".rake", ".gemspec"],
60
+ "php": [".php", ".phtml"],
61
+ "swift": [".swift"],
62
+ "kotlin": [".kt", ".kts"],
63
+ "dart": [".dart"],
64
+ "scala": [".scala", ".sc"],
65
+ "elixir": [".ex", ".exs"]
66
+ }
67
+
68
+ _TREE_SITTER_ADAPTERS: Dict[str, Callable[[str, str, str], str]] = {}
69
+
70
+ @classmethod
71
+ def has_tree_sitter(cls) -> bool:
72
+ """Returns True if optional tree-sitter library or any custom adapter is registered."""
73
+ if cls._TREE_SITTER_ADAPTERS:
74
+ return True
75
+ try:
76
+ import importlib.util
77
+ return importlib.util.find_spec("tree_sitter") is not None
78
+ except Exception:
79
+ return False
80
+
81
+ @classmethod
82
+ def register_tree_sitter_adapter(
83
+ cls,
84
+ lang: str,
85
+ adapter: Optional[Callable[[str, str, str], str]],
86
+ ) -> None:
87
+ """Registers or clears an optional tree-sitter reducer adapter for a language."""
88
+ key = (lang or "").lower()
89
+ if adapter is None:
90
+ cls._TREE_SITTER_ADAPTERS.pop(key, None)
91
+ else:
92
+ cls._TREE_SITTER_ADAPTERS[key] = adapter
93
+
94
+ @staticmethod
95
+ def _lexical_scan_lines(content: str) -> List[Tuple[str, int, int, int, int, bool]]:
96
+ """Scans lines ignoring strings (' \" `) and comments (// /* */) for brace/paren counts."""
97
+ lines = content.splitlines()
98
+ results: List[Tuple[str, int, int, int, int, bool]] = []
99
+ in_block_comment = False
100
+
101
+ for line in lines:
102
+ open_b = 0
103
+ close_b = 0
104
+ open_p = 0
105
+ close_p = 0
106
+ has_code_token = False
107
+ quote_char: Optional[str] = None
108
+ i = 0
109
+ n = len(line)
110
+
111
+ while i < n:
112
+ ch = line[i]
113
+ nxt = line[i + 1] if i + 1 < n else ""
114
+
115
+ if in_block_comment:
116
+ if ch == "*" and nxt == "/":
117
+ in_block_comment = False
118
+ i += 2
119
+ continue
120
+ i += 1
121
+ continue
122
+
123
+ if quote_char:
124
+ has_code_token = True
125
+ if ch == "\\":
126
+ i += 2
127
+ continue
128
+ if ch == quote_char:
129
+ quote_char = None
130
+ i += 1
131
+ continue
132
+
133
+ if ch == "/" and nxt == "/":
134
+ break
135
+ if ch == "/" and nxt == "*":
136
+ in_block_comment = True
137
+ i += 2
138
+ continue
139
+ if ch in ('"', "'", "`"):
140
+ has_code_token = True
141
+ quote_char = ch
142
+ i += 1
143
+ continue
144
+
145
+ if not ch.isspace():
146
+ has_code_token = True
147
+ if ch == "{":
148
+ open_b += 1
149
+ elif ch == "}":
150
+ close_b += 1
151
+ elif ch == "(":
152
+ open_p += 1
153
+ elif ch == ")":
154
+ close_p += 1
155
+ i += 1
156
+
157
+ results.append((line, open_b, close_b, open_p, close_p, not has_code_token))
158
+ return results
159
+
160
+ @classmethod
161
+ def chunk_code(
162
+ cls,
163
+ content: str,
164
+ filename: str = "",
165
+ max_chunk_tokens: int = 400,
166
+ ) -> List[str]:
167
+ """cAST-style semantic boundary chunker splitting only along AST/block boundaries."""
168
+ if not content or not content.strip():
169
+ return []
170
+ lang = cls.detect_language(filename) or ""
171
+ blocks: List[str] = []
172
+
173
+ if lang == "python":
174
+ try:
175
+ tree = ast.parse(content)
176
+ lines = content.splitlines()
177
+ prev_end = 0
178
+ for node in tree.body:
179
+ start = max(prev_end, getattr(node, "lineno", 1) - 1)
180
+ end = getattr(node, "end_lineno", start + 1)
181
+ if start > prev_end:
182
+ gap = "\n".join(lines[prev_end:start]).strip()
183
+ if gap:
184
+ blocks.append(gap)
185
+ blocks.append("\n".join(lines[start:end]))
186
+ prev_end = end
187
+ if prev_end < len(lines):
188
+ tail = "\n".join(lines[prev_end:]).strip()
189
+ if tail:
190
+ blocks.append(tail)
191
+ except SyntaxError:
192
+ blocks = []
193
+
194
+ if not blocks:
195
+ scanned = cls._lexical_scan_lines(content)
196
+ cur_lines: List[str] = []
197
+ depth = 0
198
+ for raw_line, ob, cb, _, _, _ in scanned:
199
+ cur_lines.append(raw_line)
200
+ depth = max(0, depth + ob - cb)
201
+ if depth == 0 and raw_line.strip():
202
+ if ob > 0 or cb > 0 or raw_line.strip().endswith(";"):
203
+ blocks.append("\n".join(cur_lines))
204
+ cur_lines = []
205
+ if cur_lines:
206
+ tail_blk = "\n".join(cur_lines).strip()
207
+ if tail_blk:
208
+ blocks.append(tail_blk)
209
+
210
+ if not blocks:
211
+ return [content]
212
+
213
+ chunks: List[str] = []
214
+ active: List[str] = []
215
+ active_tokens = 0
216
+ for blk in blocks:
217
+ blk_tok = count_bpe_tokens(blk)
218
+ if active and active_tokens + blk_tok > max_chunk_tokens:
219
+ chunks.append("\n\n".join(active))
220
+ active = [blk]
221
+ active_tokens = blk_tok
222
+ else:
223
+ active.append(blk)
224
+ active_tokens += blk_tok
225
+ if active:
226
+ chunks.append("\n\n".join(active))
227
+ return chunks
228
+
229
+ @classmethod
230
+ def detect_language(cls, filename: str) -> Optional[str]:
231
+ """Detect language from filename extension."""
232
+ ext = "." + filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
233
+ for lang, exts in cls.SUPPORTED_LANGUAGES.items():
234
+ if ext in exts:
235
+ return lang
236
+ return None
237
+
238
+ @staticmethod
239
+ def _attach_light_doc_comments(content: str, reduced: str) -> str:
240
+ """Preserves preceding doc-comments (/**, ///, #!) alongside declarations for T-2 light mode."""
241
+ src_lines = content.splitlines()
242
+ doc_by_decl: Dict[str, List[str]] = {}
243
+ pending_docs: List[str] = []
244
+ in_doc_block = False
245
+
246
+ for line in src_lines:
247
+ s = line.strip()
248
+ if not s:
249
+ if not in_doc_block:
250
+ pending_docs = []
251
+ continue
252
+ if s.startswith("/**") or s.startswith("/*"):
253
+ pending_docs.append(line)
254
+ if "*/" not in s[2:]:
255
+ in_doc_block = True
256
+ continue
257
+ if in_doc_block:
258
+ pending_docs.append(line)
259
+ if "*/" in s:
260
+ in_doc_block = False
261
+ continue
262
+ if s.startswith("///") or s.startswith("//!"):
263
+ pending_docs.append(line)
264
+ continue
265
+ if pending_docs:
266
+ doc_by_decl.setdefault(s, list(pending_docs))
267
+ pending_docs = []
268
+
269
+ if not doc_by_decl:
270
+ return reduced
271
+
272
+ out: List[str] = []
273
+ for r_line in reduced.splitlines():
274
+ r_stripped = r_line.strip()
275
+ # Match declarations even when { ... } suffix was collapsed
276
+ matched_docs = doc_by_decl.get(r_stripped)
277
+ if not matched_docs:
278
+ prefix_sig = r_stripped.split("{", 1)[0].strip()
279
+ if prefix_sig:
280
+ for decl_k, d_lines in doc_by_decl.items():
281
+ if decl_k.startswith(prefix_sig):
282
+ matched_docs = d_lines
283
+ break
284
+ if matched_docs:
285
+ out.extend(matched_docs)
286
+ out.append(r_line)
287
+ return "\n".join(out)
288
+
289
+ @classmethod
290
+ def reduce_code(cls, content: str, filename: str = "", mode: str = "ultra") -> str:
291
+ """Prunes code content to its structural signatures based on detected language."""
292
+ lang = cls.detect_language(filename)
293
+ if not lang or mode == "none":
294
+ return content
295
+
296
+ adapter = cls._TREE_SITTER_ADAPTERS.get(lang)
297
+ if adapter is not None:
298
+ try:
299
+ return adapter(content, filename, mode)
300
+ except Exception:
301
+ pass
302
+
303
+ norm_mode = "light" if str(mode).lower() in ("light", "balanced") else "ultra"
304
+
305
+ dispatch = {
306
+ "python": cls.reduce_python,
307
+ "javascript": cls.reduce_javascript,
308
+ "typescript": cls.reduce_javascript,
309
+ "rust": cls.reduce_rust,
310
+ "go": cls.reduce_go,
311
+ "cpp": cls.reduce_cpp,
312
+ "java": cls.reduce_java,
313
+ "solidity": cls.reduce_solidity,
314
+ "ruby": cls.reduce_ruby,
315
+ "php": cls.reduce_php,
316
+ "swift": cls.reduce_swift,
317
+ "kotlin": cls.reduce_kotlin,
318
+ "dart": cls.reduce_dart,
319
+ "scala": cls.reduce_scala,
320
+ "elixir": cls.reduce_elixir,
321
+ }
322
+ reducer = dispatch.get(lang)
323
+ if not reducer:
324
+ return content
325
+ reduced = reducer(content, norm_mode)
326
+ if norm_mode == "light" and lang != "python":
327
+ return cls._attach_light_doc_comments(content, reduced)
328
+ return reduced
329
+
330
+ @staticmethod
331
+ def reduce_python(content: str, mode: str = "ultra") -> str:
332
+ """Reduces Python source via ast.parse (multiline-safe) with line fallback on SyntaxError."""
333
+ lines = content.splitlines()
334
+ keep_docstrings = mode == "light"
335
+ try:
336
+ tree = ast.parse(content)
337
+ pruned: List[str] = []
338
+
339
+ def _emit_func(fn_node: ast.AST, indent_prefix: str = "") -> None:
340
+ for dec in getattr(fn_node, "decorator_list", []):
341
+ d_end = getattr(dec, "end_lineno", dec.lineno)
342
+ for ln in range(dec.lineno, d_end + 1):
343
+ pruned.append(lines[ln - 1])
344
+ body = getattr(fn_node, "body", [])
345
+ sig_start = fn_node.lineno
346
+ if body:
347
+ first_stmt = body[0]
348
+ if first_stmt.lineno == sig_start:
349
+ hdr = lines[sig_start - 1].split(":", 1)[0]
350
+ pruned.append(f"{hdr}: ...")
351
+ return
352
+ sig_end = max(sig_start, first_stmt.lineno - 1)
353
+ while sig_end > sig_start and not lines[sig_end - 1].strip():
354
+ sig_end -= 1
355
+ else:
356
+ sig_end = getattr(fn_node, "end_lineno", sig_start)
357
+ for ln in range(sig_start, sig_end):
358
+ pruned.append(lines[ln - 1])
359
+ last_hdr = lines[sig_end - 1].rstrip()
360
+ if not last_hdr.endswith("..."):
361
+ pruned.append(f"{last_hdr} ..." if last_hdr.endswith(":") else f"{last_hdr}: ...")
362
+ if keep_docstrings and body:
363
+ doc = ast.get_docstring(fn_node)
364
+ if doc:
365
+ pruned.append(f'{indent_prefix} """{doc.splitlines()[0]}"""')
366
+
367
+ for node in tree.body:
368
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
369
+ end_l = getattr(node, "end_lineno", node.lineno)
370
+ for ln in range(node.lineno, end_l + 1):
371
+ pruned.append(lines[ln - 1])
372
+ elif (
373
+ keep_docstrings
374
+ and isinstance(node, ast.Expr)
375
+ and isinstance(getattr(node, "value", None), ast.Constant)
376
+ and isinstance(node.value.value, str)
377
+ ):
378
+ end_l = getattr(node, "end_lineno", node.lineno)
379
+ for ln in range(node.lineno, end_l + 1):
380
+ pruned.append(lines[ln - 1])
381
+ elif isinstance(node, ast.ClassDef):
382
+ for dec in node.decorator_list:
383
+ d_end = getattr(dec, "end_lineno", dec.lineno)
384
+ for ln in range(dec.lineno, d_end + 1):
385
+ pruned.append(lines[ln - 1])
386
+ if node.body and node.body[0].lineno == node.lineno:
387
+ pruned.append(lines[node.lineno - 1].split(":", 1)[0] + ":")
388
+ else:
389
+ cls_end_hdr = max(node.lineno, (node.body[0].lineno - 1) if node.body else node.lineno)
390
+ while cls_end_hdr > node.lineno and not lines[cls_end_hdr - 1].strip():
391
+ cls_end_hdr -= 1
392
+ for ln in range(node.lineno, cls_end_hdr + 1):
393
+ pruned.append(lines[ln - 1])
394
+ if keep_docstrings:
395
+ cdoc = ast.get_docstring(node)
396
+ if cdoc:
397
+ pruned.append(f' """{cdoc.splitlines()[0]}"""')
398
+ for item in node.body:
399
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
400
+ _emit_func(item, indent_prefix=" ")
401
+ elif isinstance(item, ast.AnnAssign) and hasattr(ast, "unparse"):
402
+ pruned.append(f" {ast.unparse(item)}")
403
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
404
+ _emit_func(node, indent_prefix="")
405
+ return "\n".join(pruned) if pruned else content
406
+ except SyntaxError:
407
+ pruned_fallback: List[str] = []
408
+ for line in lines:
409
+ stripped = line.strip()
410
+ if (stripped.startswith("import ") or stripped.startswith("from ") or
411
+ stripped.startswith("def ") or stripped.startswith("async def ") or
412
+ stripped.startswith("class ") or stripped.startswith("@")):
413
+ if (stripped.startswith("def ") or stripped.startswith("async def ")) and not stripped.endswith("..."):
414
+ if stripped.endswith(":"):
415
+ pruned_fallback.append(f"{line[:-1]}: ...")
416
+ else:
417
+ pruned_fallback.append(f"{line} ...")
418
+ else:
419
+ pruned_fallback.append(line)
420
+ return "\n".join(pruned_fallback) if pruned_fallback else content
421
+
422
+ @staticmethod
423
+ def reduce_javascript(content: str, mode: str = "ultra") -> str:
424
+ """Reduces JavaScript/TypeScript source with string/comment-aware brace & multiline signature tracking."""
425
+ scanned = PolyglotTokenReducer._lexical_scan_lines(content)
426
+ pruned: List[str] = []
427
+ in_multiline_import = False
428
+ keep_block_until_depth: Optional[int] = None
429
+ skip_body_until_depth: Optional[int] = None
430
+ pending_sig: List[str] = []
431
+ pending_paren = 0
432
+ brace_depth = 0
433
+
434
+ ctrl_re = re.compile(r'^(?:else\s+)?(?:if|for|while|switch|catch|try|finally|return|throw|break|continue)\b')
435
+ iface_re = re.compile(r'^(?:export\s+)?(?:declare\s+)?(?:interface|type|enum)\s+[A-Za-z0-9_]+')
436
+ class_re = re.compile(r'^(?:export\s+)?(?:abstract\s+)?(?:default\s+)?class\s+[A-Za-z0-9_]+')
437
+ func_re = re.compile(
438
+ r'^(?:export\s+(?:default\s+)?)?(?:async\s+)?function\b'
439
+ r'|^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+\s*(?::[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z0-9_$]+)\s*=>'
440
+ r'|^(?:(?:public|private|protected|static|async|get|set|override|readonly)\s+)*(?:constructor|[A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\('
441
+ )
442
+
443
+ for raw_line, ob, cb, op, cp, is_comment_only in scanned:
444
+ stripped = raw_line.strip()
445
+ if not stripped or is_comment_only:
446
+ continue
447
+
448
+ if in_multiline_import:
449
+ pruned.append(raw_line)
450
+ brace_depth = max(0, brace_depth + ob - cb)
451
+ if "}" in stripped or ";" in stripped:
452
+ in_multiline_import = False
453
+ continue
454
+
455
+ if keep_block_until_depth is not None:
456
+ pruned.append(raw_line)
457
+ brace_depth = max(0, brace_depth + ob - cb)
458
+ if brace_depth < keep_block_until_depth:
459
+ keep_block_until_depth = None
460
+ continue
461
+
462
+ if skip_body_until_depth is not None:
463
+ brace_depth = max(0, brace_depth + ob - cb)
464
+ if brace_depth < skip_body_until_depth:
465
+ skip_body_until_depth = None
466
+ continue
467
+
468
+ if pending_sig:
469
+ pending_sig.append(raw_line)
470
+ pending_paren += op - cp
471
+ prev_depth = brace_depth
472
+ brace_depth = max(0, brace_depth + ob - cb)
473
+ if pending_paren <= 0 and (ob > 0 or stripped.endswith(";") or stripped.endswith(")")):
474
+ if ob > cb:
475
+ for sline in pending_sig[:-1]:
476
+ pruned.append(sline)
477
+ pruned.append(re.sub(r'\{.*$', '{ ... }', pending_sig[-1]))
478
+ skip_body_until_depth = prev_depth + 1
479
+ else:
480
+ pruned.extend(pending_sig)
481
+ pending_sig = []
482
+ pending_paren = 0
483
+ continue
484
+
485
+ prev_depth = brace_depth
486
+ brace_depth = max(0, brace_depth + ob - cb)
487
+
488
+ if stripped.startswith("import ") and ob > cb:
489
+ in_multiline_import = True
490
+ pruned.append(raw_line)
491
+ continue
492
+
493
+ if stripped.startswith(("import ", "require(")) or stripped.startswith("@"):
494
+ pruned.append(raw_line)
495
+ continue
496
+
497
+ if iface_re.match(stripped):
498
+ pruned.append(raw_line)
499
+ if ob > cb:
500
+ keep_block_until_depth = prev_depth + 1
501
+ continue
502
+
503
+ if class_re.match(stripped):
504
+ pruned.append(raw_line)
505
+ continue
506
+
507
+ if ctrl_re.match(stripped):
508
+ if ob > cb:
509
+ skip_body_until_depth = prev_depth + 1
510
+ continue
511
+
512
+ is_export_const_or_decl = stripped.startswith(("export ", "declare "))
513
+ if func_re.match(stripped) or is_export_const_or_decl:
514
+ if op > cp and ob == 0:
515
+ pending_sig = [raw_line]
516
+ pending_paren = op - cp
517
+ continue
518
+ if ob > cb:
519
+ pruned.append(re.sub(r'\{.*$', '{ ... }', raw_line))
520
+ skip_body_until_depth = prev_depth + 1
521
+ elif stripped.endswith("{"):
522
+ pruned.append(f"{raw_line[:-1]}{{ ... }}")
523
+ skip_body_until_depth = prev_depth + 1
524
+ else:
525
+ pruned.append(raw_line)
526
+
527
+ return "\n".join(pruned) if pruned else content
528
+
529
+ @staticmethod
530
+ def reduce_rust(content: str, mode: str = "ultra") -> str:
531
+ """Reduces Rust source code to use statements, traits, structs, enums, impls, and fn signatures."""
532
+ lines = content.splitlines()
533
+ pruned: List[str] = []
534
+ for line in lines:
535
+ stripped = line.strip()
536
+ is_fn = bool(re.match(r'^(pub(\([^)]+\))?\s+)?(async\s+)?(unsafe\s+)?fn\s+', stripped))
537
+ is_impl = bool(re.match(r'^impl\b', stripped))
538
+ if (stripped.startswith("use ") or stripped.startswith("pub use ") or
539
+ is_fn or is_impl or
540
+ stripped.startswith("pub struct ") or stripped.startswith("struct ") or
541
+ stripped.startswith("pub enum ") or stripped.startswith("enum ") or
542
+ stripped.startswith("pub trait ") or stripped.startswith("trait ") or
543
+ stripped.startswith("#[") or
544
+ stripped.startswith("pub const ") or stripped.startswith("pub type ") or
545
+ stripped.startswith("const ") or stripped.startswith("type ")):
546
+ if "{" in stripped and not stripped.endswith("}"):
547
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
548
+ elif stripped.endswith(";"):
549
+ pruned.append(line)
550
+ elif stripped.endswith("{"):
551
+ pruned.append(f"{line[:-1]}{{ ... }}")
552
+ else:
553
+ pruned.append(line)
554
+ return "\n".join(pruned) if pruned else content
555
+
556
+ @staticmethod
557
+ def reduce_go(content: str, mode: str = "ultra") -> str:
558
+ """Reduces Go source code to package, imports, types, interfaces, and func signatures."""
559
+ lines = content.splitlines()
560
+ pruned: List[str] = []
561
+ for line in lines:
562
+ stripped = line.strip()
563
+ if (stripped.startswith("package ") or stripped.startswith("import ") or
564
+ stripped.startswith("type ") or stripped.startswith("func ") or
565
+ stripped.startswith("var ") or stripped.startswith("const ")):
566
+ if stripped.startswith("func ") and "{" in stripped:
567
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
568
+ else:
569
+ pruned.append(line)
570
+ return "\n".join(pruned) if pruned else content
571
+
572
+ @staticmethod
573
+ def reduce_cpp(content: str, mode: str = "ultra") -> str:
574
+ """Reduces C/C++ source code to headers, classes, structs, templates, and prototypes."""
575
+ scanned = PolyglotTokenReducer._lexical_scan_lines(content)
576
+ pruned: List[str] = []
577
+ brace_depth = 0
578
+ skip_body_until_depth: Optional[int] = None
579
+ fn_re = re.compile(
580
+ r'^(?:(?:virtual|static|inline|explicit|constexpr)\s+)?'
581
+ r'(?:[\w:<>&*\s]+\s+)?~?[\w:]+\s*\([^;]*\)\s*(?:const)?\s*(?:override|noexcept|final)?\s*(?:\{|;)?$'
582
+ )
583
+ ctrl_re = re.compile(r'^(?:if|for|while|switch|catch|return|else)\b')
584
+
585
+ for raw_line, ob, cb, _, _, is_comment_only in scanned:
586
+ stripped = raw_line.strip()
587
+ if not stripped or is_comment_only:
588
+ continue
589
+
590
+ if skip_body_until_depth is not None:
591
+ brace_depth = max(0, brace_depth + ob - cb)
592
+ if brace_depth < skip_body_until_depth:
593
+ skip_body_until_depth = None
594
+ continue
595
+
596
+ prev_depth = brace_depth
597
+ brace_depth = max(0, brace_depth + ob - cb)
598
+ if ctrl_re.match(stripped):
599
+ if ob > cb:
600
+ skip_body_until_depth = prev_depth + 1
601
+ continue
602
+
603
+ is_container = stripped.startswith((
604
+ "#include", "#define", "template", "class ", "struct ", "namespace ", "using ", "typedef "
605
+ ))
606
+ is_fn = bool(fn_re.match(stripped))
607
+ if is_container or is_fn:
608
+ if "{" in stripped:
609
+ pruned.append(re.sub(r'\{.*$', '{ ... }', raw_line))
610
+ if is_fn and ob > cb:
611
+ skip_body_until_depth = prev_depth + 1
612
+ elif not stripped.endswith(";") and not stripped.startswith("#") and not stripped.startswith("namespace"):
613
+ pruned.append(f"{raw_line};")
614
+ else:
615
+ pruned.append(raw_line)
616
+ return "\n".join(pruned) if pruned else content
617
+
618
+ @staticmethod
619
+ def reduce_java(content: str, mode: str = "ultra") -> str:
620
+ """Reduces Java/C# source code to packages, imports, classes, interfaces, records, and method signatures."""
621
+ lines = content.splitlines()
622
+ pruned: List[str] = []
623
+ for line in lines:
624
+ stripped = line.strip()
625
+ if (stripped.startswith("package ") or stripped.startswith("import ") or
626
+ stripped.startswith("using ") or stripped.startswith("namespace ") or
627
+ "class " in stripped or "interface " in stripped or "record " in stripped or
628
+ "enum " in stripped or re.match(r'^\s*(?:public|private|protected|static|final|abstract|async)\s+.*\(.*\)', stripped)):
629
+ if "{" in stripped:
630
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
631
+ elif not stripped.endswith(";") and not stripped.startswith("package") and not stripped.startswith("import"):
632
+ pruned.append(f"{line} {{ ... }}")
633
+ else:
634
+ pruned.append(line)
635
+ return "\n".join(pruned) if pruned else content
636
+
637
+ @staticmethod
638
+ def reduce_solidity(content: str, mode: str = "ultra") -> str:
639
+ """Reduces Solidity smart contracts to pragma, interfaces, contracts, structs, events, and function headers."""
640
+ lines = content.splitlines()
641
+ pruned: List[str] = []
642
+ for line in lines:
643
+ stripped = line.strip()
644
+ if (stripped.startswith("pragma ") or stripped.startswith("import ") or
645
+ stripped.startswith("contract ") or stripped.startswith("interface ") or
646
+ stripped.startswith("library ") or stripped.startswith("struct ") or
647
+ stripped.startswith("event ") or stripped.startswith("modifier ") or
648
+ stripped.startswith("function ") or stripped.startswith("mapping(")):
649
+ if "{" in stripped and not stripped.endswith("}"):
650
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
651
+ elif stripped.startswith("function ") and not stripped.endswith(";"):
652
+ pruned.append(f"{line};")
653
+ else:
654
+ pruned.append(line)
655
+ return "\n".join(pruned) if pruned else content
656
+
657
+ @staticmethod
658
+ def reduce_ruby(content: str, mode: str = "ultra") -> str:
659
+ """Reduces Ruby source code to module/class declarations, requires, mixins, and method signatures."""
660
+ lines = content.splitlines()
661
+ pruned: List[str] = []
662
+ for line in lines:
663
+ stripped = line.strip()
664
+ if (stripped.startswith("require ") or stripped.startswith("require_relative ") or
665
+ stripped.startswith("module ") or stripped.startswith("class ") or
666
+ stripped.startswith("def ") or stripped.startswith("attr_") or
667
+ stripped.startswith("include ") or stripped.startswith("extend ") or
668
+ stripped.startswith("has_many ") or stripped.startswith("belongs_to ") or
669
+ stripped in ("private", "protected", "public")):
670
+ if stripped.startswith("def ") and not stripped.endswith("end"):
671
+ pruned.append(f"{line}; ...; end")
672
+ else:
673
+ pruned.append(line)
674
+ return "\n".join(pruned) if pruned else content
675
+
676
+ @staticmethod
677
+ def reduce_php(content: str, mode: str = "ultra") -> str:
678
+ """Reduces PHP source code to namespace, imports, classes, interfaces, traits, and method signatures."""
679
+ lines = content.splitlines()
680
+ pruned: List[str] = []
681
+ for line in lines:
682
+ stripped = line.strip()
683
+ if (stripped.startswith("<?php") or stripped.startswith("namespace ") or
684
+ stripped.startswith("use ") or "class " in stripped or
685
+ "interface " in stripped or "trait " in stripped or "enum " in stripped or
686
+ "function " in stripped):
687
+ if "{" in stripped:
688
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
689
+ elif "function " in stripped and not stripped.endswith(";"):
690
+ pruned.append(f"{line} {{ ... }}")
691
+ else:
692
+ pruned.append(line)
693
+ return "\n".join(pruned) if pruned else content
694
+
695
+ @staticmethod
696
+ def reduce_swift(content: str, mode: str = "ultra") -> str:
697
+ """Reduces Swift source code to imports, protocols, classes, structs, enums, extensions, and func signatures."""
698
+ lines = content.splitlines()
699
+ pruned: List[str] = []
700
+ for line in lines:
701
+ stripped = line.strip()
702
+ if (stripped.startswith("import ") or stripped.startswith("protocol ") or
703
+ "class " in stripped or "struct " in stripped or "enum " in stripped or
704
+ "extension " in stripped or "func " in stripped or stripped.startswith("init(")):
705
+ if "{" in stripped:
706
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
707
+ elif not stripped.endswith(";"):
708
+ pruned.append(f"{line} {{ ... }}")
709
+ else:
710
+ pruned.append(line)
711
+ return "\n".join(pruned) if pruned else content
712
+
713
+ @staticmethod
714
+ def reduce_kotlin(content: str, mode: str = "ultra") -> str:
715
+ """Reduces Kotlin source code to package, imports, classes, interfaces, objects, and function headers."""
716
+ lines = content.splitlines()
717
+ pruned: List[str] = []
718
+ for line in lines:
719
+ stripped = line.strip()
720
+ if (stripped.startswith("package ") or stripped.startswith("import ") or
721
+ "class " in stripped or "interface " in stripped or "object " in stripped or
722
+ stripped.startswith("fun ") or " fun " in stripped):
723
+ if "{" in stripped:
724
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
725
+ elif not stripped.endswith(";"):
726
+ pruned.append(f"{line} {{ ... }}")
727
+ else:
728
+ pruned.append(line)
729
+ return "\n".join(pruned) if pruned else content
730
+
731
+ @staticmethod
732
+ def reduce_dart(content: str, mode: str = "ultra") -> str:
733
+ """Reduces Dart source code to imports, exports, classes, mixins, enums, and method signatures."""
734
+ lines = content.splitlines()
735
+ pruned: List[str] = []
736
+ for line in lines:
737
+ stripped = line.strip()
738
+ if not stripped or stripped.startswith("//") or stripped.startswith("/*"):
739
+ continue
740
+ if stripped.startswith(("return ", "return;", "if ", "if(", "for ", "for(", "while ", "while(", "switch ", "throw ", "print(")):
741
+ continue
742
+ if (stripped.startswith("import ") or stripped.startswith("export ") or
743
+ stripped.startswith("part ") or "class " in stripped or
744
+ "mixin " in stripped or "enum " in stripped or "extension " in stripped or
745
+ re.match(r'^\s*(?:@\w+\s+)*(?:static\s+|async\s+)?[\w<>,]+\s+\w+\s*\(.*?\)', stripped)):
746
+ if "{" in stripped and not ("class " in stripped or "mixin " in stripped):
747
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
748
+ elif not stripped.endswith(";") and not stripped.endswith("{"):
749
+ pruned.append(f"{line} {{ ... }}")
750
+ else:
751
+ pruned.append(line)
752
+ return "\n".join(pruned) if pruned else content
753
+
754
+ @staticmethod
755
+ def reduce_scala(content: str, mode: str = "ultra") -> str:
756
+ """Reduces Scala source code to packages, imports, traits, objects, classes, and def headers."""
757
+ lines = content.splitlines()
758
+ pruned: List[str] = []
759
+ for line in lines:
760
+ stripped = line.strip()
761
+ if not stripped or stripped.startswith("//") or stripped.startswith("/*"):
762
+ continue
763
+ if (stripped.startswith("package ") or stripped.startswith("import ") or
764
+ "class " in stripped or "trait " in stripped or "object " in stripped or
765
+ "enum " in stripped or stripped.startswith("def ") or " def " in stripped):
766
+ if "{" in stripped and not ("class " in stripped or "trait " in stripped or "object " in stripped):
767
+ pruned.append(re.sub(r'\{.*$', '{ ... }', line))
768
+ elif not stripped.endswith(";") and not stripped.endswith("{"):
769
+ pruned.append(f"{line} {{ ... }}")
770
+ else:
771
+ pruned.append(line)
772
+ return "\n".join(pruned) if pruned else content
773
+
774
+ @staticmethod
775
+ def reduce_elixir(content: str, mode: str = "ultra") -> str:
776
+ """Reduces Elixir source code to module headers, structs, specs, and function signatures."""
777
+ lines = content.splitlines()
778
+ pruned: List[str] = []
779
+ for line in lines:
780
+ stripped = line.strip()
781
+ if not stripped or stripped.startswith("#"):
782
+ continue
783
+ if (stripped.startswith("defmodule ") or stripped.startswith("defstruct ") or
784
+ stripped.startswith("alias ") or stripped.startswith("import ") or
785
+ stripped.startswith("require ") or stripped.startswith("use ") or
786
+ stripped.startswith("@type ") or stripped.startswith("@spec ") or
787
+ stripped.startswith("def ") or stripped.startswith("defp ") or
788
+ stripped.startswith("defmacro ")):
789
+ if stripped.startswith("defmodule "):
790
+ pruned.append(line)
791
+ elif ", do:" in stripped:
792
+ pruned.append(re.sub(r', do:.*$', ', do: ...', line))
793
+ elif stripped.endswith(" do"):
794
+ pruned.append(re.sub(r'\s+do$', ', do: ...', line))
795
+ else:
796
+ pruned.append(line)
797
+ return "\n".join(pruned) if pruned else content
798
+
799
+