tzero-mcp 10.7.4 → 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.
- package/CHANGELOG.md +27 -0
- package/LICENSE +21 -21
- package/README.md +3 -3
- package/bin/tzero-mcp.js +7 -11
- package/bin/tzero.js +7 -11
- package/index.js +3 -3
- package/package.json +3 -2
- package/src/addmcp.py +1203 -1194
- package/src/app.py +1810 -0
- package/src/main.py +60 -60
- package/src/pc_fixer_mcp.py +25 -0
- package/src/tzero/__init__.py +54 -0
- package/src/tzero/__main__.py +6 -0
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +77 -77
- package/src/tzero/tzero_arch_test.py +463 -0
- package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +2 -2
- package/src/tzero/tzero_blackboard.py +257 -0
- package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +184 -0
- package/src/tzero/tzero_budget.py +195 -0
- package/src/tzero/tzero_card.py +431 -0
- package/src/{tzero_ci.py → tzero/tzero_ci.py} +7 -7
- package/src/{tzero_commit.py → tzero/tzero_commit.py} +1 -1
- package/src/tzero/tzero_contracts.py +1093 -0
- package/src/{tzero_cost.py → tzero/tzero_cost.py} +4 -1
- package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +1960 -1448
- package/src/tzero/tzero_debt.py +461 -0
- package/src/{tzero_deps.py → tzero/tzero_deps.py} +462 -287
- package/src/{tzero_drift.py → tzero/tzero_drift.py} +1 -1
- package/src/{tzero_explain.py → tzero/tzero_explain.py} +306 -240
- package/src/{tzero_features.py → tzero/tzero_features.py} +3024 -3022
- package/src/tzero/tzero_federation.py +299 -0
- package/src/tzero/tzero_fix.py +557 -0
- package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +334 -334
- package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +8 -8
- package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +280 -280
- package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +325 -325
- package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +489 -447
- package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +385 -385
- package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +375 -375
- package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +323 -323
- package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +2 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +364 -364
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +619 -619
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +2 -2
- package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +493 -493
- package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +1 -1
- package/src/tzero/tzero_golden.py +319 -0
- package/src/tzero/tzero_graph_hud.html +338 -0
- package/src/tzero/tzero_graph_rag.py +263 -0
- package/src/tzero/tzero_growth.py +415 -0
- package/src/{tzero_guard.py → tzero/tzero_guard.py} +11 -3
- package/src/tzero/tzero_hooks.py +565 -0
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +11 -1
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +1 -1
- package/src/tzero/tzero_jarvis/creative_director.py +333 -0
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +1 -1
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +2 -2
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +1 -1
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +1 -1
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +2 -2
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +1 -1
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +3 -3
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +1 -1
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +6 -6
- package/src/tzero/tzero_lsp.py +634 -0
- package/src/tzero/tzero_mcp.py +5314 -0
- package/src/tzero/tzero_mutation.py +358 -0
- package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +1425 -1425
- package/src/tzero/tzero_packer.py +577 -0
- package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +42 -0
- package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +1 -1
- package/src/tzero/tzero_polyglot.py +799 -0
- package/src/tzero/tzero_proxy.py +127 -0
- package/src/tzero/tzero_rust_bridge.py +198 -0
- package/src/tzero/tzero_scip.py +368 -0
- package/src/{tzero_security.py → tzero/tzero_security.py} +573 -570
- package/src/tzero/tzero_semantic_merge.py +189 -0
- package/src/tzero/tzero_snapshot.py +471 -0
- package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +1 -1
- package/src/tzero/tzero_subagent_engine.py +459 -0
- package/src/{tzero_sync.py → tzero/tzero_sync.py} +2 -2
- package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +174 -31
- package/src/{tzero_tui.py → tzero/tzero_tui.py} +313 -244
- package/src/tzero/tzero_turbo.py +264 -0
- package/src/{tzero_v3.py → tzero/tzero_v3.py} +9997 -9435
- package/src/tzero.py +6 -58
- package/src/tzero_mcp.py +25 -4858
- package/test/package.test.js +14 -2
- package/src/tzero/jarvis/semantic_compressor.py +0 -373
- package/src/tzero_fix.py +0 -228
- package/src/tzero_gateway.py +0 -885
- package/src/tzero_packer.py +0 -370
- package/src/tzero_polyglot.py +0 -422
- package/src/tzero_snapshot.py +0 -258
- /package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +0 -0
- /package/src/{tzero_infra.py → tzero/tzero_infra.py} +0 -0
- /package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +0 -0
- /package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +0 -0
- /package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +0 -0
- /package/src/{tzero_patch.py → tzero/tzero_patch.py} +0 -0
- /package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +0 -0
- /package/src/{tzero_replay.py → tzero/tzero_replay.py} +0 -0
- /package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +0 -0
package/src/tzero_polyglot.py
DELETED
|
@@ -1,422 +0,0 @@
|
|
|
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 re
|
|
14
|
-
from typing import Dict, List, Tuple, Optional
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class PolyglotTokenReducer:
|
|
18
|
-
"""Universal multi-language structural signature extractor."""
|
|
19
|
-
|
|
20
|
-
SUPPORTED_LANGUAGES = {
|
|
21
|
-
"python": [".py", ".pyw"],
|
|
22
|
-
"javascript": [".js", ".jsx", ".mjs", ".cjs"],
|
|
23
|
-
"typescript": [".ts", ".tsx"],
|
|
24
|
-
"rust": [".rs"],
|
|
25
|
-
"go": [".go"],
|
|
26
|
-
"cpp": [".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"],
|
|
27
|
-
"java": [".java", ".cs"],
|
|
28
|
-
"solidity": [".sol"],
|
|
29
|
-
"ruby": [".rb", ".rake", ".gemspec"],
|
|
30
|
-
"php": [".php", ".phtml"],
|
|
31
|
-
"swift": [".swift"],
|
|
32
|
-
"kotlin": [".kt", ".kts"],
|
|
33
|
-
"dart": [".dart"],
|
|
34
|
-
"scala": [".scala", ".sc"],
|
|
35
|
-
"elixir": [".ex", ".exs"]
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
@classmethod
|
|
39
|
-
def detect_language(cls, filename: str) -> Optional[str]:
|
|
40
|
-
"""Detect language from filename extension."""
|
|
41
|
-
ext = "." + filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
|
42
|
-
for lang, exts in cls.SUPPORTED_LANGUAGES.items():
|
|
43
|
-
if ext in exts:
|
|
44
|
-
return lang
|
|
45
|
-
return None
|
|
46
|
-
|
|
47
|
-
@classmethod
|
|
48
|
-
def reduce_code(cls, content: str, filename: str = "", mode: str = "ultra") -> str:
|
|
49
|
-
"""Prunes code content to its structural signatures based on detected language."""
|
|
50
|
-
lang = cls.detect_language(filename)
|
|
51
|
-
if not lang or mode == "none":
|
|
52
|
-
return content
|
|
53
|
-
|
|
54
|
-
if lang == "python":
|
|
55
|
-
return cls.reduce_python(content, mode)
|
|
56
|
-
elif lang in ("javascript", "typescript"):
|
|
57
|
-
return cls.reduce_javascript(content, mode)
|
|
58
|
-
elif lang == "rust":
|
|
59
|
-
return cls.reduce_rust(content, mode)
|
|
60
|
-
elif lang == "go":
|
|
61
|
-
return cls.reduce_go(content, mode)
|
|
62
|
-
elif lang == "cpp":
|
|
63
|
-
return cls.reduce_cpp(content, mode)
|
|
64
|
-
elif lang == "java":
|
|
65
|
-
return cls.reduce_java(content, mode)
|
|
66
|
-
elif lang == "solidity":
|
|
67
|
-
return cls.reduce_solidity(content, mode)
|
|
68
|
-
elif lang == "ruby":
|
|
69
|
-
return cls.reduce_ruby(content, mode)
|
|
70
|
-
elif lang == "php":
|
|
71
|
-
return cls.reduce_php(content, mode)
|
|
72
|
-
elif lang == "swift":
|
|
73
|
-
return cls.reduce_swift(content, mode)
|
|
74
|
-
elif lang == "kotlin":
|
|
75
|
-
return cls.reduce_kotlin(content, mode)
|
|
76
|
-
elif lang == "dart":
|
|
77
|
-
return cls.reduce_dart(content, mode)
|
|
78
|
-
elif lang == "scala":
|
|
79
|
-
return cls.reduce_scala(content, mode)
|
|
80
|
-
elif lang == "elixir":
|
|
81
|
-
return cls.reduce_elixir(content, mode)
|
|
82
|
-
return content
|
|
83
|
-
|
|
84
|
-
@staticmethod
|
|
85
|
-
def reduce_python(content: str, mode: str = "ultra") -> str:
|
|
86
|
-
"""Reduces Python source to imports, class/func headers, and ellipses."""
|
|
87
|
-
lines = content.splitlines()
|
|
88
|
-
pruned: List[str] = []
|
|
89
|
-
in_docstring = False
|
|
90
|
-
|
|
91
|
-
for line in lines:
|
|
92
|
-
stripped = line.strip()
|
|
93
|
-
# Handle multiline docstrings
|
|
94
|
-
if stripped.startswith('"""') or stripped.startswith("'''"):
|
|
95
|
-
if stripped.count('"""') == 1 or stripped.count("'''") == 1:
|
|
96
|
-
in_docstring = not in_docstring
|
|
97
|
-
continue
|
|
98
|
-
if in_docstring:
|
|
99
|
-
continue
|
|
100
|
-
|
|
101
|
-
if (stripped.startswith("import ") or stripped.startswith("from ") or
|
|
102
|
-
stripped.startswith("def ") or stripped.startswith("async def ") or
|
|
103
|
-
stripped.startswith("class ") or stripped.startswith("@")):
|
|
104
|
-
indent = len(line) - len(line.lstrip())
|
|
105
|
-
if (stripped.startswith("def ") or stripped.startswith("async def ")) and not stripped.endswith("..."):
|
|
106
|
-
if stripped.endswith(":"):
|
|
107
|
-
pruned.append(f"{line[:-1]}: ...")
|
|
108
|
-
else:
|
|
109
|
-
pruned.append(f"{line} ...")
|
|
110
|
-
else:
|
|
111
|
-
pruned.append(line)
|
|
112
|
-
|
|
113
|
-
return "\n".join(pruned) if pruned else content
|
|
114
|
-
|
|
115
|
-
@staticmethod
|
|
116
|
-
def reduce_javascript(content: str, mode: str = "ultra") -> str:
|
|
117
|
-
"""Reduces JavaScript/TypeScript source to imports, interfaces, types, and function signatures."""
|
|
118
|
-
lines = content.splitlines()
|
|
119
|
-
pruned: List[str] = []
|
|
120
|
-
in_multiline_import = False
|
|
121
|
-
in_interface_or_type = False
|
|
122
|
-
in_block_comment = False
|
|
123
|
-
|
|
124
|
-
for line in lines:
|
|
125
|
-
stripped = line.strip()
|
|
126
|
-
if not stripped:
|
|
127
|
-
continue
|
|
128
|
-
|
|
129
|
-
# Multi-line comment tracking
|
|
130
|
-
if in_block_comment:
|
|
131
|
-
if "*/" in stripped:
|
|
132
|
-
in_block_comment = False
|
|
133
|
-
continue
|
|
134
|
-
if stripped.startswith("/*") and not stripped.endswith("*/"):
|
|
135
|
-
in_block_comment = True
|
|
136
|
-
continue
|
|
137
|
-
if stripped.startswith("//"):
|
|
138
|
-
continue
|
|
139
|
-
|
|
140
|
-
# Multi-line imports
|
|
141
|
-
if in_multiline_import:
|
|
142
|
-
pruned.append(line)
|
|
143
|
-
if "}" in stripped or ";" in stripped:
|
|
144
|
-
in_multiline_import = False
|
|
145
|
-
continue
|
|
146
|
-
|
|
147
|
-
if stripped.startswith("import ") and "{" in stripped and "}" not in stripped:
|
|
148
|
-
in_multiline_import = True
|
|
149
|
-
pruned.append(line)
|
|
150
|
-
continue
|
|
151
|
-
|
|
152
|
-
# Interfaces and Type declarations (keep interface definitions and fields)
|
|
153
|
-
if re.match(r"^(export\s+)?(interface|type)\s+[A-Za-z0-9_]+", stripped):
|
|
154
|
-
pruned.append(line)
|
|
155
|
-
if "{" in stripped and "}" not in stripped:
|
|
156
|
-
in_interface_or_type = True
|
|
157
|
-
continue
|
|
158
|
-
|
|
159
|
-
if in_interface_or_type:
|
|
160
|
-
pruned.append(line)
|
|
161
|
-
if "}" in stripped:
|
|
162
|
-
in_interface_or_type = False
|
|
163
|
-
continue
|
|
164
|
-
|
|
165
|
-
# Function declarations, arrow functions, classes
|
|
166
|
-
if (stripped.startswith("import ") or stripped.startswith("export ") or
|
|
167
|
-
stripped.startswith("class ") or stripped.startswith("function ") or
|
|
168
|
-
stripped.startswith("async function ") or
|
|
169
|
-
(stripped.startswith("const ") and "=>" in stripped) or
|
|
170
|
-
(stripped.startswith("let ") and "=>" in stripped)):
|
|
171
|
-
if "{" in stripped and "}" not in stripped:
|
|
172
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
173
|
-
elif stripped.endswith("{"):
|
|
174
|
-
pruned.append(f"{line[:-1]}{{ ... }}")
|
|
175
|
-
else:
|
|
176
|
-
pruned.append(line)
|
|
177
|
-
return "\n".join(pruned) if pruned else content
|
|
178
|
-
|
|
179
|
-
@staticmethod
|
|
180
|
-
def reduce_rust(content: str, mode: str = "ultra") -> str:
|
|
181
|
-
"""Reduces Rust source code to use statements, traits, structs, enums, and fn signatures."""
|
|
182
|
-
lines = content.splitlines()
|
|
183
|
-
pruned: List[str] = []
|
|
184
|
-
for line in lines:
|
|
185
|
-
stripped = line.strip()
|
|
186
|
-
is_fn = bool(re.match(r'^(pub(\([^)]+\))?\s+)?(async\s+)?(unsafe\s+)?fn\s+', stripped))
|
|
187
|
-
if (stripped.startswith("use ") or stripped.startswith("pub use ") or
|
|
188
|
-
is_fn or
|
|
189
|
-
stripped.startswith("pub struct ") or stripped.startswith("struct ") or
|
|
190
|
-
stripped.startswith("pub enum ") or stripped.startswith("enum ") or
|
|
191
|
-
stripped.startswith("pub trait ") or stripped.startswith("trait ") or
|
|
192
|
-
stripped.startswith("impl ") or stripped.startswith("#[") or
|
|
193
|
-
stripped.startswith("pub const ") or stripped.startswith("pub type ") or
|
|
194
|
-
stripped.startswith("const ") or stripped.startswith("type ")):
|
|
195
|
-
if "{" in stripped and not stripped.endswith("}"):
|
|
196
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
197
|
-
elif stripped.endswith(";"):
|
|
198
|
-
pruned.append(line)
|
|
199
|
-
elif stripped.endswith("{"):
|
|
200
|
-
pruned.append(f"{line[:-1]}{{ ... }}")
|
|
201
|
-
else:
|
|
202
|
-
pruned.append(line)
|
|
203
|
-
return "\n".join(pruned) if pruned else content
|
|
204
|
-
|
|
205
|
-
@staticmethod
|
|
206
|
-
def reduce_go(content: str, mode: str = "ultra") -> str:
|
|
207
|
-
"""Reduces Go source code to package, imports, types, interfaces, and func signatures."""
|
|
208
|
-
lines = content.splitlines()
|
|
209
|
-
pruned: List[str] = []
|
|
210
|
-
for line in lines:
|
|
211
|
-
stripped = line.strip()
|
|
212
|
-
if (stripped.startswith("package ") or stripped.startswith("import ") or
|
|
213
|
-
stripped.startswith("type ") or stripped.startswith("func ") or
|
|
214
|
-
stripped.startswith("var ") or stripped.startswith("const ")):
|
|
215
|
-
if stripped.startswith("func ") and "{" in stripped:
|
|
216
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
217
|
-
else:
|
|
218
|
-
pruned.append(line)
|
|
219
|
-
return "\n".join(pruned) if pruned else content
|
|
220
|
-
|
|
221
|
-
@staticmethod
|
|
222
|
-
def reduce_cpp(content: str, mode: str = "ultra") -> str:
|
|
223
|
-
"""Reduces C/C++ source code to headers, classes, structs, templates, and prototypes."""
|
|
224
|
-
lines = content.splitlines()
|
|
225
|
-
pruned: List[str] = []
|
|
226
|
-
for line in lines:
|
|
227
|
-
stripped = line.strip()
|
|
228
|
-
if (stripped.startswith("#include") or stripped.startswith("#define") or
|
|
229
|
-
stripped.startswith("template") or stripped.startswith("class ") or
|
|
230
|
-
stripped.startswith("struct ") or stripped.startswith("namespace ") or
|
|
231
|
-
stripped.startswith("using ") or stripped.startswith("typedef ") or
|
|
232
|
-
re.match(r'^(?:virtual\s+|static\s+|inline\s+)?[\w:<>]+\s+[\w:]+\s*\([^;]*\)\s*(?:const)?\s*\{?$', stripped)):
|
|
233
|
-
if "{" in stripped:
|
|
234
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
235
|
-
elif not stripped.endswith(";") and not stripped.startswith("#") and not stripped.startswith("namespace"):
|
|
236
|
-
pruned.append(f"{line};")
|
|
237
|
-
else:
|
|
238
|
-
pruned.append(line)
|
|
239
|
-
return "\n".join(pruned) if pruned else content
|
|
240
|
-
|
|
241
|
-
@staticmethod
|
|
242
|
-
def reduce_java(content: str, mode: str = "ultra") -> str:
|
|
243
|
-
"""Reduces Java/C# source code to packages, imports, classes, interfaces, records, and method signatures."""
|
|
244
|
-
lines = content.splitlines()
|
|
245
|
-
pruned: List[str] = []
|
|
246
|
-
for line in lines:
|
|
247
|
-
stripped = line.strip()
|
|
248
|
-
if (stripped.startswith("package ") or stripped.startswith("import ") or
|
|
249
|
-
stripped.startswith("using ") or stripped.startswith("namespace ") or
|
|
250
|
-
"class " in stripped or "interface " in stripped or "record " in stripped or
|
|
251
|
-
"enum " in stripped or re.match(r'^\s*(?:public|private|protected|static|final|abstract|async)\s+.*\(.*\)', stripped)):
|
|
252
|
-
if "{" in stripped:
|
|
253
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
254
|
-
elif not stripped.endswith(";") and not stripped.startswith("package") and not stripped.startswith("import"):
|
|
255
|
-
pruned.append(f"{line} { ... }")
|
|
256
|
-
else:
|
|
257
|
-
pruned.append(line)
|
|
258
|
-
return "\n".join(pruned) if pruned else content
|
|
259
|
-
|
|
260
|
-
@staticmethod
|
|
261
|
-
def reduce_solidity(content: str, mode: str = "ultra") -> str:
|
|
262
|
-
"""Reduces Solidity smart contracts to pragma, interfaces, contracts, structs, events, and function headers."""
|
|
263
|
-
lines = content.splitlines()
|
|
264
|
-
pruned: List[str] = []
|
|
265
|
-
for line in lines:
|
|
266
|
-
stripped = line.strip()
|
|
267
|
-
if (stripped.startswith("pragma ") or stripped.startswith("import ") or
|
|
268
|
-
stripped.startswith("contract ") or stripped.startswith("interface ") or
|
|
269
|
-
stripped.startswith("library ") or stripped.startswith("struct ") or
|
|
270
|
-
stripped.startswith("event ") or stripped.startswith("modifier ") or
|
|
271
|
-
stripped.startswith("function ") or stripped.startswith("mapping(")):
|
|
272
|
-
if "{" in stripped and not stripped.endswith("}"):
|
|
273
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
274
|
-
elif stripped.startswith("function ") and not stripped.endswith(";"):
|
|
275
|
-
pruned.append(f"{line};")
|
|
276
|
-
else:
|
|
277
|
-
pruned.append(line)
|
|
278
|
-
return "\n".join(pruned) if pruned else content
|
|
279
|
-
|
|
280
|
-
@staticmethod
|
|
281
|
-
def reduce_ruby(content: str, mode: str = "ultra") -> str:
|
|
282
|
-
"""Reduces Ruby source code to module/class declarations, requires, mixins, and method signatures."""
|
|
283
|
-
lines = content.splitlines()
|
|
284
|
-
pruned: List[str] = []
|
|
285
|
-
for line in lines:
|
|
286
|
-
stripped = line.strip()
|
|
287
|
-
if (stripped.startswith("require ") or stripped.startswith("require_relative ") or
|
|
288
|
-
stripped.startswith("module ") or stripped.startswith("class ") or
|
|
289
|
-
stripped.startswith("def ") or stripped.startswith("attr_") or
|
|
290
|
-
stripped.startswith("include ") or stripped.startswith("extend ") or
|
|
291
|
-
stripped.startswith("has_many ") or stripped.startswith("belongs_to ") or
|
|
292
|
-
stripped in ("private", "protected", "public")):
|
|
293
|
-
if stripped.startswith("def ") and not stripped.endswith("end"):
|
|
294
|
-
pruned.append(f"{line}; ...; end")
|
|
295
|
-
else:
|
|
296
|
-
pruned.append(line)
|
|
297
|
-
return "\n".join(pruned) if pruned else content
|
|
298
|
-
|
|
299
|
-
@staticmethod
|
|
300
|
-
def reduce_php(content: str, mode: str = "ultra") -> str:
|
|
301
|
-
"""Reduces PHP source code to namespace, imports, classes, interfaces, traits, and method signatures."""
|
|
302
|
-
lines = content.splitlines()
|
|
303
|
-
pruned: List[str] = []
|
|
304
|
-
for line in lines:
|
|
305
|
-
stripped = line.strip()
|
|
306
|
-
if (stripped.startswith("<?php") or stripped.startswith("namespace ") or
|
|
307
|
-
stripped.startswith("use ") or "class " in stripped or
|
|
308
|
-
"interface " in stripped or "trait " in stripped or "enum " in stripped or
|
|
309
|
-
"function " in stripped):
|
|
310
|
-
if "{" in stripped:
|
|
311
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
312
|
-
elif "function " in stripped and not stripped.endswith(";"):
|
|
313
|
-
pruned.append(f"{line} {{ ... }}")
|
|
314
|
-
else:
|
|
315
|
-
pruned.append(line)
|
|
316
|
-
return "\n".join(pruned) if pruned else content
|
|
317
|
-
|
|
318
|
-
@staticmethod
|
|
319
|
-
def reduce_swift(content: str, mode: str = "ultra") -> str:
|
|
320
|
-
"""Reduces Swift source code to imports, protocols, classes, structs, enums, extensions, and func signatures."""
|
|
321
|
-
lines = content.splitlines()
|
|
322
|
-
pruned: List[str] = []
|
|
323
|
-
for line in lines:
|
|
324
|
-
stripped = line.strip()
|
|
325
|
-
if (stripped.startswith("import ") or stripped.startswith("protocol ") or
|
|
326
|
-
"class " in stripped or "struct " in stripped or "enum " in stripped or
|
|
327
|
-
"extension " in stripped or "func " in stripped or stripped.startswith("init(")):
|
|
328
|
-
if "{" in stripped:
|
|
329
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
330
|
-
elif not stripped.endswith(";"):
|
|
331
|
-
pruned.append(f"{line} {{ ... }}")
|
|
332
|
-
else:
|
|
333
|
-
pruned.append(line)
|
|
334
|
-
return "\n".join(pruned) if pruned else content
|
|
335
|
-
|
|
336
|
-
@staticmethod
|
|
337
|
-
def reduce_kotlin(content: str, mode: str = "ultra") -> str:
|
|
338
|
-
"""Reduces Kotlin source code to package, imports, classes, interfaces, objects, and function headers."""
|
|
339
|
-
lines = content.splitlines()
|
|
340
|
-
pruned: List[str] = []
|
|
341
|
-
for line in lines:
|
|
342
|
-
stripped = line.strip()
|
|
343
|
-
if (stripped.startswith("package ") or stripped.startswith("import ") or
|
|
344
|
-
"class " in stripped or "interface " in stripped or "object " in stripped or
|
|
345
|
-
stripped.startswith("fun ") or " fun " in stripped):
|
|
346
|
-
if "{" in stripped:
|
|
347
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
348
|
-
elif not stripped.endswith(";"):
|
|
349
|
-
pruned.append(f"{line} {{ ... }}")
|
|
350
|
-
else:
|
|
351
|
-
pruned.append(line)
|
|
352
|
-
return "\n".join(pruned) if pruned else content
|
|
353
|
-
|
|
354
|
-
@staticmethod
|
|
355
|
-
def reduce_dart(content: str, mode: str = "ultra") -> str:
|
|
356
|
-
"""Reduces Dart source code to imports, exports, classes, mixins, enums, and method signatures."""
|
|
357
|
-
lines = content.splitlines()
|
|
358
|
-
pruned: List[str] = []
|
|
359
|
-
for line in lines:
|
|
360
|
-
stripped = line.strip()
|
|
361
|
-
if not stripped or stripped.startswith("//") or stripped.startswith("/*"):
|
|
362
|
-
continue
|
|
363
|
-
if stripped.startswith(("return ", "return;", "if ", "if(", "for ", "for(", "while ", "while(", "switch ", "throw ", "print(")):
|
|
364
|
-
continue
|
|
365
|
-
if (stripped.startswith("import ") or stripped.startswith("export ") or
|
|
366
|
-
stripped.startswith("part ") or "class " in stripped or
|
|
367
|
-
"mixin " in stripped or "enum " in stripped or "extension " in stripped or
|
|
368
|
-
re.match(r'^\s*(?:@\w+\s+)*(?:static\s+|async\s+)?[\w<>,]+\s+\w+\s*\(.*?\)', stripped)):
|
|
369
|
-
if "{" in stripped and not ("class " in stripped or "mixin " in stripped):
|
|
370
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
371
|
-
elif not stripped.endswith(";") and not stripped.endswith("{"):
|
|
372
|
-
pruned.append(f"{line} {{ ... }}")
|
|
373
|
-
else:
|
|
374
|
-
pruned.append(line)
|
|
375
|
-
return "\n".join(pruned) if pruned else content
|
|
376
|
-
|
|
377
|
-
@staticmethod
|
|
378
|
-
def reduce_scala(content: str, mode: str = "ultra") -> str:
|
|
379
|
-
"""Reduces Scala source code to packages, imports, traits, objects, classes, and def headers."""
|
|
380
|
-
lines = content.splitlines()
|
|
381
|
-
pruned: List[str] = []
|
|
382
|
-
for line in lines:
|
|
383
|
-
stripped = line.strip()
|
|
384
|
-
if not stripped or stripped.startswith("//") or stripped.startswith("/*"):
|
|
385
|
-
continue
|
|
386
|
-
if (stripped.startswith("package ") or stripped.startswith("import ") or
|
|
387
|
-
"class " in stripped or "trait " in stripped or "object " in stripped or
|
|
388
|
-
"enum " in stripped or stripped.startswith("def ") or " def " in stripped):
|
|
389
|
-
if "{" in stripped and not ("class " in stripped or "trait " in stripped or "object " in stripped):
|
|
390
|
-
pruned.append(re.sub(r'\{.*$', '{ ... }', line))
|
|
391
|
-
elif not stripped.endswith(";") and not stripped.endswith("{"):
|
|
392
|
-
pruned.append(f"{line} {{ ... }}")
|
|
393
|
-
else:
|
|
394
|
-
pruned.append(line)
|
|
395
|
-
return "\n".join(pruned) if pruned else content
|
|
396
|
-
|
|
397
|
-
@staticmethod
|
|
398
|
-
def reduce_elixir(content: str, mode: str = "ultra") -> str:
|
|
399
|
-
"""Reduces Elixir source code to module headers, structs, specs, and function signatures."""
|
|
400
|
-
lines = content.splitlines()
|
|
401
|
-
pruned: List[str] = []
|
|
402
|
-
for line in lines:
|
|
403
|
-
stripped = line.strip()
|
|
404
|
-
if not stripped or stripped.startswith("#"):
|
|
405
|
-
continue
|
|
406
|
-
if (stripped.startswith("defmodule ") or stripped.startswith("defstruct ") or
|
|
407
|
-
stripped.startswith("alias ") or stripped.startswith("import ") or
|
|
408
|
-
stripped.startswith("require ") or stripped.startswith("use ") or
|
|
409
|
-
stripped.startswith("@type ") or stripped.startswith("@spec ") or
|
|
410
|
-
stripped.startswith("def ") or stripped.startswith("defp ") or
|
|
411
|
-
stripped.startswith("defmacro ")):
|
|
412
|
-
if stripped.startswith("defmodule "):
|
|
413
|
-
pruned.append(line)
|
|
414
|
-
elif ", do:" in stripped:
|
|
415
|
-
pruned.append(re.sub(r', do:.*$', ', do: ...', line))
|
|
416
|
-
elif stripped.endswith(" do"):
|
|
417
|
-
pruned.append(re.sub(r'\s+do$', ', do: ...', line))
|
|
418
|
-
else:
|
|
419
|
-
pruned.append(line)
|
|
420
|
-
return "\n".join(pruned) if pruned else content
|
|
421
|
-
|
|
422
|
-
|
package/src/tzero_snapshot.py
DELETED
|
@@ -1,258 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
Siber Akademi — T-Zero Sub-10ms AST Context Snapshot Engine.
|
|
4
|
-
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
-
License: MIT
|
|
6
|
-
|
|
7
|
-
Pre-computes and caches high-speed AST symbols, module dependency graphs,
|
|
8
|
-
and token metrics in .tzero/snapshot.json.
|
|
9
|
-
Enables sub-8ms context ingestion on repositories with 10,000+ files.
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
import os
|
|
13
|
-
import sys
|
|
14
|
-
import ast
|
|
15
|
-
import json
|
|
16
|
-
import time
|
|
17
|
-
import hashlib
|
|
18
|
-
from dataclasses import dataclass, field, asdict
|
|
19
|
-
from typing import Dict, List, Any, Optional, Tuple
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
@dataclass
|
|
23
|
-
class FileSnapshot:
|
|
24
|
-
rel_path: str
|
|
25
|
-
mtime: float
|
|
26
|
-
size_bytes: int
|
|
27
|
-
hash_prefix: str
|
|
28
|
-
raw_tokens: int
|
|
29
|
-
pruned_tokens: int
|
|
30
|
-
classes: List[str] = field(default_factory=list)
|
|
31
|
-
functions: List[str] = field(default_factory=list)
|
|
32
|
-
imports: List[str] = field(default_factory=list)
|
|
33
|
-
skeleton: str = ""
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
@dataclass
|
|
37
|
-
class SnapshotResult:
|
|
38
|
-
workspace_dir: str
|
|
39
|
-
created_at: float
|
|
40
|
-
file_count: int
|
|
41
|
-
total_raw_tokens: int
|
|
42
|
-
total_pruned_tokens: int
|
|
43
|
-
reduction_pct: float
|
|
44
|
-
files: Dict[str, FileSnapshot] = field(default_factory=dict)
|
|
45
|
-
generation_time_ms: float = 0.0
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
class SnapshotEngine:
|
|
49
|
-
"""Enterprise-grade AST Context Snapshot Engine for instant sub-8ms context queries."""
|
|
50
|
-
|
|
51
|
-
CACHE_DIR = ".tzero"
|
|
52
|
-
SNAPSHOT_FILENAME = "snapshot.json"
|
|
53
|
-
SKIP_DIRS = {
|
|
54
|
-
".git", "__pycache__", ".pytest_cache", "target", "dist",
|
|
55
|
-
"build", ".venv", "venv", "node_modules", ".superpowers", "bin", ".tzero"
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
@classmethod
|
|
59
|
-
def get_cache_path(cls, workspace_dir: str, custom_path: Optional[str] = None) -> str:
|
|
60
|
-
if custom_path:
|
|
61
|
-
return os.path.abspath(custom_path)
|
|
62
|
-
return os.path.join(os.path.abspath(workspace_dir), cls.CACHE_DIR, cls.SNAPSHOT_FILENAME)
|
|
63
|
-
|
|
64
|
-
@classmethod
|
|
65
|
-
def create_snapshot(cls, workspace_dir: str, cache_file: Optional[str] = None) -> SnapshotResult:
|
|
66
|
-
"""Parses workspace files, extracts AST skeletons, and saves snapshot to disk."""
|
|
67
|
-
start_t = time.perf_counter()
|
|
68
|
-
abs_root = os.path.abspath(workspace_dir)
|
|
69
|
-
files_data: Dict[str, FileSnapshot] = {}
|
|
70
|
-
|
|
71
|
-
total_raw = 0
|
|
72
|
-
total_pruned = 0
|
|
73
|
-
|
|
74
|
-
for root, dirs, fnames in os.walk(abs_root):
|
|
75
|
-
dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
|
|
76
|
-
for fname in fnames:
|
|
77
|
-
if fname.endswith(".py"):
|
|
78
|
-
fpath = os.path.join(root, fname)
|
|
79
|
-
rel = os.path.relpath(fpath, abs_root).replace("\\", "/")
|
|
80
|
-
try:
|
|
81
|
-
stat = os.stat(fpath)
|
|
82
|
-
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
|
|
83
|
-
content = f.read()
|
|
84
|
-
|
|
85
|
-
# Token estimation
|
|
86
|
-
raw_tok = max(1, len(content) // 4)
|
|
87
|
-
total_raw += raw_tok
|
|
88
|
-
|
|
89
|
-
# AST parse
|
|
90
|
-
tree = ast.parse(content, filename=fname)
|
|
91
|
-
classes = []
|
|
92
|
-
functions = []
|
|
93
|
-
imports = []
|
|
94
|
-
skeleton_lines = []
|
|
95
|
-
|
|
96
|
-
for node in tree.body:
|
|
97
|
-
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
98
|
-
if isinstance(node, ast.Import):
|
|
99
|
-
imports.extend(alias.name for alias in node.names)
|
|
100
|
-
skeleton_lines.append(f"import {', '.join(a.name for a in node.names)}")
|
|
101
|
-
else:
|
|
102
|
-
mod = node.module or ""
|
|
103
|
-
imports.append(mod)
|
|
104
|
-
skeleton_lines.append(f"from {mod} import {', '.join(a.name for a in node.names)}")
|
|
105
|
-
elif isinstance(node, ast.ClassDef):
|
|
106
|
-
classes.append(node.name)
|
|
107
|
-
bases = [ast.unparse(b) for b in node.bases] if hasattr(ast, "unparse") else []
|
|
108
|
-
base_str = f"({', '.join(bases)})" if bases else ""
|
|
109
|
-
skeleton_lines.append(f"class {node.name}{base_str}:")
|
|
110
|
-
doc = ast.get_docstring(node)
|
|
111
|
-
if doc:
|
|
112
|
-
skeleton_lines.append(f' """{doc.splitlines()[0]}"""')
|
|
113
|
-
for item in node.body:
|
|
114
|
-
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
115
|
-
prefix = "async def" if isinstance(item, ast.AsyncFunctionDef) else "def"
|
|
116
|
-
args = [a.arg for a in item.args.args]
|
|
117
|
-
skeleton_lines.append(f" {prefix} {item.name}({', '.join(args)}): ...")
|
|
118
|
-
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
119
|
-
functions.append(node.name)
|
|
120
|
-
prefix = "async def" if isinstance(item := node, ast.AsyncFunctionDef) else "def"
|
|
121
|
-
args = [a.arg for a in node.args.args]
|
|
122
|
-
skeleton_lines.append(f"{prefix} {node.name}({', '.join(args)}): ...")
|
|
123
|
-
doc = ast.get_docstring(node)
|
|
124
|
-
if doc:
|
|
125
|
-
skeleton_lines.append(f' """{doc.splitlines()[0]}"""')
|
|
126
|
-
|
|
127
|
-
skel_str = "\n".join(skeleton_lines)
|
|
128
|
-
pruned_tok = max(1, len(skel_str) // 4)
|
|
129
|
-
total_pruned += pruned_tok
|
|
130
|
-
|
|
131
|
-
hasher = hashlib.sha256()
|
|
132
|
-
hasher.update(content[:1024].encode("utf-8", errors="replace"))
|
|
133
|
-
h_prefix = hasher.hexdigest()[:16]
|
|
134
|
-
|
|
135
|
-
files_data[rel] = FileSnapshot(
|
|
136
|
-
rel_path=rel,
|
|
137
|
-
mtime=stat.st_mtime,
|
|
138
|
-
size_bytes=stat.st_size,
|
|
139
|
-
hash_prefix=h_prefix,
|
|
140
|
-
raw_tokens=raw_tok,
|
|
141
|
-
pruned_tokens=pruned_tok,
|
|
142
|
-
classes=classes,
|
|
143
|
-
functions=functions,
|
|
144
|
-
imports=imports,
|
|
145
|
-
skeleton=skel_str
|
|
146
|
-
)
|
|
147
|
-
except Exception:
|
|
148
|
-
pass
|
|
149
|
-
|
|
150
|
-
elapsed_ms = (time.perf_counter() - start_t) * 1000.0
|
|
151
|
-
sav_pct = round(((1.0 - (total_pruned / max(1, total_raw))) * 100.0), 2)
|
|
152
|
-
|
|
153
|
-
res = SnapshotResult(
|
|
154
|
-
workspace_dir=abs_root,
|
|
155
|
-
created_at=time.time(),
|
|
156
|
-
file_count=len(files_data),
|
|
157
|
-
total_raw_tokens=total_raw,
|
|
158
|
-
total_pruned_tokens=total_pruned,
|
|
159
|
-
reduction_pct=sav_pct,
|
|
160
|
-
files=files_data,
|
|
161
|
-
generation_time_ms=elapsed_ms
|
|
162
|
-
)
|
|
163
|
-
|
|
164
|
-
# Write to cache
|
|
165
|
-
cache_path = cls.get_cache_path(abs_root, cache_file)
|
|
166
|
-
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
|
167
|
-
with open(cache_path, "w", encoding="utf-8") as f:
|
|
168
|
-
f.write(json.dumps(cls.to_dict(res), indent=2))
|
|
169
|
-
|
|
170
|
-
return res
|
|
171
|
-
|
|
172
|
-
@classmethod
|
|
173
|
-
def load_snapshot(cls, workspace_dir: str, cache_file: Optional[str] = None) -> Optional[SnapshotResult]:
|
|
174
|
-
"""Loads existing snapshot from disk if available."""
|
|
175
|
-
start_t = time.perf_counter()
|
|
176
|
-
cache_path = cls.get_cache_path(workspace_dir, cache_file)
|
|
177
|
-
if not os.path.exists(cache_path):
|
|
178
|
-
return None
|
|
179
|
-
|
|
180
|
-
try:
|
|
181
|
-
with open(cache_path, "r", encoding="utf-8") as f:
|
|
182
|
-
data = json.load(f)
|
|
183
|
-
|
|
184
|
-
files_map = {}
|
|
185
|
-
for rel, fd in data.get("files", {}).items():
|
|
186
|
-
files_map[rel] = FileSnapshot(**fd)
|
|
187
|
-
|
|
188
|
-
elapsed_ms = (time.perf_counter() - start_t) * 1000.0
|
|
189
|
-
return SnapshotResult(
|
|
190
|
-
workspace_dir=data["workspace_dir"],
|
|
191
|
-
created_at=data["created_at"],
|
|
192
|
-
file_count=data["file_count"],
|
|
193
|
-
total_raw_tokens=data["total_raw_tokens"],
|
|
194
|
-
total_pruned_tokens=data["total_pruned_tokens"],
|
|
195
|
-
reduction_pct=data["reduction_pct"],
|
|
196
|
-
files=files_map,
|
|
197
|
-
generation_time_ms=elapsed_ms
|
|
198
|
-
)
|
|
199
|
-
except Exception:
|
|
200
|
-
return None
|
|
201
|
-
|
|
202
|
-
@classmethod
|
|
203
|
-
def is_valid(cls, snapshot: SnapshotResult, workspace_dir: str) -> bool:
|
|
204
|
-
"""Verifies if snapshot is still fresh against filesystem state."""
|
|
205
|
-
abs_root = os.path.abspath(workspace_dir)
|
|
206
|
-
# Spot check up to 15 files
|
|
207
|
-
checked = 0
|
|
208
|
-
for rel, snap in snapshot.files.items():
|
|
209
|
-
fpath = os.path.join(abs_root, rel.replace("/", os.sep))
|
|
210
|
-
if not os.path.exists(fpath):
|
|
211
|
-
return False
|
|
212
|
-
try:
|
|
213
|
-
stat = os.stat(fpath)
|
|
214
|
-
if abs(stat.st_mtime - snap.mtime) > 1.0 or stat.st_size != snap.size_bytes:
|
|
215
|
-
return False
|
|
216
|
-
except Exception:
|
|
217
|
-
return False
|
|
218
|
-
checked += 1
|
|
219
|
-
if checked >= 15:
|
|
220
|
-
break
|
|
221
|
-
return True
|
|
222
|
-
|
|
223
|
-
@classmethod
|
|
224
|
-
def get_or_create(cls, workspace_dir: str, force_refresh: bool = False) -> Tuple[SnapshotResult, bool]:
|
|
225
|
-
"""Returns (snapshot, was_cached). Fast-path loads snapshot in <8ms."""
|
|
226
|
-
if not force_refresh:
|
|
227
|
-
cached = cls.load_snapshot(workspace_dir)
|
|
228
|
-
if cached and cls.is_valid(cached, workspace_dir):
|
|
229
|
-
return cached, True
|
|
230
|
-
|
|
231
|
-
fresh = cls.create_snapshot(workspace_dir)
|
|
232
|
-
return fresh, False
|
|
233
|
-
|
|
234
|
-
@classmethod
|
|
235
|
-
def to_dict(cls, result: SnapshotResult) -> Dict[str, Any]:
|
|
236
|
-
return {
|
|
237
|
-
"workspace_dir": result.workspace_dir,
|
|
238
|
-
"created_at": result.created_at,
|
|
239
|
-
"file_count": result.file_count,
|
|
240
|
-
"total_raw_tokens": result.total_raw_tokens,
|
|
241
|
-
"total_pruned_tokens": result.total_pruned_tokens,
|
|
242
|
-
"reduction_pct": result.reduction_pct,
|
|
243
|
-
"generation_time_ms": round(result.generation_time_ms, 2),
|
|
244
|
-
"files": {rel: asdict(snap) for rel, snap in result.files.items()}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
@classmethod
|
|
248
|
-
def render_cli(cls, res: SnapshotResult, was_cached: bool = False):
|
|
249
|
-
mode_str = "\033[32m[CACHE HIT - SUB-8MS]\033[0m" if was_cached else "\033[36m[NEW SNAPSHOT BUILT]\033[0m"
|
|
250
|
-
print(f"\n⚡ \033[1mT-ZERO CONTEXT SNAPSHOT ENGINE\033[0m {mode_str}")
|
|
251
|
-
print("=" * 70)
|
|
252
|
-
print(f"📁 Workspace Root: {res.workspace_dir}")
|
|
253
|
-
print(f"📄 Indexed Source Files: {res.file_count:,} Python modules")
|
|
254
|
-
print(f"📊 Token Economics: {res.total_pruned_tokens:,} pruned vs {res.total_raw_tokens:,} raw (\033[32m-{res.reduction_pct}%\033[0m)")
|
|
255
|
-
print(f"⏱️ Load / Build Time: \033[33m{res.generation_time_ms:.2f} ms\033[0m")
|
|
256
|
-
print(f"💾 Snapshot Location: .tzero/{cls.SNAPSHOT_FILENAME}")
|
|
257
|
-
print("=" * 70)
|
|
258
|
-
|