tzero-mcp 11.0.0 → 11.12.1

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 (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -1,634 +1,634 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Stdio JSON-RPC Language Server (tzero lsp).
3
-
4
- Provides real-time in-editor diagnostics and CodeLens via Language Server Protocol:
5
- - 100% Zero-Leak hardcoded credential detection (Severity: Error)
6
- - tzero.rules.json architectural layer boundary violations (Severity: Error)
7
- - Breaking AST public contract change warnings (Severity: Warning)
8
- - AST token compression CodeLens per class/function symbol
9
-
10
- 100% Free, Local, Offline, Stdlib JSON-RPC.
11
- """
12
-
13
- from __future__ import annotations
14
-
15
- import ast
16
- import fnmatch
17
- import json
18
- import os
19
- import re
20
- import sys
21
- import urllib.parse
22
- from typing import Any, BinaryIO, Dict, List, Optional, Set, Tuple
23
-
24
- from tzero.tzero_polyglot import count_bpe_tokens
25
- from tzero.tzero_security import ZeroLeakEngine
26
-
27
-
28
- def uri_to_path(uri: str) -> str:
29
- """Converts a file:// URI to a local filesystem path."""
30
- if not uri.startswith("file://"):
31
- return uri
32
- parsed = urllib.parse.urlparse(uri)
33
- raw_path = urllib.parse.unquote(parsed.path)
34
- if os.name == "nt" and raw_path.startswith("/") and len(raw_path) > 2 and raw_path[2] == ":":
35
- raw_path = raw_path[1:]
36
- return os.path.normpath(raw_path)
37
-
38
-
39
- def encode_lsp_frame(payload: Dict[str, Any]) -> bytes:
40
- """Encodes a JSON-RPC message with LSP Content-Length header framing."""
41
- body = json.dumps(payload).encode("utf-8")
42
- header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
43
- return header + body
44
-
45
-
46
- def read_lsp_frame(in_stream: BinaryIO) -> Optional[Dict[str, Any]]:
47
- """Reads a single Content-Length framed JSON-RPC message from a binary stream."""
48
- content_length: Optional[int] = None
49
- while True:
50
- raw_line = in_stream.readline()
51
- if not raw_line:
52
- return None
53
- line = raw_line.decode("ascii", errors="ignore").strip()
54
- if line == "":
55
- break
56
- if ":" in line:
57
- k, v = line.split(":", 1)
58
- if k.strip().lower() == "content-length":
59
- try:
60
- content_length = int(v.strip())
61
- except ValueError:
62
- pass
63
- if content_length is None or content_length <= 0:
64
- return None
65
- body = in_stream.read(content_length)
66
- if not body or len(body) < content_length:
67
- return None
68
- return json.loads(body.decode("utf-8"))
69
-
70
-
71
- class TZeroLSPServer:
72
- """Stateful Language Server handling LSP lifecycle, diagnostics, and CodeLens."""
73
-
74
- def __init__(self, workspace_dir: str = ".") -> None:
75
- self.workspace_dir = os.path.abspath(workspace_dir)
76
- self.documents: Dict[str, str] = {}
77
- self.baselines: Dict[str, str] = {}
78
- self.shutdown_requested = False
79
- self.running = True
80
- self._rules_cache: Optional[Dict[str, Any]] = None
81
-
82
- def _load_arch_rules(self) -> Dict[str, Any]:
83
- if self._rules_cache is not None:
84
- return self._rules_cache
85
- rules_p = os.path.join(self.workspace_dir, "tzero.rules.json")
86
- if os.path.isfile(rules_p):
87
- try:
88
- with open(rules_p, "r", encoding="utf-8", errors="replace") as f:
89
- data = json.load(f)
90
- if isinstance(data, dict):
91
- self._rules_cache = data
92
- return data
93
- except Exception:
94
- pass
95
- self._rules_cache = {}
96
- return self._rules_cache
97
-
98
- def _classify_layer(self, rel_path: str, rules: Dict[str, Any]) -> Optional[str]:
99
- norm = rel_path.replace("\\", "/")
100
- layers = rules.get("layers", {})
101
- if not isinstance(layers, dict):
102
- return None
103
- for layer_name, patterns in layers.items():
104
- if not isinstance(patterns, list):
105
- continue
106
- for pat in patterns:
107
- pat_norm = str(pat).replace("\\", "/")
108
- prefix = pat_norm.split("*")[0].rstrip("/")
109
- if fnmatch.fnmatch(norm, pat_norm) or (prefix and (norm.startswith(prefix + "/") or norm == prefix)):
110
- return str(layer_name)
111
- return None
112
-
113
- def _extract_imports(self, text: str, file_path: str) -> List[tuple]:
114
- imports: List[tuple] = []
115
- if file_path.endswith(".py"):
116
- try:
117
- tree = ast.parse(text)
118
- for node in ast.walk(tree):
119
- if isinstance(node, ast.Import):
120
- for alias in node.names:
121
- imports.append((getattr(node, "lineno", 1), alias.name))
122
- elif isinstance(node, ast.ImportFrom) and node.module:
123
- imports.append((getattr(node, "lineno", 1), node.module))
124
- return imports
125
- except SyntaxError:
126
- pass
127
- for idx, line in enumerate(text.splitlines(), start=1):
128
- m = re.match(r"""^\s*(?:from|import)\s+([A-Za-z0-9_./@-]+)""", line)
129
- if m:
130
- imports.append((idx, m.group(1)))
131
- return imports
132
-
133
- def _resolve_module_rel(self, mod_name: str, rules: Dict[str, Any]) -> Optional[str]:
134
- """Resolves a dotted/slash module reference to a workspace relative path if determinable."""
135
- cand_rel = mod_name.replace(".", "/")
136
- for suffix in ("", ".py", ".ts", ".js"):
137
- p = os.path.join(self.workspace_dir, cand_rel + suffix)
138
- if os.path.exists(p):
139
- return os.path.relpath(p, self.workspace_dir).replace("\\", "/")
140
- top = mod_name.split(".")[0].split("/")[0]
141
- if top and any(top == k or any(top in str(pt) for pt in v) for k, v in (rules.get("layers") or {}).items() if isinstance(v, list)):
142
- return top
143
- return None
144
-
145
- def analyze_document(self, uri: str, text: str) -> List[Dict[str, Any]]:
146
- """Runs Zero-Leak, architecture boundary, and breaking contract checks on buffer text."""
147
- diags: List[Dict[str, Any]] = []
148
- file_path = uri_to_path(uri)
149
- try:
150
- rel_path = os.path.relpath(file_path, self.workspace_dir).replace("\\", "/")
151
- except ValueError:
152
- rel_path = os.path.basename(file_path)
153
-
154
- # 1. Zero-Leak hardcoded secrets
155
- for finding in ZeroLeakEngine.scan_text(text):
156
- ln = max(0, int(getattr(finding, "line_no", 1)) - 1)
157
- desc = getattr(finding, "description", None) or getattr(finding, "rule_id", "Secret leak")
158
- diags.append({
159
- "range": {"start": {"line": ln, "character": 0}, "end": {"line": ln, "character": 80}},
160
- "severity": 1,
161
- "code": "zero-leak",
162
- "source": "tzero-lsp",
163
- "message": f"T-Zero Zero-Leak Guard: {desc}",
164
- })
165
-
166
- # 2. Architecture boundaries (tzero.rules.json)
167
- rules = self._load_arch_rules()
168
- src_layer = self._classify_layer(rel_path, rules)
169
- forbidden = rules.get("forbidden_imports", [])
170
- if src_layer and isinstance(forbidden, list):
171
- for ln_no, imp_mod in self._extract_imports(text, file_path):
172
- tgt_rel = self._resolve_module_rel(imp_mod, rules)
173
- tgt_layer = self._classify_layer(tgt_rel, rules) if tgt_rel else None
174
- for rule in forbidden:
175
- if rule.get("from_layer") == src_layer and tgt_layer in (rule.get("cannot_import") or []):
176
- diags.append({
177
- "range": {"start": {"line": max(0, ln_no - 1), "character": 0}, "end": {"line": max(0, ln_no - 1), "character": 80}},
178
- "severity": 1,
179
- "code": "arch-boundary",
180
- "source": "tzero-lsp",
181
- "message": f"Layer '{src_layer}' cannot import '{tgt_layer}' ({imp_mod}): {rule.get('reason', 'Boundary violation')}",
182
- })
183
-
184
- # 3. Breaking API contract warnings against baseline
185
- baseline = self.baselines.get(uri)
186
- if baseline and file_path.endswith(".py") and baseline != text:
187
- try:
188
- from tzero.tzero_contracts import ASTContractComparator
189
- rep = ASTContractComparator.compare_code(baseline, text, file_path=rel_path)
190
- if getattr(rep, "is_breaking", False):
191
- diags.append({
192
- "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 1}},
193
- "severity": 2,
194
- "code": "ast-contract",
195
- "source": "tzero-lsp",
196
- "message": f"T-Zero Contract Warning: breaking public API change in {rel_path}",
197
- })
198
- except Exception:
199
- pass
200
-
201
- return diags
202
-
203
- def compute_code_lenses(self, uri: str, text: str) -> List[Dict[str, Any]]:
204
- """Computes token-cost CodeLenses for classes and functions in the document."""
205
- file_path = uri_to_path(uri)
206
- lenses: List[Dict[str, Any]] = []
207
- lines = text.splitlines()
208
-
209
- if file_path.endswith(".py"):
210
- try:
211
- tree = ast.parse(text)
212
- target_nodes: List[ast.AST] = []
213
- for node in tree.body:
214
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
215
- target_nodes.append(node)
216
- elif isinstance(node, ast.ClassDef):
217
- target_nodes.append(node)
218
- for item in node.body:
219
- if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
220
- target_nodes.append(item)
221
- target_nodes.sort(key=lambda n: getattr(n, "lineno", 0))
222
-
223
- for node in target_nodes:
224
- start_l = max(0, getattr(node, "lineno", 1) - 1)
225
- end_l = getattr(node, "end_lineno", node.lineno)
226
- block = "\n".join(lines[start_l:end_l])
227
- sig = lines[start_l] if start_l < len(lines) else ""
228
- raw_t = count_bpe_tokens(block)
229
- sig_t = count_bpe_tokens(sig)
230
- sav = max(0, int(round((1.0 - sig_t / max(1, raw_t)) * 100)))
231
- lenses.append({
232
- "range": {"start": {"line": start_l, "character": 0}, "end": {"line": start_l, "character": len(sig)}},
233
- "command": {
234
- "title": f"⚡ ~{raw_t} tok → {sig_t} sig ({sav}% saved)",
235
- "command": "tzero.copySymbolContract",
236
- "arguments": [file_path, start_l],
237
- },
238
- })
239
- return lenses
240
- except SyntaxError:
241
- pass
242
-
243
- decl_re = re.compile(r'^\s*(?:export\s+)?(?:class|interface|struct|function|func|fn|def)\s+([A-Za-z_][A-Za-z0-9_]*)')
244
- for idx, line in enumerate(lines):
245
- if decl_re.match(line):
246
- sig_t = count_bpe_tokens(line.strip())
247
- lenses.append({
248
- "range": {"start": {"line": idx, "character": 0}, "end": {"line": idx, "character": len(line)}},
249
- "command": {
250
- "title": f"⚡ ~{sig_t} tok AST sig",
251
- "command": "tzero.copySymbolContract",
252
- "arguments": [file_path, idx],
253
- },
254
- })
255
- return lenses
256
-
257
- def compute_hover(
258
- self,
259
- uri: str,
260
- text: str,
261
- line: int,
262
- character: int = 0,
263
- ) -> Optional[Dict[str, Any]]:
264
- """Computes hover info with AST metrics, token reduction, and workspace references."""
265
- file_path = uri_to_path(uri)
266
- lines = text.splitlines()
267
- sym_name: Optional[str] = None
268
- start_l: int = 0
269
- end_l: int = 0
270
- block: str = ""
271
- sig: str = ""
272
- stmt_count: int = 0
273
-
274
- if file_path.endswith(".py"):
275
- try:
276
- tree = ast.parse(text)
277
- candidates: List[Tuple[int, int, int, ast.AST]] = []
278
- for node in ast.walk(tree):
279
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
280
- s = max(0, getattr(node, "lineno", 1) - 1)
281
- e = getattr(node, "end_lineno", node.lineno)
282
- if s <= line < e:
283
- span = e - s
284
- candidates.append((span, s, e, node))
285
- if candidates:
286
- candidates.sort(key=lambda x: (x[0], -x[1]))
287
- _, start_l, end_l, sym_node = candidates[0]
288
- sym_name = getattr(sym_node, "name", "unknown")
289
- block = "\n".join(lines[start_l:end_l])
290
- sig = lines[start_l] if start_l < len(lines) else ""
291
- stmt_count = sum(
292
- 1
293
- for child in getattr(sym_node, "body", [])
294
- for s in ast.walk(child)
295
- if isinstance(s, ast.stmt)
296
- )
297
- if stmt_count == 0:
298
- stmt_count = max(1, len(getattr(sym_node, "body", [])))
299
- except SyntaxError:
300
- pass
301
-
302
- if sym_name is None:
303
- decl_re = re.compile(
304
- r'^\s*(?:export\s+)?(?:class|interface|struct|function|func|fn|def)\s+([A-Za-z_][A-Za-z0-9_]*)'
305
- )
306
- poly_candidates: List[Tuple[int, int, int, str]] = []
307
- for idx, l_text in enumerate(lines):
308
- m = decl_re.match(l_text)
309
- if m:
310
- name = m.group(1)
311
- e_idx = len(lines)
312
- open_braces = l_text.count("{") - l_text.count("}")
313
- if open_braces > 0:
314
- cur_b = open_braces
315
- for j in range(idx + 1, len(lines)):
316
- cur_b += lines[j].count("{") - lines[j].count("}")
317
- if cur_b <= 0:
318
- e_idx = j + 1
319
- break
320
- else:
321
- base_indent = len(l_text) - len(l_text.lstrip())
322
- for j in range(idx + 1, len(lines)):
323
- j_str = lines[j]
324
- if not j_str.strip():
325
- continue
326
- j_indent = len(j_str) - len(j_str.lstrip())
327
- if j_indent <= base_indent and decl_re.match(j_str):
328
- e_idx = j
329
- break
330
- if idx <= line < e_idx:
331
- span = e_idx - idx
332
- poly_candidates.append((span, idx, e_idx, name))
333
- if poly_candidates:
334
- poly_candidates.sort(key=lambda x: (x[0], -x[1]))
335
- _, start_l, end_l, sym_name = poly_candidates[0]
336
- block = "\n".join(lines[start_l:end_l])
337
- sig = lines[start_l] if start_l < len(lines) else ""
338
- stmt_count = max(1, len([l for l in lines[start_l:end_l] if l.strip()]))
339
-
340
- if sym_name is None:
341
- return None
342
-
343
- raw_t = count_bpe_tokens(block)
344
- sig_t = count_bpe_tokens(sig)
345
- sav = max(0, int(round((1.0 - sig_t / max(1, raw_t)) * 100)))
346
-
347
- ref_pat = re.compile(rf"\b{re.escape(sym_name)}\b")
348
- ref_count = 0
349
- scanned_paths: Set[str] = set()
350
-
351
- for doc_uri, buf_text in self.documents.items():
352
- scanned_paths.add(uri_to_path(doc_uri))
353
- ref_count += len(ref_pat.findall(buf_text))
354
-
355
- if uri_to_path(uri) not in scanned_paths:
356
- scanned_paths.add(uri_to_path(uri))
357
- ref_count += len(ref_pat.findall(text))
358
-
359
- disk_count = 0
360
- skip_dirs = {
361
- ".git",
362
- "__pycache__",
363
- ".venv",
364
- "venv",
365
- "node_modules",
366
- "dist",
367
- "build",
368
- ".tzero",
369
- ".superpowers",
370
- ".gemini",
371
- }
372
- src_exts = {
373
- ".py",
374
- ".ts",
375
- ".js",
376
- ".jsx",
377
- ".tsx",
378
- ".go",
379
- ".rs",
380
- ".java",
381
- ".c",
382
- ".cpp",
383
- ".h",
384
- ".hpp",
385
- ".cs",
386
- ".rb",
387
- ".php",
388
- }
389
- if os.path.isdir(self.workspace_dir):
390
- for root, dirs, files in os.walk(self.workspace_dir):
391
- dirs[:] = [d for d in dirs if d not in skip_dirs and not d.startswith(".")]
392
- for fn in files:
393
- if disk_count >= 50:
394
- break
395
- _, ext = os.path.splitext(fn)
396
- if ext.lower() in src_exts:
397
- fp = os.path.normpath(os.path.join(root, fn))
398
- if fp in scanned_paths:
399
- continue
400
- scanned_paths.add(fp)
401
- disk_count += 1
402
- try:
403
- with open(fp, "r", encoding="utf-8", errors="replace") as f:
404
- ref_count += len(ref_pat.findall(f.read()))
405
- except Exception:
406
- pass
407
- if disk_count >= 50:
408
- break
409
-
410
- hover_md = (
411
- f"### `{sym_name}` (T-Zero AST Contract)\n\n"
412
- f"- **Token Footprint:** ~{raw_t} tok → {sig_t} sig ({sav}% saved)\n"
413
- f"- **Statements:** {stmt_count}\n"
414
- f"- **References:** {ref_count}\n"
415
- )
416
-
417
- return {
418
- "contents": {
419
- "kind": "markdown",
420
- "value": hover_md,
421
- },
422
- "range": {
423
- "start": {"line": start_l, "character": 0},
424
- "end": {"line": start_l, "character": len(sig)},
425
- },
426
- }
427
-
428
- def compute_code_actions(
429
- self,
430
- uri: str,
431
- text: str,
432
- diagnostics: Optional[List[Dict[str, Any]]] = None,
433
- ) -> List[Dict[str, Any]]:
434
- """Computes LSP CodeAction quick-fixes for Zero-Leak credential diagnostics."""
435
- if diagnostics is None:
436
- diagnostics = self.analyze_document(uri, text)
437
-
438
- actions: List[Dict[str, Any]] = []
439
- lines = text.splitlines()
440
- assign_pat = re.compile(
441
- r'^(\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*(?::\s*[^=]+)?\s*=\s*)(?:"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\')(\s*(?:#.*)?)$'
442
- )
443
-
444
- for diag in diagnostics:
445
- code_val = str(diag.get("code", ""))
446
- if "zero-leak" not in code_val:
447
- continue
448
- rng = diag.get("range", {})
449
- ln = rng.get("start", {}).get("line", 0)
450
- if ln < 0 or ln >= len(lines):
451
- continue
452
- orig_line = lines[ln]
453
- m = assign_pat.match(orig_line)
454
- if m:
455
- indent = m.group(1)
456
- lhs = m.group(2)
457
- eq_part = m.group(3)
458
- comment = m.group(4) or ""
459
- env_var = re.sub(r"[^A-Z0-9_]", "_", lhs.upper()) or "TZERO_SECRET"
460
- replacement = f'{indent}{lhs}{eq_part}os.environ.get("{env_var}", ""){comment}'
461
- title = f"T-Zero Quick-Fix: Replace '{lhs}' with os.environ.get('{env_var}', '')"
462
- else:
463
- replacement = ZeroLeakEngine.sanitize_text(orig_line)
464
- title = "T-Zero Quick-Fix: Sanitize secret literal"
465
-
466
- actions.append({
467
- "title": title,
468
- "kind": "quickfix",
469
- "isPreferred": True,
470
- "diagnostics": [diag],
471
- "edit": {
472
- "changes": {
473
- uri: [
474
- {
475
- "range": {
476
- "start": {"line": ln, "character": 0},
477
- "end": {"line": ln, "character": len(orig_line)},
478
- },
479
- "newText": replacement,
480
- }
481
- ]
482
- }
483
- },
484
- })
485
-
486
- return actions
487
-
488
- def _publish_diagnostics(self, uri: str, text: str) -> Dict[str, Any]:
489
- return {
490
- "jsonrpc": "2.0",
491
- "method": "textDocument/publishDiagnostics",
492
- "params": {"uri": uri, "diagnostics": self.analyze_document(uri, text)},
493
- }
494
-
495
- def handle_message(self, msg: Dict[str, Any]) -> List[Dict[str, Any]]:
496
- """Processes one decoded JSON-RPC payload and returns outbound messages."""
497
- method = msg.get("method", "")
498
- msg_id = msg.get("id")
499
- params = msg.get("params") or {}
500
-
501
- if method == "initialize":
502
- root_uri = params.get("rootUri")
503
- if isinstance(root_uri, str) and root_uri.startswith("file://"):
504
- self.workspace_dir = uri_to_path(root_uri)
505
- self._rules_cache = None
506
- return [{
507
- "jsonrpc": "2.0",
508
- "id": msg_id,
509
- "result": {
510
- "capabilities": {
511
- "textDocumentSync": 1,
512
- "codeLensProvider": {"resolveProvider": False},
513
- "hoverProvider": True,
514
- "codeActionProvider": True,
515
- },
516
- "serverInfo": {"name": "tzero-lsp", "version": "11.0.0"},
517
- },
518
- }]
519
-
520
- if method == "textDocument/didOpen":
521
- td = params.get("textDocument") or {}
522
- uri = td.get("uri", "")
523
- text = td.get("text", "")
524
- self.documents[uri] = text
525
- self.baselines.setdefault(uri, text)
526
- return [self._publish_diagnostics(uri, text)]
527
-
528
- if method == "textDocument/didChange":
529
- td = params.get("textDocument") or {}
530
- uri = td.get("uri", "")
531
- changes = params.get("contentChanges") or []
532
- text = changes[-1].get("text", "") if changes else self.documents.get(uri, "")
533
- self.documents[uri] = text
534
- return [self._publish_diagnostics(uri, text)]
535
-
536
- if method == "textDocument/didSave":
537
- td = params.get("textDocument") or {}
538
- uri = td.get("uri", "")
539
- text = td.get("text")
540
- if text is None:
541
- fpath = uri_to_path(uri)
542
- if os.path.isfile(fpath):
543
- with open(fpath, "r", encoding="utf-8", errors="replace") as f:
544
- text = f.read()
545
- else:
546
- text = self.documents.get(uri, "")
547
- self.documents[uri] = text
548
- self._rules_cache = None
549
- return [self._publish_diagnostics(uri, text)]
550
-
551
- if method == "textDocument/codeLens":
552
- td = params.get("textDocument") or {}
553
- uri = td.get("uri", "")
554
- text = self.documents.get(uri)
555
- if text is None:
556
- fpath = uri_to_path(uri)
557
- if os.path.isfile(fpath):
558
- with open(fpath, "r", encoding="utf-8", errors="replace") as f:
559
- text = f.read()
560
- else:
561
- text = ""
562
- return [{"jsonrpc": "2.0", "id": msg_id, "result": self.compute_code_lenses(uri, text)}]
563
-
564
- if method == "textDocument/hover":
565
- td = params.get("textDocument") or {}
566
- uri = td.get("uri", "")
567
- text = self.documents.get(uri)
568
- if text is None:
569
- fpath = uri_to_path(uri)
570
- if os.path.isfile(fpath):
571
- try:
572
- with open(fpath, "r", encoding="utf-8", errors="replace") as f:
573
- text = f.read()
574
- except Exception:
575
- text = ""
576
- else:
577
- text = ""
578
- pos = params.get("position") or {}
579
- line = int(pos.get("line", 0))
580
- ch = int(pos.get("character", 0))
581
- return [{"jsonrpc": "2.0", "id": msg_id, "result": self.compute_hover(uri, text, line, ch)}]
582
-
583
- if method == "textDocument/codeAction":
584
- td = params.get("textDocument") or {}
585
- uri = td.get("uri", "")
586
- text = self.documents.get(uri)
587
- if text is None:
588
- fpath = uri_to_path(uri)
589
- if os.path.isfile(fpath):
590
- try:
591
- with open(fpath, "r", encoding="utf-8", errors="replace") as f:
592
- text = f.read()
593
- except Exception:
594
- text = ""
595
- else:
596
- text = ""
597
- ctx = params.get("context") or {}
598
- diags = ctx.get("diagnostics")
599
- return [{"jsonrpc": "2.0", "id": msg_id, "result": self.compute_code_actions(uri, text, diags)}]
600
-
601
- if method == "shutdown":
602
- self.shutdown_requested = True
603
- return [{"jsonrpc": "2.0", "id": msg_id, "result": None}]
604
-
605
- if method == "exit":
606
- self.running = False
607
- return []
608
-
609
- if msg_id is not None:
610
- return [{"jsonrpc": "2.0", "id": msg_id, "result": None}]
611
- return []
612
-
613
- def serve_stdio(
614
- self,
615
- in_stream: Optional[BinaryIO] = None,
616
- out_stream: Optional[BinaryIO] = None,
617
- ) -> None:
618
- """Runs synchronous Content-Length JSON-RPC stdio message loop."""
619
- reader = in_stream or sys.stdin.buffer
620
- writer = out_stream or sys.stdout.buffer
621
- while self.running:
622
- msg = read_lsp_frame(reader)
623
- if msg is None:
624
- break
625
- outbound = self.handle_message(msg)
626
- for pkt in outbound:
627
- writer.write(encode_lsp_frame(pkt))
628
- writer.flush()
629
-
630
-
631
- def main(workspace_dir: str = ".") -> int:
632
- srv = TZeroLSPServer(workspace_dir=workspace_dir)
633
- srv.serve_stdio()
634
- return 0 if srv.shutdown_requested else 0
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Stdio JSON-RPC Language Server (tzero lsp).
3
+
4
+ Provides real-time in-editor diagnostics and CodeLens via Language Server Protocol:
5
+ - 100% Zero-Leak hardcoded credential detection (Severity: Error)
6
+ - tzero.rules.json architectural layer boundary violations (Severity: Error)
7
+ - Breaking AST public contract change warnings (Severity: Warning)
8
+ - AST token compression CodeLens per class/function symbol
9
+
10
+ 100% Free, Local, Offline, Stdlib JSON-RPC.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import fnmatch
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+ import urllib.parse
22
+ from typing import Any, BinaryIO, Dict, List, Optional, Set, Tuple
23
+
24
+ from tzero.tzero_polyglot import count_bpe_tokens
25
+ from tzero.tzero_security import ZeroLeakEngine
26
+
27
+
28
+ def uri_to_path(uri: str) -> str:
29
+ """Converts a file:// URI to a local filesystem path."""
30
+ if not uri.startswith("file://"):
31
+ return uri
32
+ parsed = urllib.parse.urlparse(uri)
33
+ raw_path = urllib.parse.unquote(parsed.path)
34
+ if os.name == "nt" and raw_path.startswith("/") and len(raw_path) > 2 and raw_path[2] == ":":
35
+ raw_path = raw_path[1:]
36
+ return os.path.normpath(raw_path)
37
+
38
+
39
+ def encode_lsp_frame(payload: Dict[str, Any]) -> bytes:
40
+ """Encodes a JSON-RPC message with LSP Content-Length header framing."""
41
+ body = json.dumps(payload).encode("utf-8")
42
+ header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
43
+ return header + body
44
+
45
+
46
+ def read_lsp_frame(in_stream: BinaryIO) -> Optional[Dict[str, Any]]:
47
+ """Reads a single Content-Length framed JSON-RPC message from a binary stream."""
48
+ content_length: Optional[int] = None
49
+ while True:
50
+ raw_line = in_stream.readline()
51
+ if not raw_line:
52
+ return None
53
+ line = raw_line.decode("ascii", errors="ignore").strip()
54
+ if line == "":
55
+ break
56
+ if ":" in line:
57
+ k, v = line.split(":", 1)
58
+ if k.strip().lower() == "content-length":
59
+ try:
60
+ content_length = int(v.strip())
61
+ except ValueError:
62
+ pass
63
+ if content_length is None or content_length <= 0:
64
+ return None
65
+ body = in_stream.read(content_length)
66
+ if not body or len(body) < content_length:
67
+ return None
68
+ return json.loads(body.decode("utf-8"))
69
+
70
+
71
+ class TZeroLSPServer:
72
+ """Stateful Language Server handling LSP lifecycle, diagnostics, and CodeLens."""
73
+
74
+ def __init__(self, workspace_dir: str = ".") -> None:
75
+ self.workspace_dir = os.path.abspath(workspace_dir)
76
+ self.documents: Dict[str, str] = {}
77
+ self.baselines: Dict[str, str] = {}
78
+ self.shutdown_requested = False
79
+ self.running = True
80
+ self._rules_cache: Optional[Dict[str, Any]] = None
81
+
82
+ def _load_arch_rules(self) -> Dict[str, Any]:
83
+ if self._rules_cache is not None:
84
+ return self._rules_cache
85
+ rules_p = os.path.join(self.workspace_dir, "tzero.rules.json")
86
+ if os.path.isfile(rules_p):
87
+ try:
88
+ with open(rules_p, "r", encoding="utf-8", errors="replace") as f:
89
+ data = json.load(f)
90
+ if isinstance(data, dict):
91
+ self._rules_cache = data
92
+ return data
93
+ except Exception:
94
+ pass
95
+ self._rules_cache = {}
96
+ return self._rules_cache
97
+
98
+ def _classify_layer(self, rel_path: str, rules: Dict[str, Any]) -> Optional[str]:
99
+ norm = rel_path.replace("\\", "/")
100
+ layers = rules.get("layers", {})
101
+ if not isinstance(layers, dict):
102
+ return None
103
+ for layer_name, patterns in layers.items():
104
+ if not isinstance(patterns, list):
105
+ continue
106
+ for pat in patterns:
107
+ pat_norm = str(pat).replace("\\", "/")
108
+ prefix = pat_norm.split("*")[0].rstrip("/")
109
+ if fnmatch.fnmatch(norm, pat_norm) or (prefix and (norm.startswith(prefix + "/") or norm == prefix)):
110
+ return str(layer_name)
111
+ return None
112
+
113
+ def _extract_imports(self, text: str, file_path: str) -> List[tuple]:
114
+ imports: List[tuple] = []
115
+ if file_path.endswith(".py"):
116
+ try:
117
+ tree = ast.parse(text)
118
+ for node in ast.walk(tree):
119
+ if isinstance(node, ast.Import):
120
+ for alias in node.names:
121
+ imports.append((getattr(node, "lineno", 1), alias.name))
122
+ elif isinstance(node, ast.ImportFrom) and node.module:
123
+ imports.append((getattr(node, "lineno", 1), node.module))
124
+ return imports
125
+ except SyntaxError:
126
+ pass
127
+ for idx, line in enumerate(text.splitlines(), start=1):
128
+ m = re.match(r"""^\s*(?:from|import)\s+([A-Za-z0-9_./@-]+)""", line)
129
+ if m:
130
+ imports.append((idx, m.group(1)))
131
+ return imports
132
+
133
+ def _resolve_module_rel(self, mod_name: str, rules: Dict[str, Any]) -> Optional[str]:
134
+ """Resolves a dotted/slash module reference to a workspace relative path if determinable."""
135
+ cand_rel = mod_name.replace(".", "/")
136
+ for suffix in ("", ".py", ".ts", ".js"):
137
+ p = os.path.join(self.workspace_dir, cand_rel + suffix)
138
+ if os.path.exists(p):
139
+ return os.path.relpath(p, self.workspace_dir).replace("\\", "/")
140
+ top = mod_name.split(".")[0].split("/")[0]
141
+ if top and any(top == k or any(top in str(pt) for pt in v) for k, v in (rules.get("layers") or {}).items() if isinstance(v, list)):
142
+ return top
143
+ return None
144
+
145
+ def analyze_document(self, uri: str, text: str) -> List[Dict[str, Any]]:
146
+ """Runs Zero-Leak, architecture boundary, and breaking contract checks on buffer text."""
147
+ diags: List[Dict[str, Any]] = []
148
+ file_path = uri_to_path(uri)
149
+ try:
150
+ rel_path = os.path.relpath(file_path, self.workspace_dir).replace("\\", "/")
151
+ except ValueError:
152
+ rel_path = os.path.basename(file_path)
153
+
154
+ # 1. Zero-Leak hardcoded secrets
155
+ for finding in ZeroLeakEngine.scan_text(text):
156
+ ln = max(0, int(getattr(finding, "line_no", 1)) - 1)
157
+ desc = getattr(finding, "description", None) or getattr(finding, "rule_id", "Secret leak")
158
+ diags.append({
159
+ "range": {"start": {"line": ln, "character": 0}, "end": {"line": ln, "character": 80}},
160
+ "severity": 1,
161
+ "code": "zero-leak",
162
+ "source": "tzero-lsp",
163
+ "message": f"T-Zero Zero-Leak Guard: {desc}",
164
+ })
165
+
166
+ # 2. Architecture boundaries (tzero.rules.json)
167
+ rules = self._load_arch_rules()
168
+ src_layer = self._classify_layer(rel_path, rules)
169
+ forbidden = rules.get("forbidden_imports", [])
170
+ if src_layer and isinstance(forbidden, list):
171
+ for ln_no, imp_mod in self._extract_imports(text, file_path):
172
+ tgt_rel = self._resolve_module_rel(imp_mod, rules)
173
+ tgt_layer = self._classify_layer(tgt_rel, rules) if tgt_rel else None
174
+ for rule in forbidden:
175
+ if rule.get("from_layer") == src_layer and tgt_layer in (rule.get("cannot_import") or []):
176
+ diags.append({
177
+ "range": {"start": {"line": max(0, ln_no - 1), "character": 0}, "end": {"line": max(0, ln_no - 1), "character": 80}},
178
+ "severity": 1,
179
+ "code": "arch-boundary",
180
+ "source": "tzero-lsp",
181
+ "message": f"Layer '{src_layer}' cannot import '{tgt_layer}' ({imp_mod}): {rule.get('reason', 'Boundary violation')}",
182
+ })
183
+
184
+ # 3. Breaking API contract warnings against baseline
185
+ baseline = self.baselines.get(uri)
186
+ if baseline and file_path.endswith(".py") and baseline != text:
187
+ try:
188
+ from tzero.tzero_contracts import ASTContractComparator
189
+ rep = ASTContractComparator.compare_code(baseline, text, file_path=rel_path)
190
+ if getattr(rep, "is_breaking", False):
191
+ diags.append({
192
+ "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 1}},
193
+ "severity": 2,
194
+ "code": "ast-contract",
195
+ "source": "tzero-lsp",
196
+ "message": f"T-Zero Contract Warning: breaking public API change in {rel_path}",
197
+ })
198
+ except Exception:
199
+ pass
200
+
201
+ return diags
202
+
203
+ def compute_code_lenses(self, uri: str, text: str) -> List[Dict[str, Any]]:
204
+ """Computes token-cost CodeLenses for classes and functions in the document."""
205
+ file_path = uri_to_path(uri)
206
+ lenses: List[Dict[str, Any]] = []
207
+ lines = text.splitlines()
208
+
209
+ if file_path.endswith(".py"):
210
+ try:
211
+ tree = ast.parse(text)
212
+ target_nodes: List[ast.AST] = []
213
+ for node in tree.body:
214
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
215
+ target_nodes.append(node)
216
+ elif isinstance(node, ast.ClassDef):
217
+ target_nodes.append(node)
218
+ for item in node.body:
219
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
220
+ target_nodes.append(item)
221
+ target_nodes.sort(key=lambda n: getattr(n, "lineno", 0))
222
+
223
+ for node in target_nodes:
224
+ start_l = max(0, getattr(node, "lineno", 1) - 1)
225
+ end_l = getattr(node, "end_lineno", node.lineno)
226
+ block = "\n".join(lines[start_l:end_l])
227
+ sig = lines[start_l] if start_l < len(lines) else ""
228
+ raw_t = count_bpe_tokens(block)
229
+ sig_t = count_bpe_tokens(sig)
230
+ sav = max(0, int(round((1.0 - sig_t / max(1, raw_t)) * 100)))
231
+ lenses.append({
232
+ "range": {"start": {"line": start_l, "character": 0}, "end": {"line": start_l, "character": len(sig)}},
233
+ "command": {
234
+ "title": f"⚡ ~{raw_t} tok → {sig_t} sig ({sav}% saved)",
235
+ "command": "tzero.copySymbolContract",
236
+ "arguments": [file_path, start_l],
237
+ },
238
+ })
239
+ return lenses
240
+ except SyntaxError:
241
+ pass
242
+
243
+ decl_re = re.compile(r'^\s*(?:export\s+)?(?:class|interface|struct|function|func|fn|def)\s+([A-Za-z_][A-Za-z0-9_]*)')
244
+ for idx, line in enumerate(lines):
245
+ if decl_re.match(line):
246
+ sig_t = count_bpe_tokens(line.strip())
247
+ lenses.append({
248
+ "range": {"start": {"line": idx, "character": 0}, "end": {"line": idx, "character": len(line)}},
249
+ "command": {
250
+ "title": f"⚡ ~{sig_t} tok AST sig",
251
+ "command": "tzero.copySymbolContract",
252
+ "arguments": [file_path, idx],
253
+ },
254
+ })
255
+ return lenses
256
+
257
+ def compute_hover(
258
+ self,
259
+ uri: str,
260
+ text: str,
261
+ line: int,
262
+ character: int = 0,
263
+ ) -> Optional[Dict[str, Any]]:
264
+ """Computes hover info with AST metrics, token reduction, and workspace references."""
265
+ file_path = uri_to_path(uri)
266
+ lines = text.splitlines()
267
+ sym_name: Optional[str] = None
268
+ start_l: int = 0
269
+ end_l: int = 0
270
+ block: str = ""
271
+ sig: str = ""
272
+ stmt_count: int = 0
273
+
274
+ if file_path.endswith(".py"):
275
+ try:
276
+ tree = ast.parse(text)
277
+ candidates: List[Tuple[int, int, int, ast.AST]] = []
278
+ for node in ast.walk(tree):
279
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
280
+ s = max(0, getattr(node, "lineno", 1) - 1)
281
+ e = getattr(node, "end_lineno", node.lineno)
282
+ if s <= line < e:
283
+ span = e - s
284
+ candidates.append((span, s, e, node))
285
+ if candidates:
286
+ candidates.sort(key=lambda x: (x[0], -x[1]))
287
+ _, start_l, end_l, sym_node = candidates[0]
288
+ sym_name = getattr(sym_node, "name", "unknown")
289
+ block = "\n".join(lines[start_l:end_l])
290
+ sig = lines[start_l] if start_l < len(lines) else ""
291
+ stmt_count = sum(
292
+ 1
293
+ for child in getattr(sym_node, "body", [])
294
+ for s in ast.walk(child)
295
+ if isinstance(s, ast.stmt)
296
+ )
297
+ if stmt_count == 0:
298
+ stmt_count = max(1, len(getattr(sym_node, "body", [])))
299
+ except SyntaxError:
300
+ pass
301
+
302
+ if sym_name is None:
303
+ decl_re = re.compile(
304
+ r'^\s*(?:export\s+)?(?:class|interface|struct|function|func|fn|def)\s+([A-Za-z_][A-Za-z0-9_]*)'
305
+ )
306
+ poly_candidates: List[Tuple[int, int, int, str]] = []
307
+ for idx, l_text in enumerate(lines):
308
+ m = decl_re.match(l_text)
309
+ if m:
310
+ name = m.group(1)
311
+ e_idx = len(lines)
312
+ open_braces = l_text.count("{") - l_text.count("}")
313
+ if open_braces > 0:
314
+ cur_b = open_braces
315
+ for j in range(idx + 1, len(lines)):
316
+ cur_b += lines[j].count("{") - lines[j].count("}")
317
+ if cur_b <= 0:
318
+ e_idx = j + 1
319
+ break
320
+ else:
321
+ base_indent = len(l_text) - len(l_text.lstrip())
322
+ for j in range(idx + 1, len(lines)):
323
+ j_str = lines[j]
324
+ if not j_str.strip():
325
+ continue
326
+ j_indent = len(j_str) - len(j_str.lstrip())
327
+ if j_indent <= base_indent and decl_re.match(j_str):
328
+ e_idx = j
329
+ break
330
+ if idx <= line < e_idx:
331
+ span = e_idx - idx
332
+ poly_candidates.append((span, idx, e_idx, name))
333
+ if poly_candidates:
334
+ poly_candidates.sort(key=lambda x: (x[0], -x[1]))
335
+ _, start_l, end_l, sym_name = poly_candidates[0]
336
+ block = "\n".join(lines[start_l:end_l])
337
+ sig = lines[start_l] if start_l < len(lines) else ""
338
+ stmt_count = max(1, len([l for l in lines[start_l:end_l] if l.strip()]))
339
+
340
+ if sym_name is None:
341
+ return None
342
+
343
+ raw_t = count_bpe_tokens(block)
344
+ sig_t = count_bpe_tokens(sig)
345
+ sav = max(0, int(round((1.0 - sig_t / max(1, raw_t)) * 100)))
346
+
347
+ ref_pat = re.compile(rf"\b{re.escape(sym_name)}\b")
348
+ ref_count = 0
349
+ scanned_paths: Set[str] = set()
350
+
351
+ for doc_uri, buf_text in self.documents.items():
352
+ scanned_paths.add(uri_to_path(doc_uri))
353
+ ref_count += len(ref_pat.findall(buf_text))
354
+
355
+ if uri_to_path(uri) not in scanned_paths:
356
+ scanned_paths.add(uri_to_path(uri))
357
+ ref_count += len(ref_pat.findall(text))
358
+
359
+ disk_count = 0
360
+ skip_dirs = {
361
+ ".git",
362
+ "__pycache__",
363
+ ".venv",
364
+ "venv",
365
+ "node_modules",
366
+ "dist",
367
+ "build",
368
+ ".tzero",
369
+ ".superpowers",
370
+ ".gemini",
371
+ }
372
+ src_exts = {
373
+ ".py",
374
+ ".ts",
375
+ ".js",
376
+ ".jsx",
377
+ ".tsx",
378
+ ".go",
379
+ ".rs",
380
+ ".java",
381
+ ".c",
382
+ ".cpp",
383
+ ".h",
384
+ ".hpp",
385
+ ".cs",
386
+ ".rb",
387
+ ".php",
388
+ }
389
+ if os.path.isdir(self.workspace_dir):
390
+ for root, dirs, files in os.walk(self.workspace_dir):
391
+ dirs[:] = [d for d in dirs if d not in skip_dirs and not d.startswith(".")]
392
+ for fn in files:
393
+ if disk_count >= 50:
394
+ break
395
+ _, ext = os.path.splitext(fn)
396
+ if ext.lower() in src_exts:
397
+ fp = os.path.normpath(os.path.join(root, fn))
398
+ if fp in scanned_paths:
399
+ continue
400
+ scanned_paths.add(fp)
401
+ disk_count += 1
402
+ try:
403
+ with open(fp, "r", encoding="utf-8", errors="replace") as f:
404
+ ref_count += len(ref_pat.findall(f.read()))
405
+ except Exception:
406
+ pass
407
+ if disk_count >= 50:
408
+ break
409
+
410
+ hover_md = (
411
+ f"### `{sym_name}` (T-Zero AST Contract)\n\n"
412
+ f"- **Token Footprint:** ~{raw_t} tok → {sig_t} sig ({sav}% saved)\n"
413
+ f"- **Statements:** {stmt_count}\n"
414
+ f"- **References:** {ref_count}\n"
415
+ )
416
+
417
+ return {
418
+ "contents": {
419
+ "kind": "markdown",
420
+ "value": hover_md,
421
+ },
422
+ "range": {
423
+ "start": {"line": start_l, "character": 0},
424
+ "end": {"line": start_l, "character": len(sig)},
425
+ },
426
+ }
427
+
428
+ def compute_code_actions(
429
+ self,
430
+ uri: str,
431
+ text: str,
432
+ diagnostics: Optional[List[Dict[str, Any]]] = None,
433
+ ) -> List[Dict[str, Any]]:
434
+ """Computes LSP CodeAction quick-fixes for Zero-Leak credential diagnostics."""
435
+ if diagnostics is None:
436
+ diagnostics = self.analyze_document(uri, text)
437
+
438
+ actions: List[Dict[str, Any]] = []
439
+ lines = text.splitlines()
440
+ assign_pat = re.compile(
441
+ r'^(\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*(?::\s*[^=]+)?\s*=\s*)(?:"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\')(\s*(?:#.*)?)$'
442
+ )
443
+
444
+ for diag in diagnostics:
445
+ code_val = str(diag.get("code", ""))
446
+ if "zero-leak" not in code_val:
447
+ continue
448
+ rng = diag.get("range", {})
449
+ ln = rng.get("start", {}).get("line", 0)
450
+ if ln < 0 or ln >= len(lines):
451
+ continue
452
+ orig_line = lines[ln]
453
+ m = assign_pat.match(orig_line)
454
+ if m:
455
+ indent = m.group(1)
456
+ lhs = m.group(2)
457
+ eq_part = m.group(3)
458
+ comment = m.group(4) or ""
459
+ env_var = re.sub(r"[^A-Z0-9_]", "_", lhs.upper()) or "TZERO_SECRET"
460
+ replacement = f'{indent}{lhs}{eq_part}os.environ.get("{env_var}", ""){comment}'
461
+ title = f"T-Zero Quick-Fix: Replace '{lhs}' with os.environ.get('{env_var}', '')"
462
+ else:
463
+ replacement = ZeroLeakEngine.sanitize_text(orig_line)
464
+ title = "T-Zero Quick-Fix: Sanitize secret literal"
465
+
466
+ actions.append({
467
+ "title": title,
468
+ "kind": "quickfix",
469
+ "isPreferred": True,
470
+ "diagnostics": [diag],
471
+ "edit": {
472
+ "changes": {
473
+ uri: [
474
+ {
475
+ "range": {
476
+ "start": {"line": ln, "character": 0},
477
+ "end": {"line": ln, "character": len(orig_line)},
478
+ },
479
+ "newText": replacement,
480
+ }
481
+ ]
482
+ }
483
+ },
484
+ })
485
+
486
+ return actions
487
+
488
+ def _publish_diagnostics(self, uri: str, text: str) -> Dict[str, Any]:
489
+ return {
490
+ "jsonrpc": "2.0",
491
+ "method": "textDocument/publishDiagnostics",
492
+ "params": {"uri": uri, "diagnostics": self.analyze_document(uri, text)},
493
+ }
494
+
495
+ def handle_message(self, msg: Dict[str, Any]) -> List[Dict[str, Any]]:
496
+ """Processes one decoded JSON-RPC payload and returns outbound messages."""
497
+ method = msg.get("method", "")
498
+ msg_id = msg.get("id")
499
+ params = msg.get("params") or {}
500
+
501
+ if method == "initialize":
502
+ root_uri = params.get("rootUri")
503
+ if isinstance(root_uri, str) and root_uri.startswith("file://"):
504
+ self.workspace_dir = uri_to_path(root_uri)
505
+ self._rules_cache = None
506
+ return [{
507
+ "jsonrpc": "2.0",
508
+ "id": msg_id,
509
+ "result": {
510
+ "capabilities": {
511
+ "textDocumentSync": 1,
512
+ "codeLensProvider": {"resolveProvider": False},
513
+ "hoverProvider": True,
514
+ "codeActionProvider": True,
515
+ },
516
+ "serverInfo": {"name": "tzero-lsp", "version": "11.11.0"},
517
+ },
518
+ }]
519
+
520
+ if method == "textDocument/didOpen":
521
+ td = params.get("textDocument") or {}
522
+ uri = td.get("uri", "")
523
+ text = td.get("text", "")
524
+ self.documents[uri] = text
525
+ self.baselines.setdefault(uri, text)
526
+ return [self._publish_diagnostics(uri, text)]
527
+
528
+ if method == "textDocument/didChange":
529
+ td = params.get("textDocument") or {}
530
+ uri = td.get("uri", "")
531
+ changes = params.get("contentChanges") or []
532
+ text = changes[-1].get("text", "") if changes else self.documents.get(uri, "")
533
+ self.documents[uri] = text
534
+ return [self._publish_diagnostics(uri, text)]
535
+
536
+ if method == "textDocument/didSave":
537
+ td = params.get("textDocument") or {}
538
+ uri = td.get("uri", "")
539
+ text = td.get("text")
540
+ if text is None:
541
+ fpath = uri_to_path(uri)
542
+ if os.path.isfile(fpath):
543
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
544
+ text = f.read()
545
+ else:
546
+ text = self.documents.get(uri, "")
547
+ self.documents[uri] = text
548
+ self._rules_cache = None
549
+ return [self._publish_diagnostics(uri, text)]
550
+
551
+ if method == "textDocument/codeLens":
552
+ td = params.get("textDocument") or {}
553
+ uri = td.get("uri", "")
554
+ text = self.documents.get(uri)
555
+ if text is None:
556
+ fpath = uri_to_path(uri)
557
+ if os.path.isfile(fpath):
558
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
559
+ text = f.read()
560
+ else:
561
+ text = ""
562
+ return [{"jsonrpc": "2.0", "id": msg_id, "result": self.compute_code_lenses(uri, text)}]
563
+
564
+ if method == "textDocument/hover":
565
+ td = params.get("textDocument") or {}
566
+ uri = td.get("uri", "")
567
+ text = self.documents.get(uri)
568
+ if text is None:
569
+ fpath = uri_to_path(uri)
570
+ if os.path.isfile(fpath):
571
+ try:
572
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
573
+ text = f.read()
574
+ except Exception:
575
+ text = ""
576
+ else:
577
+ text = ""
578
+ pos = params.get("position") or {}
579
+ line = int(pos.get("line", 0))
580
+ ch = int(pos.get("character", 0))
581
+ return [{"jsonrpc": "2.0", "id": msg_id, "result": self.compute_hover(uri, text, line, ch)}]
582
+
583
+ if method == "textDocument/codeAction":
584
+ td = params.get("textDocument") or {}
585
+ uri = td.get("uri", "")
586
+ text = self.documents.get(uri)
587
+ if text is None:
588
+ fpath = uri_to_path(uri)
589
+ if os.path.isfile(fpath):
590
+ try:
591
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
592
+ text = f.read()
593
+ except Exception:
594
+ text = ""
595
+ else:
596
+ text = ""
597
+ ctx = params.get("context") or {}
598
+ diags = ctx.get("diagnostics")
599
+ return [{"jsonrpc": "2.0", "id": msg_id, "result": self.compute_code_actions(uri, text, diags)}]
600
+
601
+ if method == "shutdown":
602
+ self.shutdown_requested = True
603
+ return [{"jsonrpc": "2.0", "id": msg_id, "result": None}]
604
+
605
+ if method == "exit":
606
+ self.running = False
607
+ return []
608
+
609
+ if msg_id is not None:
610
+ return [{"jsonrpc": "2.0", "id": msg_id, "result": None}]
611
+ return []
612
+
613
+ def serve_stdio(
614
+ self,
615
+ in_stream: Optional[BinaryIO] = None,
616
+ out_stream: Optional[BinaryIO] = None,
617
+ ) -> None:
618
+ """Runs synchronous Content-Length JSON-RPC stdio message loop."""
619
+ reader = in_stream or sys.stdin.buffer
620
+ writer = out_stream or sys.stdout.buffer
621
+ while self.running:
622
+ msg = read_lsp_frame(reader)
623
+ if msg is None:
624
+ break
625
+ outbound = self.handle_message(msg)
626
+ for pkt in outbound:
627
+ writer.write(encode_lsp_frame(pkt))
628
+ writer.flush()
629
+
630
+
631
+ def main(workspace_dir: str = ".") -> int:
632
+ srv = TZeroLSPServer(workspace_dir=workspace_dir)
633
+ srv.serve_stdio()
634
+ return 0 if srv.shutdown_requested else 0