tokensafe 4.14.0 → 4.15.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,954 @@
1
+ """Unified per-workspace context index.
2
+
3
+ One SQLite database now backs every lookup the engine performs against a
4
+ workspace: the AST graph (``symbols``/``edges``/``api_endpoints``), the
5
+ line-level FTS corpus (``code_lines``) and the text freshness metadata
6
+ (``file_meta``). ``GraphEngine`` and ``CodeFTSIndex`` are producers/readers of
7
+ this one file, so ``scoped_search``, ``smart_read_file``, ``repo_map`` and
8
+ ``oumv index`` all answer from the same generation of the repository instead
9
+ of four unrelated caches that drift at different speeds.
10
+
11
+ Layout: ``~/.tokensafe/data/index/idx_<sha256(realpath(root))[:16]>.db``
12
+ (WAL, one writer at a time, no writes into the project tree).
13
+
14
+ The previous on-disk caches (``data/graph_cache/<md5>.db`` and
15
+ ``data/cache/fts/fts_<sha256>.db``) are imported once by ``migrate_legacy``
16
+ and then removed; a failed migration simply degrades to a rebuild.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import sqlite3
25
+ import threading
26
+ import time
27
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
28
+
29
+ from src.paths import resolve_data_dir
30
+
31
+ #: Bumped only when the physical layout below changes incompatibly.
32
+ INDEX_SCHEMA_VERSION = 1
33
+
34
+ _GRAPH_TABLES = (
35
+ "graph_meta",
36
+ "file_stats",
37
+ "symbols",
38
+ "file_symbols",
39
+ "file_imports",
40
+ "glob_imports",
41
+ "edges",
42
+ "api_endpoints",
43
+ "api_calls",
44
+ "file_mounts",
45
+ "api_links",
46
+ )
47
+
48
+ # Constant SQL kept out of f-strings: the table list above is the only source.
49
+ _DELETE_ALL_SQL = {
50
+ "file_stats": "DELETE FROM file_stats",
51
+ "symbols": "DELETE FROM symbols",
52
+ "file_symbols": "DELETE FROM file_symbols",
53
+ "file_imports": "DELETE FROM file_imports",
54
+ "glob_imports": "DELETE FROM glob_imports",
55
+ "edges": "DELETE FROM edges",
56
+ "api_endpoints": "DELETE FROM api_endpoints",
57
+ "api_calls": "DELETE FROM api_calls",
58
+ "file_mounts": "DELETE FROM file_mounts",
59
+ "api_links": "DELETE FROM api_links",
60
+ }
61
+
62
+ # Legacy import is plain row copying: ATTACH with a bound filename and
63
+ # dynamically named tables both trip injection guards for no benefit.
64
+ _LEGACY_TABLES = {
65
+ "file_stats": (
66
+ "SELECT rel_path, mtime, size FROM file_stats",
67
+ "INSERT OR REPLACE INTO file_stats (rel_path, mtime, size) VALUES (?, ?, ?)",
68
+ ),
69
+ "symbols": (
70
+ "SELECT sym_key, rel_path, name, kind, line_start, line_end, signature FROM symbols",
71
+ "INSERT OR REPLACE INTO symbols (sym_key, rel_path, name, kind, line_start, line_end, signature) VALUES (?, ?, ?, ?, ?, ?, ?)",
72
+ ),
73
+ "file_symbols": (
74
+ "SELECT rel_path, sym_key, idx FROM file_symbols",
75
+ "INSERT OR REPLACE INTO file_symbols (rel_path, sym_key, idx) VALUES (?, ?, ?)",
76
+ ),
77
+ "file_imports": (
78
+ "SELECT rel_path, imported FROM file_imports",
79
+ "INSERT OR REPLACE INTO file_imports (rel_path, imported) VALUES (?, ?)",
80
+ ),
81
+ "glob_imports": (
82
+ "SELECT rel_path, pattern FROM glob_imports",
83
+ "INSERT OR REPLACE INTO glob_imports (rel_path, pattern) VALUES (?, ?)",
84
+ ),
85
+ "edges": (
86
+ "SELECT source, target FROM edges",
87
+ "INSERT OR REPLACE INTO edges (source, target) VALUES (?, ?)",
88
+ ),
89
+ "api_endpoints": (
90
+ "SELECT rel_path, route, sym_key, method FROM api_endpoints",
91
+ "INSERT INTO api_endpoints (rel_path, route, sym_key, method) VALUES (?, ?, ?, ?)",
92
+ ),
93
+ "api_calls": (
94
+ "SELECT rel_path, route, sym_key, method FROM api_calls",
95
+ "INSERT INTO api_calls (rel_path, route, sym_key, method) VALUES (?, ?, ?, ?)",
96
+ ),
97
+ "file_mounts": (
98
+ "SELECT rel_path, prefix, ident, module FROM file_mounts",
99
+ "INSERT INTO file_mounts (rel_path, prefix, ident, module) VALUES (?, ?, ?, ?)",
100
+ ),
101
+ "api_links": (
102
+ "SELECT link_json FROM api_links",
103
+ "INSERT INTO api_links (link_json) VALUES (?)",
104
+ ),
105
+ }
106
+
107
+ _LEGACY_TEXT_TABLES = {
108
+ "file_meta": (
109
+ "SELECT rel_path, mtime, size FROM file_meta",
110
+ "INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?)",
111
+ ),
112
+ "code_lines": (
113
+ "SELECT rel_path, line_no, content FROM code_lines",
114
+ "INSERT INTO code_lines (rel_path, line_no, content) VALUES (?, ?, ?)",
115
+ ),
116
+ }
117
+
118
+ _INIT_LOCK = threading.Lock()
119
+ _INITIALIZED: Set[str] = set()
120
+
121
+ _TEXT_LINE_MAX_CHARS = 2000
122
+ _TEXT_LINE_SKIP_OVER = 10000
123
+
124
+
125
+ def _root_key(root: str) -> str:
126
+ return hashlib.sha256(os.path.abspath(root).encode("utf-8")).hexdigest()[:16]
127
+
128
+
129
+ def index_db_path(root: str) -> str:
130
+ """Path of the unified index for ``root`` (created lazily)."""
131
+ base = os.path.join(resolve_data_dir(), "index")
132
+ return os.path.join(base, f"idx_{_root_key(root)}.db")
133
+
134
+
135
+ def legacy_graph_db_path(root: str) -> str:
136
+ base = os.path.join(resolve_data_dir(), "graph_cache")
137
+ key = hashlib.md5(os.path.abspath(root).encode("utf-8")).hexdigest()[:12]
138
+ return os.path.join(base, f"{key}.db")
139
+
140
+
141
+ def legacy_fts_db_path(root: str) -> str:
142
+ base = os.path.join(resolve_data_dir(), "cache", "fts")
143
+ return os.path.join(base, f"fts_{_root_key(root)}.db")
144
+
145
+
146
+ def _unlink_db(path: str) -> None:
147
+ for suffix in ("", "-wal", "-shm"):
148
+ try:
149
+ os.remove(path + suffix)
150
+ except OSError:
151
+ pass
152
+
153
+
154
+ class ContextIndex:
155
+ """One index, many readers: graph rows + line corpus in a single file."""
156
+
157
+ def __init__(self, root: str, db_path: Optional[str] = None):
158
+ self.root = os.path.abspath(root)
159
+ self.db_path = os.path.abspath(db_path or index_db_path(self.root))
160
+ self._ensure_schema()
161
+
162
+ # ------------------------------------------------------------------ setup
163
+ def _connect(self) -> sqlite3.Connection:
164
+ os.makedirs(os.path.dirname(self.db_path) or ".", exist_ok=True)
165
+ con = sqlite3.connect(self.db_path, timeout=10.0)
166
+ try:
167
+ con.execute("PRAGMA journal_mode = WAL;")
168
+ con.execute("PRAGMA synchronous = NORMAL;")
169
+ con.execute("PRAGMA busy_timeout = 5000;")
170
+ except sqlite3.Error:
171
+ con.close()
172
+ raise
173
+ return con
174
+
175
+ def _schema_ok(self) -> bool:
176
+ """Read-only readiness check: a warm index needs no DDL transaction.
177
+
178
+ Every hook is a fresh interpreter, so ``CREATE TABLE IF NOT EXISTS``
179
+ used to run (and take a write lock) on each call; against a 39 MB index
180
+ that contended with the previous process's WAL checkpoint and produced
181
+ multi-second outliers.
182
+ """
183
+ try:
184
+ con = sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True, timeout=2.0)
185
+ except sqlite3.Error:
186
+ return False
187
+ try:
188
+ row = con.execute(
189
+ "SELECT val FROM graph_meta WHERE key = 'index_schema'"
190
+ ).fetchone()
191
+ tables = con.execute(
192
+ "SELECT name FROM sqlite_master WHERE type='table' "
193
+ "AND name IN ('symbols', 'file_meta', 'code_lines')"
194
+ ).fetchall()
195
+ return bool(row) and len(tables) == 3
196
+ except sqlite3.Error:
197
+ return False
198
+ finally:
199
+ con.close()
200
+
201
+ def _ensure_schema(self) -> None:
202
+ if self.db_path in _INITIALIZED and os.path.exists(self.db_path):
203
+ return
204
+ with _INIT_LOCK:
205
+ if self.db_path in _INITIALIZED and os.path.exists(self.db_path):
206
+ return
207
+ if os.path.exists(self.db_path) and self._schema_ok():
208
+ _INITIALIZED.add(self.db_path)
209
+ return
210
+ _INITIALIZED.discard(self.db_path)
211
+ first_time = not os.path.exists(self.db_path)
212
+ try:
213
+ self._create_schema()
214
+ if first_time:
215
+ self._migrate_legacy()
216
+ except sqlite3.DatabaseError:
217
+ # A corrupt index is a cache, never data: rebuild once.
218
+ _unlink_db(self.db_path)
219
+ self._create_schema()
220
+ _INITIALIZED.add(self.db_path)
221
+
222
+ def _create_schema(self) -> None:
223
+ con = self._connect()
224
+ try:
225
+ with con:
226
+ con.execute("CREATE TABLE IF NOT EXISTS graph_meta (key TEXT PRIMARY KEY, val TEXT)")
227
+ con.execute("CREATE TABLE IF NOT EXISTS file_stats (rel_path TEXT PRIMARY KEY, mtime REAL, size INTEGER)")
228
+ con.execute("CREATE TABLE IF NOT EXISTS symbols (sym_key TEXT PRIMARY KEY, rel_path TEXT, name TEXT, kind TEXT, line_start INTEGER, line_end INTEGER, signature TEXT)")
229
+ con.execute("CREATE TABLE IF NOT EXISTS file_symbols (rel_path TEXT, sym_key TEXT, idx INTEGER, PRIMARY KEY (rel_path, sym_key))")
230
+ con.execute("CREATE TABLE IF NOT EXISTS file_imports (rel_path TEXT, imported TEXT, PRIMARY KEY (rel_path, imported))")
231
+ con.execute("CREATE TABLE IF NOT EXISTS glob_imports (rel_path TEXT, pattern TEXT, PRIMARY KEY (rel_path, pattern))")
232
+ con.execute("CREATE TABLE IF NOT EXISTS edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
233
+ con.execute("CREATE TABLE IF NOT EXISTS api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
234
+ con.execute("CREATE TABLE IF NOT EXISTS api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
235
+ con.execute("CREATE TABLE IF NOT EXISTS file_mounts (rel_path TEXT, prefix TEXT, ident TEXT, module TEXT)")
236
+ con.execute("CREATE TABLE IF NOT EXISTS api_links (link_json TEXT)")
237
+ con.execute("CREATE TABLE IF NOT EXISTS file_meta (rel_path TEXT PRIMARY KEY, mtime REAL, size INTEGER)")
238
+ try:
239
+ con.execute("CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name)")
240
+ con.execute("CREATE INDEX IF NOT EXISTS idx_endpoints_route ON api_endpoints(route)")
241
+ except sqlite3.Error:
242
+ pass
243
+ self._create_fts(con)
244
+ finally:
245
+ con.close()
246
+
247
+ @staticmethod
248
+ def _create_fts(con: sqlite3.Connection) -> None:
249
+ exists = con.execute(
250
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='code_lines'"
251
+ ).fetchone()
252
+ if exists:
253
+ return
254
+ try:
255
+ con.execute(
256
+ 'CREATE VIRTUAL TABLE code_lines USING fts5('
257
+ 'rel_path, line_no UNINDEXED, content, tokenize = "trigram")'
258
+ )
259
+ except sqlite3.OperationalError:
260
+ con.execute(
261
+ 'CREATE VIRTUAL TABLE code_lines USING fts5('
262
+ 'rel_path, line_no UNINDEXED, content, tokenize = "unicode61")'
263
+ )
264
+
265
+ def _migrate_legacy(self) -> None:
266
+ """Imports the two pre-kernel caches, then deletes them."""
267
+ old_graph = legacy_graph_db_path(self.root)
268
+ old_fts = legacy_fts_db_path(self.root)
269
+ if not os.path.exists(old_graph) and not os.path.exists(old_fts):
270
+ return
271
+ try:
272
+ if os.path.exists(old_graph) and self._import_graph(old_graph):
273
+ _unlink_db(old_graph)
274
+ if os.path.exists(old_fts) and self._import_fts(old_fts):
275
+ _unlink_db(old_fts)
276
+ except sqlite3.Error:
277
+ # Keep the legacy files: the next scan rebuilds from source.
278
+ return
279
+
280
+ def _copy_legacy(self, legacy_path: str, tables: Dict[str, Tuple[str, str]]) -> bool:
281
+ try:
282
+ src = sqlite3.connect(legacy_path, timeout=5.0)
283
+ except sqlite3.Error:
284
+ return False
285
+ try:
286
+ dst = self._connect()
287
+ try:
288
+ with dst:
289
+ for select_sql, insert_sql in tables.values():
290
+ try:
291
+ cursor = src.execute(select_sql)
292
+ except sqlite3.Error:
293
+ continue
294
+ while True:
295
+ rows = cursor.fetchmany(2000)
296
+ if not rows:
297
+ break
298
+ dst.executemany(insert_sql, rows)
299
+ finally:
300
+ dst.close()
301
+ finally:
302
+ src.close()
303
+ return True
304
+
305
+ def _import_graph(self, legacy_path: str) -> bool:
306
+ try:
307
+ src = sqlite3.connect(legacy_path, timeout=5.0)
308
+ try:
309
+ meta = dict(src.execute("SELECT key, val FROM graph_meta").fetchall())
310
+ finally:
311
+ src.close()
312
+ except sqlite3.Error:
313
+ return False
314
+ if meta.get("root_dir") != self.root:
315
+ return False
316
+ if not self._copy_legacy(legacy_path, _LEGACY_TABLES):
317
+ return False
318
+ con = self._connect()
319
+ try:
320
+ with con:
321
+ con.executemany(
322
+ "INSERT OR REPLACE INTO graph_meta (key, val) VALUES (?, ?)",
323
+ [
324
+ ("root_dir", self.root),
325
+ ("backend", meta.get("backend", "")),
326
+ ("last_scanned", meta.get("last_scanned", "0")),
327
+ ("version", meta.get("version", "0")),
328
+ ],
329
+ )
330
+ finally:
331
+ con.close()
332
+ return True
333
+
334
+ def _import_fts(self, legacy_path: str) -> bool:
335
+ return self._copy_legacy(legacy_path, _LEGACY_TEXT_TABLES)
336
+
337
+ # -------------------------------------------------------- graph persistence
338
+ @staticmethod
339
+ def _delete_file_rows(cur: sqlite3.Cursor, rel_path: str) -> None:
340
+ cur.execute("DELETE FROM symbols WHERE rel_path = ?", (rel_path,))
341
+ cur.execute("DELETE FROM file_symbols WHERE rel_path = ?", (rel_path,))
342
+ cur.execute("DELETE FROM file_imports WHERE rel_path = ?", (rel_path,))
343
+ cur.execute("DELETE FROM glob_imports WHERE rel_path = ?", (rel_path,))
344
+ cur.execute("DELETE FROM api_endpoints WHERE rel_path = ?", (rel_path,))
345
+ cur.execute("DELETE FROM api_calls WHERE rel_path = ?", (rel_path,))
346
+ cur.execute("DELETE FROM file_mounts WHERE rel_path = ?", (rel_path,))
347
+ cur.execute("DELETE FROM file_stats WHERE rel_path = ?", (rel_path,))
348
+
349
+ @staticmethod
350
+ def _insert_file_rows(cur: sqlite3.Cursor, graph: Any, rel_path: str) -> None:
351
+ stat = graph.file_stats.get(rel_path)
352
+ if stat is None:
353
+ return
354
+ cur.execute(
355
+ "INSERT OR REPLACE INTO file_stats (rel_path, mtime, size) VALUES (?, ?, ?)",
356
+ (rel_path, float(stat[0]), int(stat[1])),
357
+ )
358
+ sym_keys = graph.file_symbols.get(rel_path, [])
359
+ for idx, sym_key in enumerate(sym_keys):
360
+ cur.execute(
361
+ "INSERT OR REPLACE INTO file_symbols (rel_path, sym_key, idx) VALUES (?, ?, ?)",
362
+ (rel_path, sym_key, idx),
363
+ )
364
+ sym = graph.symbols.get(sym_key)
365
+ if sym is None:
366
+ continue
367
+ cur.execute(
368
+ "INSERT OR REPLACE INTO symbols (sym_key, rel_path, name, kind, line_start, line_end, signature) "
369
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
370
+ (sym_key, rel_path, sym.name, sym.kind, sym.line_start, sym.line_end, sym.signature),
371
+ )
372
+ for imported in graph.file_imports.get(rel_path, ()):
373
+ cur.execute(
374
+ "INSERT OR IGNORE INTO file_imports (rel_path, imported) VALUES (?, ?)",
375
+ (rel_path, imported),
376
+ )
377
+ for pattern in graph.glob_imports.get(rel_path, ()):
378
+ cur.execute(
379
+ "INSERT OR IGNORE INTO glob_imports (rel_path, pattern) VALUES (?, ?)",
380
+ (rel_path, pattern),
381
+ )
382
+ for ep in graph.file_endpoints.get(rel_path, ()):
383
+ cur.execute(
384
+ "INSERT INTO api_endpoints (rel_path, route, sym_key, method) VALUES (?, ?, ?, ?)",
385
+ (rel_path, ep[0], ep[1], ep[2] if len(ep) > 2 else None),
386
+ )
387
+ for call in graph.file_api_calls.get(rel_path, ()):
388
+ cur.execute(
389
+ "INSERT INTO api_calls (rel_path, route, sym_key, method) VALUES (?, ?, ?, ?)",
390
+ (rel_path, call[0], call[1], call[2] if len(call) > 2 else None),
391
+ )
392
+ for mount in graph.file_mounts.get(rel_path, ()):
393
+ cur.execute(
394
+ "INSERT INTO file_mounts (rel_path, prefix, ident, module) VALUES (?, ?, ?, ?)",
395
+ (rel_path, mount[0], mount[1], mount[2] if len(mount) > 2 else ""),
396
+ )
397
+
398
+ def save_graph(
399
+ self,
400
+ graph: Any,
401
+ changed: Optional[Iterable[str]] = None,
402
+ deleted: Optional[Iterable[str]] = None,
403
+ ) -> None:
404
+ """Persists graph rows. ``changed=None`` means a full rewrite.
405
+
406
+ Per-file tables are written incrementally for ``changed``/``deleted``;
407
+ the two global tables (``edges``, ``api_links``) are replaced wholesale
408
+ because ``_resolve_local_imports`` rebuilds them for the whole graph.
409
+ """
410
+ changed_set: Optional[Set[str]] = None if changed is None else set(changed)
411
+ deleted_set: Set[str] = set(deleted or ())
412
+ con = self._connect()
413
+ try:
414
+ with con:
415
+ cur = con.cursor()
416
+ if changed_set is None:
417
+ for table in _DELETE_ALL_SQL:
418
+ cur.execute(_DELETE_ALL_SQL[table])
419
+ for rel_path in list(graph.file_stats.keys()):
420
+ self._insert_file_rows(cur, graph, rel_path)
421
+ else:
422
+ for rel_path in changed_set | deleted_set:
423
+ self._delete_file_rows(cur, rel_path)
424
+ for rel_path in changed_set - deleted_set:
425
+ self._insert_file_rows(cur, graph, rel_path)
426
+ cur.execute("DELETE FROM edges")
427
+ cur.executemany(
428
+ "INSERT OR IGNORE INTO edges (source, target) VALUES (?, ?)",
429
+ [(src, tgt) for src, tgts in graph.edges.items() for tgt in tgts],
430
+ )
431
+ cur.execute("DELETE FROM api_links")
432
+ cur.executemany(
433
+ "INSERT INTO api_links (link_json) VALUES (?)",
434
+ [(json.dumps(lk, ensure_ascii=False),) for lk in graph.api_links],
435
+ )
436
+ cur.executemany(
437
+ "INSERT OR REPLACE INTO graph_meta (key, val) VALUES (?, ?)",
438
+ [
439
+ ("version", _graph_schema_version()),
440
+ ("root_dir", self.root),
441
+ ("backend", getattr(graph, "backend", "")),
442
+ ("last_scanned", str(getattr(graph, "last_scanned", 0.0))),
443
+ ("index_schema", str(INDEX_SCHEMA_VERSION)),
444
+ ],
445
+ )
446
+ finally:
447
+ con.close()
448
+
449
+ def load_graph_rows(self) -> Optional[Dict[str, Any]]:
450
+ """Rows for ``CodeGraph._load_disk_cache``; ``None`` when unusable."""
451
+ if not os.path.exists(self.db_path):
452
+ return None
453
+ con = self._connect()
454
+ try:
455
+ cur = con.cursor()
456
+ meta = dict(cur.execute("SELECT key, val FROM graph_meta").fetchall())
457
+ if not meta or meta.get("root_dir") != self.root:
458
+ return None
459
+ return {
460
+ "meta": meta,
461
+ "symbols": cur.execute(
462
+ "SELECT sym_key, rel_path, name, kind, line_start, line_end, signature FROM symbols"
463
+ ).fetchall(),
464
+ "file_symbols": cur.execute(
465
+ "SELECT rel_path, sym_key FROM file_symbols ORDER BY rel_path, idx"
466
+ ).fetchall(),
467
+ "file_stats": cur.execute("SELECT rel_path, mtime, size FROM file_stats").fetchall(),
468
+ "file_imports": cur.execute("SELECT rel_path, imported FROM file_imports").fetchall(),
469
+ "glob_imports": cur.execute("SELECT rel_path, pattern FROM glob_imports").fetchall(),
470
+ "edges": cur.execute("SELECT source, target FROM edges").fetchall(),
471
+ "file_endpoints": cur.execute(
472
+ "SELECT rel_path, route, sym_key, method FROM api_endpoints"
473
+ ).fetchall(),
474
+ "file_api_calls": cur.execute(
475
+ "SELECT rel_path, route, sym_key, method FROM api_calls"
476
+ ).fetchall(),
477
+ "file_mounts": cur.execute(
478
+ "SELECT rel_path, prefix, ident, module FROM file_mounts"
479
+ ).fetchall(),
480
+ "api_links": cur.execute("SELECT link_json FROM api_links").fetchall(),
481
+ }
482
+ except sqlite3.Error:
483
+ return None
484
+ finally:
485
+ con.close()
486
+
487
+ # ------------------------------------------------------------ text corpus
488
+ def sync_text(
489
+ self,
490
+ changed: Iterable[str],
491
+ deleted: Iterable[str] = (),
492
+ max_file_size_bytes: int = 512 * 1024,
493
+ ) -> int:
494
+ """Re-indexes lines only for files the graph scan just touched."""
495
+ changed_set = set(changed)
496
+ deleted_set = set(deleted)
497
+ if not changed_set and not deleted_set:
498
+ return 0
499
+ indexed = 0
500
+ con = self._connect()
501
+ try:
502
+ with con:
503
+ cur = con.cursor()
504
+ for rel_path in deleted_set - changed_set:
505
+ self._delete_text_rows(cur, rel_path)
506
+ for rel_path in changed_set:
507
+ full_path = os.path.join(self.root, rel_path)
508
+ try:
509
+ st = os.stat(full_path)
510
+ except OSError:
511
+ self._delete_text_rows(cur, rel_path)
512
+ continue
513
+ if st.st_size > max_file_size_bytes:
514
+ self._delete_text_rows(cur, rel_path)
515
+ continue
516
+ try:
517
+ with open(full_path, "r", encoding="utf-8", errors="replace") as fh:
518
+ lines = fh.read().splitlines()
519
+ except OSError:
520
+ continue
521
+ self._delete_text_rows(cur, rel_path)
522
+ batch = [
523
+ (rel_path, idx + 1, line[:_TEXT_LINE_MAX_CHARS])
524
+ for idx, line in enumerate(lines)
525
+ if line.strip() and len(line) <= _TEXT_LINE_SKIP_OVER
526
+ ]
527
+ if batch:
528
+ cur.executemany(
529
+ "INSERT INTO code_lines (rel_path, line_no, content) VALUES (?, ?, ?)",
530
+ batch,
531
+ )
532
+ indexed += len(batch)
533
+ cur.execute(
534
+ "INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?)",
535
+ (rel_path, st.st_mtime, st.st_size),
536
+ )
537
+ finally:
538
+ con.close()
539
+ return indexed
540
+
541
+ @staticmethod
542
+ def _delete_text_rows(cur: sqlite3.Cursor, rel_path: str) -> None:
543
+ cur.execute("DELETE FROM code_lines WHERE rel_path = ?", (rel_path,))
544
+ cur.execute("DELETE FROM file_meta WHERE rel_path = ?", (rel_path,))
545
+
546
+ def index_text_files(
547
+ self, max_files: int = 5000, max_file_size_bytes: int = 512 * 1024
548
+ ) -> Dict[str, Any]:
549
+ """Walk-based text indexing (CLI ``tokensafe index``), incremental.
550
+
551
+ Preserves the FTS semantics: the per-run cap bounds indexing work, not
552
+ the walk, so files beyond the cap are never mistaken for deleted ones.
553
+ """
554
+ from src.fts_index import CODE_EXTS, IGNORED_DIRS, IGNORED_EXTS
555
+
556
+ t0 = time.time()
557
+ scanned_files = 0
558
+ updated_files = 0
559
+ indexed_lines = 0
560
+ pruned_files = 0
561
+ con = self._connect()
562
+ try:
563
+ with con:
564
+ cur = con.cursor()
565
+ known_meta = {
566
+ row[0]: (row[1], row[2])
567
+ for row in cur.execute("SELECT rel_path, mtime, size FROM file_meta").fetchall()
568
+ }
569
+ found_paths: Set[str] = set()
570
+ files_to_index: List[Tuple[str, str, float, int]] = []
571
+ for dirpath, dirnames, filenames in os.walk(self.root):
572
+ dirnames[:] = [
573
+ d for d in dirnames if d not in IGNORED_DIRS and not d.startswith(".")
574
+ ]
575
+ for filename in filenames:
576
+ ext = os.path.splitext(filename)[1].lower()
577
+ if ext in IGNORED_EXTS or (
578
+ ext not in CODE_EXTS and not filename.startswith("Dockerfile")
579
+ ):
580
+ continue
581
+ full_path = os.path.join(dirpath, filename)
582
+ rel_path = os.path.relpath(full_path, self.root)
583
+ found_paths.add(rel_path)
584
+ scanned_files += 1
585
+ try:
586
+ st = os.stat(full_path)
587
+ except OSError:
588
+ continue
589
+ if st.st_size > max_file_size_bytes:
590
+ continue
591
+ prev = known_meta.get(rel_path)
592
+ if prev and abs(prev[0] - st.st_mtime) < 0.001 and prev[1] == st.st_size:
593
+ continue
594
+ if len(files_to_index) < max_files:
595
+ files_to_index.append((rel_path, full_path, st.st_mtime, st.st_size))
596
+
597
+ for rel_path, full_path, f_mtime, f_size in files_to_index:
598
+ try:
599
+ with open(full_path, "r", encoding="utf-8", errors="replace") as fh:
600
+ lines = fh.read().splitlines()
601
+ except OSError:
602
+ continue
603
+ self._delete_text_rows(cur, rel_path)
604
+ batch = [
605
+ (rel_path, idx + 1, line[:_TEXT_LINE_MAX_CHARS])
606
+ for idx, line in enumerate(lines)
607
+ if line.strip() and len(line) <= _TEXT_LINE_SKIP_OVER
608
+ ]
609
+ if batch:
610
+ cur.executemany(
611
+ "INSERT INTO code_lines (rel_path, line_no, content) VALUES (?, ?, ?)",
612
+ batch,
613
+ )
614
+ indexed_lines += len(batch)
615
+ cur.execute(
616
+ "INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?)",
617
+ (rel_path, f_mtime, f_size),
618
+ )
619
+ updated_files += 1
620
+
621
+ deleted_paths = set(known_meta.keys()) - found_paths
622
+ for rel_path in deleted_paths:
623
+ self._delete_text_rows(cur, rel_path)
624
+ pruned_files = len(deleted_paths)
625
+ finally:
626
+ con.close()
627
+ return {
628
+ "scanned_files": scanned_files,
629
+ "updated_files": updated_files,
630
+ "indexed_lines": indexed_lines,
631
+ "pruned_files": pruned_files,
632
+ "duration_ms": (time.time() - t0) * 1000,
633
+ }
634
+
635
+ def search_text(
636
+ self, query: str, limit: int = 25, path_filter: Optional[str] = None
637
+ ) -> List[Dict[str, Any]]:
638
+ """BM25-ranked line search; phrase first, AND-of-terms second.
639
+
640
+ Every failure mode of SQLite (missing FTS5, corrupt cache, sub-trigram
641
+ query) degrades to an escaped LIKE or to an empty result — never an
642
+ exception on the search path.
643
+ """
644
+ clean_q = query.strip()
645
+ if not clean_q:
646
+ return []
647
+ escaped_q = clean_q.replace('"', '""')
648
+ fts_query = f'"{escaped_q}"'
649
+
650
+ def _like_escape(val: str) -> str:
651
+ return val.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
652
+
653
+ results: List[Dict[str, Any]] = []
654
+ try:
655
+ con = self._connect()
656
+ try:
657
+ if path_filter:
658
+ sql = (
659
+ "SELECT rel_path, line_no, content, bm25(code_lines) AS rank "
660
+ "FROM code_lines WHERE code_lines MATCH ? AND rel_path LIKE ? ESCAPE '\\' "
661
+ "ORDER BY rank LIMIT ?"
662
+ )
663
+ params: Tuple[Any, ...] = (fts_query, f"%{_like_escape(path_filter)}%", limit)
664
+ else:
665
+ sql = (
666
+ "SELECT rel_path, line_no, content, bm25(code_lines) AS rank "
667
+ "FROM code_lines WHERE code_lines MATCH ? ORDER BY rank LIMIT ?"
668
+ )
669
+ params = (fts_query, limit)
670
+ rows = con.execute(sql, params).fetchall()
671
+
672
+ if not rows and " " in clean_q:
673
+ and_query = " AND ".join(
674
+ f'"{term.replace(chr(34), chr(34) * 2)}"' for term in clean_q.split()
675
+ )
676
+ if path_filter:
677
+ retry_params: Tuple[Any, ...] = (
678
+ and_query,
679
+ f"%{_like_escape(path_filter)}%",
680
+ limit,
681
+ )
682
+ else:
683
+ retry_params = (and_query, limit)
684
+ rows = con.execute(sql, retry_params).fetchall()
685
+
686
+ for row in rows:
687
+ results.append(
688
+ {
689
+ "file": row[0],
690
+ "line": row[1],
691
+ "content": (row[2] or "").strip(),
692
+ "bm25_rank": row[3],
693
+ }
694
+ )
695
+
696
+ if not results:
697
+ if path_filter:
698
+ like_sql = (
699
+ "SELECT rel_path, line_no, content, 0.0 AS rank FROM code_lines "
700
+ "WHERE content LIKE ? ESCAPE '\\' AND rel_path LIKE ? ESCAPE '\\' LIMIT ?"
701
+ )
702
+ like_params: Tuple[Any, ...] = (
703
+ f"%{_like_escape(clean_q)}%",
704
+ f"%{_like_escape(path_filter)}%",
705
+ limit,
706
+ )
707
+ else:
708
+ like_sql = (
709
+ "SELECT rel_path, line_no, content, 0.0 AS rank FROM code_lines "
710
+ "WHERE content LIKE ? ESCAPE '\\' LIMIT ?"
711
+ )
712
+ like_params = (f"%{_like_escape(clean_q)}%", limit)
713
+ for row in con.execute(like_sql, like_params).fetchall():
714
+ results.append(
715
+ {
716
+ "file": row[0],
717
+ "line": row[1],
718
+ "content": (row[2] or "").strip(),
719
+ "bm25_rank": 0.0,
720
+ }
721
+ )
722
+ finally:
723
+ con.close()
724
+ except sqlite3.Error:
725
+ return []
726
+ return results
727
+
728
+ def indexed_file_count(self) -> int:
729
+ try:
730
+ con = self._connect()
731
+ try:
732
+ row = con.execute("SELECT COUNT(*) FROM file_meta").fetchone()
733
+ return int(row[0] or 0) if row else 0
734
+ finally:
735
+ con.close()
736
+ except sqlite3.Error:
737
+ return 0
738
+
739
+ def clear_text(self) -> None:
740
+ con = self._connect()
741
+ try:
742
+ with con:
743
+ con.execute("DELETE FROM code_lines")
744
+ con.execute("DELETE FROM file_meta")
745
+ finally:
746
+ con.close()
747
+
748
+ # ------------------------------------------------------------- reads
749
+ def find_symbols(self, name: str, limit: int = 20) -> List[Dict[str, Any]]:
750
+ """Exact, then case-insensitive, then suffix/prefix lookups."""
751
+ if not name:
752
+ return []
753
+ sql = (
754
+ "SELECT sym_key, rel_path, name, kind, line_start, line_end, signature FROM symbols "
755
+ "WHERE name = ? OR name = ? COLLATE NOCASE OR name LIKE ? OR name LIKE ? "
756
+ "ORDER BY CASE WHEN name = ? THEN 0 WHEN name = ? COLLATE NOCASE THEN 1 "
757
+ "WHEN name LIKE ? THEN 2 ELSE 3 END, length(name), sym_key LIMIT ?"
758
+ )
759
+ params = (
760
+ name,
761
+ name,
762
+ f"%{name}",
763
+ f"%{name}",
764
+ name,
765
+ name,
766
+ f"%{name}",
767
+ int(limit),
768
+ )
769
+ try:
770
+ con = self._connect()
771
+ try:
772
+ rows = con.execute(sql, params).fetchall()
773
+ finally:
774
+ con.close()
775
+ except sqlite3.Error:
776
+ return []
777
+ return [
778
+ {
779
+ "sym_key": row[0],
780
+ "file": row[1],
781
+ "name": row[2],
782
+ "kind": row[3],
783
+ "line_start": row[4],
784
+ "line_end": row[5],
785
+ "signature": row[6],
786
+ }
787
+ for row in rows
788
+ ]
789
+
790
+ def endpoints(
791
+ self, route: str, method: Optional[str] = None, limit: int = 10
792
+ ) -> List[Dict[str, Any]]:
793
+ if not route:
794
+ return []
795
+ sql = "SELECT rel_path, route, sym_key, method FROM api_endpoints WHERE (route = ? OR route LIKE ?)"
796
+ params: List[Any] = [route, f"%{route}"]
797
+ if method:
798
+ sql += " AND (method = ? OR method IS NULL)"
799
+ params.append(method)
800
+ sql += " LIMIT ?"
801
+ params.append(int(limit))
802
+ try:
803
+ con = self._connect()
804
+ try:
805
+ rows = con.execute(sql, params).fetchall()
806
+ finally:
807
+ con.close()
808
+ except sqlite3.Error:
809
+ return []
810
+ return [
811
+ {"file": row[0], "route": row[1], "sym_key": row[2], "method": row[3]} for row in rows
812
+ ]
813
+
814
+ def file_facts(self, rel_path: str) -> Optional[Tuple[float, int]]:
815
+ try:
816
+ con = self._connect()
817
+ try:
818
+ row = con.execute(
819
+ "SELECT mtime, size FROM file_stats WHERE rel_path = ?", (rel_path,)
820
+ ).fetchone()
821
+ finally:
822
+ con.close()
823
+ except sqlite3.Error:
824
+ return None
825
+ return (float(row[0]), int(row[1])) if row else None
826
+
827
+ def counts(self) -> Dict[str, int]:
828
+ try:
829
+ con = self._connect()
830
+ try:
831
+ files = con.execute("SELECT COUNT(*) FROM file_stats").fetchone()[0]
832
+ symbols = con.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
833
+ texts = con.execute("SELECT COUNT(*) FROM file_meta").fetchone()[0]
834
+ finally:
835
+ con.close()
836
+ except sqlite3.Error:
837
+ return {"files": 0, "symbols": 0, "text_files": 0}
838
+ return {"files": int(files or 0), "symbols": int(symbols or 0), "text_files": int(texts or 0)}
839
+
840
+ def age_seconds(self) -> Optional[float]:
841
+ try:
842
+ con = self._connect()
843
+ try:
844
+ row = con.execute(
845
+ "SELECT val FROM graph_meta WHERE key = 'last_scanned'"
846
+ ).fetchone()
847
+ finally:
848
+ con.close()
849
+ except sqlite3.Error:
850
+ return None
851
+ if not row:
852
+ return None
853
+ try:
854
+ return max(0.0, time.time() - float(row[0]))
855
+ except (TypeError, ValueError):
856
+ return None
857
+
858
+ # ------------------------------------------------------------- retention
859
+ @classmethod
860
+ def prune(
861
+ cls,
862
+ keep_path: Optional[str] = None,
863
+ max_age_days: float = 30.0,
864
+ max_mb: Optional[int] = None,
865
+ ) -> Dict[str, int]:
866
+ """Bounds ``data/index`` and removes migrated legacy directories."""
867
+ data_dir = resolve_data_dir()
868
+ removed = 0
869
+ freed = 0
870
+ try:
871
+ if max_mb is None:
872
+ max_mb = int(os.environ.get("TOKENSAFE_INDEX_MAX_MB", "2048"))
873
+ except ValueError:
874
+ max_mb = 2048
875
+ index_dir = os.path.join(data_dir, "index")
876
+ marker = os.path.join(index_dir, ".pruned")
877
+ try:
878
+ if time.time() - os.path.getmtime(marker) < 3600:
879
+ _prune_legacy_dirs(data_dir, keep_path, max_age_days)
880
+ return {"removed": 0, "freed_bytes": 0}
881
+ except OSError:
882
+ pass
883
+ try:
884
+ keep_abs = os.path.abspath(keep_path) if keep_path else ""
885
+ now = time.time()
886
+ entries: List[Tuple[float, int, str]] = []
887
+ total = 0
888
+ for name in os.listdir(index_dir):
889
+ if not name.endswith(".db"):
890
+ continue
891
+ path = os.path.join(index_dir, name)
892
+ try:
893
+ st = os.stat(path)
894
+ except OSError:
895
+ continue
896
+ entries.append((st.st_mtime, st.st_size, path))
897
+ total += st.st_size
898
+ entries.sort(reverse=True)
899
+ for idx, (mtime, size, path) in enumerate(entries):
900
+ if os.path.abspath(path) == keep_abs or (now - mtime) < 3600:
901
+ continue
902
+ too_old = (now - mtime) > max_age_days * 86400
903
+ over_cap = idx >= 400
904
+ over_bytes = total > max_mb * 1024 * 1024
905
+ if not (too_old or over_cap or over_bytes):
906
+ continue
907
+ _unlink_db(path)
908
+ total -= size
909
+ removed += 1
910
+ freed += size
911
+ os.makedirs(index_dir, exist_ok=True)
912
+ with open(marker, "w", encoding="utf-8") as fh:
913
+ fh.write(str(int(now)))
914
+ except OSError:
915
+ pass
916
+ _prune_legacy_dirs(data_dir, keep_path, max_age_days)
917
+ return {"removed": removed, "freed_bytes": freed}
918
+
919
+
920
+ def _graph_schema_version() -> str:
921
+ try:
922
+ from src.graph_engine import _CACHE_SCHEMA_VERSION
923
+
924
+ return str(_CACHE_SCHEMA_VERSION)
925
+ except Exception:
926
+ return "0"
927
+
928
+
929
+ def _prune_legacy_dirs(data_dir: str, keep_path: Optional[str], max_age_days: float = 30.0) -> None:
930
+ """Deletes pre-kernel cache files that have not been touched in a month.
931
+
932
+ Files are deleted by age, never wholesale: a root whose owner has not run
933
+ a graph tool since the upgrade still has its legacy cache available for
934
+ ``ContextIndex.migrate_legacy`` to import on first use.
935
+ """
936
+ now = time.time()
937
+ for sub, suffix in (("graph_cache", ".db"), (os.path.join("cache", "fts"), ".db")):
938
+ directory = os.path.join(data_dir, sub)
939
+ try:
940
+ names = os.listdir(directory)
941
+ except OSError:
942
+ continue
943
+ for name in names:
944
+ if not name.endswith(suffix):
945
+ continue
946
+ path = os.path.join(directory, name)
947
+ if keep_path and os.path.abspath(path) == os.path.abspath(keep_path):
948
+ continue
949
+ try:
950
+ if now - os.path.getmtime(path) < max_age_days * 86400:
951
+ continue
952
+ except OSError:
953
+ continue
954
+ _unlink_db(path)