tokensafe 4.4.9 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,408 @@
1
+ """
2
+ TokenSafe Batch Search Engine (v3.5.0).
3
+
4
+ Executes up to 20 heterogeneous code, path, and read-only git searches
5
+ concurrently in one MCP call, cutting round-trip LLM turns and avoiding
6
+ per-command remote safety evaluation overheads.
7
+
8
+ Supported query types:
9
+ - 'text': literal substring search.
10
+ - 'regex': regular expression pattern matching.
11
+ - 'glob': file name and path pattern matching.
12
+ - 'fuzzy': case-insensitive fuzzy path and symbol search.
13
+ - 'git': read-only git queries (status, diff, log, show, branch, rev-parse, ls-files).
14
+ """
15
+
16
+ import os
17
+ import re
18
+ import fnmatch
19
+ import shutil
20
+ import subprocess
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ from typing import Dict, Any, List, Optional, Tuple
23
+
24
+ from src.scoped_search import ScopedSearch, IGNORED_DIRS, IGNORED_EXTENSIONS, CODE_EXTENSIONS
25
+ from src.format_parsers.ansi import strip_ansi
26
+
27
+ MAX_BATCH_QUERIES = 20
28
+ MAX_OUTPUT_CHARS = 8000
29
+ DEFAULT_QUERY_RESULTS = 25
30
+
31
+ ALLOWED_GIT_COMMANDS = {
32
+ "status", "diff", "log", "show", "branch", "rev-parse",
33
+ "ls-files", "blame", "shortlog", "describe", "tag"
34
+ }
35
+
36
+ HARDENED_GIT_BASE_ARGS = [
37
+ "--no-optional-locks",
38
+ "-c", "core.fsmonitor=false",
39
+ "-c", "diff.external=",
40
+ "-c", "gpg.program=false",
41
+ "--no-pager"
42
+ ]
43
+
44
+
45
+ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
46
+ """Checks if git command is strictly read-only and returns tokens."""
47
+ tokens = [t for t in re.split(r"\s+", args_str.strip()) if t]
48
+ if not tokens:
49
+ return False, "Empty git command.", []
50
+ subcmd = tokens[0].lower()
51
+ if subcmd.startswith("git"):
52
+ tokens = tokens[1:]
53
+ if not tokens:
54
+ return False, "Empty git command.", []
55
+ subcmd = tokens[0].lower()
56
+
57
+ if subcmd not in ALLOWED_GIT_COMMANDS:
58
+ return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
59
+
60
+ # Block destructive or interactive flags
61
+ for tok in tokens:
62
+ if tok in ("--delete", "-d", "-D", "-m", "-M", "--hard", "--reset", "--force", "-f", "--interactive", "-i"):
63
+ return False, f"Destructive flag '{tok}' is disallowed in batch_search.", []
64
+
65
+ return True, "", tokens
66
+
67
+
68
+ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, Any]:
69
+ """Runs a read-only git query."""
70
+ is_safe, err_msg, tokens = _is_git_command_safe(pattern)
71
+ if not is_safe:
72
+ return {"error": err_msg, "matches": [], "count": 0}
73
+
74
+ git_bin = shutil.which("git")
75
+ if not git_bin:
76
+ return {"error": "git executable not found in PATH", "matches": [], "count": 0}
77
+
78
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
79
+ env = os.environ.copy()
80
+ env["GIT_TERMINAL_PROMPT"] = "0"
81
+ env["GIT_PAGER"] = "cat"
82
+
83
+ try:
84
+ proc = subprocess.run(
85
+ cmd,
86
+ cwd=cwd,
87
+ stdout=subprocess.PIPE,
88
+ stderr=subprocess.PIPE,
89
+ text=True,
90
+ timeout=timeout_sec,
91
+ env=env
92
+ )
93
+ if proc.returncode != 0:
94
+ err = proc.stderr.strip() or f"git exited with code {proc.returncode}"
95
+ return {"error": err, "matches": [], "count": 0}
96
+
97
+ raw_out = strip_ansi(proc.stdout or "").strip()
98
+ lines = [l for l in raw_out.splitlines() if l.strip()]
99
+ return {"matches": lines[:50], "count": len(lines), "raw": "\n".join(lines[:50])}
100
+ except subprocess.TimeoutExpired:
101
+ return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
102
+ except Exception as e:
103
+ return {"error": f"git execution error: {e}", "matches": [], "count": 0}
104
+
105
+
106
+ def _run_rg_query(
107
+ pattern: str,
108
+ cwd: str,
109
+ path_filter: Optional[str] = None,
110
+ is_regex: bool = False,
111
+ case_sensitive: bool = False,
112
+ file_type: Optional[str] = None,
113
+ glob_filter: Optional[str] = None,
114
+ max_results: int = 25
115
+ ) -> Optional[List[Dict[str, Any]]]:
116
+ """Attempts fast search via ripgrep if available."""
117
+ rg_bin = shutil.which("rg")
118
+ if not rg_bin:
119
+ return None
120
+
121
+ cmd = [rg_bin, "--no-heading", "--line-number", "--color=never", "--max-count", str(max_results)]
122
+ if not is_regex:
123
+ cmd.append("--fixed-strings")
124
+ if not case_sensitive:
125
+ cmd.append("--ignore-case")
126
+ else:
127
+ cmd.append("--case-sensitive")
128
+
129
+ if file_type:
130
+ cmd.extend(["--type", file_type])
131
+ if glob_filter:
132
+ cmd.extend(["--glob", glob_filter])
133
+
134
+ # Ignore default heavy folders
135
+ for d in ("node_modules", ".git", "dist", "build", ".venv", "__pycache__"):
136
+ cmd.extend(["--glob", f"!{d}/**"])
137
+
138
+ cmd.append(pattern)
139
+ target_path = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
140
+ cmd.append(target_path)
141
+
142
+ try:
143
+ proc = subprocess.run(
144
+ cmd,
145
+ cwd=cwd,
146
+ stdout=subprocess.PIPE,
147
+ stderr=subprocess.PIPE,
148
+ text=True,
149
+ timeout=5
150
+ )
151
+ matches = []
152
+ for line in proc.stdout.splitlines():
153
+ if not line.strip():
154
+ continue
155
+ parts = line.split(":", 2)
156
+ if len(parts) >= 3:
157
+ f_path = os.path.relpath(parts[0], cwd)
158
+ try:
159
+ l_num = int(parts[1])
160
+ except ValueError:
161
+ l_num = 0
162
+ snippet = parts[2].strip()
163
+ matches.append({"file": f_path, "line": l_num, "content": snippet})
164
+ if len(matches) >= max_results:
165
+ break
166
+ return matches
167
+ except Exception:
168
+ return None
169
+
170
+
171
+ def _run_python_text_search(
172
+ pattern: str,
173
+ cwd: str,
174
+ path_filter: Optional[str] = None,
175
+ is_regex: bool = False,
176
+ case_sensitive: bool = False,
177
+ scope: str = "code",
178
+ max_results: int = 25
179
+ ) -> List[Dict[str, Any]]:
180
+ """Pure Python search fallback."""
181
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
182
+ if not os.path.exists(search_root):
183
+ return []
184
+
185
+ regex = None
186
+ if is_regex:
187
+ flags = 0 if case_sensitive else re.IGNORECASE
188
+ try:
189
+ regex = re.compile(pattern, flags)
190
+ except re.error:
191
+ regex = None
192
+
193
+ matches = []
194
+ target_lower = pattern if case_sensitive else pattern.lower()
195
+
196
+ for root, dirs, files in os.walk(search_root):
197
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
198
+ for f in files:
199
+ ext = os.path.splitext(f)[1].lower()
200
+ if ext in IGNORED_EXTENSIONS:
201
+ continue
202
+ if scope == "code" and ext not in CODE_EXTENSIONS:
203
+ continue
204
+
205
+ full_path = os.path.join(root, f)
206
+ rel_p = os.path.relpath(full_path, cwd)
207
+
208
+ try:
209
+ with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
210
+ for line_idx, line in enumerate(fp):
211
+ hit = False
212
+ if regex:
213
+ hit = bool(regex.search(line))
214
+ elif case_sensitive:
215
+ hit = pattern in line
216
+ else:
217
+ hit = target_lower in line.lower()
218
+
219
+ if hit:
220
+ matches.append({
221
+ "file": rel_p,
222
+ "line": line_idx + 1,
223
+ "content": line.strip()[:180]
224
+ })
225
+ if len(matches) >= max_results:
226
+ return matches
227
+ except Exception:
228
+ continue
229
+
230
+ return matches
231
+
232
+
233
+ def _run_glob_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 50) -> List[str]:
234
+ """Finds matching files by glob pattern."""
235
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
236
+ if not os.path.exists(search_root):
237
+ return []
238
+
239
+ results = []
240
+ for root, dirs, files in os.walk(search_root):
241
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
242
+ for f in files:
243
+ rel_p = os.path.relpath(os.path.join(root, f), cwd)
244
+ if fnmatch.fnmatch(rel_p, pattern) or fnmatch.fnmatch(f, pattern):
245
+ results.append(rel_p)
246
+ if len(results) >= max_results:
247
+ return results
248
+ return results
249
+
250
+
251
+ def _run_fuzzy_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 30) -> List[str]:
252
+ """Case-insensitive fuzzy match across relative file paths."""
253
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
254
+ if not os.path.exists(search_root):
255
+ return []
256
+
257
+ pat_lower = pattern.lower().replace(" ", "")
258
+ results = []
259
+ for root, dirs, files in os.walk(search_root):
260
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
261
+ for f in files:
262
+ rel_p = os.path.relpath(os.path.join(root, f), cwd)
263
+ name_lower = rel_p.lower()
264
+ # Subsequence match
265
+ it = iter(name_lower)
266
+ if all(ch in it for ch in pat_lower):
267
+ results.append(rel_p)
268
+ if len(results) >= max_results:
269
+ return results
270
+ return results
271
+
272
+
273
+ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any]:
274
+ """Executes a single search query dict."""
275
+ pattern = str(query_dict.get("pattern") or query_dict.get("query") or "").strip()
276
+ q_type = str(query_dict.get("type") or "text").lower().strip()
277
+ path_filter = query_dict.get("path")
278
+ max_res = int(query_dict.get("max_results") or DEFAULT_QUERY_RESULTS)
279
+ case_sensitive = bool(query_dict.get("case_sensitive"))
280
+ output_mode = str(query_dict.get("output_mode") or "content").lower()
281
+ file_type = query_dict.get("file_type")
282
+ glob_filter = query_dict.get("glob")
283
+
284
+ if not pattern and q_type != "git":
285
+ return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
286
+
287
+ if q_type == "git":
288
+ res = _run_git_query(pattern, cwd)
289
+ return {"type": "git", "pattern": pattern, **res}
290
+
291
+ if q_type == "glob":
292
+ matched_paths = _run_glob_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
293
+ return {"type": "glob", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
294
+
295
+ if q_type == "fuzzy":
296
+ matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
297
+ return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
298
+
299
+ is_regex = (q_type == "regex")
300
+ # Try ripgrep first
301
+ rg_matches = _run_rg_query(
302
+ pattern=pattern,
303
+ cwd=cwd,
304
+ path_filter=path_filter,
305
+ is_regex=is_regex,
306
+ case_sensitive=case_sensitive,
307
+ file_type=file_type,
308
+ glob_filter=glob_filter,
309
+ max_results=max_res
310
+ )
311
+
312
+ matches = rg_matches if rg_matches is not None else _run_python_text_search(
313
+ pattern=pattern,
314
+ cwd=cwd,
315
+ path_filter=path_filter,
316
+ is_regex=is_regex,
317
+ case_sensitive=case_sensitive,
318
+ max_results=max_res
319
+ )
320
+
321
+ if output_mode == "files_with_matches":
322
+ unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
323
+ return {"type": q_type, "pattern": pattern, "matches": unique_files, "count": len(unique_files)}
324
+ elif output_mode == "count":
325
+ return {"type": q_type, "pattern": pattern, "count": len(matches)}
326
+
327
+ return {"type": q_type, "pattern": pattern, "matches": matches, "count": len(matches)}
328
+
329
+
330
+ def execute_batch_search(
331
+ queries: List[Dict[str, Any]],
332
+ cwd: Optional[str] = None
333
+ ) -> Dict[str, Any]:
334
+ """
335
+ Executes up to 20 mixed search queries concurrently and returns a consolidated report.
336
+ """
337
+ if not isinstance(queries, list) or not queries:
338
+ return {
339
+ "success": False,
340
+ "error": "Queries must be a non-empty array of query specifications.",
341
+ "results": [],
342
+ "summary_md": "Error: queries array is empty."
343
+ }
344
+
345
+ if len(queries) > MAX_BATCH_QUERIES:
346
+ return {
347
+ "success": False,
348
+ "error": f"Batch search exceeds maximum of {MAX_BATCH_QUERIES} queries (got {len(queries)}).",
349
+ "results": [],
350
+ "summary_md": "Error: query count exceeds maximum."
351
+ }
352
+
353
+ base_dir = os.path.abspath(cwd or os.getcwd())
354
+ results: List[Dict[str, Any]] = [{} for _ in queries]
355
+
356
+ # Concurrent execution across queries
357
+ with ThreadPoolExecutor(max_workers=min(len(queries), 8)) as executor:
358
+ future_to_idx = {
359
+ executor.submit(_execute_single_query, q, base_dir): i
360
+ for i, q in enumerate(queries)
361
+ }
362
+ for future in as_completed(future_to_idx):
363
+ idx = future_to_idx[future]
364
+ try:
365
+ results[idx] = future.result()
366
+ except Exception as e:
367
+ results[idx] = {"error": str(e), "matches": [], "count": 0}
368
+
369
+ # Format into markdown summary
370
+ md_lines: List[str] = [f"## TokenSafe Batch Search Report ({len(queries)} queries)"]
371
+ for i, res in enumerate(results):
372
+ q_type = res.get("type", "search")
373
+ pattern = res.get("pattern", "")
374
+ count = res.get("count", 0)
375
+ err = res.get("error")
376
+
377
+ if err:
378
+ md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — Error: {err}")
379
+ continue
380
+
381
+ md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — {count} match(es)")
382
+ matches = res.get("matches") or []
383
+
384
+ if q_type == "git":
385
+ raw_git = res.get("raw")
386
+ if raw_git:
387
+ md_lines.append("```text\n" + raw_git[:1200] + "\n```")
388
+ elif not matches:
389
+ md_lines.append("*(clean / no output)*")
390
+ elif isinstance(matches, list):
391
+ for m in matches[:15]:
392
+ if isinstance(m, dict):
393
+ f_name = m.get("file", "")
394
+ l_num = m.get("line", "")
395
+ content = m.get("content", "")
396
+ md_lines.append(f"- `{f_name}:{l_num}`: {content}")
397
+ elif isinstance(m, str):
398
+ md_lines.append(f"- `{m}`")
399
+ if len(matches) > 15:
400
+ md_lines.append(f"- *(+{len(matches) - 15} more matches)*")
401
+
402
+ summary_md = "\n".join(md_lines)
403
+ return {
404
+ "success": True,
405
+ "query_count": len(queries),
406
+ "results": results,
407
+ "summary_md": summary_md
408
+ }
package/src/cli.py CHANGED
@@ -106,6 +106,8 @@ def _print_help():
106
106
  print(" status One-screen health check: hooks, weekly savings, tier, sync")
107
107
  print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
108
108
  print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
109
+ print(" transcripts [--recent N] Analyze agent transcripts (Antigravity/Claude/Codex)")
110
+ print(" [--compare A B] A/B comparison of two session transcripts")
109
111
  print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
110
112
  print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
111
113
  print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
@@ -728,6 +730,55 @@ def main(argv: Optional[List[str]] = None):
728
730
  print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
729
731
  print(f" Workspace: {status.get('workspace')}\n")
730
732
 
733
+ elif command in ("transcripts", "transcript"):
734
+ from src.transcript_analyzer import (
735
+ discover_transcript_paths,
736
+ analyze_transcript,
737
+ compare_transcripts,
738
+ render_transcripts_report,
739
+ render_comparison_report
740
+ )
741
+ if "--compare" in args:
742
+ c_idx = args.index("--compare")
743
+ if len(args) < c_idx + 3:
744
+ print("Usage: tokensafe transcripts --compare <before.jsonl> <after.jsonl>")
745
+ sys.exit(1)
746
+ before_f = args[c_idx + 1]
747
+ after_f = args[c_idx + 2]
748
+ res = compare_transcripts(before_f, after_f)
749
+ print(render_comparison_report(res))
750
+ sys.exit(0)
751
+
752
+ agent_type = "auto"
753
+ explicit_path = None
754
+ limit = 10
755
+ for i, a in enumerate(args):
756
+ if a in ("--recent", "-n") and i + 1 < len(args):
757
+ try:
758
+ limit = int(args[i + 1])
759
+ except ValueError:
760
+ pass
761
+ elif a.startswith("--agent="):
762
+ agent_type = a.split("=", 1)[1]
763
+ elif a in ("--agent", "-a") and i + 1 < len(args):
764
+ agent_type = args[i + 1]
765
+ elif a.startswith("--path="):
766
+ explicit_path = a.split("=", 1)[1]
767
+ elif a in ("--path", "-p") and i + 1 < len(args):
768
+ explicit_path = args[i + 1]
769
+
770
+ found = discover_transcript_paths(agent=agent_type, explicit_path=explicit_path, limit=limit)
771
+ if not found:
772
+ print("No transcripts found. Specify path via --path <path_or_dir> or --agent <antigravity|claude|codex>.")
773
+ sys.exit(0)
774
+
775
+ analyzed = []
776
+ for ag_type, fp, _ in found:
777
+ analyzed.append(analyze_transcript(fp, agent_type=ag_type))
778
+
779
+ print(render_transcripts_report(analyzed))
780
+ sys.exit(0)
781
+
731
782
  elif command == "proxy":
732
783
  from src.proxy import run_proxy
733
784
  sub = args[1] if len(args) > 1 else ""