tzero-mcp 10.7.3 → 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 +44 -577
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -65
  5. package/bin/tzero.js +61 -64
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -67
  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 -19
  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,471 @@
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 re
14
+ import sys
15
+ import ast
16
+ import json
17
+ import time
18
+ import hashlib
19
+ import sqlite3
20
+ import subprocess
21
+ from dataclasses import dataclass, field, asdict
22
+ from typing import Dict, List, Any, Optional, Tuple
23
+
24
+ from tzero.tzero_polyglot import PolyglotTokenReducer, count_bpe_tokens
25
+
26
+
27
+ @dataclass
28
+ class FileSnapshot:
29
+ rel_path: str
30
+ mtime: float
31
+ size_bytes: int
32
+ hash_prefix: str
33
+ raw_tokens: int
34
+ pruned_tokens: int
35
+ classes: List[str] = field(default_factory=list)
36
+ functions: List[str] = field(default_factory=list)
37
+ imports: List[str] = field(default_factory=list)
38
+ skeleton: str = ""
39
+
40
+
41
+ @dataclass
42
+ class SnapshotResult:
43
+ workspace_dir: str
44
+ created_at: float
45
+ file_count: int
46
+ total_raw_tokens: int
47
+ total_pruned_tokens: int
48
+ reduction_pct: float
49
+ files: Dict[str, FileSnapshot] = field(default_factory=dict)
50
+ generation_time_ms: float = 0.0
51
+
52
+
53
+ class SnapshotEngine:
54
+ """Enterprise-grade AST Context Snapshot Engine for instant sub-8ms context queries."""
55
+
56
+ CACHE_DIR = ".tzero"
57
+ SNAPSHOT_FILENAME = "snapshot.json"
58
+ SQLITE_FILENAME = "snapshot.db"
59
+ SKIP_DIRS = {
60
+ ".git", "__pycache__", ".pytest_cache", "target", "dist",
61
+ "build", ".venv", "venv", "node_modules", ".superpowers", "bin", ".tzero"
62
+ }
63
+
64
+ @classmethod
65
+ def get_cache_path(cls, workspace_dir: str, custom_path: Optional[str] = None) -> str:
66
+ if custom_path:
67
+ return os.path.abspath(custom_path)
68
+ return os.path.join(os.path.abspath(workspace_dir), cls.CACHE_DIR, cls.SNAPSHOT_FILENAME)
69
+
70
+ @classmethod
71
+ def get_sqlite_path(cls, workspace_dir: str, custom_path: Optional[str] = None) -> str:
72
+ if custom_path:
73
+ return os.path.abspath(custom_path)
74
+ return os.path.join(os.path.abspath(workspace_dir), cls.CACHE_DIR, cls.SQLITE_FILENAME)
75
+
76
+ @classmethod
77
+ def _parse_file_snapshot(cls, fpath: str, abs_root: str) -> Optional[FileSnapshot]:
78
+ """Parses a single source file (Python AST or Polyglot lexical engine) into a FileSnapshot."""
79
+ fname = os.path.basename(fpath)
80
+ lang = PolyglotTokenReducer.detect_language(fname)
81
+ if not lang:
82
+ return None
83
+ rel = os.path.relpath(fpath, abs_root).replace("\\", "/")
84
+ try:
85
+ stat = os.stat(fpath)
86
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
87
+ content = f.read()
88
+ except OSError:
89
+ return None
90
+
91
+ raw_tok = count_bpe_tokens(content)
92
+ classes: List[str] = []
93
+ functions: List[str] = []
94
+ imports: List[str] = []
95
+ skeleton_lines: List[str] = []
96
+
97
+ if lang == "python":
98
+ try:
99
+ tree = ast.parse(content, filename=fname)
100
+ for node in tree.body:
101
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
102
+ if isinstance(node, ast.Import):
103
+ imports.extend(alias.name for alias in node.names)
104
+ skeleton_lines.append(f"import {', '.join(a.name for a in node.names)}")
105
+ else:
106
+ mod = node.module or ""
107
+ imports.append(mod)
108
+ skeleton_lines.append(f"from {mod} import {', '.join(a.name for a in node.names)}")
109
+ elif isinstance(node, ast.ClassDef):
110
+ classes.append(node.name)
111
+ bases = [ast.unparse(b) for b in node.bases] if hasattr(ast, "unparse") else []
112
+ base_str = f"({', '.join(bases)})" if bases else ""
113
+ skeleton_lines.append(f"class {node.name}{base_str}:")
114
+ doc = ast.get_docstring(node)
115
+ if doc:
116
+ skeleton_lines.append(f' """{doc.splitlines()[0]}"""')
117
+ for item in node.body:
118
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
119
+ prefix = "async def" if isinstance(item, ast.AsyncFunctionDef) else "def"
120
+ args = [a.arg for a in item.args.args]
121
+ skeleton_lines.append(f" {prefix} {item.name}({', '.join(args)}): ...")
122
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
123
+ functions.append(node.name)
124
+ prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def"
125
+ args = [a.arg for a in node.args.args]
126
+ skeleton_lines.append(f"{prefix} {node.name}({', '.join(args)}): ...")
127
+ doc = ast.get_docstring(node)
128
+ if doc:
129
+ skeleton_lines.append(f' """{doc.splitlines()[0]}"""')
130
+ skel_str = "\n".join(skeleton_lines)
131
+ except SyntaxError:
132
+ skel_str = PolyglotTokenReducer.reduce_code(content, fname, mode="ultra")
133
+ else:
134
+ skel_str = PolyglotTokenReducer.reduce_code(content, fname, mode="ultra")
135
+ for m in re.finditer(r'\b(?:class|interface|struct|trait|enum|contract|type)\s+([A-Za-z_][A-Za-z0-9_]*)', content):
136
+ if m.group(1) not in classes:
137
+ classes.append(m.group(1))
138
+ for m in re.finditer(r'\b(?:function|func|fn|def|fun)\s+([A-Za-z_][A-Za-z0-9_]*)', content):
139
+ if m.group(1) not in functions:
140
+ functions.append(m.group(1))
141
+ for m in re.finditer(r'^\s*(?:import|use)\s+["\']?([A-Za-z0-9_./:-]+)', content, re.MULTILINE):
142
+ if m.group(1) not in imports:
143
+ imports.append(m.group(1))
144
+
145
+ pruned_tok = count_bpe_tokens(skel_str) if skel_str else 0
146
+ h_prefix = hashlib.sha256(content.encode("utf-8", errors="replace")).hexdigest()[:16]
147
+ return FileSnapshot(
148
+ rel_path=rel,
149
+ mtime=stat.st_mtime,
150
+ size_bytes=stat.st_size,
151
+ hash_prefix=h_prefix,
152
+ raw_tokens=raw_tok,
153
+ pruned_tokens=pruned_tok,
154
+ classes=classes,
155
+ functions=functions,
156
+ imports=imports,
157
+ skeleton=skel_str,
158
+ )
159
+
160
+ @classmethod
161
+ def _discover_workspace_files(cls, abs_root: str) -> Dict[str, Tuple[str, os.stat_result]]:
162
+ discovered: Dict[str, Tuple[str, os.stat_result]] = {}
163
+ for root, dirs, fnames in os.walk(abs_root):
164
+ dirs[:] = sorted(d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith("."))
165
+ for fname in sorted(fnames):
166
+ if PolyglotTokenReducer.detect_language(fname):
167
+ fpath = os.path.join(root, fname)
168
+ rel = os.path.relpath(fpath, abs_root).replace("\\", "/")
169
+ try:
170
+ discovered[rel] = (fpath, os.stat(fpath))
171
+ except OSError:
172
+ pass
173
+ return discovered
174
+
175
+ @classmethod
176
+ def detect_git_changed_files(cls, workspace_dir: str) -> List[str]:
177
+ """Returns normalized relative paths changed or untracked according to git."""
178
+ abs_root = os.path.abspath(workspace_dir)
179
+ changed: List[str] = []
180
+ try:
181
+ res = subprocess.run(
182
+ ["git", "-C", abs_root, "status", "--porcelain"],
183
+ capture_output=True,
184
+ text=True,
185
+ timeout=3,
186
+ )
187
+ if res.returncode == 0:
188
+ for line in res.stdout.splitlines():
189
+ if len(line) > 3:
190
+ p = line[3:].strip().split(" -> ")[-1].strip('"')
191
+ if p:
192
+ changed.append(p.replace("\\", "/"))
193
+ except Exception:
194
+ pass
195
+ return changed
196
+
197
+ @classmethod
198
+ def _save_snapshot(cls, res: SnapshotResult, cache_file: Optional[str] = None) -> None:
199
+ abs_root = res.workspace_dir
200
+ cache_path = cls.get_cache_path(abs_root, cache_file)
201
+ os.makedirs(os.path.dirname(cache_path), exist_ok=True)
202
+ with open(cache_path, "w", encoding="utf-8") as f:
203
+ f.write(json.dumps(cls.to_dict(res), indent=2))
204
+
205
+ if cache_file is None:
206
+ db_path = cls.get_sqlite_path(abs_root)
207
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
208
+ conn = sqlite3.connect(db_path)
209
+ try:
210
+ conn.execute(
211
+ "CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)"
212
+ )
213
+ conn.execute(
214
+ "CREATE TABLE IF NOT EXISTS file_snapshots ("
215
+ "rel_path TEXT PRIMARY KEY, mtime REAL, size_bytes INTEGER, hash_prefix TEXT, "
216
+ "raw_tokens INTEGER, pruned_tokens INTEGER, classes_json TEXT, "
217
+ "functions_json TEXT, imports_json TEXT, skeleton TEXT)"
218
+ )
219
+ meta_items = [
220
+ ("workspace_dir", res.workspace_dir),
221
+ ("created_at", str(res.created_at)),
222
+ ("file_count", str(res.file_count)),
223
+ ("total_raw_tokens", str(res.total_raw_tokens)),
224
+ ("total_pruned_tokens", str(res.total_pruned_tokens)),
225
+ ("reduction_pct", str(res.reduction_pct)),
226
+ ]
227
+ conn.executemany(
228
+ "INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",
229
+ meta_items,
230
+ )
231
+ conn.execute("DELETE FROM file_snapshots")
232
+ rows = [
233
+ (
234
+ rel, fs.mtime, fs.size_bytes, fs.hash_prefix,
235
+ fs.raw_tokens, fs.pruned_tokens,
236
+ json.dumps(fs.classes), json.dumps(fs.functions),
237
+ json.dumps(fs.imports), fs.skeleton,
238
+ )
239
+ for rel, fs in res.files.items()
240
+ ]
241
+ conn.executemany(
242
+ "INSERT INTO file_snapshots VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
243
+ rows,
244
+ )
245
+ conn.commit()
246
+ finally:
247
+ conn.close()
248
+
249
+ @classmethod
250
+ def create_snapshot(cls, workspace_dir: str, cache_file: Optional[str] = None) -> SnapshotResult:
251
+ """Parses workspace files across all supported languages and saves JSON + SQLite snapshot."""
252
+ start_t = time.perf_counter()
253
+ abs_root = os.path.abspath(workspace_dir)
254
+ files_data: Dict[str, FileSnapshot] = {}
255
+
256
+ total_raw = 0
257
+ total_pruned = 0
258
+
259
+ for rel, (fpath, _) in cls._discover_workspace_files(abs_root).items():
260
+ snap = cls._parse_file_snapshot(fpath, abs_root)
261
+ if snap is not None:
262
+ files_data[rel] = snap
263
+ total_raw += snap.raw_tokens
264
+ total_pruned += snap.pruned_tokens
265
+
266
+ elapsed_ms = (time.perf_counter() - start_t) * 1000.0
267
+ sav_pct = round(((1.0 - (total_pruned / max(1, total_raw))) * 100.0), 2)
268
+
269
+ res = SnapshotResult(
270
+ workspace_dir=abs_root,
271
+ created_at=time.time(),
272
+ file_count=len(files_data),
273
+ total_raw_tokens=total_raw,
274
+ total_pruned_tokens=total_pruned,
275
+ reduction_pct=sav_pct,
276
+ files=files_data,
277
+ generation_time_ms=elapsed_ms
278
+ )
279
+ cls._save_snapshot(res, cache_file=cache_file)
280
+ return res
281
+
282
+ @classmethod
283
+ def update_incremental(
284
+ cls,
285
+ workspace_dir: str,
286
+ changed_files: Optional[List[str]] = None,
287
+ ) -> Tuple[SnapshotResult, Dict[str, int]]:
288
+ """Incrementally updates SQLite/JSON snapshot by reparsing only added or changed files."""
289
+ start_t = time.perf_counter()
290
+ abs_root = os.path.abspath(workspace_dir)
291
+ existing = cls.load_snapshot(abs_root)
292
+ if existing is None:
293
+ fresh = cls.create_snapshot(abs_root)
294
+ return fresh, {"reparsed": fresh.file_count, "reused": 0, "deleted": 0}
295
+
296
+ discovered = cls._discover_workspace_files(abs_root)
297
+ explicit_set = {p.replace("\\", "/") for p in changed_files} if changed_files is not None else set()
298
+
299
+ updated_files: Dict[str, FileSnapshot] = {}
300
+ reparsed = 0
301
+ reused = 0
302
+ deleted = 0
303
+
304
+ for rel in list(existing.files.keys()):
305
+ if rel not in discovered:
306
+ deleted += 1
307
+
308
+ for rel, (fpath, stat) in discovered.items():
309
+ prev = existing.files.get(rel)
310
+ is_dirty = (
311
+ prev is None
312
+ or rel in explicit_set
313
+ or abs(stat.st_mtime - prev.mtime) > 1e-4
314
+ or stat.st_size != prev.size_bytes
315
+ )
316
+ if not is_dirty:
317
+ updated_files[rel] = prev
318
+ reused += 1
319
+ else:
320
+ new_snap = cls._parse_file_snapshot(fpath, abs_root)
321
+ if new_snap is not None:
322
+ updated_files[rel] = new_snap
323
+ reparsed += 1
324
+
325
+ total_raw = sum(fs.raw_tokens for fs in updated_files.values())
326
+ total_pruned = sum(fs.pruned_tokens for fs in updated_files.values())
327
+ sav_pct = round(((1.0 - (total_pruned / max(1, total_raw))) * 100.0), 2)
328
+ elapsed_ms = (time.perf_counter() - start_t) * 1000.0
329
+
330
+ res = SnapshotResult(
331
+ workspace_dir=abs_root,
332
+ created_at=time.time(),
333
+ file_count=len(updated_files),
334
+ total_raw_tokens=total_raw,
335
+ total_pruned_tokens=total_pruned,
336
+ reduction_pct=sav_pct,
337
+ files=updated_files,
338
+ generation_time_ms=elapsed_ms,
339
+ )
340
+ cls._save_snapshot(res)
341
+ return res, {"reparsed": reparsed, "reused": reused, "deleted": deleted}
342
+
343
+ @classmethod
344
+ def load_snapshot(cls, workspace_dir: str, cache_file: Optional[str] = None) -> Optional[SnapshotResult]:
345
+ """Loads existing snapshot from SQLite store first, falling back to JSON."""
346
+ start_t = time.perf_counter()
347
+ abs_root = os.path.abspath(workspace_dir)
348
+ if cache_file is None:
349
+ db_path = cls.get_sqlite_path(abs_root)
350
+ if os.path.isfile(db_path):
351
+ try:
352
+ conn = sqlite3.connect(db_path)
353
+ try:
354
+ meta = dict(conn.execute("SELECT key, value FROM meta").fetchall())
355
+ rows = conn.execute(
356
+ "SELECT rel_path, mtime, size_bytes, hash_prefix, raw_tokens, "
357
+ "pruned_tokens, classes_json, functions_json, imports_json, skeleton "
358
+ "FROM file_snapshots"
359
+ ).fetchall()
360
+ finally:
361
+ conn.close()
362
+ files_map = {
363
+ r[0]: FileSnapshot(
364
+ rel_path=r[0],
365
+ mtime=r[1],
366
+ size_bytes=r[2],
367
+ hash_prefix=r[3],
368
+ raw_tokens=r[4],
369
+ pruned_tokens=r[5],
370
+ classes=json.loads(r[6]),
371
+ functions=json.loads(r[7]),
372
+ imports=json.loads(r[8]),
373
+ skeleton=r[9],
374
+ )
375
+ for r in rows
376
+ }
377
+ elapsed_ms = (time.perf_counter() - start_t) * 1000.0
378
+ return SnapshotResult(
379
+ workspace_dir=meta.get("workspace_dir", abs_root),
380
+ created_at=float(meta.get("created_at", 0.0)),
381
+ file_count=len(files_map),
382
+ total_raw_tokens=int(meta.get("total_raw_tokens", 0)),
383
+ total_pruned_tokens=int(meta.get("total_pruned_tokens", 0)),
384
+ reduction_pct=float(meta.get("reduction_pct", 0.0)),
385
+ files=files_map,
386
+ generation_time_ms=elapsed_ms,
387
+ )
388
+ except Exception:
389
+ pass
390
+
391
+ cache_path = cls.get_cache_path(workspace_dir, cache_file)
392
+ if not os.path.exists(cache_path):
393
+ return None
394
+
395
+ try:
396
+ with open(cache_path, "r", encoding="utf-8") as f:
397
+ data = json.load(f)
398
+
399
+ files_map = {}
400
+ for rel, fd in data.get("files", {}).items():
401
+ files_map[rel] = FileSnapshot(**fd)
402
+
403
+ elapsed_ms = (time.perf_counter() - start_t) * 1000.0
404
+ return SnapshotResult(
405
+ workspace_dir=data["workspace_dir"],
406
+ created_at=data["created_at"],
407
+ file_count=data["file_count"],
408
+ total_raw_tokens=data["total_raw_tokens"],
409
+ total_pruned_tokens=data["total_pruned_tokens"],
410
+ reduction_pct=data["reduction_pct"],
411
+ files=files_map,
412
+ generation_time_ms=elapsed_ms
413
+ )
414
+ except Exception:
415
+ return None
416
+
417
+ @classmethod
418
+ def is_valid(cls, snapshot: SnapshotResult, workspace_dir: str) -> bool:
419
+ """Verifies across all tracked and discovered files whether snapshot matches disk."""
420
+ abs_root = os.path.abspath(workspace_dir)
421
+ discovered = cls._discover_workspace_files(abs_root)
422
+ if set(discovered.keys()) != set(snapshot.files.keys()):
423
+ return False
424
+ for rel, snap in snapshot.files.items():
425
+ entry = discovered.get(rel)
426
+ if not entry:
427
+ return False
428
+ _, stat = entry
429
+ if abs(stat.st_mtime - snap.mtime) > 1e-4 or stat.st_size != snap.size_bytes:
430
+ return False
431
+ return True
432
+
433
+ @classmethod
434
+ def get_or_create(cls, workspace_dir: str, force_refresh: bool = False) -> Tuple[SnapshotResult, bool]:
435
+ """Returns (snapshot, was_cached). Uses incremental update when stale instead of full rebuild."""
436
+ if not force_refresh:
437
+ cached = cls.load_snapshot(workspace_dir)
438
+ if cached and cls.is_valid(cached, workspace_dir):
439
+ return cached, True
440
+ if cached:
441
+ updated, _ = cls.update_incremental(workspace_dir)
442
+ return updated, False
443
+
444
+ fresh = cls.create_snapshot(workspace_dir)
445
+ return fresh, False
446
+
447
+ @classmethod
448
+ def to_dict(cls, result: SnapshotResult) -> Dict[str, Any]:
449
+ return {
450
+ "workspace_dir": result.workspace_dir,
451
+ "created_at": result.created_at,
452
+ "file_count": result.file_count,
453
+ "total_raw_tokens": result.total_raw_tokens,
454
+ "total_pruned_tokens": result.total_pruned_tokens,
455
+ "reduction_pct": result.reduction_pct,
456
+ "generation_time_ms": round(result.generation_time_ms, 2),
457
+ "files": {rel: asdict(snap) for rel, snap in result.files.items()}
458
+ }
459
+
460
+ @classmethod
461
+ def render_cli(cls, res: SnapshotResult, was_cached: bool = False):
462
+ mode_str = "\033[32m[CACHE HIT - SUB-8MS]\033[0m" if was_cached else "\033[36m[NEW SNAPSHOT BUILT]\033[0m"
463
+ print(f"\n⚡ \033[1mT-ZERO CONTEXT SNAPSHOT ENGINE\033[0m {mode_str}")
464
+ print("=" * 70)
465
+ print(f"📁 Workspace Root: {res.workspace_dir}")
466
+ print(f"📄 Indexed Source Files: {res.file_count:,} Python modules")
467
+ print(f"📊 Token Economics: {res.total_pruned_tokens:,} pruned vs {res.total_raw_tokens:,} raw (\033[32m-{res.reduction_pct}%\033[0m)")
468
+ print(f"⏱️ Load / Build Time: \033[33m{res.generation_time_ms:.2f} ms\033[0m")
469
+ print(f"💾 Snapshot Location: .tzero/{cls.SNAPSHOT_FILENAME}")
470
+ print("=" * 70)
471
+