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,565 +1,565 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero 2026 Lifecycle Hook Runner (PreToolUse / PostToolUse).
3
-
4
- Supports Claude Code, Gemini CLI, and Cursor native hook JSON protocols:
5
- - PreToolUse: Blocks writes/edits/commands containing leaked credentials or layer violations (exit code 2).
6
- - PostToolUse: Auto-prunes oversized file reads into compact AST skeletons cleanly.
7
-
8
- 100% Free, Local, Offline, Zero-Leak Certified.
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import ast
14
- import fnmatch
15
- import json
16
- import os
17
- import re
18
- import sys
19
- from typing import Any, Dict, List, Optional, Set
20
-
21
- from tzero.tzero_polyglot import PolyglotTokenReducer, count_bpe_tokens
22
- from tzero.tzero_security import ZeroLeakEngine
23
-
24
-
25
- WRITE_TOOL_NAMES = {
26
- "write", "edit", "multiedit", "write_file", "edit_file",
27
- "replace_file_content", "multi_replace_file_content",
28
- }
29
- SHELL_TOOL_NAMES = {"bash", "run_command", "terminal", "shell"}
30
- READ_TOOL_NAMES = {"read", "read_file", "view_file", "view_file_outline"}
31
-
32
- SAFE_SECRET_TEMPLATES = {
33
- ".env.example",
34
- ".env.template",
35
- ".env.sample",
36
- ".env.schema",
37
- }
38
-
39
- EXACT_SENSITIVE_FILES = {
40
- ".env",
41
- ".env.local",
42
- ".env.production",
43
- ".env.staging",
44
- ".env.development",
45
- "id_rsa",
46
- "id_ed25519",
47
- ".npmrc",
48
- ".pypirc",
49
- "credentials.json",
50
- "secrets.json",
51
- }
52
-
53
- SENSITIVE_EXTENSIONS = {".pem", ".key", ".p12"}
54
-
55
- HOOK_TARGET_FILES = {
56
- "claude": os.path.join(".claude", "settings.local.json"),
57
- "cursor": os.path.join(".cursor", "hooks.json"),
58
- "gemini": os.path.join(".gemini", "settings.json"),
59
- }
60
-
61
-
62
- def _extract_write_blobs(tool_input: Dict[str, Any]) -> List[str]:
63
- blobs: List[str] = []
64
- for key in ("content", "Content", "text", "Text", "new_string", "Replacement", "CodeContent"):
65
- val = tool_input.get(key)
66
- if isinstance(val, str) and val:
67
- blobs.append(val)
68
- for list_key in ("edits", "ReplacementChunks"):
69
- items = tool_input.get(list_key)
70
- if isinstance(items, list):
71
- for item in items:
72
- if isinstance(item, dict):
73
- for k in ("new_string", "ReplacementContent", "content"):
74
- v = item.get(k)
75
- if isinstance(v, str) and v:
76
- blobs.append(v)
77
- return blobs
78
-
79
-
80
- def _is_sensitive_file_read(file_path: str) -> bool:
81
- if not file_path:
82
- return False
83
- base_name = os.path.basename(file_path.replace("\\", "/")).lower()
84
- if not base_name:
85
- return False
86
- if base_name in SAFE_SECRET_TEMPLATES or any(base_name.endswith(tmpl) for tmpl in SAFE_SECRET_TEMPLATES):
87
- return False
88
- if base_name in EXACT_SENSITIVE_FILES:
89
- return True
90
- if any(base_name.endswith(ext) for ext in SENSITIVE_EXTENSIONS):
91
- return True
92
- return False
93
-
94
-
95
- def _is_shell_exfiltration(cmd: str) -> bool:
96
- if not cmd:
97
- return False
98
- cmd_lower = cmd.lower()
99
- if re.search(
100
- r"\b(env|printenv|set)\b[^\n|;&]*\|[^\n|;&]*\b(curl|wget|invoke-webrequest|iwr|nc|ncat|ssh|scp)(\.exe)?\b",
101
- cmd_lower,
102
- ):
103
- return True
104
-
105
- has_net_tool = bool(re.search(
106
- r"\b(curl|wget|invoke-webrequest|iwr|nc|ncat|ssh|scp)(\.exe)?\b",
107
- cmd_lower,
108
- ))
109
- if not has_net_tool:
110
- return False
111
-
112
- has_secret_var = bool(re.search(
113
- r"(\$|%)(api_key|secret|token|aws_secret|password)",
114
- cmd_lower,
115
- ))
116
- if has_secret_var:
117
- return True
118
-
119
- if re.search(r"(?<![\w\.-])\.env(?!\.(example|template|sample|schema))\b", cmd_lower):
120
- return True
121
- if re.search(r"\b(id_rsa|id_ed25519)\b", cmd_lower):
122
- return True
123
- if re.search(r"(?<![\w\.-])(\.npmrc|\.pypirc)\b", cmd_lower):
124
- return True
125
-
126
- return False
127
-
128
-
129
- def _matches_layer_pattern(file_rel: str, patterns: List[str]) -> bool:
130
- file_rel_norm = file_rel.replace("\\", "/")
131
- base_name = os.path.basename(file_rel_norm)
132
- for p in patterns:
133
- p_norm = p.replace("\\", "/")
134
- p_clean = p_norm.rstrip("/*")
135
- if p_norm.endswith("/*") or p_norm.endswith("/**"):
136
- if file_rel_norm.startswith(p_clean + "/") or file_rel_norm == p_clean:
137
- return True
138
- elif file_rel_norm == p_clean or base_name == p_clean:
139
- return True
140
- elif fnmatch.fnmatch(file_rel_norm, p_norm) or fnmatch.fnmatch(base_name, p_norm):
141
- return True
142
- return False
143
-
144
-
145
- def _find_file_layer(file_path: str, layers: Dict[str, List[str]], workspace_dir: str) -> Optional[str]:
146
- ws_abs = os.path.abspath(workspace_dir)
147
- if os.path.isabs(file_path):
148
- try:
149
- rel_p = os.path.relpath(file_path, ws_abs).replace("\\", "/")
150
- except ValueError:
151
- rel_p = file_path.replace("\\", "/")
152
- else:
153
- full_p = os.path.abspath(os.path.join(ws_abs, file_path))
154
- try:
155
- rel_p = os.path.relpath(full_p, ws_abs).replace("\\", "/")
156
- except ValueError:
157
- rel_p = file_path.replace("\\", "/")
158
-
159
- file_norm = file_path.replace("\\", "/")
160
-
161
- for layer_name, patterns in layers.items():
162
- if _matches_layer_pattern(rel_p, patterns) or _matches_layer_pattern(file_norm, patterns):
163
- return layer_name
164
- return None
165
-
166
-
167
- def _extract_imported_modules(blob: str, filename: str) -> Set[str]:
168
- extracted: Set[str] = set()
169
- if filename.endswith(".py") or not ("." in os.path.basename(filename)):
170
- try:
171
- tree = ast.parse(blob, filename=filename)
172
- for node in ast.walk(tree):
173
- if isinstance(node, ast.Import):
174
- for n in node.names:
175
- extracted.add(n.name)
176
- elif isinstance(node, ast.ImportFrom):
177
- if node.module:
178
- extracted.add(node.module)
179
- return extracted
180
- except Exception:
181
- pass
182
-
183
- for match in re.finditer(r"^\s*from\s+([a-zA-Z0-9_\.]+)\s+import", blob, re.MULTILINE):
184
- extracted.add(match.group(1))
185
- for match in re.finditer(r"^\s*import\s+([a-zA-Z0-9_.,\s]+)", blob, re.MULTILINE):
186
- for part in match.group(1).split(","):
187
- mod_candidate = part.strip().split()[0] if part.strip() else ""
188
- if mod_candidate:
189
- extracted.add(mod_candidate)
190
- return extracted
191
-
192
-
193
- def _resolve_module_layer(mod: str, layers: Dict[str, List[str]]) -> Optional[str]:
194
- if mod in layers:
195
- return mod
196
- root_mod = mod.split(".")[0]
197
- if root_mod in layers:
198
- return root_mod
199
-
200
- candidates = [mod, f"{mod}.py", root_mod, f"{root_mod}.py", mod.replace(".", "/")]
201
- for layer_name, patterns in layers.items():
202
- for cand in candidates:
203
- if _matches_layer_pattern(cand, patterns):
204
- return layer_name
205
- return None
206
-
207
-
208
- def _check_architecture_rules(
209
- file_path: str,
210
- blobs: List[str],
211
- workspace_dir: str,
212
- ) -> Optional[Dict[str, Any]]:
213
- rules_path = os.path.join(os.path.abspath(workspace_dir), "tzero.rules.json")
214
- if not os.path.isfile(rules_path):
215
- return None
216
-
217
- try:
218
- with open(rules_path, "r", encoding="utf-8") as f:
219
- rules_data = json.load(f)
220
- except Exception:
221
- return None
222
-
223
- if not isinstance(rules_data, dict):
224
- return None
225
-
226
- layers: Dict[str, List[str]] = rules_data.get("layers", {})
227
- forbidden_imports: List[Dict[str, Any]] = rules_data.get("forbidden_imports", [])
228
- if not layers or not forbidden_imports:
229
- return None
230
-
231
- src_layer = _find_file_layer(file_path, layers, workspace_dir)
232
- if src_layer is None:
233
- return None
234
-
235
- applicable_rules = [r for r in forbidden_imports if r.get("from_layer") == src_layer]
236
- if not applicable_rules:
237
- return None
238
-
239
- extracted_modules: Set[str] = set()
240
- for blob in blobs:
241
- extracted_modules.update(_extract_imported_modules(blob, file_path))
242
-
243
- if not extracted_modules:
244
- return None
245
-
246
- for mod in extracted_modules:
247
- target_layer = _resolve_module_layer(mod, layers)
248
- root_mod = mod.split(".")[0]
249
-
250
- for rule in applicable_rules:
251
- cannot_import = rule.get("cannot_import", [])
252
- rule_reason = rule.get("reason", "Decoupling architectural policy violated")
253
-
254
- is_forbidden = False
255
- violating_target = target_layer
256
-
257
- if target_layer and target_layer in cannot_import:
258
- is_forbidden = True
259
- else:
260
- for forbidden_target in cannot_import:
261
- clean_target = forbidden_target.replace("/", ".").rstrip("/*")
262
- if (
263
- mod == clean_target
264
- or root_mod == clean_target
265
- or mod.startswith(clean_target + ".")
266
- or clean_target in mod.split(".")
267
- or fnmatch.fnmatch(mod, forbidden_target)
268
- ):
269
- is_forbidden = True
270
- violating_target = forbidden_target
271
- break
272
-
273
- if is_forbidden:
274
- return {
275
- "decision": "block",
276
- "hookSpecificOutput": {
277
- "hookEventName": "PreToolUse",
278
- "permissionDecision": "deny",
279
- },
280
- "reason": (
281
- f"Blocked by T-Zero Architecture Layer Guard: layer '{src_layer}' is forbidden from importing "
282
- f"'{mod}' (target layer: '{violating_target}'). Rule: {rule_reason}"
283
- ),
284
- "findings": 1,
285
- "exit_code": 2,
286
- }
287
-
288
- return None
289
-
290
-
291
- def evaluate_pre_tool_use(
292
- payload: Dict[str, Any],
293
- workspace_dir: str = ".",
294
- ) -> Dict[str, Any]:
295
- """Evaluates PreToolUse payload for Zero-Leak credential and architecture violations."""
296
- tool_name = str(payload.get("tool_name") or payload.get("tool") or "").strip().lower()
297
- tool_input = payload.get("tool_input") or payload.get("input") or {}
298
- if not isinstance(tool_input, dict):
299
- tool_input = {}
300
-
301
- file_path = str(
302
- tool_input.get("file_path")
303
- or tool_input.get("filepath")
304
- or tool_input.get("path")
305
- or tool_input.get("Path")
306
- or tool_input.get("AbsolutePath")
307
- or tool_input.get("TargetFile")
308
- or "snippet.txt"
309
- )
310
-
311
- if tool_name in READ_TOOL_NAMES:
312
- if _is_sensitive_file_read(file_path):
313
- base_name = os.path.basename(file_path.replace("\\", "/"))
314
- return {
315
- "decision": "block",
316
- "hookSpecificOutput": {
317
- "hookEventName": "PreToolUse",
318
- "permissionDecision": "deny",
319
- },
320
- "reason": (
321
- f"Blocked by T-Zero Zero-Leak Hook: sensitive secret file read denied "
322
- f"for {base_name}."
323
- ),
324
- "findings": 1,
325
- "exit_code": 2,
326
- }
327
-
328
- elif tool_name in SHELL_TOOL_NAMES:
329
- cmd = str(tool_input.get("command") or tool_input.get("CommandLine") or "")
330
- if cmd:
331
- findings = ZeroLeakEngine.scan_text(cmd)
332
- if findings:
333
- return {
334
- "decision": "block",
335
- "hookSpecificOutput": {
336
- "hookEventName": "PreToolUse",
337
- "permissionDecision": "deny",
338
- },
339
- "reason": f"Blocked by T-Zero Zero-Leak Hook: hardcoded secret in shell command ({len(findings)} finding(s)).",
340
- "findings": len(findings),
341
- "exit_code": 2,
342
- }
343
- if _is_shell_exfiltration(cmd):
344
- return {
345
- "decision": "block",
346
- "hookSpecificOutput": {
347
- "hookEventName": "PreToolUse",
348
- "permissionDecision": "deny",
349
- },
350
- "reason": (
351
- "Blocked by T-Zero Zero-Leak Hook: potential secret exfiltration via shell network tool."
352
- ),
353
- "findings": 1,
354
- "exit_code": 2,
355
- }
356
-
357
- elif tool_name in WRITE_TOOL_NAMES:
358
- blobs = _extract_write_blobs(tool_input)
359
- all_findings: List[Any] = []
360
- for blob in blobs:
361
- all_findings.extend(ZeroLeakEngine.scan_text(blob))
362
- if all_findings:
363
- patterns = sorted({
364
- getattr(f, "description", None) or getattr(f, "rule_id", "Secret")
365
- for f in all_findings
366
- })
367
- return {
368
- "decision": "block",
369
- "hookSpecificOutput": {
370
- "hookEventName": "PreToolUse",
371
- "permissionDecision": "deny",
372
- },
373
- "reason": (
374
- f"Blocked by T-Zero Zero-Leak Hook: {len(all_findings)} secret finding(s) "
375
- f"in {os.path.basename(file_path)} ({', '.join(patterns[:3])})."
376
- ),
377
- "findings": len(all_findings),
378
- "exit_code": 2,
379
- }
380
-
381
- arch_block = _check_architecture_rules(file_path, blobs, workspace_dir)
382
- if arch_block is not None:
383
- return arch_block
384
-
385
- return {"decision": "allow", "reason": "Clean PreToolUse check", "findings": 0, "exit_code": 0}
386
-
387
-
388
- def evaluate_post_tool_use(
389
- payload: Dict[str, Any],
390
- workspace_dir: str = ".",
391
- max_chars: int = 16000,
392
- ) -> Dict[str, Any]:
393
- """Auto-prunes oversized PostToolUse file read responses using T-Zero AST reduction."""
394
- del workspace_dir
395
- tool_name = str(payload.get("tool_name") or payload.get("tool") or "").strip().lower()
396
- tool_input = payload.get("tool_input") or payload.get("input") or {}
397
- if not isinstance(tool_input, dict):
398
- tool_input = {}
399
-
400
- raw_resp = payload.get("tool_response") or payload.get("output") or ""
401
- if isinstance(raw_resp, dict):
402
- raw_text = str(raw_resp.get("content") or raw_resp.get("text") or "")
403
- elif isinstance(raw_resp, list):
404
- raw_text = "".join(
405
- str(item.get("text") or item.get("content") or "") if isinstance(item, dict) else str(item)
406
- for item in raw_resp
407
- )
408
- else:
409
- raw_text = str(raw_resp or "")
410
-
411
- file_path = str(
412
- tool_input.get("file_path")
413
- or tool_input.get("filepath")
414
- or tool_input.get("path")
415
- or tool_input.get("Path")
416
- or tool_input.get("AbsolutePath")
417
- or tool_input.get("TargetFile")
418
- or "module.py"
419
- )
420
-
421
- if tool_name in READ_TOOL_NAMES and len(raw_text) > max_chars:
422
- reduced = PolyglotTokenReducer.reduce_code(raw_text, filename=file_path, mode="ultra")
423
- leaks = ZeroLeakEngine.scan_text(reduced)
424
- if leaks:
425
- reduced = ZeroLeakEngine.sanitize_text(reduced)
426
- raw_tok = count_bpe_tokens(raw_text)
427
- pruned_tok = count_bpe_tokens(reduced)
428
- sav_pct = round(max(0.0, (1.0 - pruned_tok / max(1, raw_tok)) * 100.0), 1)
429
- note = f" [Redacted {len(leaks)} secret(s)]" if leaks else ""
430
- return {
431
- "decision": "prune",
432
- "additionalContext": (
433
- f"// [T-Zero Auto-Pruned Hook Output{note}: {os.path.basename(file_path)} | "
434
- f"~{pruned_tok:,} vs {raw_tok:,} tokens (-{sav_pct}%)]\n{reduced}"
435
- ),
436
- "raw_tokens": raw_tok,
437
- "pruned_tokens": pruned_tok,
438
- "savings_pct": sav_pct,
439
- "exit_code": 0,
440
- }
441
-
442
- return {"decision": "allow", "reason": "No post-hook pruning needed", "exit_code": 0}
443
-
444
-
445
- def build_claude_cursor_hook_config() -> Dict[str, Any]:
446
- """Generates declarative PreToolUse/PostToolUse configuration snippet for AI coding tools."""
447
- return {
448
- "hooks": {
449
- "PreToolUse": [
450
- {
451
- "matcher": "Write|Edit|MultiEdit|Bash|Read",
452
- "hooks": [{"type": "command", "command": "tzero hook --event PreToolUse"}],
453
- }
454
- ],
455
- "PostToolUse": [
456
- {
457
- "matcher": "Read",
458
- "hooks": [{"type": "command", "command": "tzero hook --event PostToolUse"}],
459
- }
460
- ],
461
- }
462
- }
463
-
464
-
465
- def install_hooks(workspace_dir: str = ".", client: str = "all") -> Dict[str, Any]:
466
- """Installs PreToolUse/PostToolUse hooks idempotently into Claude, Cursor, or Gemini settings."""
467
- client_norm = str(client or "").strip().lower()
468
- if client_norm == "all":
469
- targets = list(HOOK_TARGET_FILES.values())
470
- elif client_norm in HOOK_TARGET_FILES:
471
- targets = [HOOK_TARGET_FILES[client_norm]]
472
- else:
473
- raise ValueError(
474
- f"Unknown client '{client}'. Expected one of: all, claude, cursor, gemini."
475
- )
476
-
477
- installed: List[str] = []
478
- tzero_cfg = build_claude_cursor_hook_config().get("hooks", {})
479
-
480
- for rel_target in targets:
481
- target_path = os.path.join(workspace_dir, rel_target)
482
- target_dir = os.path.dirname(target_path)
483
- if target_dir:
484
- os.makedirs(target_dir, exist_ok=True)
485
-
486
- data: Dict[str, Any] = {}
487
- if os.path.isfile(target_path):
488
- try:
489
- with open(target_path, "r", encoding="utf-8") as f:
490
- loaded = json.load(f)
491
- if isinstance(loaded, dict):
492
- data = loaded
493
- except Exception:
494
- data = {}
495
-
496
- if "hooks" not in data or not isinstance(data["hooks"], dict):
497
- data["hooks"] = {}
498
-
499
- for event_name, tz_entries in tzero_cfg.items():
500
- existing_event_hooks = data["hooks"].get(event_name)
501
- if not isinstance(existing_event_hooks, list):
502
- existing_event_hooks = []
503
- data["hooks"][event_name] = existing_event_hooks
504
-
505
- for tz_entry in tz_entries:
506
- already_present = any(
507
- isinstance(ex, dict)
508
- and any(
509
- isinstance(h, dict) and "tzero hook" in str(h.get("command", ""))
510
- for h in ex.get("hooks", [])
511
- )
512
- for ex in existing_event_hooks
513
- )
514
- if not already_present:
515
- existing_event_hooks.append(tz_entry)
516
-
517
- tmp_path = target_path + ".tmp"
518
- with open(tmp_path, "w", encoding="utf-8") as f:
519
- json.dump(data, f, indent=2, ensure_ascii=False)
520
- f.write("\n")
521
- os.replace(tmp_path, target_path)
522
- installed.append(os.path.normpath(target_path).replace("\\", "/"))
523
-
524
- return {
525
- "installed": installed,
526
- "client": client,
527
- "count": len(installed),
528
- }
529
-
530
-
531
- def run_hook_cli(
532
- event: str = "PreToolUse",
533
- payload_json: Optional[str] = None,
534
- workspace_dir: str = ".",
535
- max_chars: int = 16000,
536
- install_client: Optional[str] = None,
537
- ) -> int:
538
- """CLI entrypoint parsing hook JSON payload and emitting decision JSON."""
539
- if install_client is not None:
540
- result = install_hooks(workspace_dir=workspace_dir, client=install_client)
541
- print(json.dumps(result, indent=2))
542
- return 0
543
-
544
- raw_in = payload_json
545
- if raw_in is None:
546
- raw_in = sys.stdin.read() if not sys.stdin.isatty() else "{}"
547
- try:
548
- payload = json.loads(raw_in or "{}")
549
- if not isinstance(payload, dict):
550
- payload = {}
551
- except Exception:
552
- payload = {}
553
-
554
- ev = (event or str(payload.get("hook_event_name") or "PreToolUse")).strip().lower()
555
- if ev in ("post", "posttooluse", "post_tool_use"):
556
- verdict = evaluate_post_tool_use(payload, workspace_dir=workspace_dir, max_chars=max_chars)
557
- else:
558
- verdict = evaluate_pre_tool_use(payload, workspace_dir=workspace_dir)
559
-
560
- print(json.dumps(verdict, indent=2))
561
- return int(verdict.get("exit_code", 0))
562
-
563
-
564
- if __name__ == "__main__":
565
- sys.exit(run_hook_cli())
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero 2026 Lifecycle Hook Runner (PreToolUse / PostToolUse).
3
+
4
+ Supports Claude Code, Gemini CLI, and Cursor native hook JSON protocols:
5
+ - PreToolUse: Blocks writes/edits/commands containing leaked credentials or layer violations (exit code 2).
6
+ - PostToolUse: Auto-prunes oversized file reads into compact AST skeletons cleanly.
7
+
8
+ 100% Free, Local, Offline, Zero-Leak Certified.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ast
14
+ import fnmatch
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ from typing import Any, Dict, List, Optional, Set
20
+
21
+ from tzero.tzero_polyglot import PolyglotTokenReducer, count_bpe_tokens
22
+ from tzero.tzero_security import ZeroLeakEngine
23
+
24
+
25
+ WRITE_TOOL_NAMES = {
26
+ "write", "edit", "multiedit", "write_file", "edit_file",
27
+ "replace_file_content", "multi_replace_file_content",
28
+ }
29
+ SHELL_TOOL_NAMES = {"bash", "run_command", "terminal", "shell"}
30
+ READ_TOOL_NAMES = {"read", "read_file", "view_file", "view_file_outline"}
31
+
32
+ SAFE_SECRET_TEMPLATES = {
33
+ ".env.example",
34
+ ".env.template",
35
+ ".env.sample",
36
+ ".env.schema",
37
+ }
38
+
39
+ EXACT_SENSITIVE_FILES = {
40
+ ".env",
41
+ ".env.local",
42
+ ".env.production",
43
+ ".env.staging",
44
+ ".env.development",
45
+ "id_rsa",
46
+ "id_ed25519",
47
+ ".npmrc",
48
+ ".pypirc",
49
+ "credentials.json",
50
+ "secrets.json",
51
+ }
52
+
53
+ SENSITIVE_EXTENSIONS = {".pem", ".key", ".p12"}
54
+
55
+ HOOK_TARGET_FILES = {
56
+ "claude": os.path.join(".claude", "settings.local.json"),
57
+ "cursor": os.path.join(".cursor", "hooks.json"),
58
+ "gemini": os.path.join(".gemini", "settings.json"),
59
+ }
60
+
61
+
62
+ def _extract_write_blobs(tool_input: Dict[str, Any]) -> List[str]:
63
+ blobs: List[str] = []
64
+ for key in ("content", "Content", "text", "Text", "new_string", "Replacement", "CodeContent"):
65
+ val = tool_input.get(key)
66
+ if isinstance(val, str) and val:
67
+ blobs.append(val)
68
+ for list_key in ("edits", "ReplacementChunks"):
69
+ items = tool_input.get(list_key)
70
+ if isinstance(items, list):
71
+ for item in items:
72
+ if isinstance(item, dict):
73
+ for k in ("new_string", "ReplacementContent", "content"):
74
+ v = item.get(k)
75
+ if isinstance(v, str) and v:
76
+ blobs.append(v)
77
+ return blobs
78
+
79
+
80
+ def _is_sensitive_file_read(file_path: str) -> bool:
81
+ if not file_path:
82
+ return False
83
+ base_name = os.path.basename(file_path.replace("\\", "/")).lower()
84
+ if not base_name:
85
+ return False
86
+ if base_name in SAFE_SECRET_TEMPLATES or any(base_name.endswith(tmpl) for tmpl in SAFE_SECRET_TEMPLATES):
87
+ return False
88
+ if base_name in EXACT_SENSITIVE_FILES:
89
+ return True
90
+ if any(base_name.endswith(ext) for ext in SENSITIVE_EXTENSIONS):
91
+ return True
92
+ return False
93
+
94
+
95
+ def _is_shell_exfiltration(cmd: str) -> bool:
96
+ if not cmd:
97
+ return False
98
+ cmd_lower = cmd.lower()
99
+ if re.search(
100
+ r"\b(env|printenv|set)\b[^\n|;&]*\|[^\n|;&]*\b(curl|wget|invoke-webrequest|iwr|nc|ncat|ssh|scp)(\.exe)?\b",
101
+ cmd_lower,
102
+ ):
103
+ return True
104
+
105
+ has_net_tool = bool(re.search(
106
+ r"\b(curl|wget|invoke-webrequest|iwr|nc|ncat|ssh|scp)(\.exe)?\b",
107
+ cmd_lower,
108
+ ))
109
+ if not has_net_tool:
110
+ return False
111
+
112
+ has_secret_var = bool(re.search(
113
+ r"(\$|%)(api_key|secret|token|aws_secret|password)",
114
+ cmd_lower,
115
+ ))
116
+ if has_secret_var:
117
+ return True
118
+
119
+ if re.search(r"(?<![\w\.-])\.env(?!\.(example|template|sample|schema))\b", cmd_lower):
120
+ return True
121
+ if re.search(r"\b(id_rsa|id_ed25519)\b", cmd_lower):
122
+ return True
123
+ if re.search(r"(?<![\w\.-])(\.npmrc|\.pypirc)\b", cmd_lower):
124
+ return True
125
+
126
+ return False
127
+
128
+
129
+ def _matches_layer_pattern(file_rel: str, patterns: List[str]) -> bool:
130
+ file_rel_norm = file_rel.replace("\\", "/")
131
+ base_name = os.path.basename(file_rel_norm)
132
+ for p in patterns:
133
+ p_norm = p.replace("\\", "/")
134
+ p_clean = p_norm.rstrip("/*")
135
+ if p_norm.endswith("/*") or p_norm.endswith("/**"):
136
+ if file_rel_norm.startswith(p_clean + "/") or file_rel_norm == p_clean:
137
+ return True
138
+ elif file_rel_norm == p_clean or base_name == p_clean:
139
+ return True
140
+ elif fnmatch.fnmatch(file_rel_norm, p_norm) or fnmatch.fnmatch(base_name, p_norm):
141
+ return True
142
+ return False
143
+
144
+
145
+ def _find_file_layer(file_path: str, layers: Dict[str, List[str]], workspace_dir: str) -> Optional[str]:
146
+ ws_abs = os.path.abspath(workspace_dir)
147
+ if os.path.isabs(file_path):
148
+ try:
149
+ rel_p = os.path.relpath(file_path, ws_abs).replace("\\", "/")
150
+ except ValueError:
151
+ rel_p = file_path.replace("\\", "/")
152
+ else:
153
+ full_p = os.path.abspath(os.path.join(ws_abs, file_path))
154
+ try:
155
+ rel_p = os.path.relpath(full_p, ws_abs).replace("\\", "/")
156
+ except ValueError:
157
+ rel_p = file_path.replace("\\", "/")
158
+
159
+ file_norm = file_path.replace("\\", "/")
160
+
161
+ for layer_name, patterns in layers.items():
162
+ if _matches_layer_pattern(rel_p, patterns) or _matches_layer_pattern(file_norm, patterns):
163
+ return layer_name
164
+ return None
165
+
166
+
167
+ def _extract_imported_modules(blob: str, filename: str) -> Set[str]:
168
+ extracted: Set[str] = set()
169
+ if filename.endswith(".py") or not ("." in os.path.basename(filename)):
170
+ try:
171
+ tree = ast.parse(blob, filename=filename)
172
+ for node in ast.walk(tree):
173
+ if isinstance(node, ast.Import):
174
+ for n in node.names:
175
+ extracted.add(n.name)
176
+ elif isinstance(node, ast.ImportFrom):
177
+ if node.module:
178
+ extracted.add(node.module)
179
+ return extracted
180
+ except Exception:
181
+ pass
182
+
183
+ for match in re.finditer(r"^\s*from\s+([a-zA-Z0-9_\.]+)\s+import", blob, re.MULTILINE):
184
+ extracted.add(match.group(1))
185
+ for match in re.finditer(r"^\s*import\s+([a-zA-Z0-9_.,\s]+)", blob, re.MULTILINE):
186
+ for part in match.group(1).split(","):
187
+ mod_candidate = part.strip().split()[0] if part.strip() else ""
188
+ if mod_candidate:
189
+ extracted.add(mod_candidate)
190
+ return extracted
191
+
192
+
193
+ def _resolve_module_layer(mod: str, layers: Dict[str, List[str]]) -> Optional[str]:
194
+ if mod in layers:
195
+ return mod
196
+ root_mod = mod.split(".")[0]
197
+ if root_mod in layers:
198
+ return root_mod
199
+
200
+ candidates = [mod, f"{mod}.py", root_mod, f"{root_mod}.py", mod.replace(".", "/")]
201
+ for layer_name, patterns in layers.items():
202
+ for cand in candidates:
203
+ if _matches_layer_pattern(cand, patterns):
204
+ return layer_name
205
+ return None
206
+
207
+
208
+ def _check_architecture_rules(
209
+ file_path: str,
210
+ blobs: List[str],
211
+ workspace_dir: str,
212
+ ) -> Optional[Dict[str, Any]]:
213
+ rules_path = os.path.join(os.path.abspath(workspace_dir), "tzero.rules.json")
214
+ if not os.path.isfile(rules_path):
215
+ return None
216
+
217
+ try:
218
+ with open(rules_path, "r", encoding="utf-8") as f:
219
+ rules_data = json.load(f)
220
+ except Exception:
221
+ return None
222
+
223
+ if not isinstance(rules_data, dict):
224
+ return None
225
+
226
+ layers: Dict[str, List[str]] = rules_data.get("layers", {})
227
+ forbidden_imports: List[Dict[str, Any]] = rules_data.get("forbidden_imports", [])
228
+ if not layers or not forbidden_imports:
229
+ return None
230
+
231
+ src_layer = _find_file_layer(file_path, layers, workspace_dir)
232
+ if src_layer is None:
233
+ return None
234
+
235
+ applicable_rules = [r for r in forbidden_imports if r.get("from_layer") == src_layer]
236
+ if not applicable_rules:
237
+ return None
238
+
239
+ extracted_modules: Set[str] = set()
240
+ for blob in blobs:
241
+ extracted_modules.update(_extract_imported_modules(blob, file_path))
242
+
243
+ if not extracted_modules:
244
+ return None
245
+
246
+ for mod in extracted_modules:
247
+ target_layer = _resolve_module_layer(mod, layers)
248
+ root_mod = mod.split(".")[0]
249
+
250
+ for rule in applicable_rules:
251
+ cannot_import = rule.get("cannot_import", [])
252
+ rule_reason = rule.get("reason", "Decoupling architectural policy violated")
253
+
254
+ is_forbidden = False
255
+ violating_target = target_layer
256
+
257
+ if target_layer and target_layer in cannot_import:
258
+ is_forbidden = True
259
+ else:
260
+ for forbidden_target in cannot_import:
261
+ clean_target = forbidden_target.replace("/", ".").rstrip("/*")
262
+ if (
263
+ mod == clean_target
264
+ or root_mod == clean_target
265
+ or mod.startswith(clean_target + ".")
266
+ or clean_target in mod.split(".")
267
+ or fnmatch.fnmatch(mod, forbidden_target)
268
+ ):
269
+ is_forbidden = True
270
+ violating_target = forbidden_target
271
+ break
272
+
273
+ if is_forbidden:
274
+ return {
275
+ "decision": "block",
276
+ "hookSpecificOutput": {
277
+ "hookEventName": "PreToolUse",
278
+ "permissionDecision": "deny",
279
+ },
280
+ "reason": (
281
+ f"Blocked by T-Zero Architecture Layer Guard: layer '{src_layer}' is forbidden from importing "
282
+ f"'{mod}' (target layer: '{violating_target}'). Rule: {rule_reason}"
283
+ ),
284
+ "findings": 1,
285
+ "exit_code": 2,
286
+ }
287
+
288
+ return None
289
+
290
+
291
+ def evaluate_pre_tool_use(
292
+ payload: Dict[str, Any],
293
+ workspace_dir: str = ".",
294
+ ) -> Dict[str, Any]:
295
+ """Evaluates PreToolUse payload for Zero-Leak credential and architecture violations."""
296
+ tool_name = str(payload.get("tool_name") or payload.get("tool") or "").strip().lower()
297
+ tool_input = payload.get("tool_input") or payload.get("input") or {}
298
+ if not isinstance(tool_input, dict):
299
+ tool_input = {}
300
+
301
+ file_path = str(
302
+ tool_input.get("file_path")
303
+ or tool_input.get("filepath")
304
+ or tool_input.get("path")
305
+ or tool_input.get("Path")
306
+ or tool_input.get("AbsolutePath")
307
+ or tool_input.get("TargetFile")
308
+ or "snippet.txt"
309
+ )
310
+
311
+ if tool_name in READ_TOOL_NAMES:
312
+ if _is_sensitive_file_read(file_path):
313
+ base_name = os.path.basename(file_path.replace("\\", "/"))
314
+ return {
315
+ "decision": "block",
316
+ "hookSpecificOutput": {
317
+ "hookEventName": "PreToolUse",
318
+ "permissionDecision": "deny",
319
+ },
320
+ "reason": (
321
+ f"Blocked by T-Zero Zero-Leak Hook: sensitive secret file read denied "
322
+ f"for {base_name}."
323
+ ),
324
+ "findings": 1,
325
+ "exit_code": 2,
326
+ }
327
+
328
+ elif tool_name in SHELL_TOOL_NAMES:
329
+ cmd = str(tool_input.get("command") or tool_input.get("CommandLine") or "")
330
+ if cmd:
331
+ findings = ZeroLeakEngine.scan_text(cmd)
332
+ if findings:
333
+ return {
334
+ "decision": "block",
335
+ "hookSpecificOutput": {
336
+ "hookEventName": "PreToolUse",
337
+ "permissionDecision": "deny",
338
+ },
339
+ "reason": f"Blocked by T-Zero Zero-Leak Hook: hardcoded secret in shell command ({len(findings)} finding(s)).",
340
+ "findings": len(findings),
341
+ "exit_code": 2,
342
+ }
343
+ if _is_shell_exfiltration(cmd):
344
+ return {
345
+ "decision": "block",
346
+ "hookSpecificOutput": {
347
+ "hookEventName": "PreToolUse",
348
+ "permissionDecision": "deny",
349
+ },
350
+ "reason": (
351
+ "Blocked by T-Zero Zero-Leak Hook: potential secret exfiltration via shell network tool."
352
+ ),
353
+ "findings": 1,
354
+ "exit_code": 2,
355
+ }
356
+
357
+ elif tool_name in WRITE_TOOL_NAMES:
358
+ blobs = _extract_write_blobs(tool_input)
359
+ all_findings: List[Any] = []
360
+ for blob in blobs:
361
+ all_findings.extend(ZeroLeakEngine.scan_text(blob))
362
+ if all_findings:
363
+ patterns = sorted({
364
+ getattr(f, "description", None) or getattr(f, "rule_id", "Secret")
365
+ for f in all_findings
366
+ })
367
+ return {
368
+ "decision": "block",
369
+ "hookSpecificOutput": {
370
+ "hookEventName": "PreToolUse",
371
+ "permissionDecision": "deny",
372
+ },
373
+ "reason": (
374
+ f"Blocked by T-Zero Zero-Leak Hook: {len(all_findings)} secret finding(s) "
375
+ f"in {os.path.basename(file_path)} ({', '.join(patterns[:3])})."
376
+ ),
377
+ "findings": len(all_findings),
378
+ "exit_code": 2,
379
+ }
380
+
381
+ arch_block = _check_architecture_rules(file_path, blobs, workspace_dir)
382
+ if arch_block is not None:
383
+ return arch_block
384
+
385
+ return {"decision": "allow", "reason": "Clean PreToolUse check", "findings": 0, "exit_code": 0}
386
+
387
+
388
+ def evaluate_post_tool_use(
389
+ payload: Dict[str, Any],
390
+ workspace_dir: str = ".",
391
+ max_chars: int = 16000,
392
+ ) -> Dict[str, Any]:
393
+ """Auto-prunes oversized PostToolUse file read responses using T-Zero AST reduction."""
394
+ del workspace_dir
395
+ tool_name = str(payload.get("tool_name") or payload.get("tool") or "").strip().lower()
396
+ tool_input = payload.get("tool_input") or payload.get("input") or {}
397
+ if not isinstance(tool_input, dict):
398
+ tool_input = {}
399
+
400
+ raw_resp = payload.get("tool_response") or payload.get("output") or ""
401
+ if isinstance(raw_resp, dict):
402
+ raw_text = str(raw_resp.get("content") or raw_resp.get("text") or "")
403
+ elif isinstance(raw_resp, list):
404
+ raw_text = "".join(
405
+ str(item.get("text") or item.get("content") or "") if isinstance(item, dict) else str(item)
406
+ for item in raw_resp
407
+ )
408
+ else:
409
+ raw_text = str(raw_resp or "")
410
+
411
+ file_path = str(
412
+ tool_input.get("file_path")
413
+ or tool_input.get("filepath")
414
+ or tool_input.get("path")
415
+ or tool_input.get("Path")
416
+ or tool_input.get("AbsolutePath")
417
+ or tool_input.get("TargetFile")
418
+ or "module.py"
419
+ )
420
+
421
+ if tool_name in READ_TOOL_NAMES and len(raw_text) > max_chars:
422
+ reduced = PolyglotTokenReducer.reduce_code(raw_text, filename=file_path, mode="ultra")
423
+ leaks = ZeroLeakEngine.scan_text(reduced)
424
+ if leaks:
425
+ reduced = ZeroLeakEngine.sanitize_text(reduced)
426
+ raw_tok = count_bpe_tokens(raw_text)
427
+ pruned_tok = count_bpe_tokens(reduced)
428
+ sav_pct = round(max(0.0, (1.0 - pruned_tok / max(1, raw_tok)) * 100.0), 1)
429
+ note = f" [Redacted {len(leaks)} secret(s)]" if leaks else ""
430
+ return {
431
+ "decision": "prune",
432
+ "additionalContext": (
433
+ f"// [T-Zero Auto-Pruned Hook Output{note}: {os.path.basename(file_path)} | "
434
+ f"~{pruned_tok:,} vs {raw_tok:,} tokens (-{sav_pct}%)]\n{reduced}"
435
+ ),
436
+ "raw_tokens": raw_tok,
437
+ "pruned_tokens": pruned_tok,
438
+ "savings_pct": sav_pct,
439
+ "exit_code": 0,
440
+ }
441
+
442
+ return {"decision": "allow", "reason": "No post-hook pruning needed", "exit_code": 0}
443
+
444
+
445
+ def build_claude_cursor_hook_config() -> Dict[str, Any]:
446
+ """Generates declarative PreToolUse/PostToolUse configuration snippet for AI coding tools."""
447
+ return {
448
+ "hooks": {
449
+ "PreToolUse": [
450
+ {
451
+ "matcher": "Write|Edit|MultiEdit|Bash|Read",
452
+ "hooks": [{"type": "command", "command": "tzero hook --event PreToolUse"}],
453
+ }
454
+ ],
455
+ "PostToolUse": [
456
+ {
457
+ "matcher": "Read",
458
+ "hooks": [{"type": "command", "command": "tzero hook --event PostToolUse"}],
459
+ }
460
+ ],
461
+ }
462
+ }
463
+
464
+
465
+ def install_hooks(workspace_dir: str = ".", client: str = "all") -> Dict[str, Any]:
466
+ """Installs PreToolUse/PostToolUse hooks idempotently into Claude, Cursor, or Gemini settings."""
467
+ client_norm = str(client or "").strip().lower()
468
+ if client_norm == "all":
469
+ targets = list(HOOK_TARGET_FILES.values())
470
+ elif client_norm in HOOK_TARGET_FILES:
471
+ targets = [HOOK_TARGET_FILES[client_norm]]
472
+ else:
473
+ raise ValueError(
474
+ f"Unknown client '{client}'. Expected one of: all, claude, cursor, gemini."
475
+ )
476
+
477
+ installed: List[str] = []
478
+ tzero_cfg = build_claude_cursor_hook_config().get("hooks", {})
479
+
480
+ for rel_target in targets:
481
+ target_path = os.path.join(workspace_dir, rel_target)
482
+ target_dir = os.path.dirname(target_path)
483
+ if target_dir:
484
+ os.makedirs(target_dir, exist_ok=True)
485
+
486
+ data: Dict[str, Any] = {}
487
+ if os.path.isfile(target_path):
488
+ try:
489
+ with open(target_path, "r", encoding="utf-8") as f:
490
+ loaded = json.load(f)
491
+ if isinstance(loaded, dict):
492
+ data = loaded
493
+ except Exception:
494
+ data = {}
495
+
496
+ if "hooks" not in data or not isinstance(data["hooks"], dict):
497
+ data["hooks"] = {}
498
+
499
+ for event_name, tz_entries in tzero_cfg.items():
500
+ existing_event_hooks = data["hooks"].get(event_name)
501
+ if not isinstance(existing_event_hooks, list):
502
+ existing_event_hooks = []
503
+ data["hooks"][event_name] = existing_event_hooks
504
+
505
+ for tz_entry in tz_entries:
506
+ already_present = any(
507
+ isinstance(ex, dict)
508
+ and any(
509
+ isinstance(h, dict) and "tzero hook" in str(h.get("command", ""))
510
+ for h in ex.get("hooks", [])
511
+ )
512
+ for ex in existing_event_hooks
513
+ )
514
+ if not already_present:
515
+ existing_event_hooks.append(tz_entry)
516
+
517
+ tmp_path = target_path + ".tmp"
518
+ with open(tmp_path, "w", encoding="utf-8") as f:
519
+ json.dump(data, f, indent=2, ensure_ascii=False)
520
+ f.write("\n")
521
+ os.replace(tmp_path, target_path)
522
+ installed.append(os.path.normpath(target_path).replace("\\", "/"))
523
+
524
+ return {
525
+ "installed": installed,
526
+ "client": client,
527
+ "count": len(installed),
528
+ }
529
+
530
+
531
+ def run_hook_cli(
532
+ event: str = "PreToolUse",
533
+ payload_json: Optional[str] = None,
534
+ workspace_dir: str = ".",
535
+ max_chars: int = 16000,
536
+ install_client: Optional[str] = None,
537
+ ) -> int:
538
+ """CLI entrypoint parsing hook JSON payload and emitting decision JSON."""
539
+ if install_client is not None:
540
+ result = install_hooks(workspace_dir=workspace_dir, client=install_client)
541
+ print(json.dumps(result, indent=2))
542
+ return 0
543
+
544
+ raw_in = payload_json
545
+ if raw_in is None:
546
+ raw_in = sys.stdin.read() if not sys.stdin.isatty() else "{}"
547
+ try:
548
+ payload = json.loads(raw_in or "{}")
549
+ if not isinstance(payload, dict):
550
+ payload = {}
551
+ except Exception:
552
+ payload = {}
553
+
554
+ ev = (event or str(payload.get("hook_event_name") or "PreToolUse")).strip().lower()
555
+ if ev in ("post", "posttooluse", "post_tool_use"):
556
+ verdict = evaluate_post_tool_use(payload, workspace_dir=workspace_dir, max_chars=max_chars)
557
+ else:
558
+ verdict = evaluate_pre_tool_use(payload, workspace_dir=workspace_dir)
559
+
560
+ print(json.dumps(verdict, indent=2))
561
+ return int(verdict.get("exit_code", 0))
562
+
563
+
564
+ if __name__ == "__main__":
565
+ sys.exit(run_hook_cli())