tokensafe 5.0.1 → 5.0.2

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 (53) 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/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1078 -186
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -27,12 +27,31 @@ import sqlite3
27
27
  import stat
28
28
  import threading
29
29
  import time
30
+ from contextlib import contextmanager
30
31
  from typing import Dict, Set, List, Optional, Tuple, Any
31
32
 
33
+ from tokensafe.call_context import check_cancelled
32
34
  from tokensafe.paths import resolve_data_dir
33
35
  from tokensafe.context_index import ContextIndex, index_db_path, legacy_graph_db_path
34
36
  from tokensafe.globmatch import GlobPatternError, compile_patterns, matches_any, split_negations
35
37
 
38
+
39
+ def _is_unbounded_root(path: str) -> bool:
40
+ """True for a directory that is never a project: the OS scratch dir itself,
41
+ the user's home, or a filesystem/system root. find_project_root falls back to
42
+ a marker-less file's own directory, and a recursive walk of e.g. the macOS
43
+ temp dir (tens of thousands of entries) or ~ ran for many minutes."""
44
+ try:
45
+ from tokensafe.win_paths import is_system_root, transient_roots
46
+ real = os.path.realpath(path)
47
+ if is_system_root(real):
48
+ return True
49
+ return any(real == os.path.realpath(r) for r in transient_roots())
50
+ except Exception:
51
+ return False
52
+
53
+ _PROJECT_MARKERS = (".git", "package.json", "pyproject.toml", "go.mod", "Cargo.toml", "requirements.txt")
54
+
36
55
  IGNORED_DIRS = {
37
56
  ".git", ".hg", ".svn", "node_modules", "dist", "build", "venv", ".venv",
38
57
  "__pycache__", ".idea", ".vscode", "data", "coverage", ".pytest_cache",
@@ -756,6 +775,56 @@ class CodeSymbol:
756
775
  )
757
776
 
758
777
 
778
+ _GRAPH_STATE_FIELDS = (
779
+ "symbols", "file_symbols", "edges", "rev_edges", "file_mtimes", "file_stats",
780
+ "file_imports", "glob_imports", "file_endpoints", "file_api_calls",
781
+ "file_mounts", "api_links",
782
+ )
783
+
784
+
785
+ class _GraphState:
786
+ """One graph version: every container a reader may combine.
787
+
788
+ A published version is never mutated again. Holding all containers in one
789
+ object makes publishing a single attribute store (see CodeGraph._adopt), so
790
+ a reader that pins a version sees `symbols`, `file_symbols`, `edges`, ...
791
+ from the same scan, never `file_symbols` of the new version with
792
+ `symbols` of the old one (a renamed function's key then raised KeyError).
793
+ """
794
+ __slots__ = _GRAPH_STATE_FIELDS
795
+
796
+
797
+ def _graph_state_property(name: str) -> property:
798
+ def fget(self):
799
+ pinned = getattr(self._pin, "state", None)
800
+ return getattr(pinned if pinned is not None else self._state, name)
801
+
802
+ def fset(self, value):
803
+ # Writers only build unpublished versions (construction, or a fork).
804
+ setattr(self._state, name, value)
805
+
806
+ return property(fget, fset, doc=f"`{name}` of the pinned (else current) graph version.")
807
+
808
+
809
+ def _reads_snapshot(fn):
810
+ """Runs a reader against one pinned graph version (reentrant, per thread)."""
811
+ import functools
812
+
813
+ @functools.wraps(fn)
814
+ def wrapper(self, *args, **kwargs):
815
+ pin = self._pin
816
+ if getattr(pin, "state", None) is not None:
817
+ return fn(self, *args, **kwargs)
818
+ pin.state = self._state
819
+ try:
820
+ return fn(self, *args, **kwargs)
821
+ finally:
822
+ pin.state = None
823
+
824
+ wrapper.__tokensafe_snapshot__ = True
825
+ return wrapper
826
+
827
+
759
828
  class CodeGraph:
760
829
  """
761
830
  Deterministic In-Memory Knowledge Graph of a software repository.
@@ -766,6 +835,9 @@ class CodeGraph:
766
835
  def __init__(self, root_dir: str = ".", use_disk_cache: bool = False):
767
836
  self.root_dir = os.path.abspath(root_dir)
768
837
  self.use_disk_cache = use_disk_cache
838
+ # Graph containers live in one version object; readers pin it per call.
839
+ self._state = _GraphState()
840
+ self._pin = threading.local()
769
841
  self.symbols: Dict[str, CodeSymbol] = {}
770
842
  self.file_symbols: Dict[str, List[str]] = {} # file_rel_path -> [symbol_keys]
771
843
  self.edges: Dict[str, Set[str]] = {} # caller/importer -> set(callees/imported)
@@ -1034,11 +1106,26 @@ class CodeGraph:
1034
1106
 
1035
1107
  # Containers that together form one graph version. A rescan builds the next
1036
1108
  # version in copies of these and swaps them in at once (see `scan`).
1037
- _GRAPH_STATE_ATTRS = (
1038
- "symbols", "file_symbols", "edges", "rev_edges", "file_mtimes", "file_stats",
1039
- "file_imports", "glob_imports", "file_endpoints", "file_api_calls",
1040
- "file_mounts", "api_links",
1041
- )
1109
+ _GRAPH_STATE_ATTRS = _GRAPH_STATE_FIELDS
1110
+
1111
+ @contextmanager
1112
+ def snapshot(self):
1113
+ """Pins the current graph version for this thread (reentrant).
1114
+
1115
+ Public readers pin automatically. Code outside this class that combines
1116
+ several containers (e.g. `file_symbols` keys looked up in `symbols`)
1117
+ wraps the sequence in `with graph.snapshot():` so a concurrent rescan
1118
+ cannot swap the version between two reads.
1119
+ """
1120
+ pin = self._pin
1121
+ if getattr(pin, "state", None) is not None:
1122
+ yield self
1123
+ return
1124
+ pin.state = self._state
1125
+ try:
1126
+ yield self
1127
+ finally:
1128
+ pin.state = None
1042
1129
 
1043
1130
  def _fork(self) -> "CodeGraph":
1044
1131
  """A private copy of the graph state that a rescan may mutate freely.
@@ -1046,20 +1133,25 @@ class CodeGraph:
1046
1133
  Symbols are shared: a rescan never mutates an existing CodeSymbol, it
1047
1134
  replaces the entries of re-indexed files with new objects.
1048
1135
  """
1136
+ current = self._state
1049
1137
  work = copy.copy(self)
1050
- work.symbols = dict(self.symbols)
1138
+ # Own version and own pin: copy.copy shares both with `self`, and the
1139
+ # setters below would otherwise write into the published version.
1140
+ work._state = _GraphState()
1141
+ work._pin = threading.local()
1142
+ work.symbols = dict(current.symbols)
1051
1143
  work._sym_index = None
1052
- work.file_symbols = {k: list(v) for k, v in self.file_symbols.items()}
1053
- work.edges = {k: set(v) for k, v in self.edges.items()}
1054
- work.rev_edges = {k: set(v) for k, v in self.rev_edges.items()}
1055
- work.file_mtimes = dict(self.file_mtimes)
1056
- work.file_stats = dict(self.file_stats)
1057
- work.file_imports = {k: set(v) for k, v in self.file_imports.items()}
1058
- work.glob_imports = {k: set(v) for k, v in self.glob_imports.items()}
1059
- work.file_endpoints = {k: list(v) for k, v in self.file_endpoints.items()}
1060
- work.file_api_calls = {k: list(v) for k, v in self.file_api_calls.items()}
1061
- work.file_mounts = {k: list(v) for k, v in self.file_mounts.items()}
1062
- work.api_links = list(self.api_links)
1144
+ work.file_symbols = {k: list(v) for k, v in current.file_symbols.items()}
1145
+ work.edges = {k: set(v) for k, v in current.edges.items()}
1146
+ work.rev_edges = {k: set(v) for k, v in current.rev_edges.items()}
1147
+ work.file_mtimes = dict(current.file_mtimes)
1148
+ work.file_stats = dict(current.file_stats)
1149
+ work.file_imports = {k: set(v) for k, v in current.file_imports.items()}
1150
+ work.glob_imports = {k: set(v) for k, v in current.glob_imports.items()}
1151
+ work.file_endpoints = {k: list(v) for k, v in current.file_endpoints.items()}
1152
+ work.file_api_calls = {k: list(v) for k, v in current.file_api_calls.items()}
1153
+ work.file_mounts = {k: list(v) for k, v in current.file_mounts.items()}
1154
+ work.api_links = list(current.api_links)
1063
1155
  work._dirty_files = set(self._dirty_files)
1064
1156
  work._deleted_files = set(self._deleted_files)
1065
1157
  work._dirty_edge_sources = (
@@ -1070,13 +1162,14 @@ class CodeGraph:
1070
1162
  def _adopt(self, work: "CodeGraph") -> None:
1071
1163
  """Publishes a forked graph version in one step.
1072
1164
 
1073
- A single `__dict__.update` runs under the GIL without executing Python
1074
- code, so a reader sees either every old container or every new one; the
1075
- old containers are never mutated again, so an iteration that started on
1076
- them finishes on a consistent snapshot.
1165
+ Every container moves in one `_state` store, so a reader pinned to a
1166
+ version (public readers pin per call, see `snapshot`) keeps combining
1167
+ containers of that one version until it returns; the old version is
1168
+ never mutated again. The bookkeeping attributes are only read by the
1169
+ scan itself, under `_scan_mutex`.
1077
1170
  """
1078
- state = {name: getattr(work, name) for name in self._GRAPH_STATE_ATTRS}
1079
- state.update(
1171
+ state = dict(
1172
+ _state=work._state,
1080
1173
  backend=work.backend,
1081
1174
  last_scanned=work.last_scanned,
1082
1175
  _dirty_files=work._dirty_files,
@@ -1120,7 +1213,14 @@ class CodeGraph:
1120
1213
  to_index: List[Tuple[str, str, Tuple[float, int]]] = []
1121
1214
  to_drop: List[str] = []
1122
1215
  known = self.file_stats
1216
+ # Marker-less fallback roots (temp dir, ~, /) are indexed one level deep only.
1217
+ shallow = _is_unbounded_root(self.root_dir)
1123
1218
  for dirpath, dirnames, filenames in os.walk(self.root_dir):
1219
+ # A cancelled/timed-out tool call stops the crawl here (no-op outside
1220
+ # a tools/call); nothing has been published yet.
1221
+ check_cancelled()
1222
+ if shallow:
1223
+ dirnames[:] = []
1124
1224
  dirnames[:] = [
1125
1225
  d for d in dirnames
1126
1226
  if d not in IGNORED_DIRS and d not in _SNAPSHOT_DIRS and not d.startswith(".")
@@ -1171,8 +1271,16 @@ class CodeGraph:
1171
1271
  if is_system_root(self.root_dir):
1172
1272
  return 0
1173
1273
 
1174
- with self._scan_mutex:
1175
- return self._scan_locked(force)
1274
+ # A scan reads and publishes the newest version, even when this thread
1275
+ # is inside a reader that pinned an older one.
1276
+ pin = self._pin
1277
+ pinned = getattr(pin, "state", None)
1278
+ pin.state = None
1279
+ try:
1280
+ with self._scan_mutex:
1281
+ return self._scan_locked(force)
1282
+ finally:
1283
+ pin.state = pinned
1176
1284
 
1177
1285
  def _scan_locked(self, force: bool) -> int:
1178
1286
  backend = self._detect_backend()
@@ -1191,6 +1299,9 @@ class CodeGraph:
1191
1299
  self.last_scanned = time.time()
1192
1300
  return 0
1193
1301
 
1302
+ # Cancellation below discards `work` (a private fork): a cancelled scan
1303
+ # never publishes a partial version. No check runs after `_adopt`.
1304
+ check_cancelled()
1194
1305
  work = self._fork()
1195
1306
  work.backend = backend
1196
1307
  work._walked_files = current_files
@@ -1199,6 +1310,7 @@ class CodeGraph:
1199
1310
  work._drop_file(rel_path)
1200
1311
  reindexed += 1
1201
1312
  for full_path, rel_path, sig in to_index:
1313
+ check_cancelled()
1202
1314
  work._index_file(full_path, rel_path)
1203
1315
  work.file_stats[rel_path] = sig
1204
1316
  work.file_mtimes[rel_path] = sig[0]
@@ -1209,7 +1321,9 @@ class CodeGraph:
1209
1321
 
1210
1322
  if reindexed > 0 or stale or force:
1211
1323
  work._resolve_local_imports()
1324
+ check_cancelled()
1212
1325
  work._link_api_routes()
1326
+ check_cancelled()
1213
1327
 
1214
1328
  work.last_scanned = time.time()
1215
1329
  if work._dirty_edge_sources is not None:
@@ -1912,6 +2026,7 @@ class CodeGraph:
1912
2026
 
1913
2027
  ts_resolver = _TsPathResolver(self.root_dir)
1914
2028
  for rel_path, mods in self.file_imports.items():
2029
+ check_cancelled()
1915
2030
  src_node = f"file:{rel_path}"
1916
2031
  src_dir = os.path.dirname(rel_path)
1917
2032
  ext = os.path.splitext(rel_path)[1].lower()
@@ -1928,6 +2043,7 @@ class CodeGraph:
1928
2043
  # Expand `import.meta.glob` patterns last: the indexed file set is now
1929
2044
  # known, and brace patterns must be expanded rather than fnmatched.
1930
2045
  for rel_path, patterns in self.glob_imports.items():
2046
+ check_cancelled()
1931
2047
  src_node = f"file:{rel_path}"
1932
2048
  src_dir = os.path.dirname(rel_path)
1933
2049
  positive, negative = split_negations(patterns)
@@ -2413,6 +2529,7 @@ class CodeGraph:
2413
2529
 
2414
2530
  sections: List[Tuple[str, List[str]]] = []
2415
2531
  for rel_path, sym_keys in sorted(self.file_symbols.items()):
2532
+ check_cancelled() # cooperative: stops a cancelled/timed-out tools/call
2416
2533
  if not sym_keys or self._surface_skip_path(rel_path):
2417
2534
  continue
2418
2535
  sym_lines = []
@@ -3195,6 +3312,25 @@ class CodeGraph:
3195
3312
  }
3196
3313
 
3197
3314
 
3315
+ # Every public reader (and the private helpers other modules call) runs on one
3316
+ # pinned graph version. Writers (`scan`, indexing helpers) are left unwrapped.
3317
+ _SNAPSHOT_PRIVATE_READERS = (
3318
+ "_as_repo_rel", "_file_facts", "_suggest_targets", "_text_references",
3319
+ "_match_target_keys", "_resolve_callee_keys",
3320
+ )
3321
+ for _name, _member in list(vars(CodeGraph).items()):
3322
+ if not callable(_member) or isinstance(_member, (staticmethod, classmethod)):
3323
+ continue
3324
+ if _name in ("scan", "add_edge", "snapshot") or (
3325
+ _name.startswith("_") and _name not in _SNAPSHOT_PRIVATE_READERS
3326
+ ):
3327
+ continue
3328
+ setattr(CodeGraph, _name, _reads_snapshot(_member))
3329
+ for _name in _GRAPH_STATE_FIELDS:
3330
+ setattr(CodeGraph, _name, _graph_state_property(_name))
3331
+ del _name, _member
3332
+
3333
+
3198
3334
  class GraphEngine:
3199
3335
  """Multi-Project Manager for automatic background graph execution."""
3200
3336
 
@@ -3205,6 +3341,10 @@ class GraphEngine:
3205
3341
  # while it waited for a repo it never asked about.
3206
3342
  _scan_locks: Dict[str, threading.Lock] = {}
3207
3343
  _warming: Set[str] = set()
3344
+ # Lone files outside any project (see for_file): one cache per file.
3345
+ _single_file_instances: Dict[str, CodeGraph] = {}
3346
+ _LONE_DIR_MAX_FILES = int(os.environ.get("TOKENSAFE_LONE_DIR_MAX_FILES", "2000"))
3347
+ _LONE_DIR_MAX_SEC = 0.5
3208
3348
  _CACHE_MAX_FILES = int(os.environ.get("TOKENSAFE_GRAPH_CACHE_MAX", "400"))
3209
3349
  _CACHE_MAX_BYTES = int(float(os.environ.get("TOKENSAFE_GRAPH_CACHE_MAX_MB", "2048")) * 1024 * 1024)
3210
3350
 
@@ -3217,7 +3357,7 @@ class GraphEngine:
3217
3357
 
3218
3358
  root = os.path.abspath(os.sep)
3219
3359
  while curr and curr != root:
3220
- for marker in (".git", "package.json", "pyproject.toml", "go.mod", "Cargo.toml", "requirements.txt"):
3360
+ for marker in _PROJECT_MARKERS:
3221
3361
  if os.path.exists(os.path.join(curr, marker)):
3222
3362
  return curr
3223
3363
  parent = os.path.dirname(curr)
@@ -3356,15 +3496,92 @@ class GraphEngine:
3356
3496
  pass
3357
3497
  return removed
3358
3498
 
3499
+ @classmethod
3500
+ def _has_project_marker(cls, root: str) -> bool:
3501
+ return any(os.path.exists(os.path.join(root, m)) for m in _PROJECT_MARKERS)
3502
+
3503
+ @classmethod
3504
+ def _crawl_is_bounded(cls, root: str) -> bool:
3505
+ """Whether a marker-less directory is small enough to crawl as a project.
3506
+
3507
+ Counts indexable files the way `_plan_scan` would walk them and stops at
3508
+ the first of `_LONE_DIR_MAX_FILES` files or `_LONE_DIR_MAX_SEC` seconds, so
3509
+ the check itself stays cheap on a `$TMPDIR` or `~/Downloads` with
3510
+ tens of thousands of entries.
3511
+ """
3512
+ if _is_unbounded_root(root):
3513
+ return False
3514
+ deadline = time.monotonic() + cls._LONE_DIR_MAX_SEC
3515
+ count = 0
3516
+ for _dirpath, dirnames, filenames in os.walk(root):
3517
+ dirnames[:] = [
3518
+ d for d in dirnames
3519
+ if d not in IGNORED_DIRS and d not in _SNAPSHOT_DIRS and not d.startswith(".")
3520
+ ]
3521
+ for filename in filenames:
3522
+ if os.path.splitext(filename)[1].lower() in SUPPORTED_EXTS:
3523
+ count += 1
3524
+ if count > cls._LONE_DIR_MAX_FILES:
3525
+ return False
3526
+ if time.monotonic() > deadline:
3527
+ return False
3528
+ return True
3529
+
3530
+ @classmethod
3531
+ def _single_file_graph(cls, file_abs: str) -> CodeGraph:
3532
+ """A graph of one lone file (no directory crawl, no on-disk index)."""
3533
+ with cls._instances_lock:
3534
+ graph = cls._single_file_instances.get(file_abs)
3535
+ if graph is None:
3536
+ graph = _SingleFileGraph(file_abs)
3537
+ cls._single_file_instances[file_abs] = graph
3538
+ while len(cls._single_file_instances) > 64:
3539
+ cls._single_file_instances.pop(next(iter(cls._single_file_instances)))
3540
+ graph.scan() # one stat + at most one parse
3541
+ return graph
3542
+
3359
3543
  @classmethod
3360
3544
  def for_file(cls, file_path: str) -> Tuple[CodeGraph, str]:
3361
- """Resolves the owning project graph and relative file path for any arbitrary file."""
3362
- root = cls.find_project_root(file_path)
3545
+ """Resolves the owning project graph and relative file path for any arbitrary file.
3546
+
3547
+ A file with no project marker above it (a scratch file in `$TMPDIR`, a
3548
+ download) used to make its whole directory the root: a recursive crawl of
3549
+ such a directory ran for 18 minutes. Marker-less directories are crawled
3550
+ only when small; otherwise the graph holds just that file.
3551
+ """
3552
+ file_abs = os.path.abspath(file_path)
3553
+ root = cls.find_project_root(file_abs)
3554
+ if os.path.isfile(file_abs) and not cls._has_project_marker(root):
3555
+ with cls._instances_lock:
3556
+ known = root in cls._instances
3557
+ if not known and not cls._crawl_is_bounded(root):
3558
+ graph = cls._single_file_graph(file_abs)
3559
+ return graph, os.path.basename(file_abs)
3363
3560
  graph = cls.get_instance(root)
3364
- rel_path = os.path.relpath(os.path.abspath(file_path), root).replace("\\", "/")
3561
+ rel_path = os.path.relpath(file_abs, root).replace("\\", "/")
3365
3562
  return graph, rel_path
3366
3563
 
3367
3564
 
3565
+ class _SingleFileGraph(CodeGraph):
3566
+ """CodeGraph whose walk is a single file: `scan()` never lists the directory."""
3567
+
3568
+ def __init__(self, file_path: str):
3569
+ self._only_file = os.path.abspath(file_path)
3570
+ super().__init__(os.path.dirname(self._only_file), use_disk_cache=False)
3571
+
3572
+ def _plan_scan(self, force: bool) -> Tuple[Set[str], List[Tuple[str, str, Tuple[float, int]]], List[str]]:
3573
+ rel_path = os.path.basename(self._only_file)
3574
+ try:
3575
+ st = os.stat(self._only_file)
3576
+ except OSError:
3577
+ return set(), [], [rel_path] if rel_path in self.file_stats else []
3578
+ if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
3579
+ return {rel_path}, [], [rel_path] if rel_path in self.file_stats else []
3580
+ sig = (st.st_mtime, st.st_size)
3581
+ to_index = [] if (not force and self.file_stats.get(rel_path) == sig) else [(self._only_file, rel_path, sig)]
3582
+ return {rel_path}, to_index, []
3583
+
3584
+
3368
3585
  def main():
3369
3586
  import sys
3370
3587
  args = sys.argv[1:]
@@ -36,6 +36,15 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
36
36
  MCP_SERVER_PATH = os.path.join(PROJECT_ROOT, "tokensafe", "mcp_server.py")
37
37
  PYTHON_BIN = sys.executable
38
38
 
39
+ # Skills shipped in <package>/skills/ and linked into every agent that gets
40
+ # token-optimizer. A registry entry's skills_path names the token-optimizer link;
41
+ # the other skills land beside it in the same skills directory. oumv-protocol is a
42
+ # copy of oumv/skills/oumv-protocol (scripts/sync_oumv_skill.py keeps them equal).
43
+ BUNDLED_SKILLS = ("token-optimizer", "oumv-protocol")
44
+ # Written into a skill directory the installer had to copy (no symlink support),
45
+ # so uninstall can tell its own copy from a user's directory of the same name.
46
+ SKILL_COPY_MARKER = ".tokensafe-managed"
47
+
39
48
  def _app_data_dir(*parts: str) -> str:
40
49
  if sys.platform == "darwin":
41
50
  base = os.path.join(HOME, "Library", "Application Support")
@@ -60,8 +69,8 @@ UNIFIED_TOKENSAFE_RULE = (
60
69
  "10. **Secret Leak Prevention (Zero Hardcoded Fallbacks)**: Never hardcode real private keys, API secrets, or webhook secrets as fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. Whenever blocked, state:\n"
61
70
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
62
71
  "11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
63
- "`⚡ **TokenSafe**: +<tokens> tokens / <steps> steps | Total <total> tokens`\n"
64
- "12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go/Gin+Chi, FastAPI/Starlette, Express/Fastify, Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core; Flask/Django mount explicitly as WSGI), "
72
+ "`⚡ **TokenSafe**: +<tokens> tokens / <steps> steps | Total <total> tokens` (numbers from `session_context(action='metrics')` or a tool's savings line; write `n/a` when the turn was not measured, never estimate)\n"
73
+ "12.**Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go/Gin+Chi, FastAPI/Starlette, Express/Fastify, Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core; Flask/Django mount explicitly as WSGI), "
65
74
  "ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
66
75
  "static OUMV works offline on read/edit tasks too (verify answers a labelled static subset without a runtime), and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
67
76
  "In mixed monorepos use `oumv` on supported profiles and `repo_map`/`smart_read_file`/`scoped_search` on stacks without an adapter (Nest/Hono/Koa, Svelte, Go/Echo).\n"
@@ -77,11 +86,11 @@ POINTER_RULE = (
77
86
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
78
87
  "Core tools: `tokensafe:repo_map(view='graph'|'api'|'tree')` for architecture & directory trees, "
79
88
  "`tokensafe:scoped_search` (single or `queries` batch, never raw grep/find), `tokensafe:smart_read_file` (symbol, `targets` bundle, or `.d.ts` `package_name`), "
80
- "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Solid/Angular/Next, Go/Gin+Chi, FastAPI/Starlette/Flask/Django, Express/Fastify/Elysia, Spring/Laravel, ASP.NET Core — live or static offline; check `status` in mixed monorepos), "
89
+ "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Solid/Angular/Next, Go/Gin+Chi, FastAPI/Starlette (Flask/Django via explicit WSGI mount), Express/Fastify/Elysia, Spring/Laravel, ASP.NET Core — live or static offline; check `status` in mixed monorepos), "
81
90
  "`tokensafe:session_context(action='budget'|'compact'|'prune'|'mistakes')` for context & anti-stuck hygiene, and "
82
91
  "`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress'|'dict')` "
83
92
  "(string catalogs: `dict lint --locale <l>`, then `dict apply`, never read whole catalogs); "
84
- "never hardcode secret fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
93
+ "never hardcode secret fallbacks; append the `⚡ **TokenSafe**: +<tokens> tokens / <steps> steps | Total <total> tokens` footer on tool-using turns.\n"
85
94
  )
86
95
 
87
96
  AGENTS_REGISTRY = {
@@ -1821,7 +1830,7 @@ WantedBy=default.target
1821
1830
  if mutated:
1822
1831
  cls._atomic_write_json(config_file, data)
1823
1832
 
1824
- cls._remove_path_safely(info.get("skills_path"))
1833
+ cls._remove_skills(info.get("skills_path"))
1825
1834
  cls._remove_path_safely(info.get("extension_path"))
1826
1835
  cls._remove_path_safely(info.get("rules_path"))
1827
1836
  cls._remove_global_rule(os.path.join(HOME, ".cursorrules"))
@@ -1843,7 +1852,7 @@ WantedBy=default.target
1843
1852
  cls._atomic_write_json(config_file, data)
1844
1853
 
1845
1854
  if "skills_path" in info:
1846
- cls._remove_path_safely(info["skills_path"])
1855
+ cls._remove_skills(info["skills_path"])
1847
1856
 
1848
1857
  if "rules_path" in info:
1849
1858
  if info["rules_path"].endswith("Rule_TokenSafe.md"):
@@ -1868,7 +1877,7 @@ WantedBy=default.target
1868
1877
  pass
1869
1878
 
1870
1879
  if "skills_path" in info:
1871
- cls._remove_path_safely(info["skills_path"])
1880
+ cls._remove_skills(info["skills_path"])
1872
1881
 
1873
1882
  if "plugin_path" in info:
1874
1883
  cls._remove_path_safely(info["plugin_path"])
@@ -1897,7 +1906,7 @@ WantedBy=default.target
1897
1906
  cls._remove_global_rule(info["agents_md_path"])
1898
1907
 
1899
1908
  if "skills_path" in info:
1900
- cls._remove_path_safely(info["skills_path"])
1909
+ cls._remove_skills(info["skills_path"])
1901
1910
 
1902
1911
  return True, f"Removed MCP, Rule & Skill for Claude Code ({info.get('agents_md_path')})"
1903
1912
 
@@ -1935,7 +1944,7 @@ WantedBy=default.target
1935
1944
  cls._atomic_write_json(config_file, data)
1936
1945
 
1937
1946
  if "skills_path" in info:
1938
- cls._remove_path_safely(info["skills_path"])
1947
+ cls._remove_skills(info["skills_path"])
1939
1948
 
1940
1949
  if "plugin_path" in info:
1941
1950
  cls._remove_path_safely(info["plugin_path"])
@@ -1975,7 +1984,7 @@ WantedBy=default.target
1975
1984
  cls._atomic_write_json(installed_json, inst_data)
1976
1985
 
1977
1986
  if "skills_path" in info:
1978
- cls._remove_path_safely(info["skills_path"])
1987
+ cls._remove_skills(info["skills_path"])
1979
1988
 
1980
1989
  if "agents_md_path" in info:
1981
1990
  cls._remove_global_rule(info["agents_md_path"])
@@ -2156,11 +2165,61 @@ WantedBy=default.target
2156
2165
  except Exception:
2157
2166
  return False
2158
2167
 
2168
+ @staticmethod
2169
+ def _bundled_skill_links(skills_path: str) -> List[Tuple[str, str]]:
2170
+ """(skill name, link path) for every bundled skill. The first skill is
2171
+ linked at skills_path itself, the others beside it."""
2172
+ parent = os.path.dirname(skills_path)
2173
+ return [
2174
+ (name, skills_path if i == 0 else os.path.join(parent, name))
2175
+ for i, name in enumerate(BUNDLED_SKILLS)
2176
+ ]
2177
+
2178
+ @staticmethod
2179
+ def _skill_owned_by_tokensafe(link_path: str, name: str) -> bool:
2180
+ """True when link_path is a skill this installer put there: a symlink to
2181
+ <some tokensafe package>/skills/<name> (this one or an older install,
2182
+ e.g. under another Node version), a dangling symlink, or a marked copy.
2183
+ A user's own directory or a link to another checkout is not ours."""
2184
+ if os.path.islink(link_path):
2185
+ resolved = os.path.realpath(link_path)
2186
+ if not os.path.exists(resolved):
2187
+ return True
2188
+ if os.path.basename(resolved) != name:
2189
+ return False
2190
+ package_root = os.path.dirname(os.path.dirname(resolved))
2191
+ return os.path.isfile(os.path.join(package_root, "tokensafe", "installer.py"))
2192
+ return os.path.isfile(os.path.join(link_path, SKILL_COPY_MARKER))
2193
+
2159
2194
  @classmethod
2160
2195
  def _symlink_skill(cls, target_path: str):
2161
- """Symlinks the TokenSafe skill into the target agent's skills directory."""
2162
- skill_src = os.path.join(PROJECT_ROOT, "skills", "token-optimizer")
2163
- cls._symlink_dir(skill_src, target_path)
2196
+ """Links every bundled skill into the target agent's skills directory.
2197
+
2198
+ token-optimizer is (re)linked at target_path unconditionally, as before.
2199
+ A sibling skill only replaces a missing entry or one this installer owns,
2200
+ so a user's own directory of the same name is left alone."""
2201
+ for i, (name, link_path) in enumerate(cls._bundled_skill_links(target_path)):
2202
+ skill_src = os.path.join(PROJECT_ROOT, "skills", name)
2203
+ if not os.path.isdir(skill_src):
2204
+ continue
2205
+ if i > 0 and os.path.lexists(link_path) and not cls._skill_owned_by_tokensafe(link_path, name):
2206
+ continue
2207
+ cls._symlink_dir(skill_src, link_path)
2208
+ if os.path.isdir(link_path) and not os.path.islink(link_path):
2209
+ try:
2210
+ with open(os.path.join(link_path, SKILL_COPY_MARKER), "w", encoding="utf-8") as f:
2211
+ f.write("Copied by the TokenSafe installer; removed by `tokensafe uninstall`.\n")
2212
+ except OSError:
2213
+ pass
2214
+
2215
+ @classmethod
2216
+ def _remove_skills(cls, skills_path: Optional[str]) -> None:
2217
+ """Removes the bundled skills installed by _symlink_skill(skills_path)."""
2218
+ if not skills_path:
2219
+ return
2220
+ for i, (name, link_path) in enumerate(cls._bundled_skill_links(skills_path)):
2221
+ if i == 0 or cls._skill_owned_by_tokensafe(link_path, name):
2222
+ cls._remove_path_safely(link_path)
2164
2223
 
2165
2224
  @classmethod
2166
2225
  def _global_rule_installed(cls) -> bool:
@@ -48,30 +48,18 @@ class LoopDetector:
48
48
  os.makedirs(os.path.dirname(state_file) or ".", exist_ok=True)
49
49
  lock_path = state_file + ".lock"
50
50
  handle = open(lock_path, "a+")
51
- locked_posix = False
52
- locked_win = False
51
+ kind = ""
53
52
  try:
54
- try:
55
- import fcntl
56
- fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
57
- locked_posix = True
58
- except ImportError:
59
- try:
60
- import msvcrt
61
- msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
62
- locked_win = True
63
- except Exception:
64
- pass
53
+ # Bounded (1 s): a hung holder must not stall smart_read_file. Past
54
+ # the deadline the check runs unlocked; the state file is replaced
55
+ # atomically, so the worst case is one lost repeat count.
56
+ from tokensafe.bounded_flock import lock_file
57
+ kind = lock_file(handle, 1.0)
65
58
  yield
66
59
  finally:
67
60
  try:
68
- if locked_posix:
69
- import fcntl
70
- fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
71
- elif locked_win:
72
- import msvcrt
73
- handle.seek(0)
74
- msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
61
+ from tokensafe.bounded_flock import unlock_file
62
+ unlock_file(handle, kind)
75
63
  except Exception:
76
64
  pass
77
65
  handle.close()