tokensafe 3.2.0 → 4.0.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.
- package/README.md +60 -28
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +234 -2
- package/src/command_sanitizer.py +2 -0
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +1 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +202 -0
package/src/fts_index.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe SQLite FTS5 Code Search Engine (v3.3.0).
|
|
3
|
+
|
|
4
|
+
High-performance, BM25-ranked full-text search across codebases using SQLite's
|
|
5
|
+
native FTS5 module with the trigram tokenizer.
|
|
6
|
+
- Zero external dependencies: uses Python's standard `sqlite3` library.
|
|
7
|
+
- Sub-millisecond substring & identifier matching (camelCase, snake_case, symbols).
|
|
8
|
+
- Built-in BM25 relevance ranking.
|
|
9
|
+
- Incremental indexing: checks file mtime & size to only re-index modified files.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sqlite3
|
|
14
|
+
import time
|
|
15
|
+
import hashlib
|
|
16
|
+
from typing import List, Dict, Any, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
from src.paths import resolve_data_dir
|
|
19
|
+
|
|
20
|
+
# Ignored directories and extensions reused for clean index
|
|
21
|
+
IGNORED_DIRS = {
|
|
22
|
+
".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
|
|
23
|
+
".next", ".turbo", ".idea", ".vscode", "coverage", ".pytest_cache",
|
|
24
|
+
".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info",
|
|
25
|
+
"Library", "Applications", "Downloads", ".cache", ".npm", ".bun", ".rustup", ".cargo"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
IGNORED_EXTS = {
|
|
29
|
+
".pyc", ".pyo", ".pyd", ".so", ".dll", ".dylib", ".exe", ".bin",
|
|
30
|
+
".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".svg",
|
|
31
|
+
".woff", ".woff2", ".ttf", ".eot", ".mp4", ".mp3", ".wav",
|
|
32
|
+
".zip", ".tar", ".gz", ".tgz", ".whl", ".jar", ".db", ".sqlite",
|
|
33
|
+
".sqlite3", ".wasm"
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
CODE_EXTS = {
|
|
37
|
+
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
|
|
38
|
+
".py", ".pyw", ".go", ".rs", ".java", ".cpp", ".cc", ".c", ".h", ".hpp",
|
|
39
|
+
".php", ".rb", ".vue", ".svelte", ".swift", ".kt", ".kts", ".cs",
|
|
40
|
+
".json", ".toml", ".yaml", ".yml", ".md", ".sql", ".sh", ".bash"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _resolve_fts_db_path(project_root: str) -> str:
|
|
45
|
+
"""Returns path to the SQLite FTS database for a project."""
|
|
46
|
+
# Check if project has a .tokensafe directory
|
|
47
|
+
proj_tokensafe = os.path.join(project_root, ".tokensafe")
|
|
48
|
+
if os.path.isdir(proj_tokensafe):
|
|
49
|
+
return os.path.join(proj_tokensafe, "fts.db")
|
|
50
|
+
|
|
51
|
+
# Otherwise store in ~/.tokensafe/cache/fts/<project_hash>.db
|
|
52
|
+
cache_dir = os.path.join(resolve_data_dir(), "cache", "fts")
|
|
53
|
+
os.makedirs(cache_dir, exist_ok=True)
|
|
54
|
+
p_hash = hashlib.sha256(os.path.abspath(project_root).encode("utf-8")).hexdigest()[:16]
|
|
55
|
+
return os.path.join(cache_dir, f"fts_{p_hash}.db")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class CodeFTSIndex:
|
|
59
|
+
"""SQLite FTS5 Full-Text Code Search Index with BM25 Ranking."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, project_root: str, db_path: Optional[str] = None):
|
|
62
|
+
self.project_root = os.path.abspath(project_root)
|
|
63
|
+
self.db_path = db_path or _resolve_fts_db_path(self.project_root)
|
|
64
|
+
self._init_db()
|
|
65
|
+
|
|
66
|
+
def _get_connection(self) -> sqlite3.Connection:
|
|
67
|
+
os.makedirs(os.path.dirname(self.db_path) or ".", exist_ok=True)
|
|
68
|
+
con = sqlite3.connect(self.db_path, timeout=10.0)
|
|
69
|
+
try:
|
|
70
|
+
con.execute("PRAGMA journal_mode = WAL;")
|
|
71
|
+
con.execute("PRAGMA synchronous = NORMAL;")
|
|
72
|
+
except Exception:
|
|
73
|
+
con.close()
|
|
74
|
+
raise
|
|
75
|
+
return con
|
|
76
|
+
|
|
77
|
+
def _init_db(self):
|
|
78
|
+
try:
|
|
79
|
+
con = self._get_connection()
|
|
80
|
+
try:
|
|
81
|
+
with con:
|
|
82
|
+
con.execute("""
|
|
83
|
+
CREATE TABLE IF NOT EXISTS file_meta (
|
|
84
|
+
rel_path TEXT PRIMARY KEY,
|
|
85
|
+
mtime REAL,
|
|
86
|
+
size INTEGER
|
|
87
|
+
);
|
|
88
|
+
""")
|
|
89
|
+
table_check = con.execute(
|
|
90
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name='code_lines';"
|
|
91
|
+
).fetchone()
|
|
92
|
+
if not table_check:
|
|
93
|
+
try:
|
|
94
|
+
con.execute("""
|
|
95
|
+
CREATE VIRTUAL TABLE code_lines USING fts5(
|
|
96
|
+
rel_path,
|
|
97
|
+
line_no UNINDEXED,
|
|
98
|
+
content,
|
|
99
|
+
tokenize = "trigram"
|
|
100
|
+
);
|
|
101
|
+
""")
|
|
102
|
+
except sqlite3.OperationalError:
|
|
103
|
+
con.execute("""
|
|
104
|
+
CREATE VIRTUAL TABLE code_lines USING fts5(
|
|
105
|
+
rel_path,
|
|
106
|
+
line_no UNINDEXED,
|
|
107
|
+
content,
|
|
108
|
+
tokenize = "unicode61"
|
|
109
|
+
);
|
|
110
|
+
""")
|
|
111
|
+
finally:
|
|
112
|
+
con.close()
|
|
113
|
+
except Exception:
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
def index_files(self, max_files: int = 5000, max_file_size_bytes: int = 512 * 1024) -> Dict[str, Any]:
|
|
117
|
+
"""
|
|
118
|
+
Incrementally scans the project directory and updates the FTS5 index.
|
|
119
|
+
Returns indexing statistics.
|
|
120
|
+
"""
|
|
121
|
+
t0 = time.time()
|
|
122
|
+
scanned_files = 0
|
|
123
|
+
updated_files = 0
|
|
124
|
+
indexed_lines = 0
|
|
125
|
+
|
|
126
|
+
con = self._get_connection()
|
|
127
|
+
try:
|
|
128
|
+
with con:
|
|
129
|
+
# Load existing metadata
|
|
130
|
+
cur = con.execute("SELECT rel_path, mtime, size FROM file_meta;")
|
|
131
|
+
known_meta = {row[0]: (row[1], row[2]) for row in cur.fetchall()}
|
|
132
|
+
found_paths = set()
|
|
133
|
+
|
|
134
|
+
files_to_index = []
|
|
135
|
+
|
|
136
|
+
for root, dirs, files in os.walk(self.project_root):
|
|
137
|
+
dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
|
|
138
|
+
for f in files:
|
|
139
|
+
ext = os.path.splitext(f)[1].lower()
|
|
140
|
+
if ext in IGNORED_EXTS or (ext not in CODE_EXTS and not f.startswith("Dockerfile")):
|
|
141
|
+
continue
|
|
142
|
+
|
|
143
|
+
full_path = os.path.join(root, f)
|
|
144
|
+
rel_path = os.path.relpath(full_path, self.project_root)
|
|
145
|
+
found_paths.add(rel_path)
|
|
146
|
+
scanned_files += 1
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
stat_res = os.stat(full_path)
|
|
150
|
+
f_mtime = stat_res.st_mtime
|
|
151
|
+
f_size = stat_res.st_size
|
|
152
|
+
except OSError:
|
|
153
|
+
continue
|
|
154
|
+
|
|
155
|
+
if f_size > max_file_size_bytes:
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
prev = known_meta.get(rel_path)
|
|
159
|
+
if prev and abs(prev[0] - f_mtime) < 0.001 and prev[1] == f_size:
|
|
160
|
+
continue # File unchanged
|
|
161
|
+
|
|
162
|
+
files_to_index.append((rel_path, full_path, f_mtime, f_size))
|
|
163
|
+
if scanned_files >= max_files:
|
|
164
|
+
break
|
|
165
|
+
if scanned_files >= max_files:
|
|
166
|
+
break
|
|
167
|
+
|
|
168
|
+
# Index modified/new files in batches
|
|
169
|
+
for rel_path, full_path, f_mtime, f_size in files_to_index:
|
|
170
|
+
try:
|
|
171
|
+
with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
|
|
172
|
+
lines = fp.splitlines() if hasattr(fp, "splitlines") else fp.read().splitlines()
|
|
173
|
+
except Exception:
|
|
174
|
+
continue
|
|
175
|
+
|
|
176
|
+
# Remove previous lines for this file
|
|
177
|
+
con.execute("DELETE FROM code_lines WHERE rel_path = ?;", (rel_path,))
|
|
178
|
+
|
|
179
|
+
# Insert lines with content (bounded to avoid huge minified/base64 lines)
|
|
180
|
+
line_batch = [
|
|
181
|
+
(rel_path, idx + 1, line[:2000])
|
|
182
|
+
for idx, line in enumerate(lines)
|
|
183
|
+
if line.strip() and len(line) <= 10000
|
|
184
|
+
]
|
|
185
|
+
if line_batch:
|
|
186
|
+
con.executemany(
|
|
187
|
+
"INSERT INTO code_lines (rel_path, line_no, content) VALUES (?, ?, ?);",
|
|
188
|
+
line_batch
|
|
189
|
+
)
|
|
190
|
+
indexed_lines += len(line_batch)
|
|
191
|
+
|
|
192
|
+
con.execute(
|
|
193
|
+
"INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?);",
|
|
194
|
+
(rel_path, f_mtime, f_size)
|
|
195
|
+
)
|
|
196
|
+
updated_files += 1
|
|
197
|
+
|
|
198
|
+
# Prune deleted files
|
|
199
|
+
deleted_paths = set(known_meta.keys()) - found_paths
|
|
200
|
+
if deleted_paths:
|
|
201
|
+
for del_path in deleted_paths:
|
|
202
|
+
con.execute("DELETE FROM code_lines WHERE rel_path = ?;", (del_path,))
|
|
203
|
+
con.execute("DELETE FROM file_meta WHERE rel_path = ?;", (del_path,))
|
|
204
|
+
|
|
205
|
+
con.commit()
|
|
206
|
+
finally:
|
|
207
|
+
con.close()
|
|
208
|
+
|
|
209
|
+
duration_ms = (time.time() - t0) * 1000
|
|
210
|
+
return {
|
|
211
|
+
"scanned_files": scanned_files,
|
|
212
|
+
"updated_files": updated_files,
|
|
213
|
+
"indexed_lines": indexed_lines,
|
|
214
|
+
"pruned_files": len(deleted_paths) if deleted_paths else 0,
|
|
215
|
+
"duration_ms": duration_ms
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
def search(
|
|
219
|
+
self,
|
|
220
|
+
query: str,
|
|
221
|
+
limit: int = 25,
|
|
222
|
+
path_filter: Optional[str] = None
|
|
223
|
+
) -> List[Dict[str, Any]]:
|
|
224
|
+
"""
|
|
225
|
+
Performs BM25-ranked full-text search.
|
|
226
|
+
Returns matching lines with relevance ranking.
|
|
227
|
+
"""
|
|
228
|
+
clean_q = query.strip()
|
|
229
|
+
if not clean_q:
|
|
230
|
+
return []
|
|
231
|
+
|
|
232
|
+
# Format FTS5 query
|
|
233
|
+
# If query has spaces, search as a phrase or AND expression
|
|
234
|
+
escaped_q = clean_q.replace('"', '""')
|
|
235
|
+
fts_query = f'"{escaped_q}"'
|
|
236
|
+
|
|
237
|
+
results = []
|
|
238
|
+
try:
|
|
239
|
+
con = self._get_connection()
|
|
240
|
+
try:
|
|
241
|
+
if path_filter:
|
|
242
|
+
sql = """
|
|
243
|
+
SELECT rel_path, line_no, content, bm25(code_lines) AS rank
|
|
244
|
+
FROM code_lines
|
|
245
|
+
WHERE code_lines MATCH ? AND rel_path LIKE ?
|
|
246
|
+
ORDER BY rank
|
|
247
|
+
LIMIT ?;
|
|
248
|
+
"""
|
|
249
|
+
cur = con.execute(sql, (fts_query, f"%{path_filter}%", limit))
|
|
250
|
+
else:
|
|
251
|
+
sql = """
|
|
252
|
+
SELECT rel_path, line_no, content, bm25(code_lines) AS rank
|
|
253
|
+
FROM code_lines
|
|
254
|
+
WHERE code_lines MATCH ?
|
|
255
|
+
ORDER BY rank
|
|
256
|
+
LIMIT ?;
|
|
257
|
+
"""
|
|
258
|
+
cur = con.execute(sql, (fts_query, limit))
|
|
259
|
+
|
|
260
|
+
for row in cur.fetchall():
|
|
261
|
+
results.append({
|
|
262
|
+
"file": row[0],
|
|
263
|
+
"line": row[1],
|
|
264
|
+
"content": row[2].strip(),
|
|
265
|
+
"bm25_rank": row[3]
|
|
266
|
+
})
|
|
267
|
+
except sqlite3.OperationalError:
|
|
268
|
+
# If trigram MATCH fails (e.g. query < 3 chars), fallback to LIKE
|
|
269
|
+
like_sql = """
|
|
270
|
+
SELECT rel_path, line_no, content, 0.0 AS rank
|
|
271
|
+
FROM code_lines
|
|
272
|
+
WHERE content LIKE ?
|
|
273
|
+
LIMIT ?;
|
|
274
|
+
"""
|
|
275
|
+
cur = con.execute(like_sql, (f"%{clean_q}%", limit))
|
|
276
|
+
for row in cur.fetchall():
|
|
277
|
+
results.append({
|
|
278
|
+
"file": row[0],
|
|
279
|
+
"line": row[1],
|
|
280
|
+
"content": row[2].strip(),
|
|
281
|
+
"bm25_rank": 0.0
|
|
282
|
+
})
|
|
283
|
+
finally:
|
|
284
|
+
con.close()
|
|
285
|
+
except Exception:
|
|
286
|
+
return []
|
|
287
|
+
|
|
288
|
+
return results
|
|
289
|
+
|
|
290
|
+
def clear(self):
|
|
291
|
+
"""Clears index and removes database file."""
|
|
292
|
+
if os.path.exists(self.db_path):
|
|
293
|
+
try:
|
|
294
|
+
os.remove(self.db_path)
|
|
295
|
+
except Exception:
|
|
296
|
+
pass
|