tokensafe 4.16.3 → 5.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.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +1 -1
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2487
  26. package/src/mcp_server.py +11 -5437
  27. package/src/proxy.py +11 -1834
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +21 -18
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +51 -10
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +729 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/{src → tokensafe}/ingress_staging.py +9 -9
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5668 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/{src → tokensafe}/read_baseline.py +1 -1
  100. package/{src → tokensafe}/repo_compute.py +1 -1
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -26,10 +26,14 @@ import threading
26
26
  import time
27
27
  from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
28
28
 
29
- from src.paths import resolve_data_dir
29
+ from tokensafe.paths import resolve_data_dir
30
30
 
31
31
  #: Bumped only when the physical layout below changes incompatibly.
32
- INDEX_SCHEMA_VERSION = 1
32
+ #: v2: ``code_line_spans`` maps each file to the rowid range of its
33
+ #: ``code_lines`` rows, plus ``rel_path`` indexes on the per-file tables.
34
+ #: ``_schema_ok`` requires the span table, so a v1 index runs
35
+ #: ``_create_schema`` once and gets its spans derived from the existing rows.
36
+ INDEX_SCHEMA_VERSION = 2
33
37
 
34
38
  _GRAPH_TABLES = (
35
39
  "graph_meta",
@@ -143,6 +147,139 @@ def legacy_fts_db_path(root: str) -> str:
143
147
  return os.path.join(base, f"fts_{_root_key(root)}.db")
144
148
 
145
149
 
150
+ # --------------------------------------------------------------------------
151
+ # Line corpus rowid spans.
152
+ #
153
+ # FTS5 columns are not B-tree indexed, so ``DELETE FROM code_lines WHERE
154
+ # rel_path = ?`` scans the whole corpus: re-indexing N files cost O(N x corpus).
155
+ # Every writer instead gives a file's lines one contiguous, explicitly assigned
156
+ # rowid range and records it in ``code_line_spans``; a per-file delete is then a
157
+ # rowid range delete (an FTS5 index lookup). The rowids are the ones FTS5 would
158
+ # have picked itself (max + 1 upwards), so ranking ties order as before.
159
+ # An empty file gets an empty span (hi < lo) so it is never mistaken for rows
160
+ # written by an older writer, which still take the full-scan delete.
161
+ # --------------------------------------------------------------------------
162
+
163
+ _SPANS_DDL = (
164
+ "CREATE TABLE IF NOT EXISTS code_line_spans "
165
+ "(rel_path TEXT PRIMARY KEY, lo INTEGER NOT NULL, hi INTEGER NOT NULL)"
166
+ )
167
+
168
+
169
+ def _begin_write(cur: sqlite3.Cursor) -> None:
170
+ """Holds the write lock before span lookups and rowid allocation.
171
+
172
+ Python only opens a transaction at the first DML statement, so a SELECT run
173
+ first could read a span or the top rowid that another writer changes before
174
+ our DELETE/INSERT. ``BEGIN IMMEDIATE`` closes that window; ``with con``
175
+ commits it as usual.
176
+ """
177
+ if not cur.connection.in_transaction:
178
+ cur.execute("BEGIN IMMEDIATE")
179
+
180
+
181
+ def _ensure_line_spans(con: sqlite3.Connection) -> None:
182
+ """Creates ``code_line_spans``; on an existing corpus derives it once."""
183
+ existed = con.execute(
184
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='code_line_spans'"
185
+ ).fetchone()
186
+ con.execute(_SPANS_DDL)
187
+ if not existed:
188
+ _rebuild_line_spans(con)
189
+
190
+
191
+ def _rebuild_line_spans(con: sqlite3.Connection) -> None:
192
+ """Recomputes every span from the rows (migration / legacy import).
193
+
194
+ A file whose rows are not one contiguous rowid block is dropped from the
195
+ corpus together with its ``file_meta`` row, so the next sync re-indexes it
196
+ under the span scheme instead of leaving rows a range delete would miss.
197
+ """
198
+ has_lines = con.execute(
199
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='code_lines'"
200
+ ).fetchone()
201
+ if not has_lines:
202
+ return
203
+ con.execute("DELETE FROM code_line_spans")
204
+ groups = con.execute(
205
+ "SELECT rel_path, MIN(rowid), MAX(rowid), COUNT(*) FROM code_lines GROUP BY rel_path"
206
+ ).fetchall()
207
+ spans: List[Tuple[str, int, int]] = []
208
+ broken: List[str] = []
209
+ for rel_path, lo, hi, count in groups:
210
+ # count == width means every rowid in [lo, hi] belongs to this file.
211
+ if int(count) == int(hi) - int(lo) + 1:
212
+ spans.append((rel_path, int(lo), int(hi)))
213
+ else:
214
+ broken.append(rel_path)
215
+ for rel_path in broken:
216
+ con.execute("DELETE FROM code_lines WHERE rel_path = ?", (rel_path,))
217
+ con.execute("DELETE FROM file_meta WHERE rel_path = ?", (rel_path,))
218
+ con.executemany(
219
+ "INSERT OR REPLACE INTO code_line_spans (rel_path, lo, hi) VALUES (?, ?, ?)", spans
220
+ )
221
+ # Indexed files with no non-blank lines own no rows: record empty spans.
222
+ con.execute(
223
+ "INSERT OR IGNORE INTO code_line_spans (rel_path, lo, hi) "
224
+ "SELECT rel_path, 0, -1 FROM file_meta"
225
+ )
226
+
227
+
228
+ def delete_line_rows(cur: sqlite3.Cursor, rel_path: str) -> None:
229
+ """Removes a file's ``code_lines`` rows (call before its ``file_meta`` row)."""
230
+ _begin_write(cur)
231
+ span = cur.execute(
232
+ "SELECT lo, hi FROM code_line_spans WHERE rel_path = ?", (rel_path,)
233
+ ).fetchone()
234
+ if span is None:
235
+ # No span: either never indexed (nothing to delete) or indexed by an
236
+ # older writer that kept no span -- only then pay for the full scan.
237
+ known = cur.execute(
238
+ "SELECT 1 FROM file_meta WHERE rel_path = ?", (rel_path,)
239
+ ).fetchone()
240
+ if known:
241
+ cur.execute("DELETE FROM code_lines WHERE rel_path = ?", (rel_path,))
242
+ return
243
+ cur.execute("DELETE FROM code_line_spans WHERE rel_path = ?", (rel_path,))
244
+ lo, hi = int(span[0]), int(span[1])
245
+ if hi < lo:
246
+ return
247
+ # The rel_path filter keeps a stale span from touching another file's rows.
248
+ cur.execute(
249
+ "DELETE FROM code_lines WHERE rowid BETWEEN ? AND ? AND rel_path = ?",
250
+ (lo, hi, rel_path),
251
+ )
252
+ if cur.rowcount != hi - lo + 1:
253
+ # Rows were rewritten outside the span map (an older writer): fall back.
254
+ cur.execute("DELETE FROM code_lines WHERE rel_path = ?", (rel_path,))
255
+
256
+
257
+ def insert_line_rows(
258
+ cur: sqlite3.Cursor, rel_path: str, rows: List[Tuple[str, int, str]]
259
+ ) -> None:
260
+ """Inserts ``(rel_path, line_no, content)`` rows as one contiguous span.
261
+
262
+ Call after ``delete_line_rows`` for the same file.
263
+ """
264
+ _begin_write(cur)
265
+ if not rows:
266
+ cur.execute(
267
+ "INSERT OR REPLACE INTO code_line_spans (rel_path, lo, hi) VALUES (?, 0, -1)",
268
+ (rel_path,),
269
+ )
270
+ return
271
+ top = cur.execute("SELECT rowid FROM code_lines ORDER BY rowid DESC LIMIT 1").fetchone()
272
+ lo = (int(top[0]) if top else 0) + 1
273
+ cur.executemany(
274
+ "INSERT INTO code_lines (rowid, rel_path, line_no, content) VALUES (?, ?, ?, ?)",
275
+ [(lo + i, row[0], row[1], row[2]) for i, row in enumerate(rows)],
276
+ )
277
+ cur.execute(
278
+ "INSERT OR REPLACE INTO code_line_spans (rel_path, lo, hi) VALUES (?, ?, ?)",
279
+ (rel_path, lo, lo + len(rows) - 1),
280
+ )
281
+
282
+
146
283
  def _unlink_db(path: str) -> None:
147
284
  for suffix in ("", "-wal", "-shm"):
148
285
  try:
@@ -190,9 +327,9 @@ class ContextIndex:
190
327
  ).fetchone()
191
328
  tables = con.execute(
192
329
  "SELECT name FROM sqlite_master WHERE type='table' "
193
- "AND name IN ('symbols', 'file_meta', 'code_lines')"
330
+ "AND name IN ('symbols', 'file_meta', 'code_lines', 'code_line_spans')"
194
331
  ).fetchall()
195
- return bool(row) and len(tables) == 3
332
+ return bool(row) and len(tables) == 4
196
333
  except sqlite3.Error:
197
334
  return False
198
335
  finally:
@@ -238,9 +375,15 @@ class ContextIndex:
238
375
  try:
239
376
  con.execute("CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name)")
240
377
  con.execute("CREATE INDEX IF NOT EXISTS idx_endpoints_route ON api_endpoints(route)")
378
+ # Per-file deletes on tables whose key does not lead with rel_path.
379
+ con.execute("CREATE INDEX IF NOT EXISTS idx_symbols_rel_path ON symbols(rel_path)")
380
+ con.execute("CREATE INDEX IF NOT EXISTS idx_endpoints_rel_path ON api_endpoints(rel_path)")
381
+ con.execute("CREATE INDEX IF NOT EXISTS idx_api_calls_rel_path ON api_calls(rel_path)")
382
+ con.execute("CREATE INDEX IF NOT EXISTS idx_file_mounts_rel_path ON file_mounts(rel_path)")
241
383
  except sqlite3.Error:
242
384
  pass
243
385
  self._create_fts(con)
386
+ _ensure_line_spans(con)
244
387
  finally:
245
388
  con.close()
246
389
 
@@ -332,7 +475,16 @@ class ContextIndex:
332
475
  return True
333
476
 
334
477
  def _import_fts(self, legacy_path: str) -> bool:
335
- return self._copy_legacy(legacy_path, _LEGACY_TEXT_TABLES)
478
+ if not self._copy_legacy(legacy_path, _LEGACY_TEXT_TABLES):
479
+ return False
480
+ # Copied rows carry no spans yet.
481
+ con = self._connect()
482
+ try:
483
+ with con:
484
+ _rebuild_line_spans(con)
485
+ finally:
486
+ con.close()
487
+ return True
336
488
 
337
489
  # -------------------------------------------------------- graph persistence
338
490
  @staticmethod
@@ -400,15 +552,22 @@ class ContextIndex:
400
552
  graph: Any,
401
553
  changed: Optional[Iterable[str]] = None,
402
554
  deleted: Optional[Iterable[str]] = None,
555
+ edge_sources: Optional[Iterable[str]] = None,
403
556
  ) -> None:
404
557
  """Persists graph rows. ``changed=None`` means a full rewrite.
405
558
 
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.
559
+ Per-file tables are written incrementally for ``changed``/``deleted``.
560
+ ``edges`` is keyed by source node: with ``edge_sources`` (every source
561
+ whose outgoing set changed since the last save, whatever file it lives
562
+ in -- import resolution and API linking touch unchanged files too) only
563
+ those sources' rows are replaced; without it, or on a full rewrite, the
564
+ table is rewritten. ``api_links`` is always replaced wholesale.
409
565
  """
410
566
  changed_set: Optional[Set[str]] = None if changed is None else set(changed)
411
567
  deleted_set: Set[str] = set(deleted or ())
568
+ edge_set: Optional[Set[str]] = (
569
+ None if (changed_set is None or edge_sources is None) else set(edge_sources)
570
+ )
412
571
  con = self._connect()
413
572
  try:
414
573
  with con:
@@ -423,11 +582,25 @@ class ContextIndex:
423
582
  self._delete_file_rows(cur, rel_path)
424
583
  for rel_path in changed_set - deleted_set:
425
584
  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
- )
585
+ if edge_set is None:
586
+ cur.execute("DELETE FROM edges")
587
+ cur.executemany(
588
+ "INSERT OR IGNORE INTO edges (source, target) VALUES (?, ?)",
589
+ [(src, tgt) for src, tgts in graph.edges.items() for tgt in tgts],
590
+ )
591
+ elif edge_set:
592
+ # (source, target) primary key: a per-source delete is an index range.
593
+ cur.executemany(
594
+ "DELETE FROM edges WHERE source = ?", [(src,) for src in edge_set]
595
+ )
596
+ cur.executemany(
597
+ "INSERT OR IGNORE INTO edges (source, target) VALUES (?, ?)",
598
+ [
599
+ (src, tgt)
600
+ for src in edge_set
601
+ for tgt in graph.edges.get(src, ())
602
+ ],
603
+ )
431
604
  cur.execute("DELETE FROM api_links")
432
605
  cur.executemany(
433
606
  "INSERT INTO api_links (link_json) VALUES (?)",
@@ -524,12 +697,8 @@ class ContextIndex:
524
697
  for idx, line in enumerate(lines)
525
698
  if line.strip() and len(line) <= _TEXT_LINE_SKIP_OVER
526
699
  ]
527
- if batch:
528
- cur.executemany(
529
- "INSERT INTO code_lines (rel_path, line_no, content) VALUES (?, ?, ?)",
530
- batch,
531
- )
532
- indexed += len(batch)
700
+ insert_line_rows(cur, rel_path, batch)
701
+ indexed += len(batch)
533
702
  cur.execute(
534
703
  "INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?)",
535
704
  (rel_path, st.st_mtime, st.st_size),
@@ -540,7 +709,7 @@ class ContextIndex:
540
709
 
541
710
  @staticmethod
542
711
  def _delete_text_rows(cur: sqlite3.Cursor, rel_path: str) -> None:
543
- cur.execute("DELETE FROM code_lines WHERE rel_path = ?", (rel_path,))
712
+ delete_line_rows(cur, rel_path)
544
713
  cur.execute("DELETE FROM file_meta WHERE rel_path = ?", (rel_path,))
545
714
 
546
715
  def index_text_files(
@@ -551,7 +720,7 @@ class ContextIndex:
551
720
  Preserves the FTS semantics: the per-run cap bounds indexing work, not
552
721
  the walk, so files beyond the cap are never mistaken for deleted ones.
553
722
  """
554
- from src.fts_index import CODE_EXTS, IGNORED_DIRS, IGNORED_EXTS
723
+ from tokensafe.fts_index import CODE_EXTS, IGNORED_DIRS, IGNORED_EXTS
555
724
 
556
725
  t0 = time.time()
557
726
  scanned_files = 0
@@ -606,12 +775,8 @@ class ContextIndex:
606
775
  for idx, line in enumerate(lines)
607
776
  if line.strip() and len(line) <= _TEXT_LINE_SKIP_OVER
608
777
  ]
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)
778
+ insert_line_rows(cur, rel_path, batch)
779
+ indexed_lines += len(batch)
615
780
  cur.execute(
616
781
  "INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?)",
617
782
  (rel_path, f_mtime, f_size),
@@ -741,6 +906,7 @@ class ContextIndex:
741
906
  try:
742
907
  with con:
743
908
  con.execute("DELETE FROM code_lines")
909
+ con.execute("DELETE FROM code_line_spans")
744
910
  con.execute("DELETE FROM file_meta")
745
911
  finally:
746
912
  con.close()
@@ -919,7 +1085,7 @@ class ContextIndex:
919
1085
 
920
1086
  def _graph_schema_version() -> str:
921
1087
  try:
922
- from src.graph_engine import _CACHE_SCHEMA_VERSION
1088
+ from tokensafe.graph_engine import _CACHE_SCHEMA_VERSION
923
1089
 
924
1090
  return str(_CACHE_SCHEMA_VERSION)
925
1091
  except Exception:
@@ -35,8 +35,8 @@ def build_unified_graph(
35
35
  fe / be: live runtime descriptors from OUMVGateway.get_endpoints().
36
36
  rpc_call: callable(url, method, params) used to observe live surfaces.
37
37
  """
38
- from src.graph_engine import GraphEngine
39
- from src.paths import get_active_workspace
38
+ from tokensafe.graph_engine import GraphEngine
39
+ from tokensafe.paths import get_active_workspace
40
40
 
41
41
  ws = workspace_dir or get_active_workspace()
42
42
  static = GraphEngine.get_instance(ws)
@@ -14,10 +14,10 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
14
  if BASE_DIR not in sys.path:
15
15
  sys.path.insert(0, BASE_DIR)
16
16
 
17
- from src.metrics import MetricsTracker
18
- from src.license_manager import LicenseManager
17
+ from tokensafe.metrics import MetricsTracker
18
+ from tokensafe.license_manager import LicenseManager
19
19
  try:
20
- from src.version_checker import VersionChecker
20
+ from tokensafe.version_checker import VersionChecker
21
21
  except ImportError:
22
22
  VersionChecker = None
23
23
 
@@ -26,7 +26,7 @@ _AGENT_TOOL_NAMES = {"task", "agent", "subagent", "dispatch_agent", "delegate",
26
26
 
27
27
 
28
28
  def digest_path(session_id: str) -> str:
29
- from src.paths import resolve_data_dir
29
+ from tokensafe.paths import resolve_data_dir
30
30
  import hashlib
31
31
 
32
32
  digest = hashlib.sha256(str(session_id or "").encode("utf-8")).hexdigest()[:16]
@@ -143,7 +143,7 @@ def build_digest(child_transcript: str) -> Dict[str, Any]:
143
143
  """Folds the child rollout into a State Ledger plus the files it read."""
144
144
  digest = ""
145
145
  try:
146
- from src.history_compactor import HistoryCompactor
146
+ from tokensafe.history_compactor import HistoryCompactor
147
147
 
148
148
  ledger, _orig, _folded, _stats = HistoryCompactor.fold_transcript(child_transcript, 3)
149
149
  digest = str(ledger or "").strip()
@@ -160,7 +160,7 @@ def build_digest(child_transcript: str) -> Dict[str, Any]:
160
160
 
161
161
 
162
162
  def _write_atomic(path: str, text: str) -> None:
163
- from src.atomic_io import write_text_atomic
163
+ from tokensafe.atomic_io import write_text_atomic
164
164
 
165
165
  os.makedirs(os.path.dirname(path), exist_ok=True)
166
166
  write_text_atomic(path, text)
@@ -197,7 +197,7 @@ def seed_cache(session_id: str, files: List[str], tracker: Any = None) -> int:
197
197
  if not files:
198
198
  return 0
199
199
  try:
200
- from src.agent_firewall import AgentFirewall
200
+ from tokensafe.agent_firewall import AgentFirewall
201
201
 
202
202
  seeded = 0
203
203
  for path in files[:_MAX_SEED_FILES]:
@@ -8,7 +8,7 @@ import os
8
8
  import re
9
9
  import ast
10
10
  from typing import List, Dict, Tuple, Optional, Any
11
- from src.tokenizer import count_tokens
11
+ from tokensafe.tokenizer import count_tokens
12
12
 
13
13
  class DependencyPrefetcher:
14
14
  """Extracts and formats signatures of local relative imported dependencies."""
@@ -9,7 +9,7 @@ Optimizes git diff outputs and code diff streams before ingestion into agent con
9
9
 
10
10
  import re
11
11
  from typing import Tuple, List, Dict, Any, Optional
12
- from src.tokenizer import count_tokens
12
+ from tokensafe.tokenizer import count_tokens
13
13
 
14
14
  class DiffSlicer:
15
15
  """Slices and compresses code diffs."""
@@ -122,7 +122,7 @@ class DiffSlicer:
122
122
  if not re.search(r"\bgit\s+(?:-C\s+\S+\s+)?diff\b", clean_cmd):
123
123
  return None, 0, ""
124
124
 
125
- from src.command_sanitizer import CommandSanitizer
125
+ from tokensafe.command_sanitizer import CommandSanitizer
126
126
  pairs = CommandSanitizer.split_stages(clean_cmd)
127
127
  lockfile_excludes = " ':!*lock*' ':!*.min.*' ':!*.map'"
128
128
  changed = False
@@ -13,9 +13,9 @@ import time
13
13
  import urllib.request
14
14
  import urllib.error
15
15
  from typing import Optional, Dict, Any, Tuple
16
- from src.distiller_cache import DistillationCache
17
- from src.license_manager import LicenseManager
18
- from src.paths import resolve_data_dir
16
+ from tokensafe.distiller_cache import DistillationCache
17
+ from tokensafe.license_manager import LicenseManager
18
+ from tokensafe.paths import resolve_data_dir
19
19
 
20
20
  class UniversalDistiller:
21
21
  """Managed-cloud-first semantic intent compiler: TokenSafe Cloud (zero keys) with optional BYOK DeepSeek, OpenAI, and Google Gemini."""
@@ -160,9 +160,9 @@ Rules:
160
160
 
161
161
  @classmethod
162
162
  def _call_cloud_distill(cls, raw_text: str, lic_key: str, mode: str = "") -> Optional[str]:
163
- from src.secret_redactor import SecretRedactor
164
- from src.egress_counter import increment as _egress_increment
165
- from src.version_checker import CURRENT_VERSION
163
+ from tokensafe.secret_redactor import SecretRedactor
164
+ from tokensafe.egress_counter import increment as _egress_increment
165
+ from tokensafe.version_checker import CURRENT_VERSION
166
166
  cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
167
167
  endpoint = f"{cloud_url}/api/distill"
168
168
  # Egress hygiene: scrub secrets from whatever leaves this machine. Idempotent
@@ -182,7 +182,7 @@ Rules:
182
182
  }
183
183
  )
184
184
  try:
185
- from src.ssl_context import shared_ssl_context
185
+ from tokensafe.ssl_context import shared_ssl_context
186
186
  _egress_increment("booster")
187
187
  ssl_ctx = shared_ssl_context()
188
188
  try:
@@ -12,7 +12,7 @@ import threading
12
12
  from collections import OrderedDict
13
13
  from datetime import datetime
14
14
  from typing import Optional, Dict, Any, Tuple
15
- from src.paths import resolve_data_dir
15
+ from tokensafe.paths import resolve_data_dir
16
16
 
17
17
 
18
18
  _COMBINED_SLOT_RE = re.compile(
@@ -267,7 +267,7 @@ class DistillationCache:
267
267
 
268
268
  # 4. Check L3 Shared Team Cache (exact, then parametric template)
269
269
  try:
270
- from src.team_cache import TeamCache
270
+ from tokensafe.team_cache import TeamCache
271
271
  team_val = TeamCache.get("PROMPT", prompt_text)
272
272
  if team_val:
273
273
  cls.set(prompt_text, team_val, provider="team_cache", sync_remote=False)
@@ -366,7 +366,7 @@ class DistillationCache:
366
366
  # 4. Broadcast to L3 Shared Team Cache (Asynchronous)
367
367
  if sync_remote:
368
368
  try:
369
- from src.team_cache import TeamCache
369
+ from tokensafe.team_cache import TeamCache
370
370
  TeamCache.put("PROMPT", prompt_text, clean_distilled, tokens_saved=45)
371
371
  if tmpl_hash and tmpl_sexpr:
372
372
  TeamCache.put("PROMPT_TMPL", tmpl_prompt, tmpl_sexpr, tokens_saved=45)
@@ -16,7 +16,7 @@ import os
16
16
  import threading
17
17
  from typing import Dict
18
18
 
19
- from src.paths import resolve_data_dir
19
+ from tokensafe.paths import resolve_data_dir
20
20
 
21
21
  _LOCK = threading.Lock()
22
22
  KINDS = ("booster", "telemetry")
@@ -13,7 +13,7 @@ import hashlib
13
13
  import shutil
14
14
  from typing import Dict, List, Any, Optional, Tuple
15
15
 
16
- from src.tokenizer import count_tokens
16
+ from tokensafe.tokenizer import count_tokens
17
17
 
18
18
  EST_TOKENS_PER_TOOL = 25
19
19
  EST_TOKENS_PER_SKILL = 180
@@ -363,7 +363,7 @@ class EnvironmentAuditor:
363
363
 
364
364
  treesitter_info: Dict[str, Any] = {"available": False, "active": 0, "total": 0, "missing": []}
365
365
  try:
366
- from src.treesitter_backend import TreeSitterBackend
366
+ from tokensafe.treesitter_backend import TreeSitterBackend
367
367
  ts_status = TreeSitterBackend.check_all_languages()
368
368
  ok_cnt = sum(1 for v in ts_status.values() if v)
369
369
  tot_cnt = len(ts_status)
@@ -635,7 +635,7 @@ class EnvironmentAuditor:
635
635
  skipped: List[str] = []
636
636
 
637
637
  try:
638
- from src.paths import resolve_data_dir
638
+ from tokensafe.paths import resolve_data_dir
639
639
  backup_base = resolve_data_dir()
640
640
  except Exception:
641
641
  backup_base = os.path.join(os.path.expanduser("~"), ".tokensafe", "data")
@@ -651,7 +651,7 @@ class EnvironmentAuditor:
651
651
  raw_bytes = fb.read()
652
652
  _, parse_err = _parse_codex_toml_servers(raw_bytes)
653
653
  orig_text = raw_bytes.decode("utf-8", errors="replace")
654
- from src.installer import AgentInstaller
654
+ from tokensafe.installer import AgentInstaller
655
655
  if parse_err or AgentInstaller._CODEX_ORPHAN_LINE_RE.search(orig_text):
656
656
  shutil.copy2(p, f"{p}.backup")
657
657
  cleaned = AgentInstaller._clean_codex_orphans(orig_text)
@@ -732,7 +732,7 @@ class EnvironmentAuditor:
732
732
 
733
733
  # 4. Cleanup conflicting competitor hooks/rules
734
734
  try:
735
- from src.competitors import CompetitorAuditor
735
+ from tokensafe.competitors import CompetitorAuditor
736
736
  for c in CompetitorAuditor.audit():
737
737
  res = CompetitorAuditor.cleanup(c["id"])
738
738
  if res.get("removed"):
@@ -875,8 +875,8 @@ class EnvironmentAuditor:
875
875
  q_score: Dict[str, Any] = {}
876
876
  score_line = ""
877
877
  try:
878
- from src.quality_score import ContextQualityScore
879
- from src.governor import ContextBudget
878
+ from tokensafe.quality_score import ContextQualityScore
879
+ from tokensafe.governor import ContextBudget
880
880
  window = ContextBudget.resolve_window()
881
881
  static_overhead = (
882
882
  int(report.get("total_static_tokens_per_turn", 0) or 0)
@@ -26,8 +26,8 @@ import hashlib
26
26
  import tempfile
27
27
  from typing import Any, Dict, Optional
28
28
 
29
- from src.paths import resolve_data_dir
30
- from src.win_paths import state_key
29
+ from tokensafe.paths import resolve_data_dir
30
+ from tokensafe.win_paths import state_key
31
31
 
32
32
  STATE_FILENAME = "file_state.json"
33
33
  _MAX_ENTRIES = 512
@@ -133,7 +133,7 @@ def ensure_recovery(raw: str, compacted: str, kind: Optional[str] = None) -> str
133
133
  if kind not in _LOSSY_KINDS:
134
134
  return compacted
135
135
  try:
136
- from src.stash import stash_block
136
+ from tokensafe.stash import stash_block
137
137
 
138
138
  _hash8, marker = stash_block(raw, source=f"compact:{kind}")
139
139
  if not marker:
@@ -0,0 +1,20 @@
1
+ """
2
+ TokenSafe Format Parsers & Reducers package.
3
+ """
4
+
5
+ from tokensafe.format_parsers.compiler_errors import CompilerErrorCompactor
6
+ from tokensafe.format_parsers.lockfiles import LockfileReducer
7
+ from tokensafe.format_parsers.tabular import TabularReducer
8
+ from tokensafe.format_parsers.json_log import JSONLogReducer
9
+ from tokensafe.format_parsers.docker_k8s import ContainerAndK8sReducer
10
+ from tokensafe.format_parsers.ansi import strip_ansi, has_ansi
11
+
12
+ __all__ = [
13
+ "CompilerErrorCompactor",
14
+ "LockfileReducer",
15
+ "TabularReducer",
16
+ "JSONLogReducer",
17
+ "ContainerAndK8sReducer",
18
+ "strip_ansi",
19
+ "has_ansi",
20
+ ]
@@ -11,8 +11,8 @@ Specialized compactor for:
11
11
 
12
12
  import re
13
13
  from typing import Dict, Any, List, Tuple, Optional
14
- from src.stash import stash_block
15
- from src.format_parsers.ansi import strip_ansi
14
+ from tokensafe.stash import stash_block
15
+ from tokensafe.format_parsers.ansi import strip_ansi
16
16
 
17
17
  # Regex patterns for tsc output:
18
18
  # Format A: src/file.ts(12,5): error TS2322: Type 'x' is not assignable...
@@ -6,7 +6,7 @@ Compacts verbose container logs, Docker build steps, and multi-resource Kubernet
6
6
 
7
7
  import re
8
8
  from typing import Tuple, Dict, Any, List
9
- from src.stash import stash_block
9
+ from tokensafe.stash import stash_block
10
10
 
11
11
 
12
12
  class ContainerAndK8sReducer: