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
@@ -18,6 +18,13 @@ Supported Environments:
18
18
  - Any MCP-compliant client
19
19
  """
20
20
 
21
+ # Support direct execution by MCP clients and bundled launchers.
22
+ if __name__ == "__main__" and not __package__:
23
+ import os
24
+ import sys
25
+
26
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
27
+
21
28
  import os
22
29
  import sys
23
30
  import json
@@ -25,16 +32,27 @@ import re
25
32
  import ast
26
33
  import inspect
27
34
  import logging
35
+
36
+ SERVER_VERSION = "11.0.0"
37
+
38
+ # Version checks must not initialize the MCP SDK or dependency bootstrap. Besides
39
+ # being needlessly expensive, that path may wait on package discovery/network
40
+ # state in a fresh environment and make a simple `--version` call hang.
41
+ if __name__ == "__main__" and "--version" in sys.argv[1:]:
42
+ print(f"T-Zero MCP Server v{SERVER_VERSION}")
43
+ raise SystemExit(0)
44
+
28
45
  try:
29
46
  from mcp.types import ToolAnnotations
30
47
  except ImportError:
31
48
  ToolAnnotations = None
32
49
 
33
- from typing import Dict, List, Optional, Any
50
+ from typing import Dict, List, Optional, Any, Union, Tuple
34
51
  try:
35
52
  from typing import Annotated
53
+ from typing_extensions import TypedDict
36
54
  except ImportError:
37
- from typing_extensions import Annotated
55
+ from typing_extensions import Annotated, TypedDict
38
56
 
39
57
  try:
40
58
  from pydantic import Field
@@ -42,8 +60,6 @@ except ImportError:
42
60
  def Field(default=..., description=""):
43
61
  return default
44
62
 
45
- SERVER_VERSION = "10.7.0"
46
-
47
63
  # Safe UTF-8 reconfiguration for Windows console & piped subprocesses
48
64
  if sys.stdout and hasattr(sys.stdout, "reconfigure"):
49
65
  try:
@@ -56,21 +72,16 @@ if sys.stderr and hasattr(sys.stderr, "reconfigure"):
56
72
  except Exception:
57
73
  pass
58
74
 
59
- # Ensure project root is in sys.path
60
- SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
61
- if SCRIPT_DIR not in sys.path:
62
- sys.path.insert(0, SCRIPT_DIR)
63
-
64
75
  # Make sure the MCP SDK (and the core packages) are installed before importing them.
65
76
  try:
66
- import tzero_deps
77
+ from tzero import tzero_deps
67
78
  tzero_deps.ensure_dependencies(include_mcp=True)
68
79
  except ImportError:
69
80
  pass
70
81
 
71
82
  # Core T-Zero V3 Engine Imports
72
83
  try:
73
- from tzero_v3 import (
84
+ from tzero.tzero_v3 import (
74
85
  CodebaseScanner,
75
86
  TokenReducer,
76
87
  generate_offline_context,
@@ -91,14 +102,46 @@ except ImportError as e:
91
102
 
92
103
  # MCP SDK Import with cross-version compatibility (mcp 2.x MCPServer & mcp 1.x FastMCP)
93
104
  try:
94
- from mcp.server.mcpserver import MCPServer
105
+ from mcp.server.mcpserver import MCPServer, Context
95
106
  ServerClass = MCPServer
96
107
  except ImportError:
97
108
  try:
98
109
  from mcp.server.fastmcp import FastMCP
99
110
  ServerClass = FastMCP
111
+ Context = Any
100
112
  except ImportError:
101
113
  ServerClass = None
114
+ Context = Any
115
+
116
+
117
+ class ToolSearchMatch(TypedDict):
118
+ name: str
119
+ category: str
120
+ summary: str
121
+
122
+
123
+ class SearchToolsResult(TypedDict):
124
+ query: str
125
+ total_available: int
126
+ tools: List[ToolSearchMatch]
127
+
128
+
129
+ async def _safe_report_progress(
130
+ ctx: Any,
131
+ progress: float,
132
+ total: float,
133
+ message: str = "",
134
+ ) -> None:
135
+ """Safely emits MCP progress notifications without raising outside request sessions."""
136
+ if ctx is None:
137
+ return
138
+ reporter = getattr(ctx, "report_progress", None)
139
+ if reporter is None:
140
+ return
141
+ try:
142
+ await reporter(progress, total, message)
143
+ except Exception:
144
+ pass
102
145
 
103
146
 
104
147
  def get_file_imports(file_path: str) -> List[str]:
@@ -193,7 +236,7 @@ def build_workspace_import_graph(files: List[str], base_dir: str) -> Dict[str, L
193
236
 
194
237
  def scan_text_for_secrets(text: str) -> List[Dict[str, Any]]:
195
238
  """Scans raw text for hardcoded API keys, private keys, and secrets across any language."""
196
- from tzero_security import ZeroLeakEngine
239
+ from tzero.tzero_security import ZeroLeakEngine
197
240
  findings = []
198
241
  for f in ZeroLeakEngine.scan_text(text, check_entropy=True):
199
242
  findings.append({
@@ -305,11 +348,26 @@ def create_mcp_server():
305
348
  selected_files = files[:50]
306
349
 
307
350
  reduced_snippets: Dict[str, str] = {}
308
- for f in selected_files:
309
- raw_code = snippets.get(f, "")
310
- if include_file_contents:
311
- reduced_snippets[f] = TokenReducer.reduce(raw_code, f, mode=reduction_mode)
312
- else:
351
+ if include_file_contents:
352
+ try:
353
+ from tzero.tzero_turbo import get_turbo_accelerator
354
+ turbo = get_turbo_accelerator()
355
+ # Turbo Overdrive ("Kamçılama"): multi-core parallel reduction with mtime cache
356
+ full_paths = [os.path.join(abs_root, f) for f in selected_files]
357
+ reduced_map = turbo.parallel_reduce_batch(
358
+ full_paths,
359
+ lambda code, path, mode: TokenReducer.reduce(code, path, mode=mode),
360
+ mode=reduction_mode
361
+ )
362
+ for f, full_p in zip(selected_files, full_paths):
363
+ reduced_snippets[f] = reduced_map.get(full_p, snippets.get(f, ""))
364
+ except Exception:
365
+ for f in selected_files:
366
+ raw_code = snippets.get(f, "")
367
+ reduced_snippets[f] = TokenReducer.reduce(raw_code, f, mode=reduction_mode)
368
+ else:
369
+ for f in selected_files:
370
+ raw_code = snippets.get(f, "")
313
371
  reduced_snippets[f] = f"# File: {f} ({len(raw_code.splitlines())} lines)"
314
372
 
315
373
  raw_context = generate_offline_context(abs_root, selected_files, reduced_snippets)
@@ -317,7 +375,7 @@ def create_mcp_server():
317
375
 
318
376
  if token_count > max_tokens:
319
377
  try:
320
- from tzero_features import RepositoryPageRank
378
+ from tzero.tzero_features import RepositoryPageRank
321
379
  pr_analyzer = RepositoryPageRank(abs_root)
322
380
  ranks = pr_analyzer.rank(top_k=len(selected_files))
323
381
  score_map = {r["file"]: r["score"] for r in ranks}
@@ -720,7 +778,7 @@ def create_mcp_server():
720
778
  # Check T-002 Architectural Boundary Rules
721
779
  arch_violations = []
722
780
  try:
723
- from tzero_features import ArchitectureRuleEngine
781
+ from tzero.tzero_features import ArchitectureRuleEngine
724
782
  arch_engine = ArchitectureRuleEngine(abs_root)
725
783
  arch_res = arch_engine.enforce_boundaries()
726
784
  arch_violations = arch_res.get("violations", [])
@@ -980,7 +1038,7 @@ def create_mcp_server():
980
1038
  project_root: Annotated[str, Field(default=".", description="Workspace root directory containing target symbols (default: current directory).")] = "."
981
1039
  ) -> str:
982
1040
  """Traces symbol references, inbound dependents, and calculates blast radius score."""
983
- from tzero_features import ChangeImpactAnalyzer
1041
+ from tzero.tzero_features import ChangeImpactAnalyzer
984
1042
  analyzer = ChangeImpactAnalyzer(project_root)
985
1043
  analysis = analyzer.analyze_symbol(target_symbol)
986
1044
  return analyzer.format_report(analysis)
@@ -1018,7 +1076,7 @@ def create_mcp_server():
1018
1076
  rules_file: Annotated[str, Field(default="tzero.rules.json", description="Path to rules JSON file (default: 'tzero.rules.json'). Resolves relative to project_root.")] = "tzero.rules.json"
1019
1077
  ) -> str:
1020
1078
  """Audits imports against architectural layer boundaries."""
1021
- from tzero_features import ArchitectureRuleEngine
1079
+ from tzero.tzero_features import ArchitectureRuleEngine
1022
1080
  config_p = os.path.join(project_root, rules_file) if not os.path.isabs(rules_file) else rules_file
1023
1081
  engine = ArchitectureRuleEngine(project_root, config_p)
1024
1082
  res = engine.enforce_boundaries()
@@ -1060,7 +1118,7 @@ def create_mcp_server():
1060
1118
  top_k: Annotated[int, Field(default=5, description="Maximum number of top-matching code snippets to return (default: 5).")] = 5
1061
1119
  ) -> str:
1062
1120
  """Performs private local hybrid semantic search across the codebase."""
1063
- from tzero_features import LocalSemanticCodeSearch
1121
+ from tzero.tzero_features import LocalSemanticCodeSearch
1064
1122
  searcher = LocalSemanticCodeSearch(project_root)
1065
1123
  results = searcher.search(query, top_k=top_k)
1066
1124
  return searcher.format_search_results(query, results)
@@ -1098,7 +1156,7 @@ def create_mcp_server():
1098
1156
  target: Annotated[str, Field(default="all", description="Target editor format: 'cursor', 'cline', 'windsurf', 'claude', 'copilot', or 'all' (default: 'all').")] = "all"
1099
1157
  ) -> str:
1100
1158
  """Exports AI coding agent rules into workspace."""
1101
- from tzero_features import AgentRulesGenerator
1159
+ from tzero.tzero_features import AgentRulesGenerator
1102
1160
  p_name = os.path.basename(os.path.abspath(project_root)) or "Project"
1103
1161
  t = (target or "all").lower().strip()
1104
1162
  created = []
@@ -1174,8 +1232,8 @@ def create_mcp_server():
1174
1232
  team_size: Annotated[int, Field(default=5, description="Number of developers in the engineering team used to model monthly ROI savings (default: 5).")] = 5
1175
1233
  ) -> str:
1176
1234
  """Calculates token reduction and economic ROI."""
1177
- from tzero_features import TokenROICalculator
1178
- from tzero_v3 import CodebaseScanner, TokenReducer
1235
+ from tzero.tzero_features import TokenROICalculator
1236
+ from tzero.tzero_v3 import CodebaseScanner, TokenReducer
1179
1237
 
1180
1238
  abs_root = os.path.abspath(project_root)
1181
1239
  scanner = CodebaseScanner()
@@ -1222,7 +1280,7 @@ def create_mcp_server():
1222
1280
  project_root: Annotated[str, Field(default=".", description="Git repository root path (default: current directory).")] = "."
1223
1281
  ) -> str:
1224
1282
  """Generates incremental PR diff context and downstream caller signatures."""
1225
- from tzero_features import GitDiffContextBuilder
1283
+ from tzero.tzero_features import GitDiffContextBuilder
1226
1284
  builder = GitDiffContextBuilder(project_root)
1227
1285
  res = builder.build_diff_context(base_ref)
1228
1286
  return res["markdown"]
@@ -1409,7 +1467,7 @@ def create_mcp_server():
1409
1467
  project_root: Root directory of the repository (default: current directory).
1410
1468
  """
1411
1469
  abs_root = os.path.abspath(project_root)
1412
- from tzero_features import ZeroHallucinationGuard
1470
+ from tzero.tzero_features import ZeroHallucinationGuard
1413
1471
  guard = ZeroHallucinationGuard(abs_root)
1414
1472
  res = guard.validate_code(proposed_code, target_file)
1415
1473
  return res["report"]
@@ -1456,7 +1514,7 @@ def create_mcp_server():
1456
1514
  project_root: Root directory of the repository (default: current directory).
1457
1515
  """
1458
1516
  abs_root = os.path.abspath(project_root)
1459
- from tzero_features import SmartSkeletonContextBuilder
1517
+ from tzero.tzero_features import SmartSkeletonContextBuilder
1460
1518
  builder = SmartSkeletonContextBuilder(abs_root)
1461
1519
  return builder.build_skeleton(focus_file, focus_symbol)
1462
1520
 
@@ -1499,7 +1557,7 @@ def create_mcp_server():
1499
1557
  top_k: Number of top central modules to return in the ranking report (default: 15).
1500
1558
  """
1501
1559
  abs_root = os.path.abspath(project_root)
1502
- from tzero_features import RepositoryPageRank
1560
+ from tzero.tzero_features import RepositoryPageRank
1503
1561
  ranker = RepositoryPageRank(abs_root)
1504
1562
  rankings = ranker.rank(top_k=top_k)
1505
1563
  return ranker.format_report(rankings)
@@ -1546,7 +1604,7 @@ def create_mcp_server():
1546
1604
  max_depth: Maximum recursive call graph traversal depth (default: 3).
1547
1605
  """
1548
1606
  abs_root = os.path.abspath(project_root)
1549
- from tzero_features import SymbolCallChainTracer
1607
+ from tzero.tzero_features import SymbolCallChainTracer
1550
1608
  tracer = SymbolCallChainTracer(abs_root)
1551
1609
  res = tracer.trace(symbol_name, max_depth=max_depth)
1552
1610
  return tracer.format_report(res)
@@ -1587,7 +1645,7 @@ def create_mcp_server():
1587
1645
  project_root: Root directory of the repository (default: current directory).
1588
1646
  """
1589
1647
  abs_root = os.path.abspath(project_root)
1590
- from tzero_features import DeadCodeFinder
1648
+ from tzero.tzero_features import DeadCodeFinder
1591
1649
  finder = DeadCodeFinder(abs_root)
1592
1650
  dead = finder.find_unused_symbols()
1593
1651
  return finder.format_report(dead)
@@ -1627,7 +1685,7 @@ def create_mcp_server():
1627
1685
  Args:
1628
1686
  text: Input text to compress.
1629
1687
  """
1630
- from tzero_jarvis import get_global_compressor
1688
+ from tzero.tzero_jarvis import get_global_compressor
1631
1689
  compressor = get_global_compressor()
1632
1690
  res = compressor.compress_text_to_virtual_tokens(text)
1633
1691
 
@@ -1681,7 +1739,7 @@ def create_mcp_server():
1681
1739
  Args:
1682
1740
  token_or_code: The virtual token or code ID to resolve.
1683
1741
  """
1684
- from tzero_jarvis import get_global_compressor
1742
+ from tzero.tzero_jarvis import get_global_compressor
1685
1743
  compressor = get_global_compressor()
1686
1744
  decoded = compressor.decode_virtual_token(token_or_code)
1687
1745
  if not decoded:
@@ -1732,7 +1790,7 @@ def create_mcp_server():
1732
1790
  mode: Annotated[str, Field(default="auto", description="Execution mode: 'auto', 'plan', 'execute', or 'capabilities'.")] = "auto"
1733
1791
  ) -> str:
1734
1792
  """Executes autonomous workspace orchestration or presents an executive engineering plan."""
1735
- from tzero_jarvis import JarvisOrchestrator
1793
+ from tzero.tzero_jarvis import JarvisOrchestrator
1736
1794
  orchestrator = JarvisOrchestrator(workspace_root=project_root)
1737
1795
 
1738
1796
  goal_clean = (goal or "").strip()
@@ -1814,7 +1872,7 @@ def create_mcp_server():
1814
1872
  prompt: User prompt or instruction.
1815
1873
  system_prompt: System role prompt.
1816
1874
  """
1817
- from tzero_jarvis import ZeroKeyAIRouter
1875
+ from tzero.tzero_jarvis import ZeroKeyAIRouter
1818
1876
  ans = ZeroKeyAIRouter.query_intelligence(prompt, system_prompt=system_prompt)
1819
1877
  return (
1820
1878
  f"### 🤖 T-Zero Jarvis Zero-Cost Intelligence\n"
@@ -1866,7 +1924,7 @@ def create_mcp_server():
1866
1924
  entity: Target entity name.
1867
1925
  predicate: Target predicate.
1868
1926
  """
1869
- from tzero_jarvis import get_global_compressor
1927
+ from tzero.tzero_jarvis import get_global_compressor
1870
1928
  compressor = get_global_compressor()
1871
1929
  matches = compressor.codebook.query_graph(
1872
1930
  entity=entity if entity else None,
@@ -1921,7 +1979,7 @@ def create_mcp_server():
1921
1979
  Args:
1922
1980
  document_text: Full document text to ingest and compress.
1923
1981
  """
1924
- from tzero_jarvis import get_global_compressor
1982
+ from tzero.tzero_jarvis import get_global_compressor
1925
1983
  compressor = get_global_compressor()
1926
1984
  res = compressor.compress_document(document_text)
1927
1985
 
@@ -1978,7 +2036,7 @@ def create_mcp_server():
1978
2036
  action: 'save' or 'load'.
1979
2037
  file_path: Target JSON file path.
1980
2038
  """
1981
- from tzero_jarvis import get_global_compressor
2039
+ from tzero.tzero_jarvis import get_global_compressor
1982
2040
  compressor = get_global_compressor()
1983
2041
  target = file_path if file_path else None
1984
2042
 
@@ -2023,8 +2081,8 @@ def create_mcp_server():
2023
2081
  query_type: Annotated[str, Field(default="root_causes", description="Analysis mode: 'root_causes' (backward causal trace), 'effect_chain' (downstream consequence chain), 'rollback_order' (safe rollback sequence), or 'timeline' (chronological event history) (default: 'root_causes').")] = "root_causes"
2024
2082
  ) -> str:
2025
2083
  """Queries 4D Causal & Temporal Knowledge Graph."""
2026
- from tzero_jarvis import CausalTemporalGraph
2027
- from tzero_jarvis import get_global_compressor
2084
+ from tzero.tzero_jarvis import CausalTemporalGraph
2085
+ from tzero.tzero_jarvis import get_global_compressor
2028
2086
  compressor = get_global_compressor()
2029
2087
  graph = CausalTemporalGraph(compressor.codebook)
2030
2088
 
@@ -2075,7 +2133,7 @@ def create_mcp_server():
2075
2133
  max_retries: Annotated[int, Field(default=3, description="Maximum self-healing repair iterations if execution fails (default: 3).")] = 3
2076
2134
  ) -> str:
2077
2135
  """Runs command with autonomous AST error diagnosis and auto-repair."""
2078
- from tzero_jarvis import SelfHealingExecutionEngine
2136
+ from tzero.tzero_jarvis import SelfHealingExecutionEngine
2079
2137
  engine = SelfHealingExecutionEngine()
2080
2138
  res = engine.execute_and_heal(command, max_retries=max_retries)
2081
2139
 
@@ -2123,7 +2181,7 @@ def create_mcp_server():
2123
2181
  action: Annotated[str, Field(default="consolidate", description="Consolidation mode: 'consolidate' (runs compaction cycle) or 'summary' (reports consolidation status).")] = "consolidate"
2124
2182
  ) -> str:
2125
2183
  """Consolidates episodic memory into permanent abstracted knowledge."""
2126
- from tzero_jarvis import ConsolidationEngine, get_global_compressor
2184
+ from tzero.tzero_jarvis import ConsolidationEngine, get_global_compressor
2127
2185
  compressor = get_global_compressor()
2128
2186
  engine = ConsolidationEngine(compressor.codebook)
2129
2187
 
@@ -2170,7 +2228,7 @@ def create_mcp_server():
2170
2228
  domain: Annotated[str, Field(default="", description="Optional domain filter ('HARDWARE', 'PROTOCOL', 'SOFTWARE', etc.). Empty string searches across all domains.")] = ""
2171
2229
  ) -> str:
2172
2230
  """Sub-millisecond in-memory BM25 + latent code hybrid search."""
2173
- from tzero_jarvis import ZeroVectorDBSearchEngine, get_global_compressor
2231
+ from tzero.tzero_jarvis import ZeroVectorDBSearchEngine, get_global_compressor
2174
2232
  compressor = get_global_compressor()
2175
2233
  search_engine = ZeroVectorDBSearchEngine()
2176
2234
 
@@ -2231,7 +2289,7 @@ def create_mcp_server():
2231
2289
  context: Annotated[str, Field(default="", description="Optional workspace context or specific constraints to guide agent execution (default: '').")] = ""
2232
2290
  ) -> str:
2233
2291
  """Executes autonomous multi-agent swarm mission coordination."""
2234
- from tzero_jarvis import SwarmCoordinator, get_global_compressor
2292
+ from tzero.tzero_jarvis import SwarmCoordinator, get_global_compressor
2235
2293
  compressor = get_global_compressor()
2236
2294
  coordinator = SwarmCoordinator(compressor)
2237
2295
  rep = coordinator.coordinate_mission(mission_goal, context=context)
@@ -2284,7 +2342,7 @@ def create_mcp_server():
2284
2342
  output_path: Annotated[str, Field(default="", description="Destination file path for the generated HTML visualizer (default: '' uses 'tzero_graph_hud.html').")] = ""
2285
2343
  ) -> str:
2286
2344
  """Exports interactive cyberpunk HTML graph visualization."""
2287
- from tzero_jarvis import CyberpunkGraphVisualizer, CausalTemporalGraph, get_global_compressor
2345
+ from tzero.tzero_jarvis import CyberpunkGraphVisualizer, CausalTemporalGraph, get_global_compressor
2288
2346
  compressor = get_global_compressor()
2289
2347
  graph = CausalTemporalGraph(compressor.codebook)
2290
2348
 
@@ -2343,7 +2401,7 @@ def create_mcp_server():
2343
2401
  threshold: Annotated[float, Field(default=0.5, description="Minimum Jaccard similarity threshold (0.0 to 1.0) to flag as a positive match.")] = 0.5
2344
2402
  ) -> str:
2345
2403
  """Sub-microsecond MinHash LSH similarity comparison."""
2346
- from tzero_jarvis import MinHashLSHEngine, SemanticExtractor, get_global_compressor
2404
+ from tzero.tzero_jarvis import MinHashLSHEngine, SemanticExtractor, get_global_compressor
2347
2405
  engine = MinHashLSHEngine()
2348
2406
 
2349
2407
  triplets_a = SemanticExtractor.extract_triplets(text_a)
@@ -2421,7 +2479,7 @@ def create_mcp_server():
2421
2479
  context: Annotated[str, Field(default="", description="Supporting architectural context, risk parameters, or verification constraints (default: '').")] = ""
2422
2480
  ) -> str:
2423
2481
  """Executes Byzantine Fault-Tolerant swarm consensus."""
2424
- from tzero_jarvis import ByzantineFaultTolerantSwarm, SwarmCoordinator, get_global_compressor
2482
+ from tzero.tzero_jarvis import ByzantineFaultTolerantSwarm, SwarmCoordinator, get_global_compressor
2425
2483
  compressor = get_global_compressor()
2426
2484
  coordinator = SwarmCoordinator(compressor)
2427
2485
  bft = ByzantineFaultTolerantSwarm(coordinator)
@@ -2473,7 +2531,7 @@ def create_mcp_server():
2473
2531
  near_dup_threshold: Annotated[float, Field(default=0.65, description="Similarity threshold (0.0 to 1.0) for collapsing redundant sentences.")] = 0.65
2474
2532
  ) -> str:
2475
2533
  """Executes LatentPress pre-prefill context compression."""
2476
- from tzero_jarvis import LatentPressCompressor, get_global_compressor
2534
+ from tzero.tzero_jarvis import LatentPressCompressor, get_global_compressor
2477
2535
  compressor = LatentPressCompressor(get_global_compressor())
2478
2536
  res = compressor.compress_large_context(context_text, near_dup_threshold=near_dup_threshold)
2479
2537
 
@@ -2526,7 +2584,7 @@ def create_mcp_server():
2526
2584
  reduction_mode: Annotated[str, Field(default="ultra", description="Reduction tier: 'ultra' for pure interfaces (80-95% reduction), 'balanced' for interfaces + key attributes.")] = "ultra"
2527
2585
  ) -> str:
2528
2586
  """Compresses database or infrastructure schema definitions on-the-fly."""
2529
- from tzero_infra import SchemaInfraReducer
2587
+ from tzero.tzero_infra import SchemaInfraReducer
2530
2588
  reduced, savings = SchemaInfraReducer.reduce(schema_type_or_filename, content, mode=reduction_mode)
2531
2589
  raw_tokens = max(1, count_tokens_precise(content))
2532
2590
  reduced_tokens = max(1, count_tokens_precise(reduced))
@@ -2572,7 +2630,7 @@ def create_mcp_server():
2572
2630
  max_context_lines: Annotated[int, Field(default=1, description="Maximum unchanged context lines to keep around hunk modifications (default: 1).")] = 1
2573
2631
  ) -> str:
2574
2632
  """Compresses unified git diff into a compact semantic micro-patch."""
2575
- from tzero_patch import SmartMicroPatcher
2633
+ from tzero.tzero_patch import SmartMicroPatcher
2576
2634
  return SmartMicroPatcher.format_micro_patch_report(diff_content, max_context_lines=max_context_lines)
2577
2635
 
2578
2636
  # -------------------------------------------------------------------------
@@ -2608,7 +2666,7 @@ def create_mcp_server():
2608
2666
  entrypoints: Annotated[Optional[List[str]], Field(default=None, description="List of entrypoint filenames (e.g. ['main.py', 'app.py']). If omitted or null, entrypoints are auto-detected.")] = None
2609
2667
  ) -> str:
2610
2668
  """Constructs zero-waste LLM prompt context by pruning dead code via AST reachability."""
2611
- from tzero_reachability import CallGraphReachabilityEngine
2669
+ from tzero.tzero_reachability import CallGraphReachabilityEngine
2612
2670
  if isinstance(entrypoints, str):
2613
2671
  entrypoints = [x.strip() for x in entrypoints.split(",") if x.strip()]
2614
2672
  engine = CallGraphReachabilityEngine(target_dir)
@@ -2658,7 +2716,7 @@ def create_mcp_server():
2658
2716
  tier: Annotated[str, Field(default="T-3", description="Compression tier ('T-3' for AST signatures, 'T-2' for light structure, 'T-4' for agent rules) (default: 'T-3').")] = "T-3"
2659
2717
  ) -> str:
2660
2718
  """Compresses streaming code tokens on-the-fly."""
2661
- from tzero_pipe import PipeCompressor
2719
+ from tzero.tzero_pipe import PipeCompressor
2662
2720
  compressed = PipeCompressor.compress_stream(content, filename_hint=filename_hint, tier=tier)
2663
2721
  raw_tokens = max(1, count_tokens_precise(content))
2664
2722
  comp_tokens = max(1, count_tokens_precise(compressed))
@@ -2702,7 +2760,7 @@ def create_mcp_server():
2702
2760
  repo_dir: Annotated[str, Field(default=".", description="Target git repository root directory where the pre-commit hook will be installed (default: '.').")] = "."
2703
2761
  ) -> str:
2704
2762
  """Installs the pre-commit zero-leak and token optimization guard."""
2705
- from tzero_guard import GitSecurityGuard
2763
+ from tzero.tzero_guard import GitSecurityGuard
2706
2764
  res = GitSecurityGuard.install_hook(repo_dir)
2707
2765
  if res.get("success"):
2708
2766
  return (
@@ -2755,7 +2813,7 @@ def create_mcp_server():
2755
2813
  ) -> str:
2756
2814
  """Discovers existing reusable helpers across codebase AST."""
2757
2815
  abs_root = os.path.abspath(project_root)
2758
- from tzero_features import ReusableHelperSuggester
2816
+ from tzero.tzero_features import ReusableHelperSuggester
2759
2817
  suggester = ReusableHelperSuggester(abs_root)
2760
2818
  if code_snippet:
2761
2819
  guard_report = suggester.check_reinvention_guard(code_snippet=code_snippet, top_k=top_k)
@@ -3017,7 +3075,7 @@ def create_mcp_server():
3017
3075
  current_rules = {}
3018
3076
  if not current_rules:
3019
3077
  try:
3020
- from tzero_features import DEFAULT_RULES_JSON
3078
+ from tzero.tzero_features import DEFAULT_RULES_JSON
3021
3079
  current_rules = dict(DEFAULT_RULES_JSON)
3022
3080
  except Exception:
3023
3081
  current_rules = {"layers": {}, "forbidden_imports": []}
@@ -3057,7 +3115,7 @@ def create_mcp_server():
3057
3115
  return f"⚠️ Rule '{rule_name}' not found in active architecture configuration."
3058
3116
  elif act == "reset":
3059
3117
  try:
3060
- from tzero_features import DEFAULT_RULES_JSON
3118
+ from tzero.tzero_features import DEFAULT_RULES_JSON
3061
3119
  with open(rules_path, "w", encoding="utf-8") as fp:
3062
3120
  json.dump(DEFAULT_RULES_JSON, fp, indent=2, ensure_ascii=False)
3063
3121
  return f"✅ Architecture rules reset to enterprise defaults in `{rules_path}`."
@@ -3487,8 +3545,8 @@ def create_mcp_server():
3487
3545
  ) -> str:
3488
3546
  """Manages the lifecycle of persistent semantic memory stores and knowledge graphs."""
3489
3547
  op = (operation or "list").lower().strip()
3490
- from tzero_jarvis import get_global_compressor
3491
- import tzero_jarvis
3548
+ from tzero.tzero_jarvis import get_global_compressor
3549
+ from tzero import tzero_jarvis
3492
3550
  compressor = get_global_compressor()
3493
3551
  default_store_path = os.path.join(os.path.dirname(tzero_jarvis.__file__), "tzero_memory_store.json")
3494
3552
  target_store_path = os.path.join(os.path.abspath(project_root), f"{store_name}.json") if store_name != "default" else default_store_path
@@ -3578,18 +3636,32 @@ def create_mcp_server():
3578
3636
  )
3579
3637
  def orchestrate_agent_swarm(
3580
3638
  goal: Annotated[str, Field(description="High-level goal description, swarm proposal, or failing test traceback to heal.")],
3581
- orchestration_mode: Annotated[str, Field(default="goal_execute", description="Orchestration mode: 'goal_execute' for autonomous goal planning and execution, 'swarm_consensus' for Byzantine fault-tolerant voting, 'self_healing' for AST error diagnosis and automated patching.")] = "goal_execute",
3639
+ orchestration_mode: Annotated[str, Field(default="goal_execute", description="Orchestration mode: 'goal_execute' for autonomous goal planning and execution, 'swarm_consensus' for Byzantine fault-tolerant voting, 'self_healing' for AST error diagnosis and automated patching, 'dynamic_subagents' for dynamic task decomposition and on-the-fly subagent synthesis.")] = "goal_execute",
3582
3640
  agents: Annotated[str, Field(default="", description="Comma-separated list of agent roles participating in swarm execution (e.g. 'architect,coder,tester').")] = "",
3583
3641
  project_root: Annotated[str, Field(default=".", description="Workspace root for swarm execution (default: current directory).")] = "."
3584
3642
  ) -> str:
3585
3643
  """Coordinates autonomous multi-agent swarms, goal execution, PBFT consensus, and self-healing."""
3586
3644
  o_mode = (orchestration_mode or "goal_execute").lower().strip()
3587
- if o_mode == "swarm_consensus":
3645
+ if o_mode in ("dynamic_subagents", "dynamic", "subagents", "swarm_dynamic"):
3646
+ from tzero.tzero_subagent_engine import get_autonomous_swarm_coordinator
3647
+ coord = get_autonomous_swarm_coordinator(workspace_root=project_root)
3648
+ dossier = coord.execute_mission(mission_goal=goal, workspace_context=agents)
3649
+ return dossier.summary_markdown
3650
+ elif o_mode == "swarm_consensus":
3588
3651
  return _legacy_jarvis_bft_swarm_consensus(mission_goal=goal, context=agents)
3589
3652
  elif o_mode == "self_healing":
3590
3653
  return _legacy_jarvis_self_healing_execute(command=goal, max_retries=3)
3591
3654
  else:
3592
- return _legacy_jarvis_orchestrate_goal(goal=goal, project_root=project_root, mode="auto")
3655
+ goal_lower = (goal or "").strip().lower()
3656
+ if goal_lower in ("", "help", "plan", "ne yapabilirsin", "menu", "capabilities"):
3657
+ return _legacy_jarvis_orchestrate_goal(goal=goal, project_root=project_root, mode="plan")
3658
+ try:
3659
+ from tzero.tzero_subagent_engine import get_autonomous_swarm_coordinator
3660
+ coord = get_autonomous_swarm_coordinator(workspace_root=project_root)
3661
+ dossier = coord.execute_mission(mission_goal=goal, workspace_context=agents)
3662
+ return dossier.summary_markdown
3663
+ except Exception:
3664
+ return _legacy_jarvis_orchestrate_goal(goal=goal, project_root=project_root, mode="auto")
3593
3665
 
3594
3666
  # -------------------------------------------------------------------------
3595
3667
  # SUPERDESIGN ORCHESTRATOR TOOLS (Anchor-5 TDQS Certified)
@@ -3630,7 +3702,7 @@ def create_mcp_server():
3630
3702
  workspace_path: Annotated[str, Field(default=".", description="Workspace directory root for output files (default: current directory).")] = "."
3631
3703
  ) -> str:
3632
3704
  """Returns structured specifications for the AI coding agent to generate designs."""
3633
- import tzero_superdesign
3705
+ from tzero import tzero_superdesign
3634
3706
  res = tzero_superdesign.superdesign_generate(
3635
3707
  prompt=prompt,
3636
3708
  design_type=design_type,
@@ -3674,7 +3746,7 @@ def create_mcp_server():
3674
3746
  workspace_path: Annotated[str, Field(default=".", description="Workspace root (default: current directory).")] = "."
3675
3747
  ) -> str:
3676
3748
  """Returns iteration instructions for the AI coding agent to refine existing designs."""
3677
- import tzero_superdesign
3749
+ from tzero import tzero_superdesign
3678
3750
  res = tzero_superdesign.superdesign_iterate(
3679
3751
  design_file=design_file,
3680
3752
  feedback=feedback,
@@ -3715,7 +3787,7 @@ def create_mcp_server():
3715
3787
  workspace_path: Annotated[str, Field(default=".", description="Workspace root (default: current directory).")] = "."
3716
3788
  ) -> str:
3717
3789
  """Extracts and saves structured design systems from screenshots or descriptions."""
3718
- import tzero_superdesign
3790
+ from tzero import tzero_superdesign
3719
3791
  res = tzero_superdesign.superdesign_extract_system(
3720
3792
  input_path_or_description=input_path_or_description,
3721
3793
  system_name=system_name,
@@ -3751,7 +3823,7 @@ def create_mcp_server():
3751
3823
  workspace_path: Annotated[str, Field(default=".", description="Workspace directory root (default: current directory).")] = "."
3752
3824
  ) -> str:
3753
3825
  """Lists all Superdesign iterations and design systems in the workspace."""
3754
- import tzero_superdesign
3826
+ from tzero import tzero_superdesign
3755
3827
  res = tzero_superdesign.superdesign_list(workspace_path=workspace_path)
3756
3828
  return json.dumps(res, indent=2, ensure_ascii=False)
3757
3829
 
@@ -3783,7 +3855,7 @@ def create_mcp_server():
3783
3855
  workspace_path: Annotated[str, Field(default=".", description="Workspace directory root (default: current directory).")] = "."
3784
3856
  ) -> str:
3785
3857
  """Generates an interactive HTML gallery to preview all created designs."""
3786
- import tzero_superdesign
3858
+ from tzero import tzero_superdesign
3787
3859
  res = tzero_superdesign.superdesign_gallery(workspace_path=workspace_path)
3788
3860
  return json.dumps(res, indent=2, ensure_ascii=False)
3789
3861
 
@@ -3815,7 +3887,7 @@ def create_mcp_server():
3815
3887
  workspace_dir: Annotated[str, Field(default=".", description="Target repository root directory (default: current directory).")] = "."
3816
3888
  ) -> str:
3817
3889
  """Synchronizes active codebase AST topologies and rules across Cursor, Claude, Windsurf, and Git hooks."""
3818
- from tzero_sync import WorkspaceSyncManager
3890
+ from tzero.tzero_sync import WorkspaceSyncManager
3819
3891
  res = WorkspaceSyncManager.sync(workspace_dir)
3820
3892
  files_str = "\n".join(f"- `{f}`" for f in res.synced_files)
3821
3893
  return (
@@ -3856,7 +3928,7 @@ def create_mcp_server():
3856
3928
  workspace_dir: Annotated[str, Field(default=".", description="Target repository root directory (default: current directory).")] = "."
3857
3929
  ) -> str:
3858
3930
  """Calculates token reduction and quantitative financial ROI across LLM providers."""
3859
- from tzero_cost import TokenCostCalculator
3931
+ from tzero.tzero_cost import TokenCostCalculator
3860
3932
  rep = TokenCostCalculator.calculate_cost(workspace_dir)
3861
3933
  lines = [
3862
3934
  f"# 💰 T-Zero Real-Time Token Cost & ROI Cockpit",
@@ -3903,7 +3975,7 @@ def create_mcp_server():
3903
3975
  workspace_dir: Annotated[str, Field(default=".", description="Target repository root directory (default: current directory).")] = "."
3904
3976
  ) -> str:
3905
3977
  """Measures instruction drift and architectural rule decay across the codebase."""
3906
- from tzero_drift import DriftAnalyzer
3978
+ from tzero.tzero_drift import DriftAnalyzer
3907
3979
  rep = DriftAnalyzer.analyze_workspace(workspace_dir)
3908
3980
  lines = [
3909
3981
  f"# 🎯 T-Zero Instruction & Architecture Drift Analysis",
@@ -3959,7 +4031,7 @@ def create_mcp_server():
3959
4031
  force_refresh: Annotated[bool, Field(default=False, description="Whether to force rebuild the cache even if valid (default: False).")] = False
3960
4032
  ) -> str:
3961
4033
  """Pre-computes and caches high-speed AST symbols and token metrics into persistent index."""
3962
- from tzero_snapshot import SnapshotEngine
4034
+ from tzero.tzero_snapshot import SnapshotEngine
3963
4035
  snap, was_cached = SnapshotEngine.get_or_create(workspace_dir, force_refresh=force_refresh)
3964
4036
  status_badge = "CACHE HIT (SUB-8MS)" if was_cached else "NEW SNAPSHOT CREATED"
3965
4037
  return (
@@ -4003,7 +4075,7 @@ def create_mcp_server():
4003
4075
  workspace_dir: Annotated[str, Field(default=".", description="Target repository root directory (default: current directory).")] = "."
4004
4076
  ) -> str:
4005
4077
  """Statically inspects candidate code against workspace AST and repairs hallucinated symbols."""
4006
- from tzero_fix import ASTHallucinationAutoCorrector
4078
+ from tzero.tzero_fix import ASTHallucinationAutoCorrector
4007
4079
  rep = ASTHallucinationAutoCorrector.heal_code(code, workspace_dir=workspace_dir)
4008
4080
  lines = [
4009
4081
  f"# 🔧 T-Zero Self-Healing AST Auto-Corrector",
@@ -4030,6 +4102,7 @@ def create_mcp_server():
4030
4102
  lines.append("```")
4031
4103
  else:
4032
4104
  lines.append("🌟 **Flawless Code:** Zero hallucinated symbols detected. All imports and methods verified against workspace AST.")
4105
+ return "\n".join(lines)
4033
4106
 
4034
4107
  @server.tool(
4035
4108
  name="transpile_model_bridge",
@@ -4062,7 +4135,7 @@ def create_mcp_server():
4062
4135
  target_lang: Annotated[str, Field(default="ts", description="Target language: 'ts', 'rust', 'go', or 'all' (default: 'ts').")] = "ts"
4063
4136
  ) -> str:
4064
4137
  """Transpiles Python @dataclass and Pydantic models into TypeScript, Rust, or Go schemas."""
4065
- from tzero_bridge import PolyglotTypeBridge
4138
+ from tzero.tzero_bridge import PolyglotTypeBridge
4066
4139
  if not os.path.exists(file_path):
4067
4140
  return f"❌ Error: File not found at path '{file_path}'"
4068
4141
  out = PolyglotTypeBridge.transpile_file(file_path, target_lang=target_lang)
@@ -4075,7 +4148,6 @@ def create_mcp_server():
4075
4148
  f"{out}\n"
4076
4149
  f"```\n"
4077
4150
  )
4078
- return "\n".join(lines)
4079
4151
 
4080
4152
  # -------------------------------------------------------------------------
4081
4153
  # -------------------------------------------------------------------------
@@ -4115,7 +4187,7 @@ def create_mcp_server():
4115
4187
  dry_run: Annotated[bool, Field(default=False, description="Whether to preview repairs without writing to disk (default: False).")] = False
4116
4188
  ) -> str:
4117
4189
  """Diagnoses and automatically repairs environment misconfigurations, syntax errors, and orphaned caches."""
4118
- from tzero_pc_fixer import PCFixerDoctor
4190
+ from tzero.tzero_pc_fixer import PCFixerDoctor
4119
4191
  if not auto_repair or dry_run:
4120
4192
  diag = PCFixerDoctor.diagnose(workspace_dir)
4121
4193
  heal_res = PCFixerDoctor.auto_heal(workspace_dir, dry_run=True) if auto_repair else None
@@ -4175,7 +4247,7 @@ def create_mcp_server():
4175
4247
  file_path: Annotated[str, Field(description="Absolute or relative path to the Python source file to inspect.")]
4176
4248
  ) -> str:
4177
4249
  """Generates an ultra-dense AST architectural passport for prompt-ready LLM context grounding."""
4178
- from tzero_explain import ArchitecturalPassportGenerator
4250
+ from tzero.tzero_explain import ArchitecturalPassportGenerator
4179
4251
  if not os.path.exists(file_path):
4180
4252
  return f"❌ Error: File not found at '{file_path}'"
4181
4253
  passport = ArchitecturalPassportGenerator.explain_file(file_path)
@@ -4220,16 +4292,20 @@ def create_mcp_server():
4220
4292
  ),
4221
4293
  annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=True, open_world_hint=False)
4222
4294
  )
4223
- def execute_codebase_workflow(
4295
+ async def execute_codebase_workflow(
4224
4296
  action: Annotated[str, Field(default="auto", description="Workflow operation: 'auto' (comprehensive all-in-one pipeline), 'context', 'audit', 'security', 'blueprint', 'dependencies', 'impact', 'search', 'prune', 'heal', 'memory', 'swarm', 'design'.")] = "auto",
4225
4297
  target: Annotated[str, Field(default=".", description="Target repository path, file path, diff string, or code snippet (default: '.').")] = ".",
4226
4298
  query: Annotated[str, Field(default="", description="Search query, focus symbol name, or task goal prompt.")] = "",
4227
- options: Annotated[str, Field(default="", description="Optional JSON string of additional configuration parameters.")] = ""
4299
+ options: Annotated[Union[str, Dict[str, Any]], Field(default="", description="Optional JSON string or dictionary of additional configuration parameters.")] = "",
4300
+ ctx: Optional[Context] = None,
4228
4301
  ) -> str:
4229
4302
  """Autonomous all-in-one T-Zero master tool executing any codebase workflow in a single command."""
4230
4303
  act = (action or "auto").lower().strip()
4304
+ await _safe_report_progress(ctx, 1, 2, f"Executing T-Zero workflow action '{act}'...")
4231
4305
  opts = {}
4232
- if options:
4306
+ if isinstance(options, dict):
4307
+ opts = options
4308
+ elif isinstance(options, str) and options.strip():
4233
4309
  try:
4234
4310
  opts = json.loads(options)
4235
4311
  except Exception:
@@ -4318,11 +4394,11 @@ def create_mcp_server():
4318
4394
  return estimate_token_cost(project_root=target, text=query)
4319
4395
 
4320
4396
  elif act in ("memory_query", "memory_search"):
4321
- return query_memory_store(query=query or target, store_name=opts.get("store_name", "workspace"))
4397
+ return query_memory_store(query=query or target, query_mode=opts.get("query_mode", "semantic"), project_root=opts.get("project_root", "."))
4322
4398
 
4323
4399
  elif act in ("memory", "memory_manage", "compress"):
4324
4400
  op = opts.get("operation", "list")
4325
- return manage_memory_store(operation=op, store_name=opts.get("store_name", "workspace"), payload=query or target)
4401
+ return manage_memory_store(operation=op, content=query or target, store_name=opts.get("store_name", "default"), project_root=opts.get("project_root", "."))
4326
4402
 
4327
4403
  elif act in ("heal", "self_healing", "fix"):
4328
4404
  return orchestrate_agent_swarm(goal=query or target, orchestration_mode="self_healing", project_root=target if os.path.isdir(target) else ".")
@@ -4330,8 +4406,8 @@ def create_mcp_server():
4330
4406
  elif act in ("consensus", "bft"):
4331
4407
  return orchestrate_agent_swarm(goal=query or target, orchestration_mode="swarm_consensus", agents=opts.get("agents", ""))
4332
4408
 
4333
- elif act in ("swarm", "goal", "orchestrate"):
4334
- return orchestrate_agent_swarm(goal=query or target, orchestration_mode="goal_execute", project_root=target if os.path.isdir(target) else ".")
4409
+ elif act in ("swarm", "goal", "orchestrate", "subagents", "subagent", "decompose"):
4410
+ return orchestrate_agent_swarm(goal=query or target, orchestration_mode="dynamic_subagents", project_root=target if os.path.isdir(target) else ".")
4335
4411
 
4336
4412
  elif act in ("design", "ui", "superdesign"):
4337
4413
  dtype = opts.get("design_type", "ui")
@@ -4371,6 +4447,128 @@ def create_mcp_server():
4371
4447
  elif act in ("drift", "drift_analysis", "instruction_drift", "attention_drift"):
4372
4448
  return analyze_instruction_drift(workspace_dir=target if os.path.isdir(target) else ".")
4373
4449
 
4450
+ elif act in ("merge_heal", "semantic_merge", "merge", "conflict_heal"):
4451
+ from tzero.tzero_semantic_merge import ASTSemanticMerger
4452
+ target_file = target or query
4453
+ if os.path.isfile(target_file):
4454
+ res = ASTSemanticMerger.heal_file_on_disk(target_file, write_in_place=bool(opts.get("write", True)))
4455
+ return json.dumps({
4456
+ "success": res.success,
4457
+ "auto_resolved_conflicts": res.auto_resolved_conflicts,
4458
+ "unresolved_conflicts": res.unresolved_conflicts,
4459
+ "details": res.details
4460
+ }, indent=2)
4461
+ else:
4462
+ res = ASTSemanticMerger.heal_conflict_file(query or target)
4463
+ return res.merged_code
4464
+
4465
+ elif act in ("bridge_reverse", "reverse_transpile", "ts_to_py", "rust_to_py", "go_to_py"):
4466
+ from tzero.tzero_bridge import PolyglotTypeBridge
4467
+ src_code = query or target
4468
+ if os.path.isfile(src_code):
4469
+ with open(src_code, "r", encoding="utf-8", errors="replace") as f:
4470
+ src_code = f.read()
4471
+ flang = opts.get("from_lang", "ts")
4472
+ flavor = opts.get("flavor", "dataclass")
4473
+ return PolyglotTypeBridge.reverse_transpile(src_code, source_lang=flang, model_flavor=flavor)
4474
+
4475
+ elif act in ("blackboard", "swarm_memory", "invariants", "locks"):
4476
+ from tzero.tzero_blackboard import get_shared_blackboard
4477
+ bb = get_shared_blackboard(workspace_root=target if os.path.isdir(target) else ".")
4478
+ sub_op = opts.get("operation", "status")
4479
+ if sub_op == "post_invariant":
4480
+ inv_id = bb.post_invariant(source_agent=opts.get("agent", "Agent"), description=query or target, severity=opts.get("severity", "HIGH"))
4481
+ return f"✅ Posted invariant: {inv_id}"
4482
+ elif sub_op == "claim_lock":
4483
+ ok = bb.claim_symbol(agent_id=opts.get("agent", "Agent"), file_path=target, symbol_name=query or opts.get("symbol", ""))
4484
+ return f"Lock {'granted' if ok else 'denied'}"
4485
+ elif sub_op == "release_lock":
4486
+ ok = bb.release_symbol(agent_id=opts.get("agent", "Agent"), file_path=target, symbol_name=query or opts.get("symbol", ""))
4487
+ return f"Lock {'released' if ok else 'failed to release'}"
4488
+ else:
4489
+ return bb.export_status_markdown()
4490
+
4491
+ elif act in ("generate_architecture_tests", "generate_arch_tests", "arch_tests"):
4492
+ from tzero.tzero_arch_test import ArchitectureTestSuiteGenerator
4493
+ target_dir = target if os.path.isdir(target) else "."
4494
+ gen = ArchitectureTestSuiteGenerator(target_dir)
4495
+ out_path = opts.get("out_path") or (query if query and query.endswith(".py") else None)
4496
+ written = gen.write_test_file(out_path)
4497
+ return f"✅ Standalone Architecture Guard test suite generated at: {written}"
4498
+
4499
+ elif act in ("check_architecture", "check_arch", "arch_audit", "validate_architecture"):
4500
+ from tzero.tzero_arch_test import ArchitectureTestSuiteGenerator
4501
+ target_dir = target if os.path.isdir(target) else "."
4502
+ gen = ArchitectureTestSuiteGenerator(target_dir)
4503
+ report = gen.run_live_audit()
4504
+ if report["success"]:
4505
+ return (
4506
+ f"✅ ARCH-AUDIT PASS: All {report['scanned_files']} modules satisfy declared layer boundaries.\n"
4507
+ f"- Configured Layers: {report['layers_count']}\n"
4508
+ f"- Circular Import Cycles: 0\n"
4509
+ f"- Zero-Leak Violations: 0"
4510
+ )
4511
+ else:
4512
+ lines = [f"❌ ARCH-AUDIT FAILED ({len(report['layer_violations'])} boundary violations, {len(report['circular_cycles'])} cycles, {len(report['secret_leaks'])} leaks):"]
4513
+ for v in report["layer_violations"]:
4514
+ lines.append(f" - [BOUNDARY] {v['file']}:{v['line']} (layer: {v['layer']}) imports forbidden '{v['imported']}'")
4515
+ for c in report["circular_cycles"]:
4516
+ lines.append(f" - [CYCLE] {c}")
4517
+ for s in report["secret_leaks"]:
4518
+ lines.append(f" - [LEAK] {s['file']}: {s['pattern']}")
4519
+ return "\n".join(lines)
4520
+
4521
+ elif act in ("mutation_test", "mutate", "test_quality", "mutation"):
4522
+ from tzero.tzero_mutation import ASTMutationEngine
4523
+ default_target = os.path.join("tzero", "tzero_v3.py")
4524
+ if not os.path.isfile(default_target):
4525
+ default_target = "tzero_v3.py"
4526
+ file_to_mutate = next(
4527
+ (path for path in (target, query) if path and os.path.isfile(path)),
4528
+ default_target,
4529
+ )
4530
+ t_cmd = opts.get("test_cmd")
4531
+ max_m = int(opts.get("max_mutants", 10))
4532
+ rep = ASTMutationEngine.run_mutation_analysis(
4533
+ target_file=file_to_mutate,
4534
+ test_command=t_cmd,
4535
+ max_mutants=max_m
4536
+ )
4537
+ return ASTMutationEngine.format_markdown_report(rep)
4538
+
4539
+ elif act in ("contracts", "check_contracts", "api_contracts", "semver", "breaking_changes"):
4540
+ from tzero.tzero_contracts import ASTContractComparator
4541
+ target_dir = target if os.path.isdir(target) else "."
4542
+ base_ref = opts.get("base_ref") or query or "HEAD~1"
4543
+ reports = ASTContractComparator.compare_git_revision(repo_dir=target_dir, base_ref=base_ref)
4544
+ return ASTContractComparator.format_markdown_report(reports)
4545
+
4546
+ elif act in ("debt", "technical_debt", "code_health", "health", "maintainability"):
4547
+ from tzero.tzero_debt import CodeHealthAnalyzer
4548
+ target_dir = target if os.path.isdir(target) else "."
4549
+ rep = CodeHealthAnalyzer.analyze_workspace(target_dir)
4550
+ return CodeHealthAnalyzer.format_markdown_report(rep)
4551
+
4552
+ elif act in ("budget", "certificate", "cert", "token_budget", "fit_context"):
4553
+ from tzero.tzero_budget import ASTTokenBudgetOptimizer
4554
+ target_dir = target if os.path.isdir(target) else "."
4555
+ t_tok = opts.get("target_tokens") or (int(query) if query.isdigit() else None)
4556
+ m_name = opts.get("model", "claude-3-7")
4557
+ cert = ASTTokenBudgetOptimizer.optimize_budget(target_dir, target_tokens=t_tok, model_name=m_name)
4558
+ return ASTTokenBudgetOptimizer.format_markdown_certificate(cert)
4559
+
4560
+ elif act in ("golden", "goldens", "verify_golden", "check_golden"):
4561
+ from tzero.tzero_golden import ASTGoldenRegressionEngine
4562
+ target_dir = target if os.path.isdir(target) else "."
4563
+ sub_op = opts.get("operation") or query or "verify"
4564
+ if sub_op in ("generate", "update", "capture"):
4565
+ baseline = ASTGoldenRegressionEngine.generate_baseline(target_dir)
4566
+ out_p = ASTGoldenRegressionEngine.save_baseline(baseline)
4567
+ return f"✅ Captured {baseline.total_symbols} golden public AST signatures to: {out_p}"
4568
+ else:
4569
+ rep = ASTGoldenRegressionEngine.verify_against_golden(target_dir)
4570
+ return ASTGoldenRegressionEngine.format_markdown_report(rep)
4571
+
4374
4572
  # Fallback to general dispatch
4375
4573
  handler = _CANONICAL_DISPATCH.get(act) or _LEGACY_DISPATCH.get(act)
4376
4574
  if handler:
@@ -4424,6 +4622,81 @@ def create_mcp_server():
4424
4622
  _LEGACY_DISPATCH['calculate_token_cost_roi'] = calculate_token_cost_roi
4425
4623
  _LEGACY_DISPATCH['analyze_instruction_drift'] = analyze_instruction_drift
4426
4624
 
4625
+ @server.tool(
4626
+ name="search_tools",
4627
+ title="Progressive T-Zero MCP Tool Discovery Catalog",
4628
+ description=(
4629
+ "Progressively discover and search registered T-Zero tools by keyword or domain category rather than loading all 58 schemas at once "
4630
+ "(unlike codebase searches; use 'search_codebase_semantic' for searching repository source files instead).\n\n"
4631
+ "Parameters:\n"
4632
+ "- `query`: Optional keyword query (e.g., 'secret audit', 'pagerank', 'diff', 'merge').\n"
4633
+ "- `category`: Domain filter (`all`, `context`, `security`, `ast`, `memory`, `swarm`, `design`).\n"
4634
+ "- `limit`: Maximum tool entries returned (integer 1-30; defaults to 10).\n\n"
4635
+ "Behavior:\n"
4636
+ "- Mutability & Speed: Read-only, idempotent catalog lookup executing in <5ms.\n"
4637
+ "- Auth & Boundaries: Zero authentication, external credentials, or network access required.\n\n"
4638
+ "Usage Guidelines:\n"
4639
+ "- When to use: Use when running in canonical mode (21 tools) and discovering specialized AST, Jarvis, or security tools by keyword.\n"
4640
+ "- When NOT to use: Do not use when searching source files or symbols inside the workspace repository — use 'search_codebase_semantic' instead.\n\n"
4641
+ "Returns: Structured dictionary with `query`, `total_available`, and ranked `tools` (`name`, `category`, `summary`)."
4642
+ ),
4643
+ structured_output=True,
4644
+ annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=False),
4645
+ )
4646
+ async def search_tools(
4647
+ query: Annotated[str, Field(default="", description="Keyword query (e.g., 'secret audit', 'pagerank', 'diff', 'merge').")] = "",
4648
+ category: Annotated[str, Field(default="all", description="Optional category filter: 'all', 'context', 'security', 'ast', 'memory', 'swarm', 'design'.")] = "all",
4649
+ limit: Annotated[int, Field(default=10, description="Maximum number of matching tools to return (1-30).")] = 10,
4650
+ ) -> SearchToolsResult:
4651
+ """Progressive tool discovery catalog across all T-Zero MCP tools."""
4652
+ q_terms = [t for t in re.findall(r"[a-z0-9_]+", (query or "").lower()) if len(t) > 1]
4653
+ cat_filter = (category or "all").lower().strip()
4654
+ cap_n = max(1, min(30, int(limit or 10)))
4655
+
4656
+ catalog_funcs: Dict[str, Any] = {}
4657
+ catalog_funcs.update(_LEGACY_DISPATCH)
4658
+ catalog_funcs.update(_CANONICAL_DISPATCH)
4659
+ for t_meta in await server.list_tools():
4660
+ if t_meta.name not in catalog_funcs:
4661
+ catalog_funcs[t_meta.name] = t_meta
4662
+
4663
+ def _classify(t_name: str, summary: str) -> str:
4664
+ blob = f"{t_name} {summary}".lower()
4665
+ if any(k in blob for k in ("secret", "leak", "hallucinat", "guard", "security", "audit", "contract", "arch")):
4666
+ return "security"
4667
+ if any(k in blob for k in ("jarvis", "memory", "graph", "minhash", "latent", "causal")):
4668
+ return "memory"
4669
+ if any(k in blob for k in ("swarm", "bft", "subagent", "workflow", "orchestrat")):
4670
+ return "swarm"
4671
+ if "superdesign" in blob:
4672
+ return "design"
4673
+ if any(k in blob for k in ("prune", "skeleton", "impact", "pagerank", "diff", "duplic", "dead", "patch", "merge", "mutat")):
4674
+ return "ast"
4675
+ return "context"
4676
+
4677
+ scored: List[Tuple[int, ToolSearchMatch]] = []
4678
+ for t_name, item in sorted(catalog_funcs.items()):
4679
+ raw_doc = getattr(item, "description", None) or getattr(item, "__doc__", None) or ""
4680
+ summary_line = raw_doc.strip().splitlines()[0][:180] if raw_doc.strip() else t_name.replace("_", " ")
4681
+ t_cat = _classify(t_name, summary_line)
4682
+ if cat_filter != "all" and t_cat != cat_filter:
4683
+ continue
4684
+ hay = f"{t_name.lower()} {summary_line.lower()} {t_cat}"
4685
+ if q_terms:
4686
+ score = sum((5 if term in t_name.lower() else 0) + (2 if term in hay else 0) for term in q_terms)
4687
+ if score == 0:
4688
+ continue
4689
+ else:
4690
+ score = 1
4691
+ scored.append((score, {"name": t_name, "category": t_cat, "summary": summary_line}))
4692
+
4693
+ scored.sort(key=lambda pair: (-pair[0], pair[1]["name"]))
4694
+ return {
4695
+ "query": query,
4696
+ "total_available": len(catalog_funcs),
4697
+ "tools": [entry for _, entry in scored[:cap_n]],
4698
+ }
4699
+
4427
4700
 
4428
4701
  # -------------------------------------------------------------------------
4429
4702
  # TRANSPARENT COMPATIBILITY CALL_TOOL WRAPPER
@@ -4442,7 +4715,9 @@ def create_mcp_server():
4442
4715
  sig = inspect.signature(handler)
4443
4716
  valid_args = {}
4444
4717
  for p_name, param in sig.parameters.items():
4445
- if p_name in arguments:
4718
+ if p_name == "ctx":
4719
+ valid_args[p_name] = context
4720
+ elif p_name in arguments:
4446
4721
  valid_args[p_name] = arguments[p_name]
4447
4722
  elif param.default is not inspect.Parameter.empty:
4448
4723
  valid_args[p_name] = param.default
@@ -4498,7 +4773,7 @@ def create_mcp_server():
4498
4773
  mime_type="text/markdown"
4499
4774
  )
4500
4775
  def resource_polyglot_catalog() -> str:
4501
- from tzero_polyglot import PolyglotTokenReducer
4776
+ from tzero.tzero_polyglot import PolyglotTokenReducer
4502
4777
  langs = PolyglotTokenReducer.SUPPORTED_LANGUAGES
4503
4778
  md = ["# Siber Akademi T-Zero — Universal Polyglot AST Engine\n"]
4504
4779
  md.append("| Language | Extensions | Average Token Reduction | Strategy |")
@@ -4629,7 +4904,7 @@ def create_mcp_server():
4629
4904
  mime_type="text/markdown"
4630
4905
  )
4631
4906
  def resource_jarvis_plan() -> str:
4632
- from tzero_jarvis import JarvisOrchestrator
4907
+ from tzero.tzero_jarvis import JarvisOrchestrator
4633
4908
  orch = JarvisOrchestrator(workspace_root=".")
4634
4909
  plan = orch.generate_plan("")
4635
4910
  return plan["markdown"]
@@ -4641,7 +4916,7 @@ def create_mcp_server():
4641
4916
  mime_type="text/markdown"
4642
4917
  )
4643
4918
  def resource_jarvis_capabilities() -> str:
4644
- from tzero_jarvis import JarvisOrchestrator
4919
+ from tzero.tzero_jarvis import JarvisOrchestrator
4645
4920
  orch = JarvisOrchestrator(workspace_root=".")
4646
4921
  return orch.present_capabilities()
4647
4922
 
@@ -4653,7 +4928,7 @@ def create_mcp_server():
4653
4928
  )
4654
4929
  def resource_workspace_packed_context() -> str:
4655
4930
  try:
4656
- from tzero_packer import pack_workspace
4931
+ from tzero.tzero_packer import pack_workspace
4657
4932
  bundle = pack_workspace(workspace_dir=".", budget_tokens=32000)
4658
4933
  return bundle.bundle_text
4659
4934
  except Exception as e:
@@ -4667,11 +4942,43 @@ def create_mcp_server():
4667
4942
  )
4668
4943
  def resource_workspace_changelog() -> str:
4669
4944
  try:
4670
- from tzero_commit import LocalSemanticCommitSynthesizer
4945
+ from tzero.tzero_commit import LocalSemanticCommitSynthesizer
4671
4946
  return LocalSemanticCommitSynthesizer.generate_changelog_entry(version="Latest", repo_dir=".")
4672
4947
  except Exception as e:
4673
4948
  return f"Error generating changelog: {e}"
4674
4949
 
4950
+ @server.resource(
4951
+ "tzero://file/{path}/skeleton",
4952
+ name="T-Zero Dynamic File AST Skeleton",
4953
+ description="Dynamically reads and AST-prunes a workspace source file with path-traversal and Zero-Leak guards",
4954
+ mime_type="text/plain"
4955
+ )
4956
+ def resource_file_skeleton(path: str) -> str:
4957
+ import urllib.parse
4958
+ ws_root = os.path.abspath(".")
4959
+ rel_clean = urllib.parse.unquote(path or "").lstrip("/\\")
4960
+ if not rel_clean or ".." in rel_clean.replace("\\", "/").split("/"):
4961
+ return f"[BLOCKED] Unsafe relative path blocked: {rel_clean or path}"
4962
+ abs_target = os.path.abspath(os.path.join(ws_root, rel_clean))
4963
+ try:
4964
+ if os.path.commonpath([ws_root, abs_target]) != ws_root:
4965
+ return f"[BLOCKED] Path escapes workspace root: {path}"
4966
+ except ValueError:
4967
+ return f"[BLOCKED] Invalid workspace path: {path}"
4968
+ if not os.path.isfile(abs_target):
4969
+ return f"[ERROR] File not found: {rel_clean}"
4970
+ try:
4971
+ with open(abs_target, "r", encoding="utf-8", errors="replace") as fp:
4972
+ raw_code = fp.read()
4973
+ from tzero.tzero_polyglot import PolyglotTokenReducer
4974
+ reduced = PolyglotTokenReducer.reduce_code(raw_code, filename=abs_target, mode="ultra")
4975
+ from tzero.tzero_security import ZeroLeakEngine
4976
+ if ZeroLeakEngine.scan_text(reduced):
4977
+ reduced = ZeroLeakEngine.sanitize_text(reduced)
4978
+ return reduced
4979
+ except Exception as e:
4980
+ return f"[ERROR] Failed to extract skeleton for '{rel_clean}': {e}"
4981
+
4675
4982
  # -------------------------------------------------------------------------
4676
4983
  # PROMPTS
4677
4984
  # -------------------------------------------------------------------------
@@ -4680,7 +4987,7 @@ def create_mcp_server():
4680
4987
  description="Invokes Jarvis as the Master Executive Pair-Programmer to formulate a phased action plan."
4681
4988
  )
4682
4989
  def prompt_jarvis_workspace_copilot(goal: str = "", project_root: str = ".") -> str:
4683
- from tzero_jarvis import JarvisOrchestrator
4990
+ from tzero.tzero_jarvis import JarvisOrchestrator
4684
4991
  orch = JarvisOrchestrator(workspace_root=project_root)
4685
4992
  plan = orch.generate_plan(goal)
4686
4993
  cap = orch.present_capabilities()
@@ -4699,7 +5006,7 @@ def create_mcp_server():
4699
5006
  )
4700
5007
  def prompt_tzero_pack_budget(budget_tokens: str = "32000", focus_targets: str = "") -> str:
4701
5008
  try:
4702
- from tzero_packer import pack_workspace
5009
+ from tzero.tzero_packer import pack_workspace
4703
5010
  bt = int(budget_tokens) if budget_tokens.isdigit() else 32000
4704
5011
  res = pack_workspace(workspace_dir=".", budget_tokens=bt, focus=focus_targets)
4705
5012
  return (
@@ -4715,7 +5022,7 @@ def create_mcp_server():
4715
5022
  )
4716
5023
  def prompt_tzero_commit_synthesizer(target_scope: str = "") -> str:
4717
5024
  try:
4718
- from tzero_commit import LocalSemanticCommitSynthesizer
5025
+ from tzero.tzero_commit import LocalSemanticCommitSynthesizer
4719
5026
  msg = LocalSemanticCommitSynthesizer.generate_commit_message(repo_dir=".", staged=True)
4720
5027
  diff_text = LocalSemanticCommitSynthesizer.get_git_diff(repo_dir=".", staged=True)
4721
5028
  sem = LocalSemanticCommitSynthesizer.analyze_diff(diff_text)
@@ -4772,19 +5079,70 @@ def print_welcome_guide():
4772
5079
  $ tzero-mcp --stdio
4773
5080
 
4774
5081
  ================================================================================
4775
- ⭐ A MESSAGE FROM THE CREATOR (TOPRAK AHMET AYDOĞMUŞ, 15-YEAR-OLD DEVELOPER)
5082
+ ⚡ SIBER AKADEMI T-ZERO CONTEXT ARCHITECT & MCP ENGINE
4776
5083
  ================================================================================
4777
- Hi! I'm Toprak, a 15-year-old self-taught developer from Siber Akademi.
4778
- I built T-Zero from scratch to solve token bloat and AI hallucinations.
5084
+ Engineered by Toprak Ahmet Aydoğmuş & Siber Akademi to eliminate token bloat,
5085
+ reduce prompt costs by up to 95%, and stop AI hallucinations worldwide.
4779
5086
  If this open-source tool helped you, please consider giving us a ⭐ on GitHub:
4780
5087
  👉 https://github.com/toprakahmetaydogmus/TZeroAlgorithm
4781
- Every star means the world to a young open-source developer! 🚀
5088
+ 100% Free & Open-Source under MIT License. Thank you! 🚀
4782
5089
  ================================================================================
4783
5090
  """)
4784
5091
 
4785
5092
 
5093
+ def create_http_app(mode: Optional[str] = None, host: str = "127.0.0.1") -> Any:
5094
+ """Builds the MCP 2026 Streamable HTTP Starlette ASGI app (zero paid cloud deps)."""
5095
+ if mode:
5096
+ os.environ["TZERO_MCP_TOOL_MODE"] = mode
5097
+ srv = create_mcp_server()
5098
+ if hasattr(srv, "streamable_http_app"):
5099
+ return srv.streamable_http_app(streamable_http_path="/mcp", stateless_http=True, host=host)
5100
+ if hasattr(srv, "sse_app"):
5101
+ return srv.sse_app()
5102
+ raise RuntimeError("Installed MCP SDK server does not expose streamable_http_app or sse_app.")
5103
+
5104
+
5105
+ def _run_http_fallback(server: Any, host: str, port: int) -> None:
5106
+ """Runs streamable-http transport when uvicorn is unavailable, honoring host/port."""
5107
+ settings = getattr(server, "settings", None)
5108
+ if settings is not None:
5109
+ if hasattr(settings, "host"):
5110
+ try:
5111
+ settings.host = host
5112
+ except Exception:
5113
+ pass
5114
+ if hasattr(settings, "port"):
5115
+ try:
5116
+ settings.port = port
5117
+ except Exception:
5118
+ pass
5119
+
5120
+ run_kwargs: Dict[str, Any] = {"transport": "streamable-http"}
5121
+ try:
5122
+ run_params = inspect.signature(server.run).parameters
5123
+ has_varkw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in run_params.values())
5124
+ except (TypeError, ValueError):
5125
+ run_params = {}
5126
+ has_varkw = False
5127
+
5128
+ http_runner = getattr(server, "run_streamable_http_async", None)
5129
+ http_params = {}
5130
+ if http_runner is not None:
5131
+ try:
5132
+ http_params = inspect.signature(http_runner).parameters
5133
+ except (TypeError, ValueError):
5134
+ http_params = {}
5135
+
5136
+ if "host" in run_params or (has_varkw and (not http_params or "host" in http_params)):
5137
+ run_kwargs["host"] = host
5138
+ if "port" in run_params or (has_varkw and (not http_params or "port" in http_params)):
5139
+ run_kwargs["port"] = port
5140
+
5141
+ server.run(**run_kwargs)
5142
+
5143
+
4786
5144
  def main():
4787
- """Main execution entrypoint for the T-Zero MCP stdio server."""
5145
+ """Main execution entrypoint for the T-Zero MCP stdio / Streamable HTTP server."""
4788
5146
  if "--version" in sys.argv[1:]:
4789
5147
  print(f"T-Zero MCP Server {SERVER_VERSION}")
4790
5148
  return
@@ -4801,13 +5159,13 @@ def main():
4801
5159
  elif arg == "--mode" and i + 1 < len(sys.argv):
4802
5160
  os.environ["TZERO_MCP_TOOL_MODE"] = sys.argv[i + 1]
4803
5161
 
4804
- if sys.stdin.isatty() and "--stdio" not in sys.argv[1:] and "--canonical" not in sys.argv[1:]:
5162
+ if sys.stdin.isatty() and "--stdio" not in sys.argv[1:] and "--canonical" not in sys.argv[1:] and "--http" not in sys.argv[1:]:
4805
5163
  print_welcome_guide()
4806
5164
  return
4807
5165
 
4808
5166
  if "--doctor" in sys.argv[1:]:
4809
5167
  try:
4810
- import tzero_deps
5168
+ from tzero import tzero_deps
4811
5169
  sys.exit(tzero_deps.run_doctor())
4812
5170
  except ImportError:
4813
5171
  sys.stderr.write("[ERROR] tzero_deps module not found.\n")
@@ -4815,7 +5173,7 @@ def main():
4815
5173
 
4816
5174
  if "--dashboard" in sys.argv[1:] or "--web" in sys.argv[1:]:
4817
5175
  try:
4818
- import tzero_dashboard
5176
+ from tzero import tzero_dashboard
4819
5177
  tzero_dashboard.main()
4820
5178
  return
4821
5179
  except Exception as e:
@@ -4840,6 +5198,27 @@ def main():
4840
5198
  )
4841
5199
  sys.exit(1)
4842
5200
 
5201
+ if "--http" in sys.argv[1:]:
5202
+ host = "127.0.0.1"
5203
+ port = 8765
5204
+ for i, arg in enumerate(sys.argv):
5205
+ if arg == "--host" and i + 1 < len(sys.argv):
5206
+ host = sys.argv[i + 1]
5207
+ elif arg == "--port" and i + 1 < len(sys.argv):
5208
+ try:
5209
+ port = int(sys.argv[i + 1])
5210
+ except ValueError:
5211
+ pass
5212
+ try:
5213
+ import uvicorn
5214
+ app = create_http_app(host=host)
5215
+ uvicorn.run(app, host=host, port=port)
5216
+ return
5217
+ except ImportError:
5218
+ server = create_mcp_server()
5219
+ _run_http_fallback(server, host=host, port=port)
5220
+ return
5221
+
4843
5222
  # stdout is the MCP protocol channel: any stray log line there corrupts the JSON-RPC
4844
5223
  # stream. The core engine logs to stdout by default, so move those handlers to stderr.
4845
5224
  for handler in logging.getLogger().handlers: