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.
Files changed (131) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/bin/tzero-mcp.js +7 -11
  5. package/bin/tzero.js +7 -11
  6. package/index.js +3 -3
  7. package/package.json +3 -2
  8. package/src/addmcp.py +1203 -1194
  9. package/src/app.py +1810 -0
  10. package/src/main.py +60 -60
  11. package/src/pc_fixer_mcp.py +25 -0
  12. package/src/tzero/__init__.py +54 -0
  13. package/src/tzero/__main__.py +6 -0
  14. package/src/tzero/siber_akademi.ico +0 -0
  15. package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +77 -77
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +2 -2
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +184 -0
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/tzero/tzero_card.py +431 -0
  22. package/src/{tzero_ci.py → tzero/tzero_ci.py} +7 -7
  23. package/src/{tzero_commit.py → tzero/tzero_commit.py} +1 -1
  24. package/src/tzero/tzero_contracts.py +1093 -0
  25. package/src/{tzero_cost.py → tzero/tzero_cost.py} +4 -1
  26. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +1960 -1448
  27. package/src/tzero/tzero_debt.py +461 -0
  28. package/src/{tzero_deps.py → tzero/tzero_deps.py} +462 -287
  29. package/src/{tzero_drift.py → tzero/tzero_drift.py} +1 -1
  30. package/src/{tzero_explain.py → tzero/tzero_explain.py} +306 -240
  31. package/src/{tzero_features.py → tzero/tzero_features.py} +3024 -3022
  32. package/src/tzero/tzero_federation.py +299 -0
  33. package/src/tzero/tzero_fix.py +557 -0
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +334 -334
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +1 -1
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +8 -8
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +1 -1
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +1 -1
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +1 -1
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +1 -1
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +1 -1
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +280 -280
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +325 -325
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +489 -447
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +385 -385
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +375 -375
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +323 -323
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +2 -1
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +1 -1
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +1 -1
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +364 -364
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +619 -619
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +1 -1
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +2 -2
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +493 -493
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +1 -1
  58. package/src/tzero/tzero_golden.py +319 -0
  59. package/src/tzero/tzero_graph_hud.html +338 -0
  60. package/src/tzero/tzero_graph_rag.py +263 -0
  61. package/src/tzero/tzero_growth.py +415 -0
  62. package/src/{tzero_guard.py → tzero/tzero_guard.py} +11 -3
  63. package/src/tzero/tzero_hooks.py +565 -0
  64. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +11 -1
  65. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +1 -1
  66. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  67. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +1 -1
  68. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +2 -2
  69. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +1 -1
  70. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +1 -1
  71. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +2 -2
  72. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +1 -1
  73. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +3 -3
  74. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +1 -1
  75. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +6 -6
  76. package/src/tzero/tzero_lsp.py +634 -0
  77. package/src/tzero/tzero_mcp.py +5314 -0
  78. package/src/tzero/tzero_mutation.py +358 -0
  79. package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +1425 -1425
  80. package/src/tzero/tzero_packer.py +577 -0
  81. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +42 -0
  82. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +1 -1
  83. package/src/tzero/tzero_polyglot.py +799 -0
  84. package/src/tzero/tzero_proxy.py +127 -0
  85. package/src/tzero/tzero_rust_bridge.py +198 -0
  86. package/src/tzero/tzero_scip.py +368 -0
  87. package/src/{tzero_security.py → tzero/tzero_security.py} +573 -570
  88. package/src/tzero/tzero_semantic_merge.py +189 -0
  89. package/src/tzero/tzero_snapshot.py +471 -0
  90. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +1 -1
  91. package/src/tzero/tzero_subagent_engine.py +459 -0
  92. package/src/{tzero_sync.py → tzero/tzero_sync.py} +2 -2
  93. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +174 -31
  94. package/src/{tzero_tui.py → tzero/tzero_tui.py} +313 -244
  95. package/src/tzero/tzero_turbo.py +264 -0
  96. package/src/{tzero_v3.py → tzero/tzero_v3.py} +9997 -9435
  97. package/src/tzero.py +6 -58
  98. package/src/tzero_mcp.py +25 -4858
  99. package/test/package.test.js +14 -2
  100. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  101. package/src/tzero_fix.py +0 -228
  102. package/src/tzero_gateway.py +0 -885
  103. package/src/tzero_packer.py +0 -370
  104. package/src/tzero_polyglot.py +0 -422
  105. package/src/tzero_snapshot.py +0 -258
  106. /package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +0 -0
  107. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +0 -0
  108. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +0 -0
  109. /package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +0 -0
  110. /package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +0 -0
  111. /package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +0 -0
  112. /package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +0 -0
  113. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +0 -0
  114. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +0 -0
  115. /package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +0 -0
  116. /package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +0 -0
  117. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +0 -0
  118. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +0 -0
  119. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +0 -0
  120. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +0 -0
  121. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +0 -0
  122. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +0 -0
  123. /package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +0 -0
  124. /package/src/{tzero_infra.py → tzero/tzero_infra.py} +0 -0
  125. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +0 -0
  126. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +0 -0
  127. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +0 -0
  128. /package/src/{tzero_patch.py → tzero/tzero_patch.py} +0 -0
  129. /package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +0 -0
  130. /package/src/{tzero_replay.py → tzero/tzero_replay.py} +0 -0
  131. /package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +0 -0
@@ -0,0 +1,189 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Siber Akademi — T-Zero AST Semantic 3-Way Merge & Conflict Healer.
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ License: MIT
6
+
7
+ Performs AST-aware 3-way code merging and automated resolution of git conflict blocks.
8
+ Safely combines independent function additions, deduplicates polyglot imports,
9
+ and eliminates broken syntax markers without relying on external cloud APIs.
10
+ 100% Free, Zero External Dependencies, 100% Zero-Leak Certified.
11
+ """
12
+
13
+ import os
14
+ import sys
15
+ import ast
16
+ import re
17
+ from dataclasses import dataclass, field
18
+ from typing import Dict, List, Optional, Set, Tuple
19
+
20
+
21
+ @dataclass
22
+ class MergeResult:
23
+ success: bool
24
+ merged_code: str
25
+ auto_resolved_conflicts: int
26
+ unresolved_conflicts: int
27
+ symbols_added_ours: List[str] = field(default_factory=list)
28
+ symbols_added_theirs: List[str] = field(default_factory=list)
29
+ details: List[str] = field(default_factory=list)
30
+
31
+
32
+ class ASTSemanticMerger:
33
+ """Semantic AST-aware 3-way merger and git conflict block healer."""
34
+
35
+ CONFLICT_PATTERN = re.compile(
36
+ r'<<<<<<<[^\n]*\n(.*?)=======\n(.*?)>>>>>>>[^\n]*\n',
37
+ re.DOTALL
38
+ )
39
+
40
+ @classmethod
41
+ def has_conflict_markers(cls, text: str) -> bool:
42
+ """Returns True if file contains standard git conflict markers."""
43
+ return bool(cls.CONFLICT_PATTERN.search(text))
44
+
45
+ @classmethod
46
+ def extract_ast_symbols(cls, code: str) -> Dict[str, str]:
47
+ """Extracts top-level functions, classes, and imports as symbol_name -> code string."""
48
+ symbols: Dict[str, str] = {}
49
+ try:
50
+ tree = ast.parse(code)
51
+ except SyntaxError:
52
+ return symbols
53
+
54
+ lines = code.splitlines(keepends=True)
55
+ for node in tree.body:
56
+ name = None
57
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
58
+ name = node.name
59
+ elif isinstance(node, ast.Import):
60
+ name = "import::" + ",".join(a.name for a in node.names)
61
+ elif isinstance(node, ast.ImportFrom):
62
+ name = f"from::{node.module or ''}::" + ",".join(a.name for a in node.names)
63
+
64
+ if name and hasattr(node, "lineno") and hasattr(node, "end_lineno"):
65
+ node_lines = lines[node.lineno - 1:node.end_lineno]
66
+ symbols[name] = "".join(node_lines)
67
+
68
+ return symbols
69
+
70
+ @classmethod
71
+ def heal_conflict_file(cls, content: str) -> MergeResult:
72
+ """
73
+ Scans content for git conflict blocks (<<<<<<< ... ======= ... >>>>>>>)
74
+ and attempts semantic AST healing.
75
+ """
76
+ matches = list(cls.CONFLICT_PATTERN.finditer(content))
77
+ if not matches:
78
+ return MergeResult(
79
+ success=True,
80
+ merged_code=content,
81
+ auto_resolved_conflicts=0,
82
+ unresolved_conflicts=0,
83
+ details=["No conflict markers found in input."]
84
+ )
85
+
86
+ auto_resolved = 0
87
+ unresolved = 0
88
+ details = []
89
+ result_text = content
90
+ added_ours = []
91
+ added_theirs = []
92
+
93
+ # Process each conflict block
94
+ for idx, m in enumerate(matches, 1):
95
+ full_match = m.group(0)
96
+ ours_block = m.group(1)
97
+ theirs_block = m.group(2)
98
+
99
+ ours_syms = cls.extract_ast_symbols(ours_block)
100
+ theirs_syms = cls.extract_ast_symbols(theirs_block)
101
+
102
+ # Check colliding definitions (exclude imports, which are safely unified and deduplicated)
103
+ ours_defs = {k: v for k, v in ours_syms.items() if not k.startswith("import::") and not k.startswith("from::")}
104
+ theirs_defs = {k: v for k, v in theirs_syms.items() if not k.startswith("import::") and not k.startswith("from::")}
105
+ shared_defs = set(ours_defs.keys()).intersection(set(theirs_defs.keys()))
106
+
107
+ # If definitions are disjoint (or purely imports/declarations), merge safely!
108
+ if not shared_defs:
109
+ merged_snippet = ours_block.strip() + "\n\n" + theirs_block.strip() + "\n"
110
+ result_text = result_text.replace(full_match, merged_snippet, 1)
111
+ auto_resolved += 1
112
+ added_ours.extend(list(ours_defs.keys()))
113
+ added_theirs.extend(list(theirs_defs.keys()))
114
+ details.append(
115
+ f"Conflict #{idx}: Auto-healed disjoint AST symbols (Ours: {list(ours_defs.keys())}, Theirs: {list(theirs_defs.keys())})."
116
+ )
117
+ else:
118
+ # True semantic collision on same definition symbol
119
+ safe_block = (
120
+ f"# --- T-ZERO AST MERGE CONFLICT (Shared symbols: {list(shared_defs)}) ---\n"
121
+ f"# [OURS VERSION]:\n{ours_block}\n"
122
+ f"# [THEIRS VERSION]:\n{theirs_block}\n"
123
+ f"# --- END CONFLICT ---\n"
124
+ )
125
+ result_text = result_text.replace(full_match, safe_block, 1)
126
+ unresolved += 1
127
+ details.append(
128
+ f"Conflict #{idx}: Semantic collision on symbol(s) {list(shared_defs)}. Sanitized markers into comments."
129
+ )
130
+
131
+ # Post-process: deduplicate imports if syntactically valid Python
132
+ try:
133
+ tree = ast.parse(result_text)
134
+ # Check for duplicate import lines
135
+ import_lines_seen = set()
136
+ cleaned_lines = []
137
+ for line in result_text.splitlines():
138
+ stripped = line.strip()
139
+ if (stripped.startswith("import ") or stripped.startswith("from ")) and "#" not in stripped:
140
+ if stripped in import_lines_seen:
141
+ continue
142
+ import_lines_seen.add(stripped)
143
+ cleaned_lines.append(line)
144
+ result_text = "\n".join(cleaned_lines)
145
+ if not result_text.endswith("\n"):
146
+ result_text += "\n"
147
+ except SyntaxError:
148
+ pass
149
+
150
+ return MergeResult(
151
+ success=(unresolved == 0),
152
+ merged_code=result_text,
153
+ auto_resolved_conflicts=auto_resolved,
154
+ unresolved_conflicts=unresolved,
155
+ symbols_added_ours=added_ours,
156
+ symbols_added_theirs=added_theirs,
157
+ details=details
158
+ )
159
+
160
+ @classmethod
161
+ def heal_file_on_disk(cls, file_path: str, write_in_place: bool = True) -> MergeResult:
162
+ """Reads a file with git conflict markers, heals it, and optionally overwrites it."""
163
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
164
+ content = f.read()
165
+
166
+ res = cls.heal_conflict_file(content)
167
+ if write_in_place and res.auto_resolved_conflicts > 0:
168
+ with open(file_path, "w", encoding="utf-8") as f:
169
+ f.write(res.merged_code)
170
+
171
+ return res
172
+
173
+ @classmethod
174
+ def render_cli(cls, res: MergeResult, file_hint: str = "file"):
175
+ status_color = "\033[32m" if res.success else "\033[33m"
176
+ print(f"\n🧩 \033[1mT-ZERO AST SEMANTIC MERGE & CONFLICT HEALER\033[0m")
177
+ print("=" * 70)
178
+ print(f"📄 Target: {file_hint}")
179
+ print(f"⚡ Auto-Healed Blocks: \033[32m{res.auto_resolved_conflicts}\033[0m")
180
+ print(f"⚠️ Collisions: {status_color}{res.unresolved_conflicts}\033[0m")
181
+ print("=" * 70)
182
+ for d in res.details:
183
+ print(f" • {d}")
184
+ print("=" * 70)
185
+
186
+
187
+ def heal_conflicts(content: str) -> MergeResult:
188
+ """Convenience functional interface."""
189
+ return ASTSemanticMerger.heal_conflict_file(content)
@@ -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
+
@@ -23,7 +23,7 @@ import ast
23
23
  import re
24
24
  from typing import Dict, List, Optional, Tuple, Any, Set
25
25
 
26
- from tzero_features import should_skip_dir, should_skip_file
26
+ from tzero.tzero_features import should_skip_dir, should_skip_file
27
27
 
28
28
 
29
29
  def _infer_type_from_ast_node(node: Optional[ast.AST]) -> Optional[str]: