tokensafe 4.16.3 → 5.0.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.
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 +5664 -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
@@ -13,7 +13,7 @@ from contextlib import contextmanager
13
13
  from datetime import datetime, timedelta
14
14
  from typing import Dict, List, Optional, Any, Generator
15
15
 
16
- from src.paths import resolve_data_dir
16
+ from tokensafe.paths import resolve_data_dir
17
17
 
18
18
  USD_PER_TOKEN = 3.00 / 1_000_000.0 # Claude Sonnet baseline ($3.00 / 1M tokens)
19
19
 
@@ -21,7 +21,8 @@ USD_PER_TOKEN = 3.00 / 1_000_000.0 # Claude Sonnet baseline ($3.00 / 1M tokens)
21
21
  # than literally metered I/O (see METRICS.md). Everything else counts as measured.
22
22
  # GRAPH_TOPOLOGY: "original" is what a hypothetical full-file crawl would have cost.
23
23
  # HISTORY_FOLD: a folded digest is INJECTED as a system message; the full history
24
- # physically stays in the context window.
24
+ # physically stays in the context window, so it records the
25
+ # injected mass with zero savings.
25
26
  # PROMPT: the TOCP form is injected alongside the original prompt until
26
27
  # replace-mode is verified end-to-end.
27
28
  # ROLLUP_LIFETIME: pruned-and-rolled-up historical mass of mixed provenance;
@@ -86,12 +87,18 @@ class MetricsTracker:
86
87
  self.retention_days = int(os.environ.get("TOKENSAFE_RETENTION_DAYS", "30"))
87
88
  self.max_events = int(os.environ.get("TOKENSAFE_MAX_EVENTS", "5000"))
88
89
  self._event_counter = 0
89
- # One connection per (tracker, thread). Lifecycle hooks are short-lived
90
- # processes issuing ~10 short statements per invocation; a connect/pragma/
91
- # close cycle around each one was pure overhead. Threads never share a
92
- # handle (sqlite3 connections are not safe to interleave), and the handle
93
- # is dropped when the database file identity changes (reset, delete and
94
- # recreate, restored backup).
90
+ # Connection policy:
91
+ # * main thread: one cached connection per tracker. Lifecycle hooks are
92
+ # short-lived single-threaded processes issuing ~10 short statements
93
+ # per invocation; a connect/pragma/close cycle around each one was
94
+ # pure overhead. The handle is dropped when the database file
95
+ # identity changes (reset, delete and recreate, restored backup).
96
+ # * any other thread: a connection is opened for the outermost
97
+ # `_get_connection()` and closed when it exits (nested calls reuse
98
+ # it). Worker threads (proxy request threads, telemetry) are
99
+ # short-lived, and a per-thread cache leaked one handle per thread.
100
+ # Threads never share a handle (sqlite3 connections are not safe to
101
+ # interleave).
95
102
  self._conn_lock = threading.Lock()
96
103
  self._conns: Dict[int, Any] = {}
97
104
  self._depth_state = threading.local()
@@ -105,6 +112,21 @@ class MetricsTracker:
105
112
  except OSError:
106
113
  return None
107
114
 
115
+ def _open_connection(self) -> sqlite3.Connection:
116
+ """Opens a fresh connection with the per-connection pragmas applied."""
117
+ conn = sqlite3.connect(self.db_path, timeout=5.0, check_same_thread=False)
118
+ conn.row_factory = sqlite3.Row
119
+ try:
120
+ conn.execute("PRAGMA busy_timeout=3000;")
121
+ except sqlite3.Error:
122
+ pass
123
+ return conn
124
+
125
+ @staticmethod
126
+ def _caches_connection() -> bool:
127
+ """Only the main thread keeps a cached connection across calls."""
128
+ return threading.current_thread() is threading.main_thread()
129
+
108
130
  def _acquire_connection(self) -> sqlite3.Connection:
109
131
  """Returns this thread's cached connection (identity-checked)."""
110
132
  thread_id = threading.get_ident()
@@ -113,12 +135,7 @@ class MetricsTracker:
113
135
  entry = self._conns.get(thread_id)
114
136
  if entry is not None and entry[1] == identity:
115
137
  return entry[0]
116
- conn = sqlite3.connect(self.db_path, timeout=5.0, check_same_thread=False)
117
- conn.row_factory = sqlite3.Row
118
- try:
119
- conn.execute("PRAGMA busy_timeout=3000;")
120
- except sqlite3.Error:
121
- pass
138
+ conn = self._open_connection()
122
139
  with self._conn_lock:
123
140
  previous = self._conns.get(thread_id)
124
141
  self._conns[thread_id] = (conn, identity)
@@ -141,6 +158,7 @@ class MetricsTracker:
141
158
  pass
142
159
  try:
143
160
  self._depth_state.depth = 0
161
+ self._depth_state.conn = None
144
162
  except Exception:
145
163
  pass
146
164
 
@@ -152,13 +170,22 @@ class MetricsTracker:
152
170
 
153
171
  @contextmanager
154
172
  def _get_connection(self) -> Generator[sqlite3.Connection, None, None]:
155
- conn = self._acquire_connection()
156
- depth = int(getattr(self._depth_state, "depth", 0) or 0)
157
- self._depth_state.depth = depth + 1
173
+ state = self._depth_state
174
+ depth = int(getattr(state, "depth", 0) or 0)
175
+ conn = getattr(state, "conn", None) if depth > 0 else None
176
+ transient = False
177
+ if conn is None:
178
+ if self._caches_connection():
179
+ conn = self._acquire_connection()
180
+ else:
181
+ conn = self._open_connection()
182
+ transient = True
183
+ state.conn = conn
184
+ state.depth = depth + 1
158
185
  try:
159
186
  yield conn
160
187
  except BaseException:
161
- self._depth_state.depth = depth
188
+ state.depth = depth
162
189
  if depth == 0:
163
190
  try:
164
191
  conn.rollback()
@@ -166,12 +193,20 @@ class MetricsTracker:
166
193
  pass
167
194
  raise
168
195
  else:
169
- self._depth_state.depth = depth
196
+ state.depth = depth
170
197
  if depth == 0:
171
198
  try:
172
199
  conn.commit()
173
200
  except sqlite3.Error:
174
201
  pass
202
+ finally:
203
+ if depth == 0:
204
+ state.conn = None
205
+ if transient:
206
+ try:
207
+ conn.close()
208
+ except Exception:
209
+ pass
175
210
 
176
211
  @classmethod
177
212
  def _maybe_autoprune(cls, db_path: str):
@@ -202,7 +237,7 @@ class MetricsTracker:
202
237
  tracker = cls(db_path)
203
238
  tracker.prune(days=tracker.retention_days, max_events=tracker.max_events, vacuum=False)
204
239
  try:
205
- from src.telemetry_sync import TelemetrySync
240
+ from tokensafe.telemetry_sync import TelemetrySync
206
241
  TelemetrySync.sync_background()
207
242
  except Exception:
208
243
  pass
@@ -632,7 +667,7 @@ class MetricsTracker:
632
667
  # aggregate so no quota check can read a figure from before this
633
668
  # write (estimated events leave it alone — that is the hook path).
634
669
  try:
635
- from src.license_manager import LicenseManager
670
+ from tokensafe.license_manager import LicenseManager
636
671
  LicenseManager.note_quota_activity(saved_tokens)
637
672
  except Exception:
638
673
  pass
@@ -17,8 +17,8 @@ import hashlib
17
17
  import threading
18
18
  import subprocess
19
19
  from typing import Dict, Any, List, Optional, Tuple
20
- from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
21
- from src.secret_redactor import SecretRedactor
20
+ from tokensafe.paths import resolve_data_dir, ensure_tokensafe_gitignore
21
+ from tokensafe.secret_redactor import SecretRedactor
22
22
 
23
23
  # (path, mtime, size) -> parsed entries: one hook run reads the ledger twice.
24
24
  _READ_CACHE: Dict[Tuple[str, float, int], List[Dict[str, Any]]] = {}
@@ -111,7 +111,7 @@ class MistakesLedger:
111
111
 
112
112
  # Broadcast to L3 Team Sync (scrubbed, non-blocking)
113
113
  try:
114
- from src.team_cache import TeamCache
114
+ from tokensafe.team_cache import TeamCache
115
115
  safe_summary, _, _ = SecretRedactor.redact_text(summary.strip())
116
116
  h = hashlib.sha256(f"{f_basename}:{safe_summary}".encode("utf-8")).hexdigest()[:16]
117
117
  payload = json.dumps({"file": f_basename, "summary": safe_summary[:160], "timestamp": int(time.time())})
@@ -228,7 +228,7 @@ class MistakesLedger:
228
228
  return list(cls._team_mistakes_cache)
229
229
 
230
230
  try:
231
- from src.team_cache import TeamCache
231
+ from tokensafe.team_cache import TeamCache
232
232
  raw_entries = TeamCache.list_entries("TEAM_MISTAKE", limit=10, timeout=timeout)
233
233
  parsed: List[Dict[str, Any]] = []
234
234
  for item in raw_entries:
@@ -12,7 +12,7 @@ import os
12
12
  import re
13
13
  from typing import Any, Dict, List, Optional
14
14
 
15
- from src.graph_engine import GraphEngine
15
+ from tokensafe.graph_engine import GraphEngine
16
16
 
17
17
  _MAX_SKELETON_CHARS = 16000
18
18
  _MAX_ITEMS = 40
@@ -164,13 +164,31 @@ def _extract_module_state(code: str, ext: str, lines: List[str]) -> List[Dict[st
164
164
  return out[:20]
165
165
 
166
166
 
167
+ def _declaration_line(lines: List[str], sym: Any) -> str:
168
+ """The line that declares `sym`. A decorated symbol's range starts at its
169
+ first decorator (`@Component(...)`), so line_start alone would hide the
170
+ `export` keyword on the declaration below it."""
171
+ start = sym.line_start
172
+ if not 0 < start <= len(lines):
173
+ return ""
174
+ end = min(len(lines), max(start, sym.line_end or start), start + 40)
175
+ name_re = re.compile(rf"\b{re.escape(sym.name)}\b") if sym.name else None
176
+ for idx in range(start - 1, end):
177
+ text = lines[idx]
178
+ if text.lstrip().startswith("@"):
179
+ continue
180
+ if name_re is None or name_re.search(text):
181
+ return text
182
+ return lines[start - 1]
183
+
184
+
167
185
  def _file_symbols(graph: Any, rel: str, lines: List[str]) -> List[Dict[str, Any]]:
168
186
  out: List[Dict[str, Any]] = []
169
187
  for key in graph.file_symbols.get(rel, []):
170
188
  sym = graph.symbols.get(key)
171
189
  if not sym:
172
190
  continue
173
- sig_line = lines[sym.line_start - 1] if 0 < sym.line_start <= len(lines) else ""
191
+ sig_line = _declaration_line(lines, sym)
174
192
  out.append({
175
193
  "name": sym.name,
176
194
  "kind": sym.kind,
@@ -302,7 +320,7 @@ def build_brief(workspace: str, target: str, symbol: Optional[str] = None) -> Di
302
320
  skeleton = ""
303
321
  if not skeleton:
304
322
  try:
305
- from src.skeletonizer import Skeletonizer
323
+ from tokensafe.skeletonizer import Skeletonizer
306
324
  skel_path, _orig, _skel = Skeletonizer.get_skeleton_file(full, target_symbol)
307
325
  skeleton = _read_text(skel_path) if skel_path else ""
308
326
  except Exception:
@@ -15,8 +15,8 @@ import urllib.error
15
15
  import urllib.parse
16
16
  from concurrent.futures import ThreadPoolExecutor, as_completed
17
17
  from typing import Dict, Any, Optional, Tuple, List
18
- from src.paths import get_active_workspace
19
- from src.win_paths import is_within
18
+ from tokensafe.paths import get_active_workspace
19
+ from tokensafe.win_paths import is_within
20
20
 
21
21
 
22
22
  class OUMVRpcError(RuntimeError):
@@ -145,8 +145,15 @@ class OUMVGateway:
145
145
  """
146
146
  st = cls._state_for(workspace_dir)
147
147
  now = time.time()
148
- if (now - st["last_scan"] > cls._SCAN_INTERVAL_SEC) or (not st["fe"] and not st["be"]):
148
+ if now - st["last_scan"] > cls._SCAN_INTERVAL_SEC:
149
149
  cls.scan(workspace_dir=workspace_dir)
150
+ elif not st["fe"] and not st["be"]:
151
+ # Negative result cached: without a runtime, every call used to
152
+ # re-probe all 14 well-known URLs. Until the interval passes only
153
+ # the cheap descriptor files are re-read, so a dev server that
154
+ # writes its runtime.json is still picked up at once.
155
+ ws = workspace_dir or get_active_workspace() or os.getcwd()
156
+ cls._check_workspace_runtime_files(ws, st)
150
157
  cls._drop_stale_descriptor_endpoints(workspace_dir)
151
158
  return st["fe"], st["be"]
152
159
 
@@ -187,8 +194,8 @@ class OUMVGateway:
187
194
  ]
188
195
 
189
196
  with ThreadPoolExecutor(max_workers=6) as executor:
190
- future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not st["fe"] else None
191
- future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not st["be"] else None
197
+ future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend", ws) if not st["fe"] else None
198
+ future_be = executor.submit(cls._probe_candidates, be_candidates, "backend", ws) if not st["be"] else None
192
199
 
193
200
  if future_fe:
194
201
  found_fe = future_fe.result()
@@ -236,7 +243,7 @@ class OUMVGateway:
236
243
  recorded_real = os.path.realpath(os.path.abspath(recorded))
237
244
  if workspace_dir and recorded_real != os.path.realpath(os.path.abspath(workspace_dir)):
238
245
  return False # entry under this key describes another root: stale reuse
239
- from src.paths import is_transient_dir
246
+ from tokensafe.paths import is_transient_dir
240
247
  if is_transient_dir(recorded_real) and not os.path.isdir(recorded_real):
241
248
  return False
242
249
  return True
@@ -389,11 +396,13 @@ class OUMVGateway:
389
396
  return removed
390
397
 
391
398
  @classmethod
392
- def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
399
+ def _probe_candidates(cls, urls: List[str], kind: str, workspace_dir: Optional[str] = None) -> Optional[Dict[str, Any]]:
393
400
  for url in urls:
394
401
  try:
395
402
  res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.0.0"}, timeout=0.35)
396
403
  if res and isinstance(res, dict) and "runtimeInfo" in res:
404
+ if workspace_dir is not None and not cls._probed_runtime_belongs_to(res, url, workspace_dir):
405
+ continue
397
406
  return {
398
407
  "kind": kind,
399
408
  "name": res.get("runtimeInfo", {}).get("name", f"{kind}-runtime"),
@@ -425,6 +434,41 @@ class OUMVGateway:
425
434
  continue
426
435
  return None
427
436
 
437
+ @classmethod
438
+ def _probed_runtime_belongs_to(cls, handshake: Dict[str, Any], url: str, workspace_dir: str) -> bool:
439
+ """Whether a runtime found by a well-known-port probe may serve `workspace_dir`.
440
+
441
+ Port probes (5173, 3000, …) find whatever dev server listens there, which
442
+ may belong to another checkout: workspace B then observed and mutated
443
+ workspace A's runtime. A runtime that reports its root must match; one that
444
+ reports none is refused when another workspace in this process already
445
+ adopted that URL (one dev server serves one root).
446
+ """
447
+ want = cls._ws_key(workspace_dir)
448
+ info = handshake.get("runtimeInfo") if isinstance(handshake.get("runtimeInfo"), dict) else {}
449
+ reported = None
450
+ for src in (info, handshake):
451
+ for key in ("workspaceRoot", "root", "cwd"):
452
+ val = src.get(key) if isinstance(src, dict) else None
453
+ if isinstance(val, str) and val.strip():
454
+ reported = val.strip()
455
+ break
456
+ if reported:
457
+ break
458
+ if reported:
459
+ try:
460
+ return os.path.realpath(os.path.abspath(reported)) == want
461
+ except Exception:
462
+ return False
463
+ for ws_key, st in cls._workspace_states.items():
464
+ if ws_key == want:
465
+ continue
466
+ for slot in ("fe", "be"):
467
+ entry = st.get(slot)
468
+ if entry and entry.get("url") == url:
469
+ return False
470
+ return True
471
+
428
472
  @classmethod
429
473
  def _runtime_is_reachable(cls, url: Optional[str], token: Optional[str] = None) -> bool:
430
474
  """True when a live OUMV runtime answers a handshake at `url`."""
@@ -528,7 +572,7 @@ class OUMVGateway:
528
572
  # Auto detection based on target
529
573
  if target:
530
574
  try:
531
- from src.retrofit import OUMVProjectContext
575
+ from tokensafe.retrofit import OUMVProjectContext
532
576
  ctx = OUMVProjectContext.get_for_workspace()
533
577
  detected_rt = ctx.resolve_target_runtime(target)
534
578
  if detected_rt == "backend" and be:
@@ -556,7 +600,7 @@ class OUMVGateway:
556
600
 
557
601
  @classmethod
558
602
  def _runtime_marker_path(cls, workspace_dir: Optional[str] = None) -> str:
559
- from src.paths import resolve_data_dir
603
+ from tokensafe.paths import resolve_data_dir
560
604
  ws = os.path.realpath(os.path.abspath(workspace_dir or get_active_workspace()))
561
605
  ws_id = hashlib.sha256(ws.encode("utf-8")).hexdigest()[:16]
562
606
  return os.path.join(resolve_data_dir(), f".oumv_used_{ws_id}")
@@ -634,7 +678,7 @@ class OUMVGateway:
634
678
  # Out-of-the-box stack detection
635
679
  stack_info = {}
636
680
  try:
637
- from src.retrofit import detect_project_stack_cached
681
+ from tokensafe.retrofit import detect_project_stack_cached
638
682
  stack_info = detect_project_stack_cached(ws)
639
683
  except Exception:
640
684
  pass
@@ -684,7 +728,7 @@ class OUMVGateway:
684
728
  # crawl thread at exit, so warming there costs the same seconds.
685
729
  if warm_graph:
686
730
  try:
687
- from src.graph_engine import GraphEngine
731
+ from tokensafe.graph_engine import GraphEngine
688
732
  GraphEngine.warm_async(ws)
689
733
  except Exception:
690
734
  pass
@@ -708,7 +752,7 @@ class OUMVGateway:
708
752
  return adapters
709
753
 
710
754
  try:
711
- from src.retrofit import get_adapters_catalog
755
+ from tokensafe.retrofit import get_adapters_catalog
712
756
  catalog = get_adapters_catalog()
713
757
  except Exception:
714
758
  catalog = []
@@ -789,7 +833,7 @@ class OUMVGateway:
789
833
  return None
790
834
  ws = workspace_dir or get_active_workspace()
791
835
  try:
792
- from src.retrofit import detect_project_stack
836
+ from tokensafe.retrofit import detect_project_stack
793
837
  stack = detect_project_stack(ws)
794
838
  be = stack.get("backend") or {}
795
839
  if be and not be.get("oumv_supported", True):
@@ -846,7 +890,7 @@ class OUMVGateway:
846
890
  if runtime == "backend" and not be:
847
891
  notice = cls._unsupported_backend_notice(workspace_dir, runtime)
848
892
  if notice:
849
- from src.graph_engine import GraphEngine
893
+ from tokensafe.graph_engine import GraphEngine
850
894
  ws = workspace_dir or get_active_workspace()
851
895
  res = GraphEngine.get_instance(ws).get_static_oumv_slice(level=level, target=target)
852
896
  res.update(notice)
@@ -868,7 +912,7 @@ class OUMVGateway:
868
912
 
869
913
  # Out-of-the-box fallback when both are offline
870
914
  if not fe and not be:
871
- from src.graph_engine import GraphEngine
915
+ from tokensafe.graph_engine import GraphEngine
872
916
  ws = workspace_dir or get_active_workspace()
873
917
  graph = GraphEngine.get_instance(ws)
874
918
  results["staticAnalysis"] = graph.get_static_oumv_slice(level="L0")
@@ -889,7 +933,7 @@ class OUMVGateway:
889
933
  return res
890
934
  except RuntimeError:
891
935
  # Level 1 Static Fallback via GraphEngine
892
- from src.graph_engine import GraphEngine
936
+ from tokensafe.graph_engine import GraphEngine
893
937
  ws = workspace_dir or get_active_workspace()
894
938
  graph = GraphEngine.get_instance(ws)
895
939
  return graph.get_static_oumv_slice(level=level, target=target)
@@ -900,7 +944,7 @@ class OUMVGateway:
900
944
  workspace_dir: Optional[str] = None, path: Optional[str] = None) -> Any:
901
945
  cls.mark_oumv_used(workspace_dir)
902
946
  target = cls._observe_target(target, path, workspace_dir)
903
- from src.oumv_brief import build_brief
947
+ from tokensafe.oumv_brief import build_brief
904
948
  ws = workspace_dir or get_active_workspace() or os.getcwd()
905
949
  return build_brief(ws, target or "", symbol=symbol)
906
950
 
@@ -916,7 +960,7 @@ class OUMVGateway:
916
960
  if notice:
917
961
  return notice
918
962
 
919
- from src.graph_engine import GraphEngine
963
+ from tokensafe.graph_engine import GraphEngine
920
964
  ws = workspace_dir or get_active_workspace()
921
965
  graph = GraphEngine.get_instance(ws)
922
966
 
@@ -1024,10 +1068,14 @@ class OUMVGateway:
1024
1068
  return {"edges": edges[:30], "count": len(edges), "evidence": evidence}
1025
1069
 
1026
1070
  @staticmethod
1027
- def _file_symbols(ws: str, rel_path: str) -> List[Any]:
1028
- """Symbols declared in one file, parsed without crawling the repository."""
1071
+ def _file_symbol_items(ws: str, rel_path: str) -> List[Tuple[str, Any]]:
1072
+ """(qualified name, symbol) pairs declared in one file, e.g. ("UserService::save", sym).
1073
+
1074
+ Parsed without crawling the repository. The qualified name is the graph key
1075
+ minus its `<rel_path>::` prefix, so nesting (class -> method) is kept.
1076
+ """
1029
1077
  try:
1030
- from src.graph_engine import CodeGraph
1078
+ from tokensafe.graph_engine import CodeGraph
1031
1079
  full = os.path.join(ws, rel_path)
1032
1080
  if not os.path.isfile(full):
1033
1081
  return []
@@ -1035,27 +1083,71 @@ class OUMVGateway:
1035
1083
  graph._index_file(full, rel_path)
1036
1084
  except Exception:
1037
1085
  return []
1038
- return [graph.symbols[k] for k in graph.file_symbols.get(rel_path, []) if k in graph.symbols]
1086
+ prefix = f"{rel_path}::"
1087
+ items: List[Tuple[str, Any]] = []
1088
+ for key in graph.file_symbols.get(rel_path, []):
1089
+ sym = graph.symbols.get(key)
1090
+ if sym is None:
1091
+ continue
1092
+ qual = key[len(prefix):] if key.startswith(prefix) else sym.name
1093
+ items.append((qual, sym))
1094
+ return items
1095
+
1096
+ @classmethod
1097
+ def _file_symbols(cls, ws: str, rel_path: str) -> List[Any]:
1098
+ """Symbols declared in one file, parsed without crawling the repository."""
1099
+ return [sym for _qual, sym in cls._file_symbol_items(ws, rel_path)]
1039
1100
 
1040
1101
  @classmethod
1041
1102
  def _resolve_symbol_range(cls, ws: str, rel_path: str, symbol: str) -> Optional[tuple]:
1042
- """Line range of a declaration: exact name, then case-insensitive, then suffix."""
1043
- syms = cls._file_symbols(ws, rel_path)
1044
- if not syms:
1103
+ """Line range of exactly one declaration, or None when absent or ambiguous.
1104
+
1105
+ `UserService.save` / `UserService::save` must name that method: the old
1106
+ lookup dropped the qualifier, matched every `save` (and, as a last resort,
1107
+ any name ending in it, e.g. `autosave`) and kept the tightest range, so
1108
+ `mutate` could overwrite `OrderRepo.save` instead. Now:
1109
+ 1. exact qualified path (`save` = top-level, `UserService::save` = method);
1110
+ 2. a qualified path ending in the requested one (`Outer::UserService::save`);
1111
+ 3. the bare name, then case-insensitively, only when a single declaration
1112
+ carries it (functions/methods outrank same-named locals).
1113
+ Several remaining candidates are ambiguous and return None, never a guess.
1114
+ """
1115
+ items = cls._file_symbol_items(ws, rel_path)
1116
+ if not items:
1045
1117
  return None
1046
1118
  wanted = (symbol or "").strip()
1047
- short = wanted.split("::")[-1].split(".")[-1]
1048
- matches = [s for s in syms if s.name in (wanted, short)]
1049
- if not matches:
1050
- matches = [s for s in syms if s.name.lower() == short.lower()]
1051
- if not matches:
1052
- matches = [s for s in syms if s.name.lower().endswith(short.lower())]
1053
- if not matches:
1119
+ parts = [p for p in re.split(r"::|\.", wanted) if p]
1120
+ if not parts:
1054
1121
  return None
1055
- # A method outranks a same-named local; among equals the tightest range wins.
1056
- matches.sort(key=lambda s: (0 if s.kind in ("function", "method") else 1, s.line_end - s.line_start))
1057
- best = matches[0]
1058
- if best.line_start < 1 or best.line_end < best.line_start:
1122
+ qualified = "::".join(parts)
1123
+ short = parts[-1]
1124
+
1125
+ def _pick(cands: List[Tuple[str, Any]]) -> Optional[Any]:
1126
+ if not cands:
1127
+ return None
1128
+ funcs = [c for c in cands if c[1].kind in ("function", "method")]
1129
+ pool = funcs or cands
1130
+ spans = {(s.line_start, s.line_end) for _q, s in pool}
1131
+ return pool[0][1] if len(spans) == 1 else None
1132
+
1133
+ stages = [
1134
+ [c for c in items if c[0] == qualified],
1135
+ [c for c in items if c[0].endswith("::" + qualified)],
1136
+ ]
1137
+ if len(parts) == 1:
1138
+ stages.append([c for c in items if c[1].name == short])
1139
+ stages.append([c for c in items if c[1].name.lower() == short.lower()])
1140
+ else:
1141
+ # Languages whose graph keys carry no class nesting (e.g. Go receivers)
1142
+ # still resolve a qualified request when the bare name is unique.
1143
+ stages.append([c for c in items if c[1].name == short])
1144
+
1145
+ best = None
1146
+ for cands in stages:
1147
+ if cands:
1148
+ best = _pick(cands)
1149
+ break
1150
+ if best is None or best.line_start < 1 or best.line_end < best.line_start:
1059
1151
  return None
1060
1152
  return best.line_start, best.line_end
1061
1153
 
@@ -1063,6 +1155,10 @@ class OUMVGateway:
1063
1155
  def _file_symbol_names(cls, ws: str, rel_path: str) -> List[str]:
1064
1156
  return [s.name for s in cls._file_symbols(ws, rel_path)]
1065
1157
 
1158
+ @classmethod
1159
+ def _file_symbol_qualified_names(cls, ws: str, rel_path: str) -> List[str]:
1160
+ return [qual.replace("::", ".") for qual, _s in cls._file_symbol_items(ws, rel_path)]
1161
+
1066
1162
  @staticmethod
1067
1163
  def _splice_range(content: str, start_line: int, end_line: int, replacement: str) -> str:
1068
1164
  """Replaces lines [start_line, end_line] (1-based, inclusive) in `content`."""
@@ -1154,10 +1250,11 @@ class OUMVGateway:
1154
1250
  rel_path = os.path.relpath(abs_path, os.path.abspath(ws)).replace("\\", "/")
1155
1251
  symbol_range = cls._resolve_symbol_range(ws, rel_path, symbol)
1156
1252
  if not symbol_range:
1157
- known = cls._file_symbol_names(ws, rel_path)
1253
+ known = cls._file_symbol_qualified_names(ws, rel_path)
1158
1254
  raise RuntimeError(
1159
- f"[OUMV SYMBOL_NOT_FOUND] '{symbol}' is not declared in {path}. "
1160
- f"Known symbols: {', '.join(known[:8]) or 'none'}. "
1255
+ f"[OUMV SYMBOL_NOT_FOUND] '{symbol}' is not declared in {path}, "
1256
+ f"or several declarations share that name (qualify it, e.g. Class.method). "
1257
+ f"Known symbols: {', '.join(known[:12]) or 'none'}. "
1161
1258
  f"For a non-declaration range use apply_edits(start_line/end_line) instead."
1162
1259
  )
1163
1260
  start_line, end_line = symbol_range
@@ -1169,7 +1266,7 @@ class OUMVGateway:
1169
1266
  )
1170
1267
 
1171
1268
  # Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
1172
- from src.syntax_guard import check_syntax
1269
+ from tokensafe.syntax_guard import check_syntax
1173
1270
  syntax_check = check_syntax(abs_path, new_content)
1174
1271
  if syntax_check.get("status") == "failed":
1175
1272
  raise RuntimeError(
@@ -1185,12 +1282,12 @@ class OUMVGateway:
1185
1282
  os.makedirs(backup_dir, exist_ok=True)
1186
1283
  digest = hashlib.sha256(content).hexdigest()[:8]
1187
1284
  backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
1188
- from src.atomic_io import write_atomic
1285
+ from tokensafe.atomic_io import write_atomic
1189
1286
  write_atomic(backup_path, content)
1190
1287
  except Exception:
1191
1288
  backup_path = None
1192
1289
 
1193
- from src.atomic_io import write_atomic
1290
+ from tokensafe.atomic_io import write_atomic
1194
1291
  write_atomic(abs_path, new_content)
1195
1292
 
1196
1293
  new_version = "sha256:" + hashlib.sha256(new_content.encode("utf-8")).hexdigest()
@@ -1310,7 +1407,7 @@ class OUMVGateway:
1310
1407
  source = f.read()
1311
1408
  except OSError:
1312
1409
  source = ""
1313
- from src.syntax_guard import check_syntax
1410
+ from tokensafe.syntax_guard import check_syntax
1314
1411
  checks["syntax"] = check_syntax(abs_path, source) if source else {"status": "skipped", "reason": "unreadable file"}
1315
1412
  checked.append("syntax check")
1316
1413
  if checks["syntax"].get("status") == "failed":
@@ -1334,7 +1431,7 @@ class OUMVGateway:
1334
1431
  if not symbol_range:
1335
1432
  failures.append(f"symbol '{wanted_symbol}' is not declared in {rel}")
1336
1433
  try:
1337
- from src.graph_engine import GraphEngine
1434
+ from tokensafe.graph_engine import GraphEngine
1338
1435
  surface = GraphEngine.get_instance(ws).get_static_oumv_slice(level="L1", target=rel)
1339
1436
  checks["staticSurface"] = {
1340
1437
  "endpoints": len(surface.get("endpoints") or []),
@@ -1354,7 +1451,7 @@ class OUMVGateway:
1354
1451
  route_method = method_match.group(1).upper()
1355
1452
  lookup = method_match.group(2)
1356
1453
  try:
1357
- from src.graph_engine import GraphEngine
1454
+ from tokensafe.graph_engine import GraphEngine
1358
1455
  surface = GraphEngine.get_instance(ws).get_static_oumv_slice(level="L1", target=lookup)
1359
1456
  endpoints = surface.get("endpoints") or []
1360
1457
  symbols = surface.get("matchingSymbols") or []
@@ -1441,7 +1538,7 @@ class OUMVGateway:
1441
1538
  def graph(cls, query: str = "overview", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> Any:
1442
1539
  """Unified graph over static + runtime evidence, with §11.4-style queries."""
1443
1540
  fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
1444
- from src.cross_stack import build_unified_graph, who_depends_on, impact_from_graph
1541
+ from tokensafe.cross_stack import build_unified_graph, who_depends_on, impact_from_graph
1445
1542
 
1446
1543
  ws = workspace_dir or get_active_workspace()
1447
1544
 
@@ -1474,7 +1571,7 @@ class OUMVGateway:
1474
1571
  symbol) breaks ties. Falls back to the FTS5 content index when the graph
1475
1572
  holds nothing for the query, and labels that fallback honestly.
1476
1573
  """
1477
- from src.graph_engine import GraphEngine
1574
+ from tokensafe.graph_engine import GraphEngine
1478
1575
  ws = workspace_dir or get_active_workspace() or os.getcwd()
1479
1576
  q = (query or "").strip()
1480
1577
  if not q:
@@ -1525,7 +1622,7 @@ class OUMVGateway:
1525
1622
  provenance = "static-graph"
1526
1623
  if not matches:
1527
1624
  try:
1528
- from src.fts_index import CodeFTSIndex
1625
+ from tokensafe.fts_index import CodeFTSIndex
1529
1626
  fts_rows = CodeFTSIndex(ws).search(q, limit=limit) or []
1530
1627
  matches = [
1531
1628
  {
@@ -1624,7 +1721,7 @@ class OUMVGateway:
1624
1721
  offline["diff"] = "".join(diff_lines)
1625
1722
  offline["unchanged"] = current == (replacement or "")
1626
1723
  offline["currentVersion"] = cls._hash_version(abs_path)
1627
- from src.syntax_guard import check_syntax
1724
+ from tokensafe.syntax_guard import check_syntax
1628
1725
  offline["syntaxCheck"] = check_syntax(abs_path, replacement)
1629
1726
  return offline
1630
1727
  raise
@@ -70,7 +70,7 @@ def profile_for(tier: Optional[str] = None, payload: Optional[Dict[str, Any]] =
70
70
 
71
71
  def current() -> Tuple[str, str]:
72
72
  """(profile, tier) for the active license. License reads are cached upstream."""
73
- from src.license_manager import LicenseManager
73
+ from tokensafe.license_manager import LicenseManager
74
74
 
75
75
  try:
76
76
  tier, payload = LicenseManager.get_active_license()
@@ -21,7 +21,7 @@ import shutil
21
21
  import sqlite3
22
22
  from typing import Optional
23
23
 
24
- from src.win_paths import is_plugin_dir, is_system_root, transient_roots
24
+ from tokensafe.win_paths import is_plugin_dir, is_system_root, transient_roots
25
25
 
26
26
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
27